text:
Q: How do I resolve occasional severe internet connection problems with overseas trading company software, is this caused by routing lags? I live in Australia, and login to a US based trading company software for work. Generally my connection to this software is good with maybe 1-2 dropouts every 1-2 days (in a 5-6 hour period). When this occurs I usually just need to log back in and everything is fine after that, however a couple of times a month I will experience several hours where I either:

*

*Can login, but then data on the software is not updating properly (with the software sometimes displaying a "connecting" error), and so then I can't use the software.

*Or I login, but then soon after have a connection problem and get logged out.

These periods are extremely dangerous because if there is a market move against me and I can't trade, I can't make any adjustments to my trades and I'm flying blind. An occasional logout, but then being able to log back in in a couple of minutes is no problem.
It seems like in good times and bad my internet connection speeds (wired LAN), and ping/tracert results are pretty similar.

*

*My internet connection speed is around 47MBps download speed.

*I have attached ping/tracert example results during a bad connection period.

Optus ISP ping/tracert results:

(Click images to enlarge)
The trading company says it is the lag in Singapore through my Optus ISP that is causing the problem, and that I should see if the ISP can optimize my routing to login.silexx.com. Unfortunately my ISP is not proving very helpful with this. Someone also mentioned to me that due to the distance of the jump, the lag is expected/normal.
I have also tried logging in through a VPN (just to have a different routing path). This seems to yield similar ping/tracert time results,  and when I was having serious connection problems yesterday - using the VPN wasn't resolving the issue.
VPN tracert/ping results:

My questions are:

*

*How do I check that the lag/internet routing is the actual problem - and not just an excuse used by the software company?

*If the ISP won't/can't optimize my route is there a way of doing so myself?

*Is there any point trying a different VPN?

*Is there any point having a backup mobile internet connection with a different provider, but how do I know which provider's routing might be successful/how do I know this will resolve the problem?

*Are there any other solutions that I haven't thought of?

A: I think your vendor is full of crap, but first, the answers to your questions:

How do I check that the lag/internet routing is the actual problem - and not just an excuse used by the software company?

A typical tracert will only show three round-trips for each hop.  When the problem ("connecting error") happens, run a My traceroute (Windows version: WinMTR) repeatedly for several thousand samples and monitor the packet loss.  You can also test at shorter intervals, like 1/10 of a second, to get more results.
If the packet loss starts somewhere in the middle and at the end is more than a few percent, that is more likely to mean that there is a routing issue.  Where the packet loss begins is the culprit.
If the packet loss starts at a hop controlled by your vendor (close to the end or at the end), it's probably on them.
If there is no packet loss, it's probably not a routing issue.

If the ISP won't/can't optimize my route is there a way of doing so myself?

You're already doing the right thing by trying a VPN.

Is there any point trying a different VPN?

Sure, to get another route.  If a certain route is working better, maybe routing is involved.  If you're not seeing any difference, then it's less likely that routing is a contributing factor to the problem.

Is there any point having a backup mobile internet connection with a different provider, but how do I know which provider's routing might be successful/how do I know this will resolve the problem?

A VPN connection should cover this case already, unless the routing error is starting early in the traceroute.
If your packet loss starts early in the hops, this means that your ISP is dropping packets to the Internet.  You may notice that websites all over are slow or not loading.  In this case, it would be helpful to try a backup ISP.

Are there any other solutions that I haven't thought of?

Yes, your software vendor is probably deflecting the true cause of the connectivity issues.
You said, "I login, but then soon after have a connection problem and get logged out.", but think about almost every other web service you log in to.  If you disconnect from and reconnect to the Internet while using the website, you're probably not going to be logged out.  Why does your vendor log you out?
Seems like crappy software.
Furthermore, your traceroutes during the "bad" times are pretty typical for Australia to United States with no conclusive evidence of packet loss.
Ruling out the network connection, the next-most likely cause is that the vendor's server becomes inoperative "a couple of times a month" for "several hours", and the vendor's software can't cope with the server being unusable for any amount of time.
My advice to you is to start developing a contingency plan for if/when your vendor disappears.  It sounds like there is no ability to work offline, which suggests that your data is locked in with them.
You can also try to get the vendor to fix their software so that it's more resilient to server unreachable conditions, but I wouldn't count on it.


text:
Q: Почему параграф уезжает влево если задавать ему максимальную ширину Мне нужно чтобы данный параграф был по центру и с максимальной шириной, но если задать ему её то он уезжает влево, как это исправить?
.about_partners_subtitle{
    text-align: center;
    font-family: 'Futura PT';
    font-style: normal;
    font-weight: 500;
    font-size: 40px;
    line-height: 106.7%;
    text-align: center;
    color: #FFFFFF;
    max-width: 678px;
}

A: Такое нужно?

.about_partners_subtitle{
    text-align: center;
    font-family: 'Futura PT';
    font-style: normal;
    font-weight: 500;
    font-size: 40px;
    line-height: 106.7%;
    text-align: center;
    /*color: #FFFFFF;*/
    max-width: 80%;
    margin-left: auto;
    margin-right: auto;
}
<p class='about_partners_subtitle'>Мне нужно чтобы данный параграф был по центру и с максимальной шириной, но если задать ему её то он уезжает влево, как это исправить?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Missing Nuget.targets I'm net with C# and Visual Studio 2017. It seems that VS says that Nuget packages are missing. When I'm trying to build the solution the console outputs the following:

"This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is D:\xxxx\xxxx\Desktop\Koodipohjaa\trunk\.nuget\NuGet.targets"

The project is copied from the original location to the desktop (because reasons). In /trunk/ I have a folder called "packages" but no ".nuget" folder. I've tried the "restore nuget packages" from the solution level and it says that there is nothing to update. When I open the references from the project, there is this very cute little yellow triangle with all the packages.
I've tried to update packages, remove them all and reinstalling them automatically etc. In "nuget package manager" I have tried all possible in package restore.

A: This is issue was resolved quite easily. As .nuget folder is mandatory, I managed to get a copy of the folder and pasted it in the right place. I tried a lot of tips and tricks with VS 2017 and 2019 and none of them worked. Now that the .nuget folder is there, all is working.

A: Please try:
1.In VS2017,go Tools menu=>Nuget Package Manager=>Package Manager settings, make sure you've checked these two options like this:

2.Right-click the project in Solution Explorer=>Unload Project=> Right-click the project name and Edit the xx.csproj, you will find a EnsureNuGetPackageBuildImports target in this format:
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\xxx')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xxx'))" />
  </Target>

Delete the target and save files. Then right-click the project to reload the project and run a rebuild.
I assume you may have such target in your project file(xx.csproj), which tries to find the nuget.targets file, delete the target to check if it helps. Similar issue see here.

A: The .nuget/nuget.targets was an old "integration" of NuGet with Visual Studio between Visual Studio 2010 to Visual Studio 2013. Visual Studio 2015 onwards no longer has the feature to create this file, because NuGet's integration is more direct. Since you copied the project, and not the whole solution, you didn't copy the .nuget/ folder. You said there's no .nuget folder in the source repo, but then I don't see how the original solution could possibly compile successfully.
I suggest you follow the instructions on how to migrate to automatic package restore. It's just undoing what "enable package restore" did in VS2013 and earlier.

A: As you said that you copy the project from other location to desktop, I am assuming that you don't copy the sln file. try adding a sln file at desktop and add the project to that sln after that try restor the nuget. One thing to remember please try to make sure the folder structure hierarchic relative to the sln file and project location.


