text:
Q: Split Too Long String I have a string like in the following picture:

I'm Consuming an API which take this large string in json like this {"data" : "the large string which in the picture"}
So i wanted to develop it and send the string in 2 request but when i was trying to use Length / 2 i got the half of that large string but not completed row like in the follow picture:

i wanna get the half of that string with completed row to avoid timing out in requests
the code which gave me that result:
            DataPart1.data = Encoding.ASCII.GetString(dataByte.Take(dataByte.Length / 2).ToArray());

            DataPart2.data = Encoding.ASCII.GetString(dataByte.Skip(DataPart1.data.Count()).ToArray()).ToString();

A: To find the exact index you want to split the string at, you might want to try looking up for the closest \r\n next to the middle of the string using the String.IndexOf(string value, int startIndex) method.
The code would look something like
var str = "1,2,3,4\r\n5,6,7,8\r\n9,10,11,12";
var half = str.Substring(0, str.IndexOf("\r\n", str.Length / 2));

Which results in "1,2,3,4\r\n5,6,7,8"
You might want to add some additional validation for cases like if the middle of the string is within the last line or if line delimiter used is other than \r\n.

A: Given that the input string can be a varying length, it may be better to batch the requests to a known length rather than simply splitting to half.
int REQUEST_SIZE = 1024;
string requestDelimiter = "\r\n";
int requestStart = 0;
int requestEnd = 0;

while(requestStart < dataByte.Length)
{
   // Sending loop
   int batchLength = requestStart+REQUEST_SIZE;
   if (requestStart+batchLength > dataByte.Length)
   {
      // Cover for when the end of the string exceeds batchLength
      // Ensure that the batchLength is adjusted to be within the string length
      batchLength = dataByte.Length - requestStart;
   }
   requestEnd = dataByte.IndexOf(requestDelimiter, batchLength, StringComparison.Ordinal);
   var requestData = dataByte.Substring(requestStart, requestEnd - requestStart);
   // TODO: process requestData

   requestStart = requestEnd;
}

The above code breaks the request into 1024 character chunks.
Please note: Untested code - there might be typos.


text:
Q: Experiences with SEDA and C#? I'm thinking about SEDA. We design at the moment an application (which is running on a server as a service) which must be multithreaded and message / event based.
The SEDA idea is very intresting and should match. But I cannot find articles etc. writing about experiences made with it.
My question(s) now is(are):

*

*Do you use ActiveMQ, MSMQ to implement the queues or do you have a self written class which acts as queue? We have written once a thread-safe FIFO Queue class which is very helpful in a multithreaded environment.

*Fit's the threadpool class of .NET for this or did you implement an own Threadpool / sheduler ?
Are there any traps / good practices?

A: Seems that nobody has ever done somthing on this topic.
So we decided to implement our own (thread-safe) messaging infrastructure.

A: You should see this blog post I did found. I am currently working on this subject.
http://surana.wordpress.com/2010/01/07/seda-on-net/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatically adding numbers in Rails form_for This is a form_for in my Rails view:

  <%= f.label :num1 %>

  <%= f.text_field :num1 %>
  <%= f.label :num2 %>

  <%= f.text_field :num2 %>
  <%= f.label :sum %>

  <%= f.text_field :sum %>

I would like to make it so that, when the user inputs numbers into the first two fields, the third field automatically shows the sum of the two numbers, but the user can manually change the third field. I'm not sure how I could do this, maybe with some Javascript?

A: It's pretty simple with jQuery:
$('#num1').change(function() {
    var one = this.val();
    var two = $('#num2').val();
    $('#sum').val(one + two);
});
$('#num2').change(function() {
    var one = $('#num1').val();
    var two = this.val();
    $('#sum').val(one + two);
});

Done.


text:
Q: При падении сервера, сайт не работает до перезагрузки браузера Есть клиент-северное приложение, в котором в качестве интерфейса между клиентом и сервером используется REST API. Проблема в том, что сервер бывает перегружен и по этой причине стоит timeout(500 мс) по истечению которого делает повторный запрос. С каждым повторным запросом интервал увеличивается...
Все хорошо, но проблема в том, в консоле дальше выдаются ошибки (о том, что сервер не доступный), но если зайти с другого браузера проблемы нет(до определенной момента). Как это можно исправить? Может проблема в каком-то кэше, если да, то как можно исправить? В качестве API для AJAX использую jQuery.
Если этот же браузер закрыть и открыть, то проблема тоже пропадет. Тестировал на Google Chrome, Mozilla Firefox.


text:
Q: C++ linker error when using same .h-file in inherited class I have two classes: ClassA and ClassB. ClassB inherits the ClassA. There is a utility.h-header file included to both classa.cpp and classb.cpp so that I can use the method
round(double number, int precision)

from the utilities.h in both .cpp-files.
When using it in ClassA like this:
double roundANumber(double number, int precision)
{
    return Utilities::round(number, precision);
}

it works fine. But when I try to use it in the ClassB like this:
double roundAnotherNumber(double number, int precision)
{
    return Utilities::round(number, precision);
}

linker gives me error:
error LNK2005: "double __cdecl Utilities::round(double,int)" (?
round@hUtilities@@YANNH@Z) already defined in classa.obj

and I can't seem to find a reason why this is.
Thank you in advance.
Edit: Added that the Utilities.h only contains this
 #include <cmath>

 namespace MathUtilities {

 double round(double number, int precision) {
     int precisionFactor = std::pow(10, precision);
     return std::round(number * precisionFactor) / precisionFactor;
 }
 }

A: Headers are just parsed as if they were included directly. Thus, you end up duplicating the function definition.
To fix this, use inline:
inline double round(double number, int precision) {...}


text:
Q: C# Backgroundworker race - any alternative? I have some problem with backgroundWorker class. I wish I could within one function cancel Backroundworker and just after it start Backgroundworker dowork from scratch. It cause race and I have no idea how to change it. Is there any alternative to Backgroundworker in .net 3.5
Edited:
My code:

BackgroundWorker worker = new BackgroundWorker();

public void Func()
{

if(worker.IsBusy)
{
    worker.CancelAsync();
    worker = new BackgroundWorker();
}

View.Clear();

worker.WorkerSupportsCancellation = true;
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
    BackgroundWorker sender = s as BackgroundWorker;
    if(sender.CancellationPending)
    {
        args.Cancel = true;
        return;
    }

    View.Generate(Filter);
};

worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
    if(args.Error != null)
    {
        MessageBox.Show(args.Error.Message);
        return;
    }
    BackgroundWorker sender = s as BackgroundWorker;
    if(args.Cancelled )
    {
        View.Clear();
    }
};

worker.RunWorkerAsync();

}

The problem is: cancelAsync doesnt close worker at all and my view is generated in incorrect way

A: You can use CancelAsync() and set WorkerSupportsCancellation to true and implements a loop to get CancellationPending
while(x.CancellationPending) { /*TODO*/ }


text:
Q: How do you add a link to Label text in Xaml? I have a xaml mobile project with a label inside a scroll view. In the text of the label I want to link to another xaml page in my app. How would I call a function I'm my code behind when this text is clicked? "Sign up for free!"
    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Mobile.Views.Welcome"
             Title="Welcome!!!!">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Image Source="(iOS: ImageSource.FromFile('Logo.png'), Android: ImageSource.FromFile('Logo.png'), WinPhone: ImageSource.FromFile('Images/Logo.png'))" />
    <ScrollView Grid.Row="1" HorizontalOptions="Center">
      <Label Font="15"  HorizontalOptions="Center">
       With your free account you can:
        Search Colleges, College programs and careers.

        Use out interest profiler to get a personalized list of careers that may interest you. Take a survey to find career clusters that are in line with your interests.

        Store your favorite careers, colleges, programs, and more in your personal locker.

        Yes, I want to do this! Sign up for free!</Label>
    </ScrollView>
    <Button Grid.Row="2" BackgroundColor="Blue" Text="Log In" TextColor="White" FontAttributes="Bold" ></Button>
    <Button Grid.Row="3" BackgroundColor="Aqua" Text="Browse as Guest" TextColor="White" FontAttributes="Bold"></Button>
 </Grid>

</ContentPage>


text:
Q: Asp.Net Web Service Application missing in Visual Studio 2010
Possible Duplicate:
VS 2010 Web Service project template missing?

I'm wondering why Asp.Net Web Service Application is missing in Visual Studio 2010. If it's updated to something new in Visual Studio 2010 what is it? If it's drop then how can I accomplish that task?

A: ASP.NET Web Service Application project template is not available for .Net framework 4.0, however, available for .Net Framework 3.5.
If you're building your application on .net framework 4.0, You can use WCF Service Application as ASMX in legacy. Please note that you'd need to enable AspNetCompatibilityMode to access HttpContext objects.
If you still want to use ASMX, choose ASP.NET Empty Web application and then you can add ASMX files to the project.

A: I too had the same problem when publishing web services from Navision. For that I created the project based on the .Net framework 3.5 (as the ASP.NET Web Service Application template is available for this version) in Visual Studio 2010 and it works fine for me.

A: To create a ASP.NET Web Service Application in Visual Studio 2010 using the .NET Framework 4.0, first create a new project targeting the .NET Framework 3.5 (as the ASP.NET Web Service Application template is available for this version). Then right-click the project and re-target it to use the .NET Framework 4.0. Build, debug, done!

A: I hit the same problem.  It looks like .svc files are no longer necessary as of WCF 4.0, as Configuration-Based Activation will take care of this for you.


text:
Q: How to change client TLS preferences in Java? I'm trying to make a POST request to an endpoint in Java, and when I try to send the request, I get the following error:
Caused by: javax.net.ssl.SSLHandshakeException: The server selected protocol version TLS10 is not accepted by client preferences [TLS13, TLS12]

This is what I have so far
Map<Object, Object> data = new HashMap<>();
data.put("username","foo");
data.put("password","bar");

String url = "https://google.com";

HttpRequest request = HttpRequest.newBuilder()
     .POST(buildFormDataFromMap(data))
     .uri(URI.create(url))
     .build();

try{
     HttpResponse<String> response =  httpClient.send(request,
          HttpResponse.BodyHandlers.ofString());
     System.out.println(response.statusCode());
     System.out.println(response.body());
} catch (Exception e){
     e.printStackTrace();
}

Then when I run the code, the error gets thrown when sending the request/making the response object. My question is, if the TLS preferences are different for the server than the client, how can I change the preferences within Java so it can still make the request?

A: To solve this problem in jdk 11, I had to create an javax.net.ssl.SSLParameters object to enable "TLSv1", etc:
SSLParameters sslParameters = new SSLParameters();
        sslParameters.setProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"});