text:
Q: The given name was not found in the service operations This is my code:
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetServiceOperationAccessRule("getSMSs", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
public IQueryable<SM> getSMSs()
{
    SelfServiceEntities db = new SelfServiceEntities();
    return from d in db.SMS select d;
}

I got this exception:
The given name 'getSMSs' was not found in the service operations.

A: you need to define your method as service operation
[WebGet]
public IQueryable<SM> getSMSs()
{


text:
Q: Qt5 Bind TCP Socket on Multihomed Network I am having troubling using the new bind feature of the QTcpSocket class in Qt5. Any help figuring this out would be appreciated.
I have a multihomed server that contains two NICs each with a separate IP address. I have setup routing on the servers so that sending from the source address is sent out of the appropriate NIC regardless of the target remote address. That is, sending from x.x.x.0 goes out over eth0 and x.x.x.1 goes out over eth1 regardless of who the data is being sent to. These NICs are connected via ethernet to long range Wifi links that are then connected to a switch. These wifi links act as a transparent bridge and can rather be seen as two ethernet cables (but they are limited in bandwidth). The switch is then connected to a computer. The goal is to transfer data between the server and the computer, and to use the two wifi links in parallel to increase bandwidth. Although the server is physically a server, the software has the computer running as the software server (as others connect to it). That is, the physical  server (software client) opens TCP sockets and attempts to connect to the listening computer (software server).
I use the bind feature of Qt5 to bind one TCP socket to the eth0 IP address and bind another TCP socket to the eth1 IP address. I have verified this works with other programs like PING or file transfer via SCP. See http://qt-project.org/doc/qt-5.0/qtnetwork/qabstractsocket.html#bind
When I call bind the call succeeds and subsequent requests for the local IP address returns the correct value. E.g. socket->bind(ip) returns true and then socket->localAddress() equals ip. However, when I call connectToHost the localAddress is lost when it starts the connection attempt and after connecting it has a different localAddress that is not the one I wanted it to have.
Can anyone shed light into what is going on? I am trying to avoid rewriting the software to reverse the roles of software client / server as these programs are quite big. Thanks for the help.

A: There is an open bug on this in the Qt project bug tracker.


text:
Q: How to deep link direct message in telegram I want a deep link to a telegram user and forward a message.
something like this:
http://t.me/apada?message="hello!"
in whatsapp i can do this:
whatsapp://send?text=WHATEVER_YOU_WANT&abid=RECIPIENT_ADDRESSBOOK_ID
but i want it in telegram too


text:
Q: Keep kernels alive in parallel evaluations of several scripts I have written a parallel script file that after initializing the kernels it puts the result of some computation in a file. I provide some external parameters to the script. I would like to run the script several times with different parameters, however every time the script runs it inizialises again the kernels, wasting a lot of time.
The script structure is something like
ClearAll["Global`*"];
LaunchKernels[4];
param = ToExpression[ $ScriptCommandLine[[2]] ];

dat=ParallelTable[RandomReal[],{j,param}];
MaxDat=Max[dat];

s=OpenWrite["datafile.txt"];
WriteString[s,param<>"  "<>ToString@MaxDat<>"\n"];
Close[s];

and I run in terminal through, for instance for param=2 and param=3
wolframscript -script prova.wls 2
wolframscript -script prova.wls 3

Every time I called the command the script launches the kernels. It is possible to inizializes the kernels only during the first run and keep them opened? I had a look at similar questions but I did not find the answer.


text:
Q: Restart PHP FCGI process automatically once it dies on Windows when using with nginx I am using PHP FCGI to execute PHP scripts (These are Restful Web Services written in PHP which handles web requests from web pages) with Nginx on Windows. Everything works fine until the request counts reaches "php_fcgi_max_requests". I am setting this to 1000 as every tutorial for Nginx + PHP FCGI out there suggests this value for PHP stability. But I want to know if there is a way if the PHP FCGI can be recycled while using with Nginx on Windows OS. In other words, once the 1000 requests are handled and PHP FCGI dies, then PHP FCGI restarts itself and start handling requests again. I require this nginx+ PHP FCGI always running on Windows until and unless it is explicitly closed  by the user.
I have researched a lot online but could not find a solution for this for Nginx on Windows. Any other operating system is, unfortunately, not an option. I need a solution for Windows only and I need a light server which does not take up much memory and is quick to install.
If you think my goal cannot be achieved with Nginx + PHP FCGI, I am open to suggestions if the PHP FCGI can be used with any other light server (like Nginx) on Windows where it can handle as many requests as possible (no limit to requests or at least recycle itself when the process dies off on reaching max requests).
It would be very helpful if somebody can provide me any guidance.
FYI, I start the Nginx server and PHP FCGI like below:
set PATH=<customized path>;%PATH%
set PHP_FCGI_MAX_REQUESTS=1000
RunHiddenConsole.exe %CD%\nginx\PHP\php-cgi.exe -b 127.0.0.1:9000
RunHiddenConsole.exe nginx.exe

here, RunHiddenConsole.exe is from here: https://www.nginx.com/resources/wiki/start/topics/examples/phpfastcgionwindows/
Please let me know if anybody need any more technical details.
Thanks a lot in advance.

A: Not sure if you are still stuck with this issue. The work around I used was to design a windows service that monitors the number of requests Nginx has handled. I used multiple instances of PHP-CGI (Fast CGI) in order to load-balance the server.
I cannot share the full code as I did this for work, but I can provide the steps to design your own implementation.
Some background information on why I implemented this the way I did:

*

*Nginx is not able to restart php-cgi.exe (on Windows at least)

*The default value for PHP_FCGI_MAX_REQUESTS is 500. By default php-cgi.exe will terminate after handling 500 web requests.

*Our web server is on an embedded system, it will not be seeing high traffic.

Step 1
Configure Nginx to allow for active monitoring. This will allow you to track the number of requests your server has been getting.
Even if PHP-CGI has crashed, it is still possible to get the request information from Nginx.
Add the following location information into your server{} block in nginx.conf
    location /nginx_status {
        stub_status on;
        access_log   off;
        allow 127.0.0.1;
        deny all;
    }

Now, from your server, if you visit localhost/nginx_status you will be able to see the number of handled (the 3rd number in the 3rd line is the number of requests). Nginx Doc on stub_status
Step 2
Access the Nginx status from your service (mine is written in C# .NET 4.0)
My service checks and updates the requests value throughout it's lifetime. You can get the string from the web page using the following code:
//
// Get the Nginx Status String containing the number of requests to the site.
//
private string ReadSiteStatus()
{
    string nginxStatus = ERROR_NO_NGINX;
    using (WebClient client = new WebClient())
    {
        try
        {
            nginxStatus = client.DownloadString("http://127.0.0.1/nginx_status");
        } catch (Exception ex)
        {
            WriteToFile(ex.Message);
        }
    }
    return nginxStatus;
}

From here you can set up a function to parse the request number from this string.
Step 3
Setup Nginx to load balance multiple PHP-CGI instances. For our implementation, we used three instances. In the http{} block of nginx.conf, add the following block.
#Reference the three Fast CGI servers
upstream myproject{
    server 127.0.0.1:9000 weight=1 fail_timeout=5;
    server 127.0.0.1:9001 weight=1 fail_timeout=5;
    server 127.0.0.1:9002 weight=1 fail_timeout=5;
}

In your server{} block, locate the location ~\.php${} block. Update the fastcgi_pass to reference the upstream block defined in http.
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000, 9001, and 9002
location ~ \.php$ {
    fastcgi_pass   myproject;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
    include        fastcgi_params;
}

Step 4
Start the three instances of PHP-CGI. One listening on each of the ports: 9000, 9001, and 9002.
I wanted to do this from within my service but had issues with calling the PHP-CGI executable directly. I wrote a batch file that starts PHP-CGI. It takes a port number as a parameter. The file was named start-php.bat
@ECHO OFF
SET PHP_FCGI_MAX_REQUESTS=2000
C:\Nginx\RunHiddenConsole.exe C:\NGinx\PHP\php-cgi -b 127.0.0.1:%1 -c
C:\NGinx\PHP\php.ini
EXIT

Example usage:

> start-php.bat 9000

Would start an instance listening on port 9000.
RunHiddenConsole.exe is required to run PHP-CGI in the background, it is referred to on NGinx's site here.
Step 5
Build the service.
Here is the part that is up to your implementation. I can provide you with the general workflow / algorithm.

*

*On Start, stop all instances of PHP-CGI

*Start the instances of PHP-CGI required by your Nginx config file (call into batch script provided)

*Create a queue of the PHP-CGI processes, keep track of which one is on which port.

*Create a loop to check the status every x-seconds.

*If you have reached a certain number of requests, stop the next process in the queue. Get the port of that process (track it in your service). Start a new instance of PHP-CGI on that port, add it back to the queue.

Hope this helps.


text:
Q: Upgrade EC2 instance (ubuntu) without losing IP I know I can associate an instance with an Elastic IP. However, is it possible to "reserve" or transfer over a current public IP that an instance has so that it can be used when I upgrade the instance?

A: The short answer is no.  The only way you can guarantee a specific IP to an instance is via use of elastic IP.  So you would have to have that previously attached to the running instance, shut the instance down for size upgrade, then re-attach the elastic IP to the new instance.


text:
Q: rotate the elements of the given array k times to the right I have made this code to rotate an array by k times. In this when I'm adding i=0 , it is showing an "ArrayOutOfBounds" exception, and when I'm changing the value of i by 1, it is showing wrong output. Why is it showing this exception? And is there any way I could correct this code?

    public void rotate(int[] nums, int k)
    { int j=0, temp=0;
        for(j=0;j<k;j++)
        {
        for(int i=0;i<nums.length;i++)
        {
              temp=nums[i-1];
              nums[i-1]=nums[i];
              nums[i]=temp;

        }

        }
    }
}

A: At i=0 you are trying to access nums[i-1] = num[-1] which is an invalid position and hence an ArrayOutOfBound exception is thrown.
So, the modified version would be:
        for (j=0; j<k; j++)
        {
            for (int i=1;i<nums.length;i++)
            {
                temp=nums[i-1];
                nums[i-1]=nums[i];
                nums[i]=temp;
            }
        }

But the above will rotate the array by k times towards the left not right as you are shifting the elements towards the left. So, to get the right rotation you need to shift the elements from the end of the array. Like:
        for (j=0; j<k; j++)
        {
            for (int i=nums.length-1; 0<i; i--)
            {
                // shifting towards the right
                temp=nums[i-1];
                nums[i-1]=nums[i];
                nums[i]=temp;
            }
        }

A: Edit (from comments above): If i is 0, you're trying to get an index of -1 which will raise an ArrayOutOfBounds exception. If i starts from 1, then you're not dealing with the first number.
Here's the function you can use to rotate integers to the right:
public void rotate(int[] nums, int k) {
    int arrLen = nums.length;

    // If the number of times you want to rotate is bigger than the size of the array, get the minimum number of rotations to get the same result.
    while (k > n) {
        k = k - arrLen;
    }
    k = arrLen - k;
    k = k % arrLen;
    int i, m, n, temp;
    int g_c_d = gcd(k, arrLen);
    // Move the value in the i-th index
    for (i = 0; i < g_c_d; i++) {
        temp = arr[i];
        m = i;
        while (true) {
            n = m + k;
            if (n >= arrLen) {
                n = n - arrLen;
            }
            if (n == i) {
                break;
            }
            arr[m] = arr[n];
            m = n;
        }
        arr[m] = temp;
    }
}

// Find the greatest common divisor of two numbers, a and b
public void gcd(int a, int b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

Let me briefly explain what it does. This is one of the most known algorithms: juggling. You divide the array into the n number of sets where n denotes the greatest common divisor of the length of the array and the number of times you want to rotate. Then, you move the numbers within sets.
This might be the most efficient in terms of time (as its time complexity is O(n)).

A: A better solution would be taking a copy of the given array with the values '0' then looping through the given array to obtain a new_index.
Formula for the New_index for the Clock-wise rotating array:
for(int i=0;i<nums.length;i++){
 int new_index = (old_index+k)%(a.length)
 copy[new_index] = a[old_index]
}

Now the entire function code would be:

public static void rotate(int[] a, int k)
    {
     int n = a.length;
     int[] copy = new int[n];
    //  fill the values with zeroes
     for(int i=0;i<n;i++){
         copy[i]=0;
     }
    //  rotate the array
    for(int i=0;i<n;i++){
        int new_index = (i+k)%n;
        copy[new_index] = a[i];
    }
    // Now that the array is copied, copy the elements to the original array. Because they asked to rotate the given array.
    for(int i=0;i<n;i++){
         a[i]=copy[i];
     }
    }

A:
function solution(arr, k) {
  if(k == 0) return arr;
  if(arr.length == k) return arr;
  if(arr !== undefined && arr !== null){
    let counter = k > arr.length ? k % arr.length : k;
    let rotArray = [];
    rotArray = arr.slice(arr.length - counter, arr.length).concat(arr.slice(0,arr.length - counter))
    return rotArray;
   }
  return arr;
}


text:
Q: Mysql list data from left join query I have 2 table and i want to pull data from both of them.
This is sample for my table structure:
Table tbl_a = id, time, note, customer
Table tbl_b = id, time, name, surname, note
This is my mysql request:
Select * from tbl_a left join tbl_b on tbl_a.customer=tbl.b=id where tbl_a.id=5;

When i run this query directly from mysql i can see result exactly as i want but i dont know how to display it in my php page.
i am doing it like this:
$sql = mysql_query("Select * from tbl_a left join tbl_b on tbl_a.customer=tbl.b=id where tbl_a.id=5");
$data = mysql_fetch_array($sql);

echo $data[id]." - ".$data[time]." - ".$data[note]." - ".$data[customer]." - ".$data[id]." - ".$data[name]." - ".$data[surname]." - ".$data[note];

i know that column names that are repeated could not be used again but i dont know what the right way is.

A: I suggest instead of using the ALL (*). just type the column names with an AS attached such as: TableA.id AS TableAId,TableB.id AS TableBId and so on.


text:
Q: C# generic delegate that accept function without arguments I've created a generic delegate and I want to assign to it a function without any arguments.
Is it possible?
Here is what I tried so far:
class Program
    {
        public delegate void TemplateDel<T>(T item);

        public static void fWriteLetters(char[] p_cLetters)
        {
            for (int i = 0; i < p_cLetters.Length; i++)
                Console.WriteLine(p_cLetters[i]);
        }
        void fNoArg()
        {
            Console.WriteLine("No arguments!");
        }
        static void Main(string[] args)
        {
            TemplateDel<char[]> l_dWriteLeters  = new TemplateDel<char[]>(fWriteLetters);
            TemplateDel<void> l_dNoArg              = new TemplateDel<void>(fWriteLetters);

        }
    }

the last line of code doesn't compile...

A: No it is not possible.void is only valid in return types.You can't use it as a type in other contexts. (except the unsafe context)
You need add another overload for your delegate.
public delegate void TemplateDel();

Or simply use an Action.

A: As Selman22 notes in the other answer:

No it is not possible.

But there is another way, use a lambda to throw away the argument:
TemplateDel<bool> l_dNoArg = new TemplateDel<bool>(_ => fWriteLetters);

(Using _ as the identifier here matches F#'s wildcard – ignore this argument – syntax.)
While not helpful here, this kind of wrapper is helpful when arguments are not interested in are passed and saves writing an extra member just to ignore or re-arrange arguments.


text:
Q: Wordpress - добавление собственных кнопок в редактор + стилизация Добавляю в редактор кнопки таким образом, через function.php:
QTags.addButton( 'sheens_jQtooltip', 'Phone', '+(7) 965 000-00-00');

Меня интересуют два вопроса:
1) Как можно придать созданной кнопке в редакторе цвет?
2) Если кнопок много, как их "категоризировать"? Допустим, я хочу, чтобы на одной линии были такие кнопки, как: телефон, адрес, имя, фамилия.
При обычном добавлении кнопки она просто становится в ряд по указанному типу. Как создать свой тип, и чтобы они были по линиям? Нужно, ибо когда они все вразброс - тяжеловато искать: одна - там, другая - сям.

A: Порядок кнопок задается седьмым параметром (priority) функции QTags.addButton:
QTags.addButton( id, display, arg1, arg2, access_key, title, priority, instance );

где

*

*id - html id кнопки,

*display - текст на кнопке,

*arg1 - открывающий тег,

*arg2 - закрывающий тег,

*access_key - клавиатурный шорткод кнопки,

*title - тултип (текст при наведении),

*priority - приоритет кнопки (позиция в строке),

*instance - экземпляр панели кнопок.

Добавьте в function.php такой пример:
function kagg_add_quicktags() {
    if (wp_script_is('quicktags')){
        ?>

        <?php
    }
}

add_action( 'admin_print_footer_scripts', 'kagg_add_quicktags' );

Этот код добавляет 4 кнопки: p, hr, pre и Phone. Обратите внимания на приоритеты и картинку с результатом внизу.
Чтобы задать цвет вашей кнопке, нужно запустить собственный файл стилей в админке. Добавьте следующий код в function.php:
function admin_style() {
    wp_enqueue_style('admin-styles', get_stylesheet_directory_uri().'/admin.css');
}

В папку вашей темы добавьте файл admin.css со следующим содержимым:
input#qt_content_kagg_paragraph,
input#qt_content_kagg_hr,
input#qt_content_kagg_pre,
input#qt_content_kagg_phone {
    background: red;
    color: white;
}

Вот такой результат я получил на своем тестовом сайте:


text:
Q: IModelBinder in WebApi string manipulation In Asp.Net MVC the System.Web.Mvc.IModelBinder allow the follow implementation to change all strings:
public class CustomMvcTextBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (result == null)
            return null;

        var value = result.AttemptedValue.Trim().ToUpper();

        return value;
    }
}

And then I just add this to ModelBinders:
ModelBinders.Binders.Add(typeof(string), new CustomMvcTextBinder());

However the Asp.Net WebApi implementation System.Web.Http.ModelBinding.IModelBinder has a different implementation returning a bool instead object.
How I could change the string value in the WebApi version of IModelBinder?
public class CustomWebApiTextBinder : IModelBinder
{
    public bool BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (result == null)
            return false;

        var value = result.AttemptedValue.Trim().ToUpper();

        return true;
    }
}

A: You would set bindingContext.Model and return true:
var value = result.AttemptedValue.Trim().ToUpper();
bindingContext.Model = value;

return true;

That is assuming your model is just a single string, of course. Otherwise some more object creation/casting might be necessary.


text:
Q: php dynamic dropdown menu get value i am trying to do a dynamic dropdown menu, i manage to retrieve the first menu value but i can't manage to retrieve the second menu value.
HTML part

        Marca
        <select type="text" id="marca" name="marca" onChange="getModel()">
        <option value="">Alege Marca</option>

        <?php    while($row = mysqli_fetch_assoc($resultMarca)){ ?>

            <option value="<?php echo $row["id"]  ?>"> <?php echo $row["nume_marca"]  ?> </option>

            <?php  } ?>

        </select>

        Model
        <select id="model" nume="model">

        <option value="">Alege Model</option>

        </select>

Ajax Part

PHP
?>
        Model
        <select id="model" nume="model" onchange='model_schimba()'>
        <option value="">Alege Model</option>

<?php
    while($row = mysqli_fetch_array($res)){ ?>

            <option value="<?php echo $row["id"] ?>"> <?php echo $row["name"]  ?> </option>

            <?php  }
        ?> </select> <?php

}

i mange to take the variable here
 $modelSc = (document.getElementById("model").value);
but when i push the submit button i can't reach the variable
$model = $_POST["model"];

A:
"but when i push the submit button i can't reach the variable $model = $_POST["model"];"

nume="model"
PHP syntax is English-based, not in your language.
You need to change it to name="model".
The "name" attribute is the same in any language.
Having use PHP's error reporting, it would have thrown you an undefined index notice.

*

*http://php.net/manual/en/function.error-reporting.php

A: First, code separation is important for readability.
Second, I think your AJAX return
document.getElementById("model_masina").innerHTML=xmlhttp.responseText;

is mistakenly pointing at a
 container instead of the <select> list. Should be,
document.getElementById("model").innerHTML=xmlhttp.responseText;

because you are outputting select menu <option>


text:
Q: How to render content inside the block with ng-click? I've setup dropdown button on frontend and now I have to display my array inside separate content block only when dropdown item is selected.
How do I do this?
Here's my plunker
HTML

  <button id="single-button" type="button" class="btn btn-default btn-xl" dropdown-toggle="" ng-disabled="disabled">
        Options
      </button>

          Display tasks

Js
var myApp = angular.module('myApp', ['ui.bootstrap']);

myApp.controller('DropdownCtrl', function ($scope) {

  $scope.tasks =  [
    {title:'First Task'},
    {title: 'Second Task'}
  ];

});

A: I would suggest you to add selected property in your each task element which will show you the current element has been selected or not. On basis of the you could have filter on selected while doing ng-repeat on tasks.
Markup

 0">Below are selected Tasks

No task selected

      {{task.title}}

      {{task.title}}

Demo Plunkr


text:
Q: Апк с ярлыком Здравствуйте, скажите, пожалуйста, как создать апк, при установке которого бы на главном экране появлялся ярлык?
A: 1) при установкЕ.
2) Никак. при установке APK невозможно выполнить какой-либо код из него. Можно только, например, при первом запуске


text:
Q: Solving $f(t)=t+\frac{1}{6}\int_{0}^{t} (t-u)^3f(u) \ du$ Using Laplace Transforms
I am trying to use the Laplace Transformation to find the unknown function $f:[0,\infty)\rightarrow\mathbb{R}$ in the integral equation, $$f(t)=t+\frac{1}{6}\int_{0}^{t} (t-u)^3f(u) \ du.$$

I start by noticing,
$$f(t)=t+\frac{1}{6}(f*t^3)(t) \ \ \ \ \text{(where $*$ denotes the convolution)}.$$
Then, \begin{align}
\mathcal{L}(f)(z)&=\mathcal{L}(t)(z)+\frac{1}{6}\mathcal{L}(f)(z)\mathcal{L}(t^3)(z) \\
\mathcal{L}(f)(z)&=\frac{1}{z^2}+\frac{\mathcal{L}(f)(z)}{z^4} \\
\mathcal{L}(f)(z)&=\frac{z^2}{z^4-1}
\end{align}
Using partial fraction, $$\frac{z^2}{z^4-1}=-\frac{1}{4}\left(\frac{1}{z+1}\right)+\frac{1}{4}\left(\frac{1}{z-1}\right)-\frac{1}{4i}\left(\frac{1}{z+i}\right)+\frac{1}{4i}\left(\frac{1}{z-i}\right).$$
So, $$\mathcal{L}(f)(z)=-\frac{1}{4}e^{-t}+\frac{1}{4}e^t-\frac{1}{4i}e^{-ti}+\frac{1}{4i}e^{ti}.$$
Is this solution correct? I was unable to determine this via back substitution using Mathematica.

A: It's correct, although It's odd for me  to see $(f*t^3) (t) $ rather than $f(t) *t^3 $. Also in the last line it should be $f(t)$ instead of $ \mathcal{L}(f)(z)$, after all that is what you want to find,  or $\mathcal{L}^{-1}(f)(z)=f(t)$.  We can simplify the last line if we  use the complex form of the sine function: $ \displaystyle{2\sin z= e^{iz} - e^{-iz}} $, also with $2 \sin h( z) = e^z-e^{-z}$
$$f(t)=\frac12\left(\frac{1}{2} e^t-\frac{1}{4}e^{-t}\right) +\frac12\left(\frac{1}{2i}e^{it}-\frac{1}{2i}e^{-it}\right)=\frac{\sinh t} {2} +\frac{\sin t} {2} $$
Here is another approach to find that inverse laplace trasform. $$\mathcal{L}(f)(z) =\frac{z^2} {z^4 - 1}=\frac12\frac{2 z^2} {(z^2 - 1)(z^2 +1)}$$
$$=\frac12\frac {z^2 +1 +z^2 - 1}{(z^2 - 1)(z^2 +1)}=\frac12\left(\frac{1} {z^2 - 1}+\frac{1} {z^2 +1}\right)$$ Now we can directly see that: $$f(t) =\frac12(\sinh t + \sin t) $$


text:
Q: symfony2: sent data with ajax to controller i have an input in the main of my site web that help people to search about something in my database but i want this input search like Facebook search bar .''ajax searching''
i have tried some code but without result . i was used the event keyup to search in instant .
my router is
acme_estm_site_espace_supr_admin_recuperer_donnes_recherche:
    path: /chercher
    defaults: { _controller: AcmeEstmSiteBundle:Default:recupererdonnesrechercheAction}

and this is my controller:
  $('#search').keyup(function(key) {
      var rac = $(this).val();

      var data = {
          request: rac
      };

      $.ajax({
          type: "POST",
          url: "{{ path('acme_estm_site_espace_supr_admin_recuperer_donnes_recherche') }}",
          data: data,
          success: function(data, dataType) {
              alert(data);
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
              alert('Error : ' + errorThrown);
          }
      })
  });

public function recupererdonnesrechercheAction(Request $request){

     if($this->getRequest()->isXmlHttpRequest()){

         echo "c est une requete ajax";

         $data = $request->request->get('request');
         echo $data;

     }

    return new Response();

}