Then create the HttpClient and add the sslParamters object:
HttpClient httpClient = HttpClient.newBuilder()
            .sslParameters(sslParameters)
            .build();

If you also want to disable hostname verification, add following code BEFORE HttpClient initialization;
final Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());

Also you can add a new TrustManager to trust all certificates (self signed).
To do so, add following code into your Class:
    TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
                }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

After this, you have to create an SSLContext object and add the TrustManger object:
SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

And finally alter the HttpClient initialization like this:
httpClient = HttpClient.newBuilder()
            .sslContext(sslContext)
            .sslParameters(sslParameters)
            .build()

Here is a complete Class example:
import java.net.http.HttpClient;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Properties;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpSSLClient {

    private SSLContext sslContext;
    private SSLParameters sslParameters;
    private HttpClient httpClient;

    public HttpSSLClient() throws KeyManagementException, NoSuchAlgorithmException {

        sslParameters = new SSLParameters();
        sslParameters.setProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"});

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        final Properties props = System.getProperties();
        props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());

        httpClient = HttpClient.newBuilder()
                .sslContext(sslContext)
                .sslParameters(sslParameters)
                .build();
    }

    public HttpClient getHttplClient() {
        return httpClient;
    }

    TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                    }
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
}

You can use the getHttplClient() function while calling your HttpRequest.

A: I had the same issue and this solution does not work for me.
Instead I saw this answer Android Enable TLSv1.2 in OKHttp and I tried this code:
ConnectionSpec spec = new ConnectionSpec
.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2,TlsVersion.TLS_1_0,TlsVersion.TLS_1_1,TlsVersion.TLS_1_3).build();
client =client.newBuilder().connectionSpecs(Collections.singletonList(spec)).build();
And it worked for me:)

A: I think mmo's answer should be highlighted in bold. I had similar issue, but found out that the open-jdk jvm I was using has TLSv1 and TLSv1.1 as disabled in the jdk.tls.disabledAlgorithms line in java.security. So as soon as I removed it and restarted the JVM, I was able to connect usingthe older TLS protocols.
But please pay ATTENTION, This is not advisable in Production since it degrades the secure communication. So I'd say change it if you want at YOUR OWN RISK!!!


text:
Q: Taking a complicated partial derivative Mostly I believe in math. However I have trouble in my economic textbook (which really should be right).
I have the following equation:
$$ u(c,d)=\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}}$$
where $\theta=(1-\gamma)/(1-1/\psi)$, $a\in (0,1),b\in (0,1), c>0, d>0, \gamma>0$, and $\psi\in(0,\infty)$.

Is the derivative of $u$ wrt. $c$ really
  $$ u_c(c,d)=ac^{\frac{1-\gamma}{\theta}-1}\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}-1}=ac^{-1/\psi}u(c,d)^{1/\psi}$$

If so, can someone tell me why? I would write it as
$$ u_c(c,d)=ac^{\frac{1-\gamma}{\theta}-1}\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}-1}=ac^{-1/\psi}u(c,d)^{-1}$$
Hope to hear from someone,
thanks in advance.

A: I think the following is a simpler way. Let $\delta = \frac{1-\gamma}{\theta}$ ; now take the logarithm of both sides, to get:
$$ \log u(c,d) = \log(ac^\delta + bd^\delta) / \delta   $$
Differentiating this partially w.r.t $c$ leads to:
$$ \frac{1}{u} \frac{\partial u} { \partial c} = \frac{1}{\delta (ac^\delta+bd^\delta) } (a\delta c^{\delta -1})  $$.
by the chain rule.
Can you now multiply by $u$ on both sides to get $\frac{\partial u} { \partial c}$?

A: $$\frac{\partial}{\partial c}u(c,d)=\frac{\partial}{\partial c}\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}}$$
$$\Rightarrow \left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}-1}\frac{\partial}{\partial c}\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)$$
$$\Rightarrow \left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}-1}ac^{\frac{1-\gamma}{\theta}-1}$$
Since
$$u=\left(ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}}\Rightarrow u^{\frac{1-\gamma}{\theta}}=ac^{\frac{1-\gamma}{\theta}}+b d^{\frac{1-\gamma}{\theta}}$$
And
$$u_c=\left(u^{\frac{1-\gamma}{\theta}}\right)^{\frac{\theta}{1-\gamma}-1}ac^{\frac{1-\gamma}{\theta}-1}$$
$$\Rightarrow u_c=u^{\frac{\theta+\gamma-1}{\theta}}ac^{\frac{1-\gamma-\theta}{\theta}}=u^{\frac{\theta+\gamma-1}{\theta}}ac^{-\frac{\gamma+\theta-1}{\theta}}$$
Because
$$\theta=(1-\gamma)/(1-1/\psi)\Rightarrow \frac1{\psi}=\frac{\theta+\gamma-1}\theta $$
$$\Rightarrow u_c=u^{\frac 1{\psi}}ac^{-\frac1{\psi}}$$


text:
Q: Определение координат крайней точки вращающегося отрезка Я хочу определить координаты крайней точки вращающегося отрезка в Corona SDK.
Для визуальной проверки полученных координат, добавил пару строк кода для зарисовки окружностей. Получилось вот что:

Как мы видим, полученные координаты ошибочные. Не подскажите, где ошибка?
PI = math.pi
length = 100

x1 = display.contentCenterX
y1 = display.contentCenterY
x2 = x1 + length
y2 = y1 + length

alfa = 0
dalfa = 4

line = display.newLine(x1, y1, x2, y2)
line.anchorSegments = true
line.anchorX = 0.1
line.anchorY = 0.1
line.strokeWidth = 3

function moveR()
    angle = (2 * PI) - ((alfa * PI) / 180)   -- переводим градусы в радианы с учетом периода в 2 пи
    x2 = length * math.sin(corner) + x1       -- считаем новые координаты точки по оси х
    y2 = length * math.cos(corner) + y1       -- считаем новые координаты по оси у
    local myCircle = display.newCircle( x2, y2, 1 )
end

function flop()
    line.anchorX = 0
    line.anchorY = 0
    line.x = x2
    line.y = y2

end

function update()
    moveR()
    if alfa >= 360 then
        alfa = 0
    end
    line.rotation = alfa
    --print(line.rotation)
    alfa = alfa + dalfa
end

Runtime:addEventListener( "tap", flop )
Runtime:addEventListener( "enterFrame", update )

A: Кроме этого момента:
x2 = x1 + length
y2 = y1 + length

остальное выглядит нормально (но я не знаю сути anchorX). Здесь правда подразумевалась линия длиной 141 под углом 45?


text:
Q: Why is MySQLSlap giving me additional prompt instead of running? I am trying to benchmark some queries using mysqlslap.  I've never used it before.  I am trying to follow some tutorials and am trying to run a simple command to get a hang of how it works like from this tutorial.
When I run the command mysqlslap --concurrency=20 --iterations=4 --query="sELCT * FROM listusers;" --create-schema=my_database instead of actually testing and returning some metrics, I just get another prompt like

I have tried this command with username and password fields as well with the same results.
What is this prompt and how do I get the command to actually run the metrics?

A: mysqlslap is not a MySQL command, but a separate binary tool.
So instead of trying to use it inside mysql console, use it directly in bash/shell.


text:
Q: Apache config being re-generated when using OSX Server? I recently installed OSX Server on a clean install of Yosemite 10.10.3, and wanted to customise the apache config to change the version of PHP being used by the server. I installed php using homebrew and made the changes to the apache config file. This worked fine, until the next day when I noticed that apache had reverted back to using the default version of PHP that ships with Yosemite.
After playing around for a bit I realised that the apache config file I was editing (/Library/Server/Web/Config/apache2/httpd_server_app.conf) is being re-generated every time the OSX Server application is re-started, reverting it back to the default version of PHP that ships with Yosemite.
Is there a default httpd.conf that OSX Sever generates it's httpd_server_app.conf from?
UPDATE:
I did a little more digging. When I added the LoadModule call to the httpd_server_app.conf I commented out the old version and added the call to the new one on the next line.
#LoadModule php5_module libexec/apache2/libphp5.so
LoadModule php5_module /usr/local/opt/php56/libexec/apache2/libphp5.so

When restarting the server, the newly re-generated file looks like so (the call to the new module remains, but the call to the old module is uncommented):
LoadModule php5_module libexec/apache2/libphp5.so
LoadModule php5_module /usr/local/opt/php56/libexec/apache2/libphp5.so

Apache loads the first module, which in this case would be the old version. If I place the the new module call above the old one, then this solves the problem for me. Although it doesn't feel like an ideal solution, as I am still left with the other LoadModule call uncommented.
I imagine there are other scenarios relating to editing the apache config where simply changing the order wouldn't solve the problem.


text:
Q: Error while launching the app My app is playing crazy. When I run the app it installs it on the device but won't run it. Here is the log:
$ adb shell am start -n "com.callrecorderpro/com.callrecorder.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Error while executing: am start -n "com.callrecorderpro/com.callrecorder.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.callrecorderpro/com.callrecorder.MainActivity }
Error type 3
Error: Activity class {com.callrecorderpro/com.callrecorder.MainActivity} does not exist.

Error while Launching activity

I have the MainActivity class and it is declared in the Manifest, I can run the app after is installed manually.

A: Go to Settings -> Applications -> Click on your app and delete it.
After that if your app marks as "didn't installed" click on it -> click on settings button at the top right and chose "remove for all users".
If it's your case, error will disappear.


text:
Q: Form submission in MVC using Ajax. Can't prevent default form submission I'm trying to submit a form using Ajax in ASP.NET, everything works fine but I can't prevent default form submission using e.preventdefault() method.
This is my jquery ajax submission code :
 $('#submitBtn').on('click', function () {
    $('#addNewContact').submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function (message) {
                console.log(message);
            },
            error: function (message) {
                console.log(message);
            }

        })

    })
})

A: If e.preventDefault() is not working you can write - return false; - statement at the end of the function which performs the desired functionality and will prevent default form submission.

A: If you have a form with id addNewContact and a submit button then you may register it using something like this:
$('#addNewContact').submit(function (e) {

    e.preventDefault();

    $.ajax({
        // ...
    });

});

In your code, you've used $(this).attr('action') which means that, you are trying to use a form submit event but you did it wrong in your code. What you did is:
$('#submitBtn').on('click', function () { // Click handler registered

    $('#addNewContact').submit(function (e) { // Submit handler registered

        e.preventDefault();

        $.ajax({
            // ...
        });

    });
});