but when i run it . i have an alert error :Error : Not Found
please help me
thank you in advance

A:
Hello,
in your code i see you use Request $request as a parameter
And if($this->getRequest()->isXmlHttpRequest()){
to finally use $request->request->get('request');
I think you should do something like
public function recupererdonnesrechercheAction(){

     if($this->getRequest()->isXmlHttpRequest()){

         echo "c est une requete ajax";

         $data = $this->getRequest()->request->get('request');
         echo $data;

     }

    return new Response();

}

And about the route, you should remove "Action" in your method name
acme_estm_site_espace_supr_admin_recuperer_donnes_recherche:
    path: /chercher
    defaults: { _controller: AcmeEstmSiteBundle:Default:recupererdonnesrecherche}


text:
Q: Custom Global Actions in Salesforce Mobile Application I want to access custom global actions in Mobile Application of Salesforce. I am not able to see them in any Salesforce Lightning App apart from "Salesforce Mobile" that also in Chatter. Is there any way of accessing custom Global actions in Mobile Application in any Salesforce Lightning App.
Thanks in advance.


text:
Q: Getting historical price for specific dates using R I am trying to get the past 4 fiscal years' stock price, which are the close price for each specific date from yahoo using R.
The following is:
getFin("AAPL")
viewFin(AAPL.f, "IS", "A")
x <- viewFin(AAPL.f, "IS", "A")
y <- colnames(x)
getSymbols("AAPL")
AAPL[y]

But I find that I can not get the price while I was using AAPL[y], it gave me nothing.
Can someone give me a hand? Thanks!!

A: AAPL[y] returned an empty xts object because AAPL didn't trade on those dates.  You can get the previous close by merging AAPL with an empty xts object containing the y Dates and using na.locf.
Note that if fill is a function, the function will be applied to the result of the merge before merge returns.  It's a handy feature.
merge(AAPL, xts(,sort(as.Date(y))), fill=na.locf)[y,]


text:
Q: Java Version 1.7 in Visual Studio 2015 Basic Application (Android, Gradle) I'm attempting to use the diamond operator in a basic android gradle  application:
ArrayList<TextView> texts = new ArrayList<>();
TextView  tv = new TextView(this);
tv.setText("Hello World!");
texts.add(tv);

setContentView(texts.get(0));

Unfortunately, this simple test fails to build:
1>  ... error: diamond operator is not supported in -source 1.6
1>          ArrayList<TextView> texts = new ArrayList<>();
1>                                                    ^
1>    (use -source 7 or higher to enable diamond operator)

In the default build.gradle.template, I only see these compile options being set:
compileOptions.with {
    sourceCompatibility=JavaVersion.VERSION_1_7
    targetCompatibility=JavaVersion.VERSION_1_7
}

How do I tell Visual Studio 2015 and/or gradle to use version 1.7 instead of 1.6? (Where is it being told to use 1.6 for that matter?)
Thanks!

A: I solved this by adding the following inside allprojects in the build.gradle file located in the Visual Studio 2015 project's root directory:
tasks.withType(JavaCompile) {
    sourceCompatibility = "1.7"
    targetCompatibility = "1.7"
}

I'm still not sure why it was being set to 1.6 without this, though.


text:
Q: Performing near point-to-point merge with ArcPy? I have a series of .csv datasets with points in Lat/Long mapped to Town Names:

In addition, I have a shapefile containing similar data (town names with their corresponding x/y):

I also have geobuffer data with buffers for each of these towns.
My goal is to join each of the towns in the shapefile to the nearest (within certain limits) town in each of the .csv files. This has to be done spatially (i.e, on a lat/long basis), and the end result would ideally be a table containing:

*

*The town name in the shapefile

*The coordinates of the point in the shapefile

*The name of the matched town from the csv data

*The coordinates of the matched town from the csv data

Points 1 and 3 are essential.
I am fairly new to ArcGIS, so I am struggling to get this done. Ideally, I would have to perform this on ArcPy. I have tried using the near command to no avail. I have also tried creating a feature class from the csv data, and then trying to do a "Point to point" join using the join tool, but I am struggling as well.
What would be the best way to go about this?

A: *

*Use Make XY Event Layer to convert the CSV file(s) into feature layers.

*Use the Near tool with your shapefile as the in_features and the layer from step 1 as the near_features.

*Join the shapefile and the feature layer from step 1 on the NEAR_FID field (added to the shapefile in step 2). There is also a NEAR_DST field you can use to filter out matches above some distance threshold.

*Rinse and repeat for additional CSVs.

The docs linked above have code examples, you can follow the same basic approach in arcpy or in ArcMap.


text:
Q: WaitForSingleObject Crash I am trying to protect a section of code through the use of a mutex. Due to the code crashing I've created a simple bit of test code below which does the same. The crash is not necessarily on the same line of code each time but is always around the "WaitForSingleObject" or "Sleep" calls.
Any assistance would be appreciated.
#include <thread>
#include <windows.h>
#include <process.h>

static HANDLE myMutex;

//The function we want to make the thread run.
void task1()
{

    WaitForSingleObject(myMutex, INFINITE);

    for (int i = 0; i < 20; i++)
    {
        Sleep(500);
    }

    ReleaseMutex(myMutex);
}

void task2()
{

    Sleep(10);
    WaitForSingleObject(myMutex, INFINITE);

    for (int i = 0; i < 20; i++)
    {
        Sleep(10);
    }

    ReleaseMutex(myMutex);
}

int main(int argc, char **argv)
{

    myMutex = CreateMutex(0, FALSE, 0);

    std::thread t1(task1);

    std::thread t2(task2);
}

A: The problem is that you're not waiting for the threads to exit before your main method exits.  The destructors on the thread objects are being called without the thread exiting.  You need to call join in order to have your main method wait.  Try:
int main(int argc, char **argv)
{

    myMutex = CreateMutex(0, FALSE, 0);

    std::thread t1(task1);

    std::thread t2(task2);
    if(t1.joinable())
        t1.join();

    if(t2.joinable())
        t2.join();

}

According to std::thread destructor docs:

Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.


text:
Q: How to organize primary keys for good locality? I have a table for users and a table for documents.  Documents have exactly one user as an owner, and for the application I'm building, I know that I will typically be accessing a group of documents associated with a single given user.
Let's say the average user has K documents, and certain common queries fetch all of the documents for a given user.  I don't want my database (PostgreSQL) to have to do K disk seeks (on average) to fetch all the documents for a user.  Ideally, the documents would be stored in contiguous blocks so that fetches would only require a few seeks.
Is it possible (and reasonable) to organize the document table schema to create such locality?  I know that no-SQL implementations do this all the time? E.g. the BigTable paper talks about how row keys for web tables are assigned by URL, except that the url is reversed, e.g. com.cnn.www, so that all the pages for CNN are located near eachother in the data store.  It doesn't appear possible to something similar in Postgres because the tables cannot be index-organized, although it might be possible in MySQL w/ InnoDB.  This post comes to a similar conclusion.

A: The command you're looking for is CLUSTER, but it has drawbacks. It completely rewrites the table when you run it, which requires a lock on it, so you may only want to do this when traffic is low. Also, Postgres will do nothing to keep rows in that order during INSERTs and UPDATEs, so your data will tend to fragment as the table is written to and you may have to recluster it regularly.
What you can also do is set a low fillfactor on the table, so that UPDATEs are more likely to keep a given row on the same page. This should prevent some fragmentation, which just leaves INSERTs, but with a low fillfactor INSERTs will tend to be placed on newer pages, and these will probably be commonly accessed enough to be kept in RAM. I'm making assumptions about your usage patterns which may be wrong, but regardless, your best course of action is probably to just recluster whenever you see I/O start to become a problem.
Finally, there's also a tool called pg_repack that can cluster a table without taking such a heavy lock, in a similar manner to how CREATE INDEX CONCURRENTLY works, but it's a third-party tool, so you'll want to experiment with it before running in production.


text: Q: In which cases shlex.quote() is used? I stumbled across shlex.quote(). I have read explanations about what shlex.quote() is, but I am wondering when to use it and when not. I see that I should use it when I am using Python as a subshell. For example, using os.system() or subprocess.call() or even using pexpect. Should I use it when I am trying to check for a file using os.path.isfile, or are there any other useful ways to use it properly?


text:
Q: How to download .msi file in Java I want to download .msi file using Java.  I have tried to download file using following code
PrintWriter out = null;
FileInputStream fileToDownload = null;
BufferedReader bufferedReader = null;
try {
        out = response.getWriter();
        fileToDownload = new FileInputStream(DOWNLOAD_DIRECTORY + FILE_NAME);
        bufferedReader = new BufferedReader(new InputStreamReader(fileToDownload));

        //response.setContentType("application/text");
        //response.setContentType("application/x-msi");
        //response.setContentType("application/msi");
        //response.setContentType("octet-stream");
        response.setContentType("application/octet-stream");
        //response.setContentType("application/x-7z-compressed");
        //response.setContentType("application/zip");
        response.setHeader("Content-disposition","attachment; filename=" +FILE_NAME );
        response.setContentLength(fileToDownload.available());

        System.out.println("\n now file download is starting");
        String NextLine = "";
        while((NextLine = bufferedReader.readLine()) != null){
            out.println(NextLine);
        }
        out.flush();

    } catch (IOException e) {
        out.write("
The Installer is not Available on Server
");
        System.out.println("\n Got Exception while getting the input Stream from the file==>"+e);
        log.error("Error::", e);
    }
    finally{
        if(null != bufferedReader){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                System.out.println("\n Error in closing buffer Reader==>"+e);
                log.error("Error::", e);
            }
        }// End of if

        if(null != fileToDownload){
            try {
                fileToDownload.close();
            } catch (IOException e) {
                System.out.println("\n Error in closing input stream==>"+e);
                log.error("Error::", e);
            }
        }// End of if
    }// End of finally

A: You Can't read binary(msi) file with readline() in this case.Your Code is totally wrong and will not work.
Here is a simple function which lets you do what you want.
    private void doDownload( HttpServletRequest req, HttpServletResponse resp,String filename, String original_filename )throws IOException
            {
            File f = new File(filename);
            int  length   = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context  = getServletConfig().getServletContext();
            String  mimetype = context.getMimeType( filename );
            resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
            resp.setContentLength( (int)f.length() );
            resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
            byte[] bbuf = new byte[BUFSIZE];
            DataInputStream in = new DataInputStream(new FileInputStream(f));
            while ((in != null) && ((length = in.read(bbuf)) != -1)){
            op.write(bbuf,0,length);
            }
            in.close();
            op.flush();
            op.close();
        }

Create doDownload() function in your servlet and pass requierd parameters to that function from doGet,doPost or whatever valid place you like.
Parameters:

*

*@param req The request

*@param resp The response

*@param filename The name of the file you want to download.

*@param original_filename The name the browser should receive.


text:
Q: At what value of y does the population grow the fastest? Why? I wasn't sure how to solve $\frac{dy}{dt} = y(4-y^2)$.

A: Since this is a population model, we consider the model only for $y\geq 0$.
$\frac{dy}{dt}$ ist the growth rate. So, you need to find the maximum of $f(y)=y(4-y^2)$ for $y\geq 0$.
Using the classical derivative test, you find that the growth rate is maximal for $\boxed{y = \frac 2{\sqrt 3}}$.

A: HINT: Use partial fractions $$\frac{dy}{dt} = y(4-y^2)$$
$$\frac{dy}{y(4-y^2)}=dt$$
$$\frac14\left(\frac{1}{y}-\frac{y}{y^2-4}\right)dy=dt$$


text:
Q: How to Remove the class 'in' dynamically which is inbuilt class in bootstrap when only clicked when clicked on the button the class "in" in div element must be removed dynamically.
`

Simple Collapsible

Click on the button to toggle between showing and hiding content.

    <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo">Simple collapsible</button>

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod.

`

A: Here is a sample code.
Explanation
In this example, in class render element as bold.
A very simple directive called onclick-toggle-class declared as an attribute of the element binds onclick event on this element and add/remove the css class passed in param (We use the directive attribute value).

angular.module('app', []);

angular.module('app').directive('toggleNextElementClass', function() {
  return {
      restrict: 'A',
      link: function(scope, element, attrs) {
         element.bind('click', function() {
          // get next element
          var nextElement = element[0].nextElementSibling;
          if(nextElement) {
          angular.element(nextElement).toggleClass(attrs.toggleNextElementClass);
          }
          });
      }
  };
});
<!doctype html>

  <meta charset="utf-8">

Simple Collapsible

Click on the button to toggle between showing and hiding content.

    <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo" toggle-next-element-class="in">Simple collapsible</button>

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod.


text:
Q: Array becomes 'undefined' in forEach inside polymer property observer i have a problem that's driving me crazy, i can't understand why this is happening.
I have a custom Polymer element, in this element i set an array with a function, in this element i have a paper-input of which the value is bound to a variable, that variable has an observer and each time that variable changes i run a function that iterates through an array and does some simple checks. Everything works fine until the input value enters the 6-9 range, at which point the array i iterate becomes 'undefined' until i exit that range, i attached an observer to that array and the strange thing is that when the array becomes 'undefined' the observer isn't fired so i guess the actual array isn't changed.
Here is the code
    <link rel="import" href="../custom_elements/paper-file-input.html">
<link rel="import" href="../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<dom-module id="property-editor">

    <template style="width:100%; height:100%;">

PROPRIETA':

            <template is="dom-if" if="{{selected}}">

                    Tempo:

                        <paper-input class="prop" style="width:100%; margin-right:8pt;" type="number" label="Da" value="{{from}}" min="0" max="100"></paper-input>
                        <paper-input class="prop" style="width:100%;" type="number" label="A" value="{{to}}" min="0" max="100"></paper-input>

                    Posizione:

                        <paper-input class="prop" style="width:100%; margin-right:8pt;" type="number" label="Left" value="{{left}}" min="0" max="1000"></paper-input>
                        <paper-input class="prop" style="width:100%;" type="number" label="Top" value="{{top}}" min="0" max="1000"></paper-input>

                    Generale:
                    <paper-input class="prop" label="Nome" value="{{nome}}"></paper-input>
                    <template is="dom-if" if="{{_or(button, link, text)}}">
                        <paper-input class="prop" label="Testo" value="{{testo}}"></paper-input>
                    </template>
                    <template is="dom-if" if="{{_or(button, link, text)}}">
                        Testo:
                        <paper-input class="prop" type="number" label="Dimensione font" min="0" max="100"></paper-input>
                        <paper-color-input allow-alpha class="prop" shape="square" type="hsl" label="Colore font"></paper-color-input>
                        <paper-dropdown-menu class="prop" label="Famiglia font">
                            <paper-listbox class="dropdown-content">
                                <paper-item>Roboto</paper-item>
                                <paper-item>Arial</paper-item>
                                <paper-item>Common Sans</paper-item>
                            </paper-listbox>
                        </paper-dropdown-menu>
                    </template>
                    Elemento:
                    <paper-file-input class="prop" label="Sfondo"></paper-file-input>
                    <paper-color-input allow-alpha class="prop" shape="square" type="hsl" label="Colore sfondo"></paper-color-input>

                    <paper-button raised class="fullwidth white" on-tap="_handleTimestamp">AGGIORNA</paper-button>

            </template>
            <template is="dom-if" if="{{!selected}}">

                    Seleziona un elemento

                    <paper-button raised disabled class="fullwidth white">AGGIORNA</paper-button>

            </template>

    </template>

</dom-module>

The error that is thrown when i enter the 6-9 range is this one
property-editor.html:183 Uncaught TypeError: Cannot read property 'forEach' of undefined

Please help, i'm at a loss...
Thanks

A: The this inside the Ajax call
_retrieveOverlayTimestamps: function(){
    var app = this;
    $.ajax({
        url: 'php/get-timestamp.php',
        method: 'POST',
        data: {'id': app.id},
        success: function(data){
            var result = JSON.parse(data);
            this.timestamps = result;   //<-- wrong
        }
    });
}

should be
app.timestamps = result;


text:
Q: Proving $\sum_{n=0}^{\infty }\frac{1}{(48n+1)(48n+47)}=\frac{\pi}{2208}(\cot(\frac{\pi}{24})+\sec(\frac{11\pi}{24}))$ Proving

$$\sum_{n=0}^{\infty }\frac{1}{(48n+1)(48n+47)}=\frac{\pi}{2208}(\cot(\frac{\pi}{24})+\sec(\frac{11\pi}{24}))$$

When I used the WolframAlpha, I got the the following result:

I could get the alternative form of result which is above, but I m not sure if the closed-form is corrected ?
Any help

A: This question is extremely similar to your other question.
We have:
$$S=\sum_{n\geq 0}\frac{1}{(48n+1)(48n+47)}=\sum_{n\geq 0}\frac{1}{(48n+24)^2-23^2}=\frac{\pi}{4\cdot 23\cdot 24}\tan\frac{23 \pi}{48},$$
hence

$$ S = \frac{\pi}{2208}\cot\frac{\pi}{48} $$

and since $\cot\frac{\pi}{6}=\sqrt{3}$ while $\cot\frac{x}{2}=\cot x+\sqrt{1+\cot^2 x}$, we have:
$$\cot\frac{\pi}{12}=2+\sqrt{3},\quad \cot\frac{\pi}{24}=2+\sqrt{3}+2\sqrt{2+\sqrt{3}}$$
and:

$$\cot\frac{\pi}{48}=2+\sqrt{3}+2\sqrt{2+\sqrt{3}}+2\sqrt{4+2 \sqrt{3}+2 \sqrt{2+\sqrt{3}}+\sqrt{3 \left(2+\sqrt{3}\right)}}$$

is an algebraic number over $\mathbb{Q}$ with degree $8$ and minimal polynomial
$1+16 x+4 x^2-112 x^3+6 x^4+112 x^5+4 x^6-16 x^7+x^8$.

A: You may recall the following series representation for the digamma function
$$\begin{equation}
\psi(x+1) = -\gamma - \sum_{n=1}^{\infty} \left( \frac{1}{n+x} -\frac{1}{n}
\right), \quad \Re x >-1, \tag1
\end{equation}
$$ where $\gamma$ is the Euler-Mascheroni constant.
Then by partial fraction decomposition we have
$$
\begin{align}
\frac{1}{(48n+1)(48n+47)} &= \frac{1}{46}\left(\frac{1}{48n+1}-\frac{1}{48n+47}\right)\\\\
&=\frac{1}{2208}\left(\frac{1}{n+1/48}-\frac{1}{n+47/48}\right)\\\\
&=\frac{1}{2208}\left[\left(\frac{1}{n+1/48}-\frac1n\right)-\left(\frac{1}{n+47/48}-\frac1n\right)\right]
\end{align}
$$ then summing from $n=1$ to $+\infty$, using $(1)$, we get
$$
\begin{align}
\sum_{n=1}^{\infty}\frac{1}{(48n+1)(48n+47)} &=\frac{1}{2208}\left(\psi\left(\frac{47}{48}\right)-\psi\left(\frac{1}{48}\right)\right)\\\\
&=\frac{1}{2208}\left(\psi\left(1-\frac{1}{48}\right)-\psi\left(\frac{1}{48}\right)\right)
\end{align}
$$ then recall that, from the Euler reflection formula you have
$$
\psi\left(x\right)-\psi\left(1-x\right)=- \pi \cot(\pi x)
$$
leading to

$$
\sum_{n=1}^{\infty}\frac{1}{(48n+1)(48n+47)}=\frac{\pi}{2208}\cot\left(\frac{\pi}{48}\right).
$$

A: This is a comment to the "Olivier Oloa"s answer. Using this page and some fun with radicals we get:
$$\cot\Big(\frac{\pi}{48}\Big)=\sqrt{\frac{2+\sqrt{2+\sqrt{2+\sqrt{3}}}}{2-\sqrt{2+\sqrt{2+\sqrt{3}}}}}$$


text:
Q: Accessing a state object in the this.state constructor I have a state with 2 objects (players), of which only 1 can be the player on turn.
How do I save the player on turn into the state, so I can use its data?
class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      playerOne: {
        name: "foo"
      },
      playerTwo: {
        name: "bar"
      }
      playerOnTurn: {} // This has to become the same Object as 'playerOne'.
    }
  }
}

I have tried the following 3 things:

1) Directly accessing the state (within the state):

playerOnTurn: this.state.playerOne

Unfortunately it doesn't work, as the state isn't yet defined due to still constructing the state.

2) Writing the same Object twice:
playerOnTurn: { name: "foo" }

It works, but I don't want to write it twice, because a player can contain many properties. It seems like a bad solution in terms maintainability. Because properties could be added/removed later, which could cause them to become nonidentical.

3) Declaring the object before setting it in the state:
class App extends React.Component {
  constructor(props) {
    super(props);

    const playerOne = {
      name: "foo"
    }

    this.state = {
      playerOne: playerOne,
      playerTwo: {
        name: "bar"
      }
      playerOnTurn: playerOne
    }
  }
}

It works, but it doesn't seem like a great solution in terms of readability. Because I declare both players in different ways.

Maybe it requires a different approach? E.g. by adding a boolean onTurn to each player?
Any input/advice is welcome.

A: In this case, you should use componentDidMount lifecycle method to update your state.
class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      playerOne: {
        name: "foo"
      },,
      playerTwo: {
        name: "bar"
      }
      playerOnTurn: {}
    }
  }

  setPlayerOnTurn(player){
      this.setState({ playerOnTurn : player });
  }

  componentDidMount(){
      // other initialization
      this.setPlayerOnTurn(this.state.playerOne);
  }
}

A: Your 3rd option is correct, if you want it to not look like you are declaring them in different ways, you can do,
    const playerOne = {
      name: "foo"
    }

    const playerTwo = {
      name: "bar"
    }

    this.state = {
      playerOne,
      playerTwo,
      playerOnTurn: playerOne
    }