So, your code should be as given below (for form submit event):
$('#addNewContact').submit(function (e) {

    e.preventDefault();

    $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: $(this).serialize(),
        dataType: 'json',
        success: function (message) {
            console.log(message);
        },
        error: function (message) {
            console.log(message);
        }
    });

});


text:
Q: Установил vpn и перестал работать nginx+phpfpm Все работало красиво, nginx+phpfpm!
Черт дернул установить vpn. Нужен статический ip для работы.
Установил вот это PoPTop  pptpd
Делал по этому руководству http://www.comss.ru/page.php?id=2512
Ну и сразу вывалились все сайты в 500 ошибку
хотя nginx пашет
в логе сайта
2016/08/23 00:19:43 [error] 8920#8920: *64 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 69.162.124.237, server: xxx.ru, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host: "xxxxxx.ru", referrer: "http://xxxxxxx.ru/"

A: Ответ был в вопросе.
При установке pptpd внес правило в таблицу
echo "Обновление IPtables Routing и добавление этого в автозагрузку"
iptables -t nat -A POSTROUTING -j SNAT --to $ip
# saves iptables routing rules and enables them on-boot
iptables-save > /etc/iptables.conf

я его удалил, перезагрузил весь сервер
и заработало (не понял как перезагрузить службу, не работало не хотела перезапускаться)


text:
Q: Android split text via voice command I have implemented voice commands on my app to make it easier for the user to set variables, I have tried using StringTokenizer to split the commands so I only get the variable but that doesn't seem to work, can someone point me in the right direction?
 @Override
public void OnResult(ArrayList<String> commands) {
    for(String command:commands)
    {
       if (command.contains("set amount to")){
       StringTokenizer tokens = new StringTokenizer(command, "to");
        String first = tokens.nextToken();
        String second = tokens.nextToken();

           Log.e("TAG", command);
           Log.e("TAG", "First " + first);
           Log.e("TAG", "Second " + second);
       }
    }
}

The command I give is for example set amount to 5 and it comes back as First se and Second am and I am not sure how to make it find the 5 or if they add on additional words after like 5 dollars I don't want to pick up the dollars.


text:
Q: Error in Processing Request Error code: 403 Error text: Forbidden Apache2 Error in Processing Request Error code: 403 Error text: Forbidden
This kind of error pops up when i am trying to do anything that requires ajax in phpmyadmin.[enter image description here][1]


text:
Q: Angular & Firebase.Firestore: private and public collection of users I'm working on a social-media app.

When a user registers with the app, a new 'user' object is created in the 'users' collection in Firestore. (users to be registered in order to be signed in)
export interface User {
  uid: string;
  email: string | null;
  photoURL: string | null;

  created: firestore.Timestamp | null;
  nickname: string | null;
  gender: Gender | null;
  isRegistered: boolean;

  birthday: firestore.Timestamp | null;
  location: string | null;

  phone: string | null;
  firstName: string | null;
  lastName: string | null;
}

Each 'user' object contains all the data about the respective user.

After the registration process the user is redirected to the welcome page, where a table with other registered users is displayed. To achieve this we call usersService.loadUsers({ limit: 25 }).

We obviously don't want to load the 'users' collection, because that would retrieve user objects with all the users' data, even the private fields (birthday, phone, firstName, lastName, etc.).

What would be the best approach to structure the database, If I wanted to retrieve only the public facing data of all other users?

My thoughts are as follows:

*

*create a new collection - e.g. 'publicUsers'

*when a new user registers, a new 'user' object is created in the 'users' collection

*the process of registering a new user would trigger a cloud function that would create a copy of the 'user' object in the 'publicUsers' collection - with private data removed

Is this viable or are there some better (industry standard) ways of achieving this?

A:
My thoughts are as follows:

*

*create a new collection - e.g. 'publicUsers'

*when a new user registers, a new 'user' object is created in the 'users' collection

*the process of registering a new user would trigger a cloud function that would create a copy of the 'user' object in the
  'publicUsers' collection - with private data removed

  Is this viable or are there some better (industry standard) ways of
  achieving this?

This is indeed a totally viable approach and probably the best, with regards to your requirements.
It is totally classical, in the NoSQL world, to duplicate data in order to fulfill your needs in terms of querying: in your case a "query mode" with all data and another "query mode" with public data only.


text:
Q: How to add a password as blank in yaml? I have my enable password set as nothing. Basically I just hit enter to have access to my enable mode when prompted for a password. How can i configure this in yaml?

A: In YAML empty scalars are usually interpreted as null, as indicated in the specification. As this is not the same as an empty string, you should use
password: ''

or the equivalent:
password: ""


text:
Q: how to disable pypy assert statement? $ ./pypy -O
Python 2.7.2 (a3e1b12d1d01, Dec 04 2012, 13:33:26)
[PyPy 1.9.1-dev0 with GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: `` amd64 and ppc are only
available in enterprise version''
>>>> assert 1==2
Traceback (most recent call last):
  File "", line 1, in
AssertionError
>>>>
But when i execute
$ python -O
Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> assert 1==2
>>>

A: PyPy does silently ignore -O. The reasoning behind it is that we believe -O that changes semantics is seriously broken, but well, I guess it's illegal. Feel free to post a bug (that's also where such reports belong, on bugs.pypy.org)

A: For anyone coming here in the future, Oct 3 2021 pypy3 does accept the -O flag and turn off assertion statements


text:
Q: Magento Cloud Autodetect Browser language and redirect How can I autodetect the user's browser language and redirect to the "right" store view in Magento Commerce Cloud?
Thanks!

A: If you can reliably use the HTTP header "Accept-Language" then there may be two ways of doing it (rely on the HTTP header availability, so please validate the fallback.)
For example:
Accept-Language: en-US,en;q=0.5

Using Fastly Custom VCLs
Fastly provides a way of reading this header, process/filter it and apply custom redirect. https://docs.fastly.com/en/guides/accept-language-header-vcl-features
Using ./magento-vars.php File
PHP provides the ability to parse the HTTP Accept-Language header https://www.php.net/manual/en/locale.acceptfromhttp.php

*

*$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);

*$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
You may write your own custom logic on ./magento-vars.php and do the necessary redirections. ./magento-vars.php has the visibility to $_SERVER, $_ENV, $_COOKIE etc.
Multi-store setup and sample snippets can be found on this DevDocs link: https://devdocs.magento.com/cloud/project/project-multi-sites.html#modify-magento-variables
For an example:
<?PHP

// enable, adjust and copy this code for each store you run
// Store #0, default one

// ./magento-vars.php

function customStoreLogic()
{
    $storeView = false;
    if (!isset($_SERVER['HTTP_HOST'])) {
        return false;
    }

    $locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);

    switch ($locale) {
        case "en_US":
            $storeView = 'us_store';
            break;
        default:
            $storeView = 'default';
            break;
    }
    return $storeView;
}

$storeView = customStoreLogic();

if ($storeView) {
    $_SERVER["MAGE_RUN_CODE"] = $storeView;
    $_SERVER["MAGE_RUN_TYPE"] = "store";
}

Hope this helps.

A: I think you could try to using javascript for detecting the user language
var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

If the user language is different from the current store view language, you will redirect to the correct URL using javascript.


text:
Q: Call a java method in R using rJava I use rJava to call a java code from R, trying  to call an algorithm from SPMF tool. I tried to use a wrapper function as in this question, but this did not work with the SPMF code.
this is my R code:
   library(rJava)
   .jinit()
   .jaddClassPath ( "C:/mydrive/eclipse-workspace/myfile/src")
   print(.jclassPath())
   obj <- .jnew("AlgoFPGrowth_Strings")
   s <- .jcall(obj, returnSig= "V", method="runAlgorithm",
   "input.csv","output.txt") ,  0.4 )

it gives me error ,method runAlgorithm with signature (D)V not found
this is the main in java:
    public static void main(String[] args) throws Exception {
    AlgoFPGrowth_Strings fpwindow=new AlgoFPGrowth_Strings();
    String input="input.csv";
    String output="output.txt";
    double minsupp = 0.4;
    fpwindow.runAlgorithm( input,  output,  minsupp);
    fpwindow.printStats();

}

I tried to change  returnSig value into S and Ljava/lang/String; but I got the same error, could not find the method
when I apply the code on different java code with simple method it works, is there any idea how can I change my code?

A: Try the below methods,

*

*Change your jclassPath, where you directly specify the complete pathname of your jar file including the jar name, say /home/user/mypath/myclass_name.jar

*Or, you can unzip your jar file in a folder and refer to that path in your jclassPath.
If, the above does not work,

*Try to write the 'runAlgorithm' method in the same class where you are calling. I have faced issues with calling external libraries/classes.


text:
Q: How do I avoid going past the end of my animation in a beamer presentation I would like to animate some overlays using animatevalue, but I don't know of a way to stop the animation at the last overlay.  Is there a way to make this independent of OS and pdf reader?  If not, how do you do it in whatever reader it can be done in (I suspect only Adobe Reader does it, but I don't know for sure.).
Here is a minimal example of what I want to animate and stop right before the second frame.
\documentclass[12pt,t]{beamer}
\DeclareGraphicsExtensions{.pstex,.eps,.ps,.pdf,.png,.jpeg,.jpg}
\setbeameroption{hide notes}
%\usetheme{default}
%\useinnertheme{default}
\usepackage{graphicx,wrapfig}
\setbeamertemplate{footline}{%
    \raisebox{5pt}{\makebox[\paperwidth]{\hfill\makebox[20pt]{\color{gray}
          \scriptsize\insertframenumber/\inserttotalframenumber}}}\hspace*{5pt}}
\usenavigationsymbolstemplate{}
\begin{document}
\newlength\ciscowidth
\begin{frame}
  \animate<2-35>
  \animatevalue<1-35>{\ciscowidth}{0.7\textwidth}{0.2\textwidth}
  \frametitle{``Layered'' Data Centre}
\begin{wrapfigure}[5]{R}{\ciscowidth}%\ciscowidth}
  %\includegraphics[width=\ciscowidth]{cisco-layered.jpg}
\end{wrapfigure}
~\uncover<36->{
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
Here is a bunch of text
}
\end{frame}

\begin{frame}
  \frametitle{Another frame}
\end{frame}
\end{document}


text:
Q: Use sixxs subnet on one machine I've got a sixxs subnet with aiccu on my debian vps, and want to use the complete subnet at my vps. Currently only the 2001:4dd0:f000:000f::2 is usable. My config:
(ip a)
3: sit0: <NOARP> mtu 1480 qdisc noop state DOWN
    link/sit 0.0.0.0 brd 0.0.0.0
6: sixxs: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1280 qdisc noqueue state UNKNOWN
    link/sit 109.111.111.11 peer 70.11.11.111
    inet6 2001:4dd0:f000:000f::2/64 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::0006:e000/64 scope link
       valid_lft forever preferred_lft forever

eth0 and lo are not important, I think.
How can I use the complete /64 on my vps?

A: You will have to add the IPv6 addresses that you want to use to the interface. For example like this:
ip -6 addr add 2001:4dd0:f000:000f::3/64 dev sixxs


text:
Q: Battery life is inconsistent If I charge my battery above 95%
Ubuntu shows 12 hour battery life.
If I charge to 92% it shows 3 hour battery life.

A: I am on ubuntu 16.04 but other version should have similar tools.
Launch "Power statistics" app.
From the list on the left choose "Laptop battery" then choose "Statistics". There, from the drop-down menu for "graph type" you can select "charge / discharge accuracy". Mine shows a "Prediction accuracy vs cell charge" graph and clearly the prediction accuracy drops significantly when the cell charge exceeds 90 percent. Of course yours will be different than mine but the very fact that these graphs exist signals that this kind of a problem is common. The predictions are also bad when the cell charge is below 10 percent.
Hope this helps.


text:
Q: Text box showing   We are displaying some text in text box coming from database. We set this value in text box using one Js function. Problem is that the string from DB is "My  Name". In textbox it should be displayed as "My  Name", but it gets displayed as "My  Name".
How to solve this problem?
My HTML for text box is as follows,
<input type="text" class="textfield" id="searchText">

Note : Can't change the value returned from DB.
Using javascript->java->ORACLE to pull value from the DB.

A: You need to decode the string in JavaScript, if you're unable to modify it on the server-side.
var foo = Encoder.htmlDecode(stringValueFromDb);

The problem is that if the DB expects values to be HTML-encoded, you'll need to do that somewhere too, unless it already happens server-side.

A: Textbox cannot understand HTML formatting. Have you heard of GIGO - Garbage In Garbage Out?  Make sure the db holds the right values.
Other hack could be to use String parsing function to substitute   with a space.

A: $("#searchText").val( $("<div>").html(database.data).text() );

This works by creating a temporary element and filling its .html() with your database string. Then the raw .text() is extracted from that and passed to your input element. Any HTML entity will be replaced by the corresponding character.
This is an ugly hack. I strongly suggest fixing your database values instead.

A: What function(s) are you using to get the info from the database?
If "My  Name" is in the database, then you would have to strip the HTML tags.
If "My Name" is in the database, then you should remove functions like html_entity_decode.

A: You just need to do htmldeDecode before you assign the value.
function htmlDecode(value){
  return $('<div/>').html(value).text();
}

$('#searchText').val( htmldeDecode('My  Name') )

If you don't want to use the jquery method, you can find some custom htmlDecode method like,
JavaScript html_entity_decode


text:
Q: XMLStarlet - replace a part of attribute I am using XMLStartlet for a quick deploy cmd (Windows) script for my app, and I am changing the configuration xml file.
Manipulation of the whole nodes/attributes works just perfect, but i need to replace a part of an attribute with a specific value, for example:
<list>
    <address id="a1">
        <data url="http://localhost:8000/a1.html" />
    </address>
    <address id="a2">
        <data url="http://localhost:8000/a2.html" />
    </address>
</list>

I need to change the port part of a /list/address/data/@url to get:
<list>
    <address id="a1">
        <data url="http://localhost:8001/a1.html" />
    </address>
    <address id="a2">
        <data url="http://localhost:8001/a2.html" />
    </address>
</list>

Any help with a suitable xmlstarlet command would be much appreciated. I don't want to mix sed into my script.

A: Using XPath string functions, concat and substring-after:
xmlstarlet ed -u /list/address/data/@url ^
  -x "concat('http://localhost:8001/', substring-after(substring-after(., 'http://localhost:'), '/'))" ^
  addr-list.xml > new-addr-list.xml
move new-addr-list.xml addr-list.xml

You can edit --inplace instead of move:
xmlstarlet ed --inplace -u /list/address/data/@url ^
  -x "concat('http://localhost:8001/', substring-after(substring-after(., 'http://localhost:'), '/'))" ^
  addr-list.xml

A: For a batch + xmlstarlet solution
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "count=1"

    rem For each url in the xml file
    for /f "delims=" %%v in ('
        xml sel -t -v "/list/address/data/@url" input.xml
    ') do (

        rem Split the line using colons as delimiters
        rem So we have %%a = http    %%b = //localhost    %%c = 8001/....
        for /f "tokens=1,2,* delims=:" %%a in ("%%v") do (

            rem Remove the port number from %%c using the numbers as delimiters
            for /f "tokens=* delims=0123456789" %%d in ("%%c") do (

                rem Here we have all the needed elements. Retrieve the number of the
                rem element being updated (with delayed expansion) and update the
                rem xml document (without delayed expansion to avoid problems)
                setlocal enabledelayedexpansion
                for %%n in (!count!) do (
                    endlocal
                    xml edit -L -u "/list/address[%%n]/data/@url" -v "%%a:%%b:8003%%d" input.xml
                )
            )
        )
        rem This instance has been processed. Increment counter
        set /a "count+=1"
    )


text:
Q: How to put files in flume spooldir one by one? I am using flume spooldir to put files in HDFS, but I am getting so many small files in HDFS. I thought of using batch size and roll interval, but I don't want to get dependent on size and interval. So I decided to push files in flume spooldir one at a time. How can I do this?

A: According to https://flume.apache.org/FlumeUserGuide.html#spooling-directory-source, if you set a1.sources.src-1.fileHeader = true, then you can specify any headers (for example the file name header) in the HDFS Sink (see %{host} in the escape sequence description at https://flume.apache.org/FlumeUserGuide.html#hdfs-sink.
EDIT:
For an example config, you can try the following:
a1.sources = r1
a1.sources.r1.type = spooldir
a1.sources.r1.channels = c1
a1.sources.r1.spoolDir = /flumespool
a1.sources.r1.basenameHeader = true

a1.channels = c1
a1.channels.c1.type = memory

a1.sinks = k1
a1.sinks.k1.type = hdfs
a1.sinks.k1.channel = c1
a1.sinks.k1.hdfs.path = /flumeout/%{basename}
a1.sinks.k1.hdfs.fileType = DataStream


text:
Q: Python time.sleep() DRY issue i am making a tiny terminal game.
based of many text with yes/no questions
and i must use "time.sleep()" many times for delay effect.
i try to follow the DRY(Dont Repeat Yourself) principle.
how can i avoid using this method many times?
print('some texts')
time.sleep(1)

if True:
   print('some texts')
   time.sleep(1)

print('some texts')
time.sleep(1)

A: You can encapsulate your print and time.sleep calls into a function that you define which accepts a string (to print) and an integer (to pass to time.sleep)


text:
Q: Apparent memory leak in AsyncLocal<> I've got a massive CI build test suite, well over 3,000 tests. In order to run tests in parallel, I'm making liberal use of AsyncLocal<T> objects. Trouble is, since I started doing this, the CI build bot is reaching about 75% complete, and then it bombs out because it's run out of memory. There's no other culprit to point a finger at, other than the newly introduced AsyncLocal<T> objects, which are being used to store anything from booleans to complex objects.
I guess I'm abusing the system somehow, and there's some "proper" way to use AsyncLocal<T> so that its values get garbage collected once the current context terminates.
It may help to know that before I discovered the existence of AsyncLocal<T>, I was attempting to implement this functionality myself using my own class, called Parallelizable<T>. That worked using NUnit's TestExecutionContext.CurrentContext.CurrentTest.FullName, but it was slow as molasses, and then I dug into the underlying code and found that was using AsyncLocal<>, so I decided to cut out my implementation and change Parallelizable<T> to be a wrapper around AsyncLocal<T>, so that I would do the minimum violence to my existing tests. And that's when I started getting out of memory failures.
What is the proper way to ensure that these values are GC'd?
Here's my code for Parallelizable<T>, FWIW:
    public class Parallelizable<T>
    {
        private readonly AsyncLocal<T> _asyncLocal = new AsyncLocal<T>();
        private readonly AsyncLocal<bool> _valueSet = new AsyncLocal<bool>();
        private readonly T _defaultValue;
        private readonly Func<T> _defaultFunc;

        public Parallelizable()
        {
            _valueSet.Value = false;
        }

        public Parallelizable(T defaultValue)
        {
            _defaultValue = defaultValue;
        }

        public Parallelizable(Func<T> defaultFunc)
        {
            _defaultFunc = defaultFunc;
        }

        public T Value
        {
            get
            {
                if (!_valueSet.Value)
                {
                    _asyncLocal.Value = _defaultFunc != null ? _defaultFunc.Invoke() : _defaultValue;
                    _valueSet.Value = true;
                }

                return _asyncLocal.Value;
            }
            set
            {
                _asyncLocal.Value = value;
                _valueSet.Value = true;
            }
        }
    }

UPDATE: I worked around the problem by finding the place in my test fixture base class that made the most intensive use of AsyncLocal<> with large objects, and inside the TearDown() method made sure to dispose and set the value of the AsyncLocal properties to null. This solved my problem.
The question, however, remains open: why, when the AsyncLocal<> objects themselves were GC'd, did all their values also not get GC'd? That seems to be a bug in the implementation of AsyncLocal<>, does it not?


text:
Q: Xamarin Android Grid control Is there a suitable grid control in Xamarin Android, table-like, for a business app that supports databindind with collections that help altering various columns/cells?
As far as I find out, there are alternatives only by inheriting an existing control like ListView and creating a custom control.
If a control as one I am searching for does not exist, what could be the best option left?
Many thanks in advance!!

A:
Is there a suitable grid control in Xamarin Android, table-like, for a business app that supports databindind with collections that help altering various columns/cells?

You can refer to GridView, it displays items in a two-dimensional, scrollable grid.
And this tutorial will show how to create a Grid View.


text:
Q: Splitting string by fixed length I am looking for ways to split a string of a unicode alpha-numeric type to fixed lenghts.
for example:

    992000199821376John Smith          20070603

and the array should look like this:
Array (
 [0] => 99,
 [1] => 2,
 [2] => 00019982,
 [3] => 1376,
 [4] => "John Smith",
 [5] => 20070603
)

array data will be split like this:

    Array[0] - Account type - must be 2 characters long,
    Array[1] - Account status - must be 1 character long,
    Array[2] - Account ID - must be 8 characters long,
    Array[3] - Account settings - must be 4 characters long,
    Array[4] - User Name - must be 20 characters long,
    Array[5] - Join Date - must be 8 characters long.

A: Or if you want to avoid preg:
$string = '992000199821376John Smith          20070603';
$intervals = array(2, 1, 8, 4, 20, 8);