A: You can use a getter function, which allows you to access this (in context of the object) inside a function:
class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      playerOne: {
        name: "foo"
      },,
      playerTwo: {
        name: "bar"
      }
      get playerOnTurn() {
        return this.playerOne
      }
    }
  }
}


text:
Q: Composite Keys on Trigger I want to know the best way to accomplish this task, I have these 3 Objects Suscripcion_Detalle_c, Direccion_Entrega__c and Paquete_Detalle__c.
What I need to do is every time there's a new Suscripcion_Detalle__c, is to insert a new Direccion_Entrega__c with the Paquete_Detalle__c values. The thing is that I need to access Paquete_Detalle_c with a 3 field(Empresa_c, Paquete_c, Producto_c) composite key, it should be something like this:
 Trigger SuscripcionDet_CreaDireccionEntrega on Suscripcion_Detalle__c (after insert) {

    Set<Id> idSusDetalle = new Set<Id>();

    List<Direccion_Entrega__c> insertaDe = new List<Direccion_Entrega__c>();

    for(Suscripcion_Detalle__c sd : trigger.new){
        idSusDetalle.add(sd.Id);

    }

    List<Suscripcion_Detalle__c> susDetalles = [SELECT s.Id FROM Suscripcion_Detalle__c s
                                                WHERE s.Id IN: idSusDetalle];

    for(Suscripcion_Detalle__c sd : susDetalles){

        Direccion_Entrega__c de = new Direccion_Entrega__c(Suscripcion_Detalle_Buscar__c = sd.Id);

                //this is one of the fields I need to fill and should be extracted from Paquete_Detalle__c, I know I can´t use queries inside a for loop, it´s just an example

        de.Cantidad__c = (Cantidad__c FROM Paquete_Detalle__c
                                 WHERE Empresa__c = de.Empresa__c
                                 AND  Paquete__c = de.Paquete__c
                                 AND Producto__c = de.Producto__c);

        insertaDe.add(de);
    }

    insert insertaDe;
}

A: In above we can skip some lines by doing this way
Trigger SuscripcionDet_CreaDireccionEntrega on Suscripcion_Detalle__c (after insert) {
//Set<Id> idSusDetalle = new Set<Id>();
List<Direccion_Entrega__c> insertaDe = new List<Direccion_Entrega__c>();
//for(Suscripcion_Detalle__c sd : trigger.new){
// idSusDetalle.add(sd.Id);
//}
List<Suscripcion_Detalle__c> susDetalles = [SELECT s.Id FROM Suscripcion_Detalle__c s
                                        WHERE s.Id IN:trigger.newMap.keyset()]

writing inside for loop is not good, while trigger running in bulk mode it gives problem, i am not sure about relationships between the three objects, based on proper relationships we can eliminate query inside for loop, one good practise is , writing triggers with helper class, like moving logics to the apex class, invoking apex class from the triggers based on context variables.


text:
Q: Magento's webservice returns a session even if credentials are not complete I have a 1.10.1.1 Magento Enterprise version running and tried out the webservice. If I correctly login I get a session id which I can use to make further calls to the web service.
If I leave either the user or password field empty or both empty and want to login I also get a session id. But if I then want to call another method with this session id I get the message I have to relogin.
If I use wrong credentials (both user and password are filled with something) I get a message "Access denied".
So why do I get a session id I can't use if i leave one field (user/password) empty and why don't I get a message "Acces denied" then? Is this an error?


text:
Q: Testing http intercetpor in angular2 I'm testing an angular2 HTTP interceptor and I get the following error:
Error: Expected no open requests, found 1: GET /web-service

it('check if request path...',
     inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
        http.get('/web-service').subscribe(
            response => {
                expect(response).toBeTruthy();
            }
        );
    }));

I don't seem to understand the error. An open request is found and the response is there so my expect statement should pass, instead it throws an error that it doesn't expect an request?


text:
Q: Sum of Series S =?
Proving:
$$\displaystyle\sum_{n=0}^{\infty}\frac{(n^2+4n-1)(\pi-\phi)^{3n}}{n!(n+2)}=(\pi-\phi)^3e^{(\pi-\phi)^3}+2\left(e^{(\pi-\phi)^3}-1\right)-5\left(\frac{e^{(\pi-\phi)^3}((\pi-\phi)^3-1)+(\pi-\phi)^4-(\pi-\phi)^3+1}{(\pi-\phi)^6}\right) $$
Where .$ \phi $ is  golden ration

Note:this series is convergent
Proof :
we put $$S=\displaystyle\sum_{n=0}^{\infty}\frac{n^2+4n-1}{n!(n+2)}x^{3n}$$
we have :
\begin{align*}
\lim_{n\to\infty}|\frac{a_{n+1}}{a_n}|
&=\lim_{n\to\infty}|\frac{\frac{(n+1)^2+4(n+1)-1}{(n+1)!(n+3)}}{\frac{n^2+4n-1}{n!(n+2)}}|\\
&=\lim_{n\to\infty}\frac{(n+1)^2+4(n+1)-1}{n^2+4n-1}\frac{(n+2)}{(n+1)(n+3)}=0\\
&\implies R=\infty
\end{align*}
So This series is convergent for each $x\in \mathrm R$

A: Note that for $n\geq 1$,
$$
\frac{{n^2  + 4n - 1}}{{n!(n + 2)}}x^{3n}  = \frac{{x^{3n} }}{{(n - 1)!}} + 2\frac{{x^{3n} }}{{n!}} - 5\frac{{x^{3n} }}{{n!(n + 2)}}.
$$
Hence,
$$
\sum\limits_{n = 0}^\infty  {\frac{{n^2  + 4n - 1}}{{n!(n + 2)}}x^{3n} }  = e^{x^3 } (x^3  + 2) - 5\sum\limits_{n = 0}^\infty  {\frac{{x^{3n} }}{{n!(n + 2)}}} .
$$
But
\begin{align*}
\sum\limits_{n = 0}^\infty  {\frac{{x^{3n} }}{{n!(n + 2)}}} & = \frac{1}{{x^6 }}\sum\limits_{n = 0}^\infty  {\frac{{x^{3(n + 2)} }}{{n!(n + 2)}}}  = \frac{1}{{x^6 }}\sum\limits_{n = 0}^\infty  {\frac{{(n + 1)x^{3(n + 2)} }}{{(n + 2)!}}} \\ & = \frac{1}{{x^3 }}\sum\limits_{n = 0}^\infty  {\frac{{x^{3(n + 1)} }}{{(n + 1)!}}}  - \frac{1}{{x^6 }}\sum\limits_{n = 0}^\infty  {\frac{{x^{3(n + 2)} }}{{(n + 2)!}}} \\ & = \frac{1}{{x^3 }}(e^{x^3 }  - 1) - \frac{1}{{x^6 }}(e^{x^3 }  - 1 - x^3 ) = \frac{{e^{x^3 } (x^3  - 1) + 1}}{{x^6 }}.
\end{align*}
Accordingly,
$$
\sum\limits_{n = 0}^\infty  {\frac{{n^2  + 4n - 1}}{{n!(n + 2)}}x^{3n} }  = e^{x^3 } (x^3  + 2) - 5\frac{{e^{x^3 } (x^3  - 1) + 1}}{{x^6 }}.
$$
Note that this expression differs from your result. The term $(\pi-\phi)^4$ in your answer is suspicious to me. Please check it numercially again.


text:
Q: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: I know this question has been asked before, but I haven't found an answer that solves my situation.
I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://http://localhost:8000/polls/, it gives me this error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^% [name='index']
^admin/
The current URL, polls/, didn't match any of these.

I'm using Django 1.10.5 and Python 2.7.
Here is the code I have in relevant url and view files:
In mysite/polls/views.py:
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
  return HttpResponse("Hello, world. You're at the polls index.")

In mysite/polls/urls.py:
from django.conf.urls import url

from . import views

urlpatterns = [
  url(r'^%', views.index, name='index'),
]

In mysite/mysite/urls.py:
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

What's going on? Why am I getting 404s?

A: Your url conf regex is incorrect, you have to use $ instead of %.
from django.conf.urls import url

from . import views

urlpatterns = [
   url(r'^$', views.index, name='index'),
]

The $ acts as a regex flag to define the end of the regular expression.

A:  urlpatterns = [path('', views.index, name='index'), ]

A: I ran into the same issue with the tutorial!
The issue is that if you look closely it references two url.py files, mysite/polls/url.py and mysite/url.py.
Putting the provided code in the correct url.py files should correct the issue.

A: Adding STATIC_URL and STATIC_MEDIA when debug is ON, helped me:
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
Q: Eclipse RCP : How to use Nebula NatTable feature? I am following this tutorial to have a NatTable in my e4 RCP applicaton product. My app is feature based not plug in based as shown in Tutorial. I followed and installed these features. When I try to launch the product, I encounter following error
Unresolved requirement: Require-Bundle: org.eclipse.nebula.widgets.nattable.core; bundle-version="1.3.0"
Can anybody share any sample about how to use nebula features successfully?

A: I resolved this problem, by
run configurations --> Plug ins --> Add Required Plug-ins
Then it worked.

A: As explained in the tutorial you posted, NatTable Core has dependencies to the following plug-ins:

*

*org.eclipse.swt

*org.eclipse.jface

*org.eclipse.equinox.common

*org.eclipse.core.commands

*org.apache.commons.logging

In most cases org.apache.commons.logging is missing in the product configuration and needs to be added in another feature.


text:
Q: Why is it so hard to show the URL of the current category and how to do it? If I'm on a singular page, it is quite easy to show the current post URL outside the loop:
the_permalink();

If I am on a category page it is quite simple to show the category description outside the loop:
category_description();

Unless I'm missing something, it is not equally easy to show the current category URL outside the loop - which is strange.
echo get_category_link(); - doesn't work like this.
I need to use my category URL in the <head>, for canonical link, og:url etc. How can I do that?
I did read this question and found that you have to create a new function just to show the current category. Is there any other way to do it?
/**
 * Pass in a taxonomy value that is supported by WP's `get_taxonomy`
 * and you will get back the url to the archive view.
 * @param $taxonomy string|int
 * @return string
 */
function get_taxonomy_archive_link( $taxonomy ) {
  $tax = get_taxonomy( $taxonomy ) ;
  return get_bloginfo( 'url' ) . '/' . $tax->rewrite['slug'];
}

A: On a category archive, get_queried_object_id() will give you the category's ID, which you can pass to get_category_link():
echo get_category_link( get_queried_object_id() );


text:
Q: How to exclude a column out of multiple in select query in SQL Server? I have 3 tables out of which one is containing two foreign keys for the primary keys of the corresponding tables. Now I want to run a query which will fetch data from these tables and will store the result-set in a new table with only one primary key of each.

*

*Tab 1: CUSTOMER (cust_id, col2, col3.....)

*Tab 2: PRODUCT (prod-id, col2, col3.....)

*Tab 3: SALES (s_id, cust_id,prod_id, col2, col3.....)