$start = 0;
$parts = array();

foreach ($intervals as $i)
{
   $parts[] = mb_substr($string, $start, $i);

   $start += $i;
}

A:     $s = '992000199821376Николай Шмидт       20070603';

    if (preg_match('~(.{2})(.{1})(.{8})(.{4})(.{20})(.{8})~u', $s, $match))
    {
        list (, $type, $status, $id, $settings, $name, $date) = $match;
    }

A: Using the substr function would do this quite easily.
$accountDetails = "992000199821376John Smith          20070603";
$accountArray = array(substr($accountDetails,0,2),substr($accountDetails,2,1),substr($accountDetails,3,8),substr($accountDetails,11,4),substr($accountDetails,15,20),substr($accountDetails,35,8));

Should do the trick, other than that regular expressions (as suggested by akond) is probably the way to go (and more flexible). (Figured this was still valid as an alternate option).

A: It is not possible to split a unicode string in a way you ask for.
Not possible without making the parts invalid.
Some code points have no way of standing out, for example: שׁ is 2 code points (and 4 bytes in UTF-8 and UTF-16) and you cannot split it because it is undefined.
When you work with unicode, "character" is a very slippery term. There are code points, glyphs, etc. See more at http://www.utf8everywhere.org, the part on "length of a string"


text:
Q: Delphi TImage Loading GIF Bad Qality While a process is running in the background, I show a loading animation on the screen. But the GIF looks very bad quality. How can I fix this problem?
unit Unit3;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.GIFImg, Vcl.ExtCtrls,
  Vcl.StdCtrls;

type
  TForm3 = class(TForm)
    Image1: TImage;
    procedure FormShow(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  var
    sFile: string;
  end;

var
  Form3: TForm3;
  aGIF: TGIFImage;
  bmp:TBitmap;

implementation

{$R *.dfm}

procedure TForm3.FormShow(Sender: TObject);

begin
  aGIF := TGIFImage.Create;
  aGIF.LoadFromFile(sFile);
  aGIF.Animate := True;
  Image1.Picture.Assign(aGIF);
  aGIF.Free;
end;

end.


text:
Q: Monitoring DB used connections and http threads via zabbix I'm trying to adjust zabbix monitoring for my application on glassfish. But can't find if it is possible to adjust monitoring of used DB connections from glassfish connection pools and http threads. Was thinking of monitoring via JMX items but cant find any ways to boot AMX. So i'm here to ask if there is any way of booting AMX for MBeans or other ways to get used DB connections and http threads.

A: I will assume that you already can collect jmx information with zabbix and known how to create a jmx item to monitor.
For number of current connections
jmx["com.sun.appserv:name=NAME_OF_THE_APPLICATION,type=jdbc-connection-pool,category=monitor,server=server",NumConnUsed-current]

For number of destroyed connections
jmx["com.sun.appserv:name=NAME_OF_THE_APPLICATION,type=jdbc-connection-pool,category=monitor,server=server",NumConnDestroyed-count]

Number of creations connections
jmx["com.sun.appserv:name=NAME_OF_THE_APPLICATION,type=jdbc-connection-pool,category=monitor,server=server",NumConnCreated-count]

Number of available connections
jmx["com.sun.appserv:name=NAME_OF_THE_APPLICATION,type=jdbc-connection-pool,category=monitor,server=server",NumConnFree-current]

These are examples, the best way to find what you want to monitor with jmx is using jconsole.


text:
Q: Spring saves Date as String in MongoDB - Failed to convert from type String to type Date I use org.springframework.data.mongodb.core.MongoTemplate to save data to MongoDB. My sample data is following bean:
public class SampleBean{
    private Date date;
    private List<Date>  datesList;
    private TreeMap<Date, Integer> datesMap;
    // setters and getters
}

I am calling following instructions.
SampleBean bean = new SampleBean();
MongoTemplate mongo = new MongoTemplate();

List<Date> dateList = new ArrayList<Date>();
dateList.add(new Date());
TreeMap<Date,Integer> dateMap = new TreeMap<Date, Integer>();
dateMap.put(new Date(), new Integer(1));

bean.setDate(new Date());
bean.setDateList(dateList);
bean.setDateMap(dateMap);

mongo.save(bean, "SampleBean");

And this is what i get in mongo:
{
    "_id" : ObjectId("53d028eeb71a1523582b1b1c"),
    "_class" : "example.SampleBean",
    "date" : ISODate("2014-07-23T21:28:14.869Z"),
    "datesList" : [
        ISODate("2014-07-23T21:28:14.876Z")
    ],
    "datesMap" : {
        "Wed Jul 23 23:28:14 CEST 2014" : 1
    }
}

Because of way it's stored I am not able to load bean from MongoDB
 I get
 Handler execution resulted in exception - forwarding to resolved error view
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value 'Wed Jul 23 23:28:14 CEST 2014'; nested exception is java.lang.IllegalArgumentException

Why Date from TreeMap is not stored as ISODate?
Am I doing anything wrong?

A: What you are doing here is breaking a cardinal rule of general "Hash" structures that exists everywhere else outside of Java. The basic concept here is that the "keys" of a Hash or Map can only be a string and not a specific type.
MongoDB uses BSON which is the "binary" and "typed" form derived from the JSON spec. Conforming to the general JSON semantics, the "keys" of a BSON document must be strings and not of any other specific type.
This is at least how MongoDB enforces it. So the general rule of thumb here is don't put other types in the key of a Map other than string.
This really isn't good practice anyway, as "data" as a key is generally bad news. You are better off presenting as an array, like so:
"dates": [
    { "date": ISODate("2014-07-23T21:28:14.876Z"), "count": 1 }
]

These are easier for MongoDB to process in queries without using client side processing or JavaScript as in MapReduce. For general MongoDB queries, Map type structures need to be represented with absolute paths to their keys.
So 1. Don't use other types for keys than strings, they will be stringified anyway. 2. Don't use data as keys, use arrays instead.


text:
Q: Adding users to a list via user input C# I have a users class which I would like to use to create a list of users until the user no longer wishes to. I don't know how to get input from console. I've deleted my main code as it is a confusing mess and would prefer to start from scratch. My Users class is below.
class Users
{
    List<Users> _userList = new List<Users>();

    private string _name;
    private int _age;
    private string _address;
    private string _phone;

    public Users(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }

    public string GetName()
    {
        return _name;
    }

    public void SetName(string name)
    {
        _name = name;
    }

    public int GetAge()
    {
        return _age;
    }

    public void SetAge(int age)
    {
        _age = age;
    }

    public string GetAddress()
    {
        return _address;
    }

    public void SetAddress(string address)
    {
        _address = address;
    }

    public string GetPhone()
    {
        return _phone;
    }

    public void SetPhone(string phone)
    {
        _phone = phone;
    }

}

Cheers

A: First remove List from your Users class and rename it to User.
public class User
{
    private string _name;
    private int _age;
    private string _address;
    private string _phone;

    public User(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }

    //...
}

Then declare List of User classes in console Program class and add new user to the list. Set user properties according to the user console input.
List<User> _userList = new List<User>();

static void Main(string[] args)
{
    Console.Write("Name: ");
    string name = Console.ReadLine();

    Console.Write("Age: ");
    int age = int.Parse(Console.ReadLine());

    Console.Write("Address: ");
    string address = Console.ReadLine();

    Console.Write("Phone: ");
    string phone = Console.ReadLine();

    User user = new User(name, age, address, phone);
    _userList.Add(user);
}

A: Firstly, take note that List<Users> _userList = new List<Users>(); is unneeded in your class. You're not using it anywhere. A List<T> structure is a good way to store multiple users - just replace T with a type that represents a user. You should change the name of your class to represent a single user (User would be a good idea here) and use a List<User> outside of the class.
Take a look at this contrived example, where user has one string property - the name of the user. It enables you to add multiple users to a list with names of your choosing and then prints each of the names in a new line. Note that I used an auto-implemented property to store the user's name.
class User
{
    public User(string name)
    {
        Name = name;
    }

    public Name { get; private set; }
}

public static void Main()
{
    List<User> users = new List<User>();
    bool anotherUser = true;
    while (anotherUser)
    {
        Console.WriteLine("Please specify a name.");
        string userName = Console.ReadLine();
        User user = new User(userName);
        users.Add(user);
        string next = Console.WriteLine("Do you want to add another user (type Y for yes)?");
        anotherUser = (next == "Y");
    }

    Console.WriteLine("\nNames of added users:");
    foreach(User u in users)
    {
        Console.WriteLine(u.Name);
    }

    Console.ReadKey();
}

Of course you have to expand on this answer to really get what you want. This is merely a point of reference.

A: Let us consider a simple use case to get a basic understanding:
As others suggested already you can improve the User class as shown below and C# has a concept of Auto-Implemented Properties and the compiler will handle the getter/setter code generation behind the scenes for you and so at least your code is clean enough!! Again at times you may need to have constructor injected property values or explicit methods to set values and I am not going into that.
public class User
{
   public string Name { get; set; }
   public int Age { get; set; }

   //Other properties/indexers/delegates/events/methods follow here as required. Just find what all these members are in C#!!
}

Code to accept user input:
static void Main(string[] args)
{
     List<User> users = new List<User>();

     char createAnotherUser = 'N';

     do
     {
          var user = new User();
          int age;

          Console.Write("\nUser Name: ");
          user.Name = Console.ReadLine();

          Console.Write("Age: ");
          string ageInputString = Console.ReadLine();

          //Validate the provided age is Int32 type. If conversion from string to Int32 fails prompt user until you get valid age.
          //You can refactor and extract to separate method for validation and retries etc., as you move forward.
          while (!int.TryParse(ageInputString, out age)) //Notice passing parameter by reference with 'out' keyword and it will give us back age as integer if the parsing is success.
          {
               Console.Write("Enter a valid Age: ");
               ageInputString = Console.ReadLine();
          }

          //Accept other data you need and validate if required

          users.Add(user); //Add the user to the List<User> defined above

          //Confirm if another user to be created
          Console.Write("Do you want to create another User[Y/N]? : ");
          createAnotherUser = char.ToUpper(Console.ReadKey(false).KeyChar); //Compare always upper case input irrespective of user input casing.

    } while (createAnotherUser == 'Y');

You can learn more about passing variable by reference using out keyword in MSDN
Hope this provide you some idea...


text:
Q: How to submit a guest post with rich text editor? I am looking for a way to design a form like this to allow my website visitors to submit guest posts.
[
These guest posts will then appear for preview and approval on admin area. From where, they can be accepted or rejected.
Here is the link to what I want to develop.
Can anybody give me a head start on this, in terms of backend development and especially getting the rich text editor.

A: Recently I did complete a project that have front end form to submit. But i used ACF Plugin for this purpose that allow us to create front end form and save them as draft. After review that post you can click on Publish button to show them on front end.
Please see the attached screenshot what i did in my case.

Let me know if it helps you.


text:
Q: IBM Worklight 6.1 - How to display a prompt dialog? It was able to display a prompt box  in common resources ("preview as common resources"), but it is not working in the Android Emualtor.
What is the reason?

A: Have you tried using Cordova's navigator.prompt?
For example, in common\main.js:
function wlCommonInit() {
    navigator.notification.prompt(
        'Please enter your name',  // message
        onPrompt,                  // callback to invoke
        'Registration',            // title
        ['Ok','Exit'],             // buttonLabels
        'Jane Doe'                 // defaultText
    );
}

function onPrompt() {
    alert("prompted");
}

I tested this in iOS, but it will work in Android as well.
When previewing your application, use some stub or "regular" JS implementation, but for the mobile environments, use Cordova's.


text:
Q: AutoFixture RepeatCount Is there a way to know the RepeatCount from a ISpecimenBuilder? I am creating a new specimen builder for certain parameter name. Basically the Create method will ask for the parameter name and in case it is e.g. "myParamName", and the type is e.g. "MyParamType" it will return a customized object.
This works perfect, however, if the parameter type is IEnumerable{MyParamType} I would like to "CreateMany". The problem is...how many?
I cannot call context.Resolve or context.CreateMany{MyParamType} for the simple reason that it would not create my objects the way I need. Example: if MyParamType is string, it would not create the formatted string I need. That is exactly why I created a specimen builder in the first place!:) I also cannot register my new specimen builder for MyParamType as I only need this customization for parameter value requests of a specific name. Otherwise, I need the default behavior
Thank you in advance

A: I'm not entirely sure if this is what you're trying to do, but you don't have to worry about handling requests for IEnumerable<T> in your custom specimen builder; AutoFixture will automatically convert requests for IEnumerable<T> into multiple requests for T, which is then handled by your specimen builder.
For example, let's assume we have a custom specimen builder that simply return the value "foo" for all requests for string:
public class FooBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        return request.Equals(typeof(string))
            ? (object)"foo"
            : new NoSpecimen();
    }
}

Now, this test passes:
[Fact]
public void Should_return_all_foos_for_a_sequence_of_strings()
{
    var fixture = new Fixture { RepeatCount = 4 };
    fixture.Customizations.Insert(0, new FooBuilder());

    var many = fixture.Create<IEnumerable<string>>();

    Assert.Equal(4, many.Count());
    Assert.All(many, i => Assert.Equal("foo", i));
}

because AutoFixture makes sure to invoke the FooBuilder as many times as it's needed in order to satisfy the request.

A:
The problem is...how many?

By default, that's 3. You may change this parameter when creating a new Fixture instance:
  var fixture = new Fixture { RepeatCount = 4 };


text:
Q: jQuery validation custom error message I can't seem to get jQuery validation to use the data-val-lookup attribute held against the input field it is validating:
Here is the code I am using to add the validation class rule.
$(function () {
    $.validator.addMethod('lookup', function (value, element, params) {
        var hiddenId = $(element).attr("id");
        var textBoxId = hiddenId + "_LookupText";
        return !(($('#' + hiddenId).val() == "") && ($('#' + textBoxId).val() != ""));
    });

    $.validator.addClassRules('lookup', { lookup: true });
});

Here is what I have for my lookup input fields:
<input class="lookup" data-val="true" data-val-lookup="Campaign must be a valid lookup item" data-val-number="The field Campaign must be a number." id="CampaignId" name="CampaignId" type="text" value="" />

<input type="text" id="CampaignId_LookupText" class="form-control" name="CampaignId_LookupText" />

The validation works but I get "Warning: No message defined for CampaignId" instead of the message.
I can specify a default message... but it needs to be field specific (containing the field name).
If I add a "title" attribute to the field, it is using this as the error message... but I want it to use data-val-myvalidation instead as this seems to be convention.
Thanks

A: It should be data-msg-<rule>
data-msg-lookup="Campaign must be a valid lookup item"

The customMessage method is as follows
customDataMessage: function (element, method) {
    return $(element).data("msg" + method[0].toUpperCase() + method.substring(1).toLowerCase()) || $(element).data("msg");
},


text:
Q: Search in joined table with multiple records I have a table 'contacts' which is structured like this:

*

*id, name, surname, etc

And contacts_related

*

*contact_id, name, surname

One contact can have multiple related contacts (joined by contact_id). What I would like to do is make a SELECT query on contacts that if a search input is given (example: 'John') it prints all contacts that have John in name OR contacts that have a related contact with 'John' in the name.
Any suggestions on how to do this, without making two distinct queries?

A: A possible solution is
SELECT
    DISTINCT C.*
FROM
    contacts C LEFT JOIN contacts_related R
    ON C.id=R.contact_id
WHERE
    C.name LIKE '%John%' OR
    R.name LIKE '%John%'

A: You want those contacts that are either Johns themselves or have a John relation. To look up the relations use EXISTS or IN.
select *
from contacts
where name like '%John%'
or exists
(
  select *
  from contacts_related
  where name like '%John%'
  and contact_id = contacts.id
);

Or:
select *
from contacts
where name like '%John%'
or id in
(
  select contact_id
  from contacts_related
  where name like '%John%'
);

A: try this,
select a.id,a.name,a.surname from
contacts a join contacts_related b
on SOUNDEX(a.name)=SOUNDEX(a.name)

or
select a.id,a.name,a.surname from
contacts a, contacts_related b
where SOUNDEX(a.name)=SOUNDEX(b.name)

select column according to your need.

A: Below is your answer,  i have tested and its working!!!
SELECT c.name
FROM contact T
    INNER JOIN contact_r C ON C.Id = T.id
WHERE C.name LIKE '%saif%'

data in contact Table

data in contact_r Table:


text:
Q: How can I initialize a database with some tables in a container using docker compose? I have my db service:
...
mysql-server:
    container_name: silos-database
    init: true
    restart: always
    build:
      context: .
      dockerfile: Dockerfile-db
    environment:
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_USER=${USER}
      - MYSQL_PASSWORD=${USER_PASSWORD}
    ports:
      - target: 3036
        published: 3036
    networks:
      - backend-net
    volumes:
      - type: volume
        source: db_vol
        target: /var/lib/mysql
...

This is my Dockerfile
FROM mysql:latest

The init.sql file contain same tables that my database must have
...
-- users data
CREATE TABLE IF NOT EXISTS users (
  email VARCHAR(128) PRIMARY KEY,
  username VARCHAR(64) UNIQUE,
  -- password is SHA256 hashed, so 64 characters
  password CHAR(64) NOT NULL
);

CREATE TABLE IF NOT EXISTS sessions (
  email VARCHAR(128) PRIMARY KEY,
  token TEXT NOT NULL,
  expireDate BIGINT(13) NOT NULL,
  FOREIGN KEY (email) REFERENCES users(email) ON UPDATE CASCADE ON DELETE CASCADE
);
...

How can I build a service with the content of init.sql file already inside the service?

A: The simplest way would be to add init.sql file to Your docker image:
FROM mysql:latest
ADD init.sql /docker-entrypoint-initdb.d

If You want to provide init.sql during container start instead of build time, You can mount directory containing init.sql into container:
mysql-server:
    container_name: silos-database
    init: true
    restart: always
    build:
      context: .
      dockerfile: Dockerfile-db
    environment:
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_USER=${USER}
      - MYSQL_PASSWORD=${USER_PASSWORD}
    ports:
      - target: 3036
        published: 3036
    networks:
      - backend-net
    volumes:
      - type: volume
        source: db_vol
        target: /var/lib/mysql
      - /local/path/with/initsql:/docker-entrypoint-initdb.d


text:
Q: Get row count using two columns with Pandas I have the following data frame:
         ID                DBA BUILDING     STREET   SCORE GRADE GRADE DATE
0  50054472  LE PAIN QUOTIDIEN      395  S END AVE       9     A 2016-10-13

I want to get the count of rows that satisfy a given criterion as I loop over the rows:
df = pd.read_csv(CSV_URL, parse_dates=['GRADE DATE'], keep_default_na=False)

for index, row in df.iterrows():
    df[(df['ID'] == row[0]) & df['GRADE DATE'] == pd.Timestamp(row[6])]

However, I keep getting this error:
TypeError: cannot astype a datetimelike from [datetime64[ns]] to [bool]

I understand that I am getting a Timestamp object using the parse_dates so that is why I am converting it to a pd.Timestamp before the query. Any ideas on where I am going wrong?

A: The comments are correct that df[(df['ID'] == row[0]) & df['GRADE DATE'] == pd.Timestamp(row[6])] looks like it needs to be edited at least to: df[(df['ID'] == row[0]) & (df['GRADE DATE'] == pd.Timestamp(row[6]))]
There is almost always a way for you to avoid using for loops with pandas, pandas advises you to avoid for loops. Since this appears to be the NYC health inspections dataset...
import pandas as pd
CSV_URL = 'https://data.cityofnewyork.us/api/views/43nn-pn8j/rows.csv?accessType=DOWNLOAD'
df = pd.read_csv(CSV_URL, parse_dates=['GRADE DATE'], keep_default_na=False)

def id_counter(row):
  return df[(df['CAMIS'] == row[0]) & (df['GRADE DATE'] == row['GRADE DATE'])].shape[0]

df["RESULT"]=df.apply(id_counter, axis=1)

This tries to store the amount of violations at ID (CAMIS) on GRADE DATE in RESULT without using a for loop. But from having worked with city data before, I would say your mileage may vary.


text:
Q: Xpages source formatting I wonder if there is anything more advanced for source formatting of Xpages than what is built-in to the editor. In particular I would like to remove white space from the code.
Anything out there?

A: I use the "Clear all blank lines" option in the DDE File > Preferences > XML > XML Files > Editor. There are a couple options there you may find of use, such as ensuring "Insert whitepsace before closing empty end-tags" is un-checked and whether you choose to "Preserve whitespace in tags with PCDATA content". It may not be "advanced", but is usually serves me well.
Reminder, XPage design element formatting (XPages, Custom Controls) is for readability only, as they get compiled into Java classes on project build (visible in Project Explorer, under Local > xsp).


text:
Q: android: admob InterstitialAd crash at loadAd I'm using InterstitialAd by Admob. My app crashes at "loadAd" only in the first time it's called, and it's not reproducible (it happens once in 100-200 runs less or more). the ad unit id is correct for sure. So if loadAd doesn't fail in the first time it's called, it won't fail at all at this run.
class member:
InterstitialAd mInterstitialAd;