Now, I want result-set to be stored in a new table "RES" containing one 'cust_id', one 'prod_id' along with rest columns rather than those of two columns.
Please help.........
Thank you :)
I tried like this:
select *
into RES
from customer c
inner join sales s on s.cust_id = c.cust_id
where c.cust_id in (select cust_id
                    from sales
                    group by cust_id
                    having count(cust_id) >= 2)
order by s.cust_id;

but I get this error:

Msg 2705, Level 16, State 3, Line 1
  Column names in each table must be unique. Column name 'cust_id' in table 'RES' is specified more than once.

A:
Msg 2705, Level 16, State 3, Line 1 Column names in each table must be
  unique. Column name 'cust_id' in table 'RES' is specified more than
  once.

You are getting this error because you are inserting all the columns of tables customer and sales into RES, where custid column is present in both the tables.
Using * for insert is not a good practice. Instead of this you can change your query like following.
INSERT INTO RES(COL1,COL2.....COLN)
SELECT COL1, COL2, ........
FROM
<QUERY>

Even you are using SELECT .. INTO, in this case also you select explicit columns.


text:
Q: Composition of binary relations properties I'm studying for my exams and I'm stuck at Abstract Algebra. We have $R = ( A , B , G ) , S = ( B , C , H ) , R ′ = ( A , B , G ′ )$ as binary relations: $\operatorname{codom} ( R ) = \operatorname{codom} ( R ′ ) = \operatorname{dom} ( S ) $.
And now we have these properties :
$$S \cdot (R \cap R' ) \subseteq (S \cdot R) \cap (S \cdot R' )$$
$$S \cdot (R \cup R' ) = (S \cdot R) \cup (S \cdot R' )$$
I don't understand why the first one is an inclusion and the second one is an equality.
$$S \cdot (R \cap R') = ( A , C , H \cdot (G \cap G') )$$
$$(S \cdot R) \cap (S \cdot R') = ( A , C , H \cdot G \cap H \cdot G' )$$
$$H \cdot G = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G \land (b, c) \in H\}$$
$$H · G' = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G' \land (b, c) \in H\}$$
$$H \cdot (G \cap G') = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G \land (a, b) \in G' \land (b, c) \in H\}$$
$$H \cdot G \cap H \cdot G' = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G \land (b, c) \in H\} \cap \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G' \land (b, c) \in H\}$$
This is same as :
$$H \cdot G \cap H \cdot G' = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G \land (b, c) \in H \land (a, b) \in G' \land (b, c) \in H\}$$
And then since $\land$ is commutative and $(b, c) \in H \land (b, c) \in H = (b, c) \in H $:
$$H \cdot G \cap H \cdot G' = \{(a, c) \in A \times C \mid (\exists)b \in B : (a, b) \in G \land (a, b) \in G' \land (b, c) \in H\}$$
$$H \cdot G \cap H \cdot G' = H \cdot (G \cap G')$$
Same goes for "$\cup$" , just change "$\land$" with "$\lor$" .
What am I missing
PS : If you are downvoting this question ,atleast tell me why.

A: Here is a counterexample to equality in the first case; you'll see by inspecting it where the problem lies in your argument -- in short " you can't pick the same $b$. "
$$
A:=\{0\}; B:=\{1,1'\}; C:=\{2\}\\
G=\{(0,1)\}; G':=\{(0,1')\}; H:=\{(1,2),(1',2)\}
$$


text:
Q: repeat html within the same component I am looking for a way to repeat the same markup on multiple spots in my component. I know I could just use a new component but im looking for something a little less serious.
The html

{{i+1}}

Is there a way to use ng-template to repeat this same mark up in multiple places within the same component... Something like below

 <ng-template [innHTML]="#pages"></ng-template>

...

 <ng-template [innHTML]="#pages"></ng-template>

<ng-container #pages>

{{i+1}}

</ng-container>

A: You can insert the content of an ng-template with ng-container Angular elements and the ngTemplateOutlet directive.

  <ng-container *ngTemplateOutlet="pages; context: { text: 'value1' }"></ng-container>

...

  <ng-container *ngTemplateOutlet="pages; context: { text: 'value2' }"></ng-container>

<ng-template #pages let-value="text">

The value is {{value}}

{{i+1}}

</ng-template>

A: Create a child component containing your html in it's template and use it as many times you need in your (parent) component, like so:
Child component:
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child-comp',
  template: `

{{i+1}}

  `,
  styleUrls: ['./child-comp.component.css']
})
export class ChildCompComponent implements OnInit {
  @Input() pages;

  constructor() { }

  ngOnInit() {
  }

  onPageChange(index, event) {
  }

}

Parent Component:

  <app-child-comp [pages]="pages"></app-child-comp>

...

  <app-child-comp [pages]="pages"></app-child-comp>


text:
Q: In wiki page how to create a table with rows having autonumbering I am looking for wiki table with row having auto numbering feature. If it is not a table, using # will generate the autonumbering.
Currently the numbers are hardcoded as below
{| border="1"
|-
! style="background: #aaaaaa" | S.No
! style="background: #aaaaaa" | Project
! style="background: #aaaaaa" | File
! style="background: #aaaaaa" | Modified By
! style="background: #aaaaaa" | Modified Date
! style="background: #aaaaaa" | Changes Made
! style="background: #aaaaaa" | Reviewed By
! style="background: #aaaaaa" | Comments
|-
| 1
| /abcd
|
|
|
|
|
| needs merge
|-
| 2
| /abcd
|
|
|
|
|
| needs merge
|-
| 3
| /abcd
|
|
|
|
| needs merge
|}

Please advise

A: You can use Extension:Autoincrement
Then simply add {{AUTOINCREMENT}} where the numbers should be.
Each time the {{AUTOINCREMENT}} hook is used on a page it will return a number increased by one from the last use.
Keep in mind that if you have two tables on the same page, the second table will start from where previous table numbering stopped + 1

A: You can use CSS counters, or Javascript.


text:
Q: certfile and keyfile FileNotFoundError: [Errno 2] No such file or directory I have created a flask app which also has dash in it and i am working on windows 64 bit.
I have installed pyopenssl and after running below code
app.run_server(debug=False,ssl_context=('cert.pem', 'key.pem'))

after running code i get below mentioned error:
  File "~\Anaconda3\lib\ssl.py", line 1402, in wrap_socket
    context.load_cert_chain(certfile, keyfile)

FileNotFoundError: [Errno 2] No such file or directory

Please help to resolve it, as I am new to python please explain in detail...
Thanx in advance.

A: *

*) first open terminal, go to the your code folder.

*) create new folder :> mkdir certs and :> cd certs  go new created certs folder

*) next install this library :> pip install pyopenssl

*) copy and past this:> code:> openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365

*) finally answer the questions asked.

*) Done your 'cert.pem', 'key.pem' created.


text:
Q: HashCode Deduplication? Background:
Ever since I found out you can Use Custom Types in Map Keys and Sets, I wondered if you can map data by the hashCode value. I suspect it's a bad idea.
I understand the basics of how hash tables work, and I know collision is possible, but I am not sure how to measure the probability. I found this article which has a bunch of useful information and seems to confirm my hunch.

*

*Does Apex also have 232 possible values?

*

*(looks to me like the same max int)

*Can the hashCode values for the same object really change?

*Would the proposed sha1 alternative be computationally expensive in Apex?

Scenario:
I have a Location object (~2400 records) which I want to sync from an address field. Since this functionality involves creating child records, I want a way to quickly check if an address is already in the system. If it already exists, simply don't create the record. If they added a rule to duplicate management where you just drop records that already exist, I could just use that. So how viable is it to use hashCode for de-duplication purposes?
public class CompositeAddress
{
    final Id accountId;
    final String street, city, state, postal;
    public CompositeAddress
        (Id accountId, String street, String city, String state, String postal)
    {
        this.accountId = accountId;
        this.street = street;
        this.city = city;
        this.state = state;
        this.postal = postal;
    }
    public Integer hashCode()
    {
        return xor(street.hashCode(), xor(city.hashCode(),
                xor(state.hashCode(), postal.hashCode())
        ));
    }
    Integer xor(Integer a, Integer b) { return a ^ b; }
}

Alternatives:

*

*Just query all siblings and use CompositeAddress as a map key.

*Construct a hash using the sha1 algorithm.

*Concatenate values into a text key.

I think a collision probability of < 0.5% is tolerable, but I'm not sure if my data set fits within that bound. My bigger concern is, if the algorithm can actually hash the same object in different ways, I might create duplicate records by trusting the result.

A:

*

*Does Apex also have 232 possible values?

*

*(looks to me like the same max int)

Yes.

*

*Can the hashCode values for the same object really change?

HashCode means different things in different contexts. Since I do play with them from time to time, I know that the implementations are pretty consistent, but not across data types. For example:
System.debug(System.hashCode(1));  // [Integer] 1
System.debug(System.hashCode(Decimal.valueOf(1))); // [Decimal] 31
System.debug(System.hashCode(Double.valueOf(1))); // [Double] 1072693248
System.debug(System.hashCode('A')); // [String] 65
System.debug(System.hashCode(new Account())); // [Account] 0
System.debug(System.hashCode(new Account(Name='A'))); // [Account(Name='A')] 2420458

While String.hashCode seems to be stable and consistent (note that 'A' is Unicode 65, which means the algorithm is based on some computation of the bits), it should not be relied on.

Would the proposed sha1 alternative be computationally expensive in Apex?

You can use Crypto.generateDigest to make your comparisons.
Integer hashCode = System.hashCode('hello world');

100,000 hashCode calls against 'hello world': 4.724 seconds