onCreate:
mInterstitialAd = new InterstitialAd(this);

mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));

mInterstitialAd.setAdListener(new AdListener() {
    @Override
    public void onAdClosed() {
        requestNewInterstitial();
        finish();
    }
});

requestNewInterstitial();

requestNewInterstitial method:
private void requestNewInterstitial() {
    if (mInterstitialAd != null) {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(getResources().getString(R.string.test_device))
                .build();

        if (adRequest == null) {
            return;
        }

        // HERE'S THE CRASH
        try {
            mInterstitialAd.loadAd(adRequest);
        }catch(Exception e) {
            return;
        }
    }
}

The catch doesn't catch the crash of "loadAd".
How can I catch it or at least cause it not to crash my app? I wish that when loadAd fails, no ad will be displayed.
LOGCAT:
A/libc: Fatal signal 5 (SIGTRAP), code 1 in tid 27794 (AdWorker(Defaul)
W/VideoCapabilities: Unrecognized profile 2130706433 for video/avc
I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es

I don't know if the last 2 lines are about this crash but the first one is for sure.

A: Sometimes what happen is Ad does to get loaded into your buffer so when you try to call loadAd, it crashes
onCreate:
    mInterstitialAd = new InterstitialAd(this);
    // set the ad unit ID
    mInterstitialAd.setAdUnitId(getString(R.string.ad_id));

    AdRequest adRequest2 = new AdRequest.Builder()
            .build();
    // Load ads into Interstitial Ads

    mInterstitialAd.loadAd(adRequest2);

    mInterstitialAd.setAdListener(new AdListener() {
        public void onAdLoaded() {
            showInterstitial();
        }
    });

In the same class:
private void showInterstitial() {
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    }
}

A: Activtiy_m1.java
public class Activity_m1 extends AppCompatActivity {

    InterstitialAd interstitial;
    Activity mactivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_m1);
        setTitle("ABCD");
        Advertise.displaym1(getApplicationContext());
    }

    @Override
    public void onBackPressed() {
            Advertise adv = new Advertise();
            adv.disp_adm1();
        finish();
    }
}

Advertise.java
public class Advertise {
    public static InterstitialAd interstitial;

    public static void displaym1(Context act) {
        interstitial = new InterstitialAd(act);
        interstitial.setAdUnitId("ca-app-pub-2621588945556564/3343556333");
        AdRequest adRequest1 = new AdRequest.Builder().build();
        interstitial.loadAd(adRequest1);
    }
    public void disp_adm1() {
        if (interstitial.isLoaded())
            interstitial.show();
    }
}


text:
Q: Most Efficient Way Of Clearing Cache Using ASP.NET I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.
But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.
So in my create, delete and update methods I am calling the following method:
public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is this really bad? I can't see how else I am supposed to clear the cached items?

A: Clearing the whole ASP.NET cache for just one specific functional domain seems a bit overkill.
You could create an intermediate object, and store all your cached queries in there. This object could be just a wrapper on a dictionary object. All queries should use this object instead of playing with the ASP.NET cache directly.
Then you add this object to the ASP.NET Cache when you need it. When you need to clear the queries, just get to this object and clear the underlying dictionary. Here is a sample implentation:
    public sealed class IntermediateCache<T>
    {
        private Dictionary<string, T> _dictionary = new Dictionary<string, T>();

        private IntermediateCache()
        {
        }

        public static IntermediateCache<T> Current
        {
            get
            {
                string key = "IntermediateCache|" + typeof(T).FullName;
                IntermediateCache<T> current = HttpContext.Current.Cache[key] as IntermediateCache<T>;
                if (current == null)
                {
                    current = new IntermediateCache<T>();
                    HttpContext.Current.Cache[key] = current;
                }
                return current;
            }
        }

        public T Get(string key, T defaultValue)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            T value;
            if (_dictionary.TryGetValue(key, out value))
                return value;

            return defaultValue;
        }

        public void Set(string key, T value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            _dictionary[key] = value;
        }

        public void Clear()
        {
            _dictionary.Clear();
        }
    }

If my query is represented like this:
    public class MyQueryObject
    {
       ....
    }

Then, I would use the "regional" cache like this:
// put something in this intermediate cache
IntermediateCache<MyQueryObject>.Current.Set("myKey", myObj);

// clear this cache
IntermediateCache<MyQueryObject>.Current.Clear();

A: It would have been very easy for the designers of the Cache class to add a Clear method to it. But they have not and it was by design - hence your code is bad.
One problem is threading implications of enumerating through a collection if the collection is modified. That would throw an error.
You really should never need to clear the whole of the cache. If server needs memory, it will clear it. Cache access is by key (for a reason) hence you need to know what you are trying to access. So if you need to remove and item, do it by a key.
UPDATE
My advice would be to design the cache in a way that clearing the cache would be very easy. For example group your cache items (create a class to hold related cache results) by an ID and use the ID as the key. Whenever something related to that ID is changed, clear the cache for that ID. Easy, peasy.

A: Have you considered using a Cache Dependency?
Here's the MSDN explanation and a few tidbits from there:

Establishes a dependency relationship between an item stored in an ASP.NET application's Cache object and a file, cache key, an array of either, or another CacheDependency object. The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed.

// Insert the cache item.
CacheDependency dep = new CacheDependency(fileName, dt);
cache.Insert("key", "value", dep);

// Check whether CacheDependency.HasChanged is true.
if (dep.HasChanged)
  Response.Write("
The dependency has changed.");
else Response.Write("
The dependency has not changed.");

And this very enthusiastic fellow explains some more about it.

A: Yep, never loop through the cache and remove items. It will give you a world of pain (I went through this recently). As you'll get an error "collection was modified, enumeration may not execute".
I also have a cache for searching, and I don't set an expiry - I manually invalidate when required.
The trick is the data is held into "buckets". That "bucket" is usually the parent identifier, or if you want to get into database terms, the foreign key.
So if you need to clear all "Orders" for a given "Customer", the cache key should be the CustomerId. In my case, I cache a ReadOnlyCollection<T>. So I don't need to loop, just remove it, then add in the fresh copy.
Also, to be doubly safe - I use a ReaderWriterLockSlim to invalidate the cache. When I know it needs to be invalidated, I first call the database, get a write lock, flush and refresh the relevant cache, then close the write lock.
That way it's all seamless.

A: The method you use is actually the correct way to clear your cache, there is just one minor 'error' in your code. The enumerator only is valid as long as the original collection remains unchanged. So while the code might work most of the time, there might be small errors in certain situations. Best is to use the following code, which does essentially the same, but does not use the enumerator directly.
List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = Cache.GetEnumerator();

while (enumerator.MoveNext())
  keys.Add(enumerator.Key.ToString());

for (int i = 0; i < keys.Count; i++)
  Cache.Remove(keys[i]);


text:
Q: How do i increase the height of the message box only not rest of the boxes? I want the the input box of class message to be of 50px of height but it is not increasing even though i have added padding to it (refer the last part of css code) . All are coming of the same length. Please help me with this one .Any help would be appreciated.
HTML code

        Contact Us

        <input type="text" class="name" id="name" placeholder="Enter Your name" />
        <input type="text" class="name" id="name" placeholder="Enter Your phone" />
        <input type="email" class="name" id="name" placeholder="Enter Your email" />
        <input type="text" class="message" id="message" placeholder="Enter Your message" />

CSS code
* {
    box-sizing: border-box;
}
.contact {
    background-color: rgb(233, 230, 227);
    height: 100%;
}
.contact h3 {
    text-align: center;
}
.form {
    text-align: center;
    max-width: 344px;
    width: 100%;
    position: relative;
    left: 50%;
    transform: translatex(-50%);
}
.form input {
    width: 100%;
    padding: 7px;
    border: 1px solid grey;
    border-radius: 5px;
    margin: 15px 0px;
}
.form message {
    padding: 50px;
}

A: You forgot to add a . to this .form message.

* {
    box-sizing: border-box;
}
.contact {
    background-color: rgb(233, 230, 227);
    height: 100%;
}
.contact h3 {
    text-align: center;
}
.form {
    text-align: center;
    max-width: 344px;
    width: 100%;
    position: relative;
    left: 50%;
    transform: translatex(-50%);
}
.form input {
    width: 100%;
    padding: 7px;
    border: 1px solid grey;
    border-radius: 5px;
    margin: 15px 0px;
}
.form .message {
    padding: 50px;
}

        Contact Us

        <input type="text" class="name" id="name" placeholder="Enter Your name" />
        <input type="text" class="name" id="name" placeholder="Enter Your phone" />
        <input type="email" class="name" id="name" placeholder="Enter Your email" />
        <input type="text" class="message" id="message" placeholder="Enter Your message" />

A: Also, you can use textarea tag like this
<textarea rows="4" cols="50">Enter your message here </textarea>

A: please check complete code :

* {
  box-sizing: border-box;
}
.contact {
  background-color: rgb(233, 230, 227);
  height: 100%;
}
.contact h3 {
  text-align: center;
}
.form {
  text-align: center;
  max-width: 344px;
  width: 100%;
  position: relative;
  left: 50%;
  transform: translatex(-50%);
}
.form input {
  width: 100%;
  padding: 7px;
  border: 1px solid grey;
  border-radius: 5px;
  margin: 15px 0px;
}
.form textarea {
resize:none;
width:100%;
border-radius: 5px;
 padding: 7px;
}

            Contact Us

            <input type="text" class="name" id="name" placeholder="Enter Your name">
            <input type="text" class="name" id="name" placeholder="Enter Your phone">
            <input type="email" class="name" id="name" placeholder="Enter Your email">
            <textarea rows="4" placeholder="Enter Your message"></textarea>


text:
Q: R matrix of lists a=matrix(list(),2,2)
a[1,2]=list(2) ##works

a=matrix(list(),2,2)
a[1,2]=list(2,3) ##doesn't work

Error in a[1, 2] = list(2, 3) :    number of items to replace is not a
  multiple of replacement length

That's the error message from the fourth line. If I try
x=list()
x=list(2,4)

it works, I don't see the difference as a[1,2] is a NULL list..
Thanks in advance.

A: When you replace with list(2), look at the output:
a=matrix(list(),2,2)
a[1,2]=list(2)    sapply(a, class)
# [1] "NULL"    "NULL"    "numeric" "NULL"

That is, the [1,2] element is not a list.
list(2,3) can be coerced like that to a single element; as RichardScriven points out, the replacement must be length-1; the following works (a bit silly, I agree):
a = matrix(list( ), 2, 2)
a[1, 2] = list(list(2, 3))
a
#      [,1] [,2]
# [1,] NULL List,2
# [2,] NULL NULL

(just for reference, I figured this out by playing with dput, like so:)
#What happens if we declare 'a' as a
#  matrix of appropriately-sized lists to start with?
a <- matrix(replicate(4, vector("list", 2), simplify = FALSE), 2, 2)
a
#      [,1]   [,2]
# [1,] List,2 List,2
# [2,] List,2 List,2
#
# can we replace now?
a[1,2] <- list(2,3)
# (same error; what IS 'a[1,2]' for this matrix?)
dput(a[1, 2])
# list(list(NULL, NULL))
# BINGO! we must replace 'a[1,2]' with a length-one list.


text:
Q: Python deadlock related to packaging and mayavi? I have a curious problem that I hope someone can shed some light on.
I have a complex piece of code, that started as a directory full of scripts, that I decided to rework into a package. This code change appears to have been the trigger for some strange deadlocks to appear.
Below is an attempt at canonical reproduction of the problem; which fails, in the sense that this code runs as expected. Actually reproducing the issue may require a lot of code; but I cannot for the life of my imagine what is different for the offending code snippet in-context.
import numpy as np
from scipy.sparse import csr_matrix
from threading import Thread

def dummy():
    print 'this is printed'
    I = np.eye(3)
    print 'all is still fine'
    csr_matrix(I)
    print 'this is never printed; csr_matrix appears to be a trigger for deadlock'
    print np.ones(4)
    print 'same problem; somehow, printing ndarrays is no longer cool either'

thr = Thread(target=dummy)
thr.start()

Perhaps this terse comment in the docs is related? I am not sure I fully appreciate what is being said here
http://docs.python.org/2/library/threading#importing-in-threaded-code
Firstly, other than in the main module, an import should not have the side effect of spawning a new thread and then waiting for that thread in any way. Failing to abide by this restriction can lead to a deadlock if the spawned thread directly or indirectly attempts to import a module.
Some context: I am using python 2.7, numpy 1.8, where I try to spawn this new thread from within a mayavi/traitsui thread (which I dont see why it should be relevant, and which worked fine before the package structure, but ok). Also, there is a boatload of numpy/scipy code in my spawned thread that executes perfectly fine; its just printing ndarrays and creating sparse matrices which so far have proven to be triggers for deadlock.
I am suspecting some funky interaction with mayavi, since closing the mayavi window causes all deadlocked threads to start running again. Perhaps these specific statement trigger the python thread to yield back to the mayavi thread, but they somehow fail to gain focus again?
Any hints that lead to further narrowing down on this mystery are much appreciated!

A: From your comments, it looks like you start up the UI event loop at the top level of one of your subsidiary modules. This is not a good idea because it causes exactly the same problems that the documentation alludes to. import foo should never start a UI event loop. The problem is that the main thread grabs the import lock to handle the import of the module. This module starts up the UI event loop before completing the import. This is essentially the same situation as the waiting for the other threads to finish; you are waiting for the UI loop to finish. If your UI starts up other threads, the code that is running in the other threads will not be able to import anything (both csr_matrix() and ndarray.__repr__() import other modules) because the main thread is still holding onto the import lock.


text:
Q: Is it possible to customize items in split action bar? I'm working with split action bar for my project, i would like to know is it possible to customize the items position in split action bar (i.e) i want some of the menu items in top of the action bar and some of them bottom of the action bar dynamically as my wish is it possible ?
Thanks in advance,

A: It is not possible to use normal actions on the top and split ActionBar at the same time. There is a trick you can use that is described below:
How to display both normal and split ActionBar?
But it is an old question and ActionBar is deprecated. You can now use multiple Toolbar objects instead of ActionBar. That way you can keep one of them at the bottom and add whatever actions you want to it.


text:
Q: Using Pandas Series of dates(strings) as x ticks on a plot I have 3 csv's with stock data, all from 2012-01-1 to 2017-01-01. I have used Pandas to make Dataframes out of them, and am instructed to turn them into this example plot:
[Desired outcome][1]
My only issue is that Pandas isn't taking the 'Date' Series from my Dataframe to create the X axis of time like in the picture, instead I get an X axis of values 0-1400 [My failed plot][2] (I have 1258 dates, so it's getting the index of the date rather than the date itself).
This is my code for the plot right now:
ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot(x=ford['Date'],figsize=(16,8),title='Open price',xlabel='Date')
plt.legend(['Ford','Tesla','GM'])

I have tried using the xticks argument and passing it tesla['Date'] (The name of the date series), but when I do I get this error:

ConversionError: Failed to convert value(s) to axis units: 0       2012-01-03
1       2012-01-04
2       2012-01-05
3       2012-01-06
4       2012-01-09
...
1253    2016-12-23
1254    2016-12-27
1255    2016-12-28
1256    2016-12-29
1257    2016-12-30
Name: Date, Length: 1258, dtype: object

I couldn't find this particular issue on google and I've looked for an hour. I'm definitely missing something but I don't know what. Thanks for any help
[1]: https://i.stack.imgur.com/bz8GU.png
[2]: https://i.stack.imgur.com/lSihy.png

A: With pandas plots, you can create a graph by stacking each of them without specifying the x-axis. The data was obtained from Yahoo Finance in one-month units.
import matplotlib.pyplot as plt

fig = plt.figure()
ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot(figsize=(16,8),title='Open price',xlabel='Date')
plt.legend(['Ford','Tesla','GM'])
plt.show()

A: Select the index of the dates you want to display (say, one tick every 200 value), and use plt.xticks. Try this:
import numpy as np

ford['Open'].plot()
tesla['Open'].plot()
GM['Open'].plot()
plt.legend(['Ford','Tesla','GM'])
ticks = np.arange(0, len(ford['Date']), 200)
plt.xticks(ticks, ford['Date'][ticks])


text:
Q: Wordpress Custom Form Submission via admin-post.php stopped working I have a page with a custom form which sends post data via admin-post.php. This used to work fine a few days ago but now it seems that its not even triggering the function. Here is the code. I also have some other similar forms on the same site but all of them have stopped working.
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="POST">
    <input type="hidden" name="action" value="create_user">
    <?php wp_nonce_field('create_user'); ?>
    <input type="text" class="form-control" name="first_name" placeholder="First Name" required/>
    <input type="text" class="form-control" name="last_name" placeholder="Last Name" required/>
</form>

In my functions.php i have this
function create_user() {
    $retrieved_nonce = $_POST['_wpnonce'];
    if (!wp_verify_nonce($retrieved_nonce, 'create_user' ) ){
        $status = 'failed';
    }else{

      // My Code goes here
    }
}
add_action( 'admin_post_create_user', 'estudy_create_user' );

I have tried echoing something and dieing out the script just to check whether the function is being triggered or not but that too is not working.
Any help in the right direction would be great :)

A: Well after some digging i found out that admin-post.php is used for admin side forms (which should have been obvious). While i was using it on the front end forms.
The solution for front end forms is quite similar, instead of admin-post.php use admin-ajax.php. Secondly replace admin_post_* hook with wp_ajax_* hook. And for frontend guest users use wp_ajax_nopriv_*.


text:
Q: Undefined method on mock object implementing a given interface in PHPUnit? I'm new to unit testing and PHPUnit.
I need a mock, on which I have a full control, implementing ConfigurationInterface interface. Test subject is ReportEventParamConverter object and test must check the interaction between my object and the interface.
ReportEventParamConverter object (here simplified):
class ReportEventParamConverter implements ParamConverterInterface
{
    /**
     * @param Request $request
     * @param ConfigurationInterface $configuration
     */
    function apply(Request $request, ConfigurationInterface $configuration)
    {
        $request->attributes->set($configuration->getName(), $reportEvent);
    }

    /**
     * @param ConfigurationInterface $configuration
     * @return bool
     */
    function supports(ConfigurationInterface $configuration)
    {
        return 'My\Namespaced\Class' === $configuration->getClass();
    }
}

And this is the way I'm trying to mock the interface:
$cls = 'Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface';
$mock = $this->getMock($mockCls);

I need to simulate the returned values for two methods: getClass() and getName(). For example:
$mock->expects($this->any())
    ->method('getClass')
    ->will($this->returnValue('Some\Other\Class'))
;

When i create a new ReportEventParamConverter and test supports() method, i get the following PHPUnit error:

Fatal error: Call to undefined method
  Mock_ConfigurationInterface_21e9dccf::getClass().

$converter = new ReportEventParamConverter();
$this->assertFalse($converter->supports($mock));

A: It's because there is no declaration of "getClass" method in ConfigurationInterface. The only declaration in this interface is method "getAliasName".
All you need is to tell the mock what methods you will be stubing:
$cls = 'Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface';
$mock = $this->getMock($cls, array('getClass', 'getAliasName'));

Notice that there is no "getClass" declaration but you can stub/mock non existing method as well. Therefor you can mock it:
$mock->expects($this->any())
    ->method('getClass')
    ->will($this->returnValue('Some\Other\Class'));

But in addtion you need to mock "getAliasName" method as well as long as it's interface's method or abstract one and it has to be "implemented". Eg.:
$mock->expects($this->any())
   ->method('getAliasName')
   ->will($this->returnValue('SomeValue'));

A: Cyprian's answer helped me, but there's a gotcha to be aware of. You can mock classes that don't exist, and PHPUnit won't complain. So you could do
$mock = $this->getMock('SomeClassThatDoesntExistOrIsMisspelledOrPerhapsYouForgotToRequire');

This means that if ConfigurationInterface doesn't exist at that point during runtime, you'll still get a message like

Fatal error: Call to undefined method
  Mock_ConfigurationInterface_21e9dccf::getClass().

If you're sure the method really exists on the class, then the likely problem is the class itself doesn't exist (because you haven't required it, or you misspelled it, etc).

The OP is using an interface. Be advised that you must call getMock without specifying the list of methods to override, or if you do, you must either pass array(), or pass ALL the method names, or you'll get an error like the following:

PHP Fatal error:  Class Mock_HttpRequest_a7aa9ffd contains 4 abstract
  methods and must therefore be declared abstract or implement the
  remaining methods (HttpRequest::setOption, HttpRequest::execute,
  HttpRequest::getInfo, ...)

A: Tyler Collier's warning is fair but doesn't contain a code snippet on how to code around it. Note this is very nasty and you should fix the interface instead. With that warning added:
$methods = array_map(function (\ReflectionMethod $m) { return $m->getName();}, (new \ReflectionClass($interface))->getMethods());
$methods[] = $missing_method;
$mock = $this->getMock($interface,  $methods);