String sha1Code = EncodingUtil.base64Encode(
           Crypto.generateDigest('sha1', Blob.valueOf('hello world'));

100,000 generateDigest calls against 'hello world': 17.211 seconds

As you can see, in order to make a sha1 code that you can store in a text format (at minimum), you need about 4 times more CPU time for 100,000 records.
Note that since your proposed algorithm was calling hashCode four times, using sha1 would be marginally faster than using hashCode, assuming you simply concatenated the strings together:
String sha1Code = EncodingUtil.base64Encode(
    Crypto.generateDigest(
        'sha1',
        Blob.valueOf(street+'♥'+city+'♥'+state+'♥'+postal)));

Finally, all of this is still bit-dependent, so to really catch duplicates, you need to compare like case to like case:
String sha1Code = EncodingUtil.base64Encode(
    Crypto.generateDigest(
        'sha1',
        Blob.valueOf(
            (street+'♥'+city+'♥'+state+'♥'+postal).toLowerCase()
        )));

You can use a case-indexed field to make looking up duplicates easier. You'll still want to verify if they're duplicates by comparing each of the four fields, but you'll save about 99% of the work by building digest codes. Once you queried potential duplicates back into memory, you can then use hashCode/equals to verify those duplicates.
So, in conclusion... do not trust hashCode outside of the current transaction, make sure you take case sensitivity into account, and always double-check potential duplicate candidates to make sure they really are equal.
Edit: Also, you could use sha256, also supported, to get much longer values and reduce the chance of collision significantly.


text:
Q: How to document a mixture of synchronous and asynchronous APIs? Do we use AsyncAPI or OpenAPI or both? Consider an application consisting of multiple end-points, some synchronous and others are asynchronous following the event-driven architecture with Kafka as the message broker, communicating with other microservices.
What should be the standard for documentation of these APIs? Do we need to create the separate documentation pages for asynchronous(using AsyncAPI) and synchronous APIs(using OpenAPI), or is there any way to combine the two in a single document? I've read online that AsyncAPI is the documentation standard for asynchronous APIs, and OpenAPI should be used for normal synchronous Rest APIs but could not find any relevant links on what to use if we have a mixture of different kind of APIs in a single application.
I'd appreciate any help/guidance on this.

A: In my company we use both OpenAPI and AsyncAPI with shared Schema objects.
Schema Object could be moved to a separate file(s) and then used by refLink from both API spec.
Be aware, standards of JSON Schema Specification in OpenAPI and AsyncAPI are different, e.g. approach to define discriminator is different.

A: For now, you can as @kris13 wrote in his answer, reuse JSON Schemas between AsyncAPI and OpenAPI documents. AsyncAPI parser has a plugin that can parse OpenAPI schemas. AsyncAPI supports multiple schemaFormats.
Future is more bright, have a look at https://github.com/asyncapi/bindings/issues/2 and involve in a discussion about HTTP Binding where we could enable reuse of OpenAPI's Path Item Object so you could reuse even more OpenAPI in AsyncAPI.


text:
Q: JavaScript ES6 promises Question: What is the difference between these four promises?
doSomething().then(function () { return doSomethingElse(); });

doSomething().then(function () { doSomethingElse(); });

doSomething().then(doSomethingElse());

doSomething().then(doSomethingElse);

A: Option 1:
doSomething().then(function () { return doSomethingElse(); });

This executes doSomething(), then when it resolves, it executes doSomethingElse() and the resolved value of the promise chain is the resolved value or return value of doSomethingElse().  No arguments are passed to doSomethingElse().
If you were to summarize this option, you'd say it was:
Chained in Sequence, with no parameter passing.

Option 2:
doSomething().then(function () { doSomethingElse(); });

Same as option 1, except the resolved value of the promise chain is undefined because there is no return value from the .then() handler.  Any return value from doSomethingElse(), whether a promise or a value is ignored.
If you were to summarize this option, you'd say it was:
Executed in Sequence (not chained), with no parameter passing.

Option 3:
doSomething().then(doSomethingElse());

This is pretty much never what you want.  This executes doSomething() and then, before doSomething() has resolved, it also executes doSomethingElse() and passes the return value from doSomethingElse() as the .then() handler.  This is a coding mistake unless doSomethingElse() returns a function to be used as the .then() handler.
If you were to summarize this option, you'd say it was:
Executed Immediately, Probably a Bug

Option 4:
doSomething().then(doSomethingElse);

This is the same as option 1 except that the resolved value from doSomething() is passed as the first argument to doSomethingElse(val).  This is structurally the same as this:
doSomething().then(function(result) { return doSomethingElse(result)});

If you were to summarize this option, you'd say it was:
Chained in Sequence, with parameter passing.

Other Notes:

*

*If doSomethingElse() returns a promise, then only Options 1 and 4 will add that promise to the chain (because they are the only options that return the promise from the .then() handler) so the chain will wait for that promise to resolve.

*In options 1, 2 and 4, if doSomethingElse() throws a synchronous exception, then the promise chain will become rejected with the exception as the reason.  In option 3, the function is executed outside the promise chain so if it throws a synchronous exception, it will throw to a higher scope (similar to if doSomething() threw synchronously).

A: In first case, after resolving promise returned by doSomething(), callback is invoked. Callback function can return another promise (that's why we call promises 'chainable'). In your case, doSomethingElse() is expected to return another promise.
In second case, nothing is returned by callback function, thus next promises in execution chain will be invoked, but with undefined parameter.
In third case, callback function is provided as result of doSomethingElse() function.
And finally, doSomethingElse is expected to be a function, which will be executed after fulfilling first promise.


text:
Q: Setting cgroup limits to all users in network I have a FreeIPA user authentication set up. There are many users in the system already, along with many host systems (configured IPA clients). I want to set up cgroup restrictions on the tasks these users are doing (specifically, for CPU and memory/RAM). I could test it on a single host using a single test user (using these steps). However, this involves listing all users in each host, and managing and scaling it is difficult.
I thought of adding all IPA users to a system/user group on these host PCs and adding a cgrule for this group. However, this could require me to add each IPA user to a group on each host (creating another scaling problem). Is there a way to synchronize user groups for this particular setting?
I could find something on Group Merging but couldn't figure out how to make it work.
The FreeIPA server runs Fedora, and the hosts run Ubuntu (18.04 and 20.04). The hosts are simulation servers, so GUI access to the IPA users is needed. The cgroup limit should be on the tasks run by all these users. Ideally, I'd prefer to add the IPA users to a linux user group on the FreeIPA server (when adding the user to IPA) and have that synchronized across all the hosts. Then I would set a cgrule for this group. Is such a thing possible? It would greatly help me set up even docker access for users (add them to docker group).

A: Turns out all this is not needed. The groups created in the FreeIPA server are synchronized across clients without group merging.
I created a group on the server portal and added users to it. Then, on each host, I set a limit on this group.
Some reference links

*

*https://www.paranoids.at/cgroup-ubuntu-18-04-howto/

*https://docs.oracle.com/cd/E37670_01/E37355/html/ol_cgrules_cgroups.html


text:
Q: How to read Bin file in C preamble by preamble For example i have a bin file and many messages in this file i know msg starting preamble first two byte is 0x43 and 0x78 for example msg look like
CxdjjdjdjdjdjdeiCxejejejejdjdclCxejdjdd
How to read.Read Preamble by preamble
i want to read like this
1. Cxdjjdjdjdjdjdei
2. Cxejejejejdjdcl
3. Cxejdjdd
File is not a small file its a big file. i want to pick msg by msg and then read byte by byte then parse byte into the library function and check the result of this msg then read next and repeat all thing of every msg. i know msg not greater than 1400 bytes

A: A simple way is to use a buffer larger than the maximum size of a message including the preamble. Since you said that no message will be greater than 1400 bytes, a 2048 buffer would be enough.
Pseudo code:
read a buffer
note no beginning of message
loop searching a preamble
    search (memchr) the first character of the preamble (0x43 or `'C'`)
    test is a full preamble is there - if not iterate previous search
    Ok, we have a preamble
    If a beginning of message was present
        we have a full message : process it
    If less that 1500 character remaining if the buffer
        copy the content of the buffer starting with the current preamble to the beginning of the buffer
        read enough bytes to have a full buffer
        if EOF: FINISHED
    Note the beginning of the message
end loop

As the messages are rather short, I would use buffered read (fread) to take advantage of the standard library buffering
Basis for C implementation:
const char preamble[] = {0x43, 0x78};
char buffer[2048];
size_t sz = fread(buffer, 1, sizeof(buffer), fd);
char *msg_start = NULL;        // no start of message
char *search_start = buffer;
size_t search_size = sz;
for(;;) {
    char *end = memchr(search_start, preamble[0], search_sz);
    if (end == NULL) {
        end = buffer + sz;
    }
    if ((end < buffer + sz - sizeof(preamble)) && memcmp(end, preamble, sizeof(preamble)) != 0) {
        size_t delta = end - search_start + 1;
        search_sz -= delta;
        search_start += delta;
        if (search_sz > sizeof(preamble)) continue;
        end = buffer + sz;
    }
    if (msg_start != NULL) {
        // process the message between  msg_start and end
    }
    if (end == buffer + sz) break;
    for (char *dest = buffer, char *src = end; src < end; src++, end++) *dest = *src;
    size_t delta =fread(buffer + sz, 1, sizeof(buffer) + sz, fd);
    if (delta == 0) break;
    sz += delta
    search_start = msg_start = buffer + sizeof(preamble);
}

BEWARE: untested and may content typos or incorrect code...


text:
Q: WPF - Keyboard and mouse click at the same time is it possible in PowerShell and WPF to trigger an event out of a keyboard click and a mouse click?
I have for example following button in my WPF:
<Button Name="button_test" Content="Test" Grid.Column="0" Grid.Row="4" />

I would like to trigger to two events with it. One event with a standard mouse click:
$button_test.Add_Click({ #do something })

And something when I hold CTRL and do a mouse click on the same button.
A keyboard click I do like this
$window.add_KeyDown{
    param
    (
      [Parameter(Mandatory)][Object]$sender,
      [Parameter(Mandatory)][Windows.Input.KeyEventArgs]$e
    )

    if($e.Key -eq 'CTRL')  { #do something else}
}

But I don't know how to combine these two events. Is it even possible?
Thanks
Stephan

A: sorry for the late respond. I "solved" it with an extra variable, but I am not sure if this is the correct way, so any suggestion would be appreciated.
$title = "test"

Add-Type -AssemblyName PresentationFramework

# GUI
[xml]$xaml = @"
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window_GuiManagement" Title="$title" WindowStartupLocation = "CenterScreen"
        Width = "Auto" Height = "350.000" Visibility="Visible" WindowStyle="ToolWindow" ResizeMode="NoResize" SizeToContent="WidthAndHeight" >
    <Grid>
        <DockPanel Margin="5">
            <StackPanel DockPanel.Dock="Bottom" >
                <Button Name="button_1" Content="Button 1" />
                <Button Name="button_2" Content="Button 2"  />
            </StackPanel>
        </DockPanel>
    </Grid>
</Window>
"@

$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)

# Declare objects
$button_1 = $window.FindName("button_1")
$button_2 = $window.FindName("button_2")

$global:ctrl = $false

$button_1.Add_Click({ Write-Host "Button 1 clicked" })

$button_2.Add_Click({
        if($global:ctrl){
            Write-Host "do more" $ctrl
        } else {
            Write-Host "do standard" $ctrl
        }
})

$window.add_KeyDown{
    param
    (
      [Parameter(Mandatory)][Object]$sender,
      [Parameter(Mandatory)][Windows.Input.KeyEventArgs]$e
    )
    #Write-Host $e.Key
    if($e.Key -eq "LeftCtrl")
    {
        return ($global:ctrl = $true)
    }
}

$window.add_KeyUp{
    param
    (
      [Parameter(Mandatory)][Object]$sender,
      [Parameter(Mandatory)][Windows.Input.KeyEventArgs]$e
    )
    #Write-Host $e.Key
    if($e.Key -eq "LeftCtrl")
    {
        return ($global:ctrl = $false)
    }
}

$Window.ShowDialog() | Out-Null


text: Q: setting getter on lwc after selecting it with querySelector I a list of cards that show a form when selected only one form should show at a time.. The form is inside a template that shows when disabled is false. I select the previous card with querySelector but I need to know how to set the disabled getter after I select the previous element. Any one know if this is possible and how to do it?