text:
Q: Create campaign, mails and schedule the send to subscribers lists with FuelSDK C# I'm trying to schedule the sent of some mails with the FuelSDK (C#) in ExactTarget, but the documentation is really scarse and I'm not even sure how to begin.
Basically what I have is a structure like the following:
Campaign: It has a given date.
 |- First Mail Data: Subject, HTML
 |   |- List of subscribers to send at 9 AM
 |   |- List of subscribers to send at 10 AM
 |   |- List of subscribers to send at 11 AM
 |   ...
 |- Second Mail Data:  Subject, HTML
 |   |- List of subscribers to send at 9 AM
 |   |- List of subscribers to send at 10 AM
 |   |- List of subscribers to send at 11 AM
 |   ...
 ...

So, basically I need to create a campaign, add mails to it, and send each mail to a different subscribers lists at differents hours. I don't know if it's important, but different mails to schedule might be for different Business Units.
Researching the FuelSDK demo and examples, I think I have to do something like this:
Create campaign
Foreach mail data
    Create email
    Create email asset with previous email
    Add email asset to campaign
    Foreach subscribers list
        Create subscriber list
        Foreach subscriber
            Add subscriber to list
        Create Email Send Definition
        Associate Email Send Definition to email and list
        Schedule Email Send Definition to the corresponding hour

That last part is where I'm not sure if it's ok. Every example I've found is a basic CRUD operation, rarely interacting with other structures. I'm not even sure if those are the correct structures to use, as I haven't been able to find too much documentation on ExactTarget itself.
After all this my question would be: Is the previous workflow ok? is it using the correct structures to achieve what I want?
If possible, please share some working example, it might give me a better idea than the simple ones I've found.


text:
Q: Article before concerns Could anyone explain the difference between these two sentences:

*

*In that sense, concerns about the preservation of traditional
knowledge, and the continued way of life of those holding such
knowledge, may be symptomatic of the underlying problems that face
these communities in the face of external pressures.

*The concerns about commercial advertising had still not been
addressed successfully.
Why the first sentence has no 'the' before 'concerns', while the second has?

A: Without seeing the rest of the original text, I cannot be sure, but I would suggest that, in the case of the second sentence, there was a previous sentence which introduced or described the concerns.
The first sentence introduces the concerns about preservation of knowledge; while the second sentence assumes that the concerns about advertising are already introduced.

A: "The" is a definite article, which means that sentence 2 is more specific about the concerns in question than sentence 1.
In sentence 1, the speaker is acknowledging the possibility that some concerns may exist, without specifying any single concern.  This is very similar in meaning to:

In that sense, [any] concerns about the...

In sentence 2, the speaker is saying that there are a defined set of specific concerns.  Using "the" here means that the speaker knows exactly which concerns they are referencing, and assumes that the reader is also familiar with them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery Mobile Listview trigger create scrolling I'm having trouble with jquerymobile listview. If I add li-items with javascript to the listview and trigger create to refresh the listview, the page scrolls up to the top of the listview.
Is it possible to refresh a listview and stay at the current y scrolling position?
The ul is in a div with the id List_Container.
I'm calling
$('#List_Container').html(content_sql_list).trigger('create');

Same results with
$('ul').listview('refresh');

Any ideas?
Thanks for your help.


text:
Q: How to create a css-only slide-down animation (using JS only to manage toggling state)? I am trying to create a sliding animation only using CSS.
JavaScript is used just to toggle the open/close state of the element.
I can use translated and rotateX CSS transforms to hide/show the menu. But those techniques do not reduce/increase the height of the element, and thus the parent does not follow the children height.
I want to be able to slide up/down an element inside its parent, while the parent also collapses and expands. And I want to do this using transitions so that a sliding-up/down animation would be shown.
Here is my codesandbox

A: add a class to open and close then toggle the class with js
using yourclass.classList.toggle(classname)
your updated sandbox https://codesandbox.io/s/xenodochial-benji-boil1b?file=/index.html

A: I would recommend to use a transform: translate and change layout of navbar

#parent {
        overflow-y: hidden;
      }
      #slide {
        background: gray;
        z-index: 30;
        position: relative;
      }
      #slideMenu {
        transform: translateY(-100%);
        overflow: hidden;
        z-index: -1;
        transition: 1s transform ease-in;
        position: relative;
      }
      #slideMenu.open {
        transform: translateY(0);
      }
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>

        <button>sldie</button>

item 1

item 2

item 3

item 4

item 5


text:
Q: Python tkinter setting label text from function I have a label in a tkinter window and a function which outputs the current date in spanish. I am trying to set the label text to the date given by the function but it doesnt work.
the code is the following:
root = Tk()
root.title("Tarea Programada 2")
root.geometry("800x700+350+100")
fecha = Label(root, text=" ", font=('times',10), fg= 'black', bg= 'white', width = 30, height = 1)
fecha.place(x=551,y=100)

def horayfecha():
   dia = time.strftime("%A")
   fecha = time.strftime("%m")
   mes = time.strftime("%B")
      año = time.strftime("%Y")
   if dia == "Monday":
       dia = "Lunes"
   if dia == "Tuesday":
       dia = "Martes"
   if dia == "Wednesday":
       dia = "Miercoles"
   if dia == "Thursday":
       dia = "Jueves"
   if dia == "Friday":
       dia = "Viernes"
   if dia == "Satuday":
       dia = "Sabado"
   if dia == "Sunday":
       dia = "Domingo"
   if mes == "January":
       mes = "enero"
   if mes == "February":
       mes = "febrero"
   if mes == "March":
       mes = "marzo"
   if mes == "April":
       mes = "abril"
   if mes == "May":
       mes = "mayo"
   if mes == "June":
       mes = "junio"
   if mes == "July":
       mes = "julio"
   if mes == "August":
       mes = "agosto"
   if mes == "September":
       mes = "stiembre"
   if mes == "October":
       mes = "octubre"
   if mes == "November":
       mes = "noviembre"
   if mes == "December":
       mes = "diciembre"
   comp = ("San José, Costa Rica " + dia + " " + fecha + " de " + mes + " de " + año)
   fecha.setLabel("{}".format(comp))

root.mainloop()

Can anyone help me with this?
Thanks in advance

A: Your code had many problems, including missing imports, indentation, style, non-unique variable names, mixing up which variables refer to which objects, spelling errors (yes, those count, because they bother the user almost as much as crashing bugs), poor widget placement, strange string formatting, failure to call defined functions, function results that are thrown away instead of returned, and possibly more that I'm forgetting.
Here is a cleaned-up version of your code that works properly:
from tkinter import *
import time

root = Tk()
root.title("Tarea Programada 2")
root.geometry("800x700+350+100")

fecha = Label(root, text=" ", font=('times',10), fg= 'black', bg= 'white', width = 50, height = 1)
fecha.place(x=350,y=100)

def horayfecha():
    día, fecha, mes, año = time.strftime("%A %m %B %Y").split()

    días = {'Monday':'Lunes', 'Tuesday':'Martes', 'Wednesday':'Miércoles',
            'Thursday':'Jueves', 'Friday':'Viernes', 'Saturday':'Sábado', 'Sunday':'Domingo'}

    meses = {'January':'Enero', 'February':'Febrero', 'March':'Marzo', 'April':'Abril', 'May':'Mayo',
             'June':'Junio', 'July':'Julio', 'August':'Agosto', 'September':'Setiembre', 'October':'Octubre',
             'November':'Noviembre', 'December':'Diciembre'}

    return ' '.join(["San José, Costa Rica", días.get(día), fecha, "de", meses.get(mes), "de", año])

fecha.config(text=horayfecha())
root.mainloop()


text:
Q: .deps.json not found executing vs test after vs build in dev ops I can´t past the task "execute test" because this error, in all my tests projects.
##[error]Unable to find D:\a\13\s$\testcore\obj\Debug\netcoreapp3.1\Project.TestCore.deps.json. Make sure test project has a nuget reference of package "Microsoft.NET.Test.Sdk".
Nuget is installed in the last version and the file deps.json always exist when build in my local machine.
Project is dot net core 3.1
Any ideas? Thank you very much in advance

A:
.deps.json not found executing vs test after vs build in dev ops

According to the error message, the .deps.json exists in the web application output folder, but it is not copied to the test project output folder.
Please try to reference the nuget package Microsoft.AspNetCore.Mvc.Testing directly from the integration test project.
From the document ASP.NET Core integration tests:

The Microsoft.AspNetCore.Mvc.Testing package handles the following
tasks:

*

*Copies the dependencies file (.deps) from the SUT into the test    project's bin directory.

*Sets the content root to the SUT's project root so that static files    and pages/views are found when the tests are executed.

*Provides the WebApplicationFactory class to streamline bootstrapping    the SUT with TestServer.

Note: deps.json file may causes this build error if project name has multiple words separated by whitespace, please try to rename the project to just one word.

A: I was having the same issue with .NET 6 and minimal API
This article helped https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#basic-tests-with-the-default-webapplicationfactory
The summary is that:

*

*Your Microsoft.AspNetCore.Mvc.Testing must be compatible with your xUnit project. So if you're using .NET 6, make sure you use some version like 6.x.x

*Your xUnit project MUST have a reference to the WebApi project

*Be careful with the Startup or Program you're using to build the TestServer. If you're using a minimal Web API you have to expose the Program.cs as per link above.

In my case I added this to the Web Api project
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <InternalsVisibleToSuffix Include=".FunctionalTests" /> <!-- THIS LINE to make private classes like Program.cs available to any xUnit project with suffix .FunctionalTests-->
    <ProjectReference Include="..\ExchangeRateCalculation\ExchangeRateCalculation.csproj" />
  </ItemGroup>
</Project>

Then my minimal API looks like this
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Map("/", () => "hello world");
app.Run();

// NOTICE this declaration! This is what makes Program.cs available
partial class Program { } // See https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0

And my TestServer
public class SampleTests
{
    private readonly HttpClient _httpClient;

    public CalculateCryptoInEurTests()
    {
        var application =
            new WebApplicationFactory<Program>()
                .WithWebHostBuilder(builder =>
                {
                    builder.ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        var env = hostingContext.HostingEnvironment;

                        config
                            .AddJsonFile("appsettings.json", true, false)
                            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, false)
                            .AddEnvironmentVariables();

                        if (env.IsDevelopment())
                        {
                            var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                            config.AddUserSecrets(appAssembly, true);
                        }
                    });
                });

        var client = application.CreateClient();

        _httpClient = client;
    }

    // FACTs using the _httpClient here
}


text:
Q: remove duplicate rows regardless of order I have a data.frame like so:
df <- structure(list(X1 = c("PF00041", "PF00041", "PF00041", "PF00041",
"PF00041", "PF00041", "PF00041", "PF00041", "PF00041", "PF00047",
"PF00041", "PF00041", "PF00041", "PF00054", "PF00054", "PF02210",
"PF07679", "PF07714", "PF07714", "PF07714", "PF07714", "PF07714",
"PF07714", "PF00041", "PF00041", "PF00041"), X2 = c("PF00041",
"PF00041", "PF00041", "PF00041", "PF00041", "PF00041", "PF07679",
"PF07679", "PF07679", "PF13895", "PF00047", "PF00047", "PF00047",
"PF02210", "PF13895", "PF07645", "PF13895", "PF07714", "PF07714",
"PF07714", "PF07714", "PF07714", "PF07714", "PF13895", "PF13895",
"PF13895"), pfam_name.x = c("fn3", "fn3", "fn3", "fn3", "fn3",
"fn3", "fn3", "fn3", "fn3", "ig", "fn3", "fn3", "fn3", "Laminin_G_1",
"Laminin_G_1", "Laminin_G_2", "I-set", "Pkinase_Tyr", "Pkinase_Tyr",
"Pkinase_Tyr", "Pkinase_Tyr", "Pkinase_Tyr", "Pkinase_Tyr", "fn3",
"fn3", "fn3"), pfam_name.y = c("fn3", "fn3", "fn3", "fn3", "fn3",
"fn3", "I-set", "I-set", "I-set", "Ig_2", "ig", "ig", "ig", "Laminin_G_2",
"Ig_2", "EGF_CA", "Ig_2", "Pkinase_Tyr", "Pkinase_Tyr", "Pkinase_Tyr",
"Pkinase_Tyr", "Pkinase_Tyr", "Pkinase_Tyr", "Ig_2", "Ig_2",
"Ig_2"), value.x = c("5", "5", "13", "13", "17", "17", "5", "13",
"17", "18", "5", "13", "17", "11", "11", "12", "14", "6", "6",
"15", "15", "20", "20", "5", "13", "17"), value.y = c("13", "17",
"5", "17", "5", "13", "14", "14", "14", "19", "18", "18", "18",
"12", "19", "8", "19", "15", "20", "6", "20", "6", "15", "19",
"19", "19")), row.names = c(2L, 3L, 4L, 6L, 7L, 8L, 10L, 11L,
12L, 13L, 15L, 16L, 17L, 19L, 20L, 25L, 27L, 29L, 30L, 31L, 33L,
34L, 35L, 38L, 39L, 40L), class = "data.frame")

I'd like to be able to filter this data.frame based on columns value.x and value.y but I don't want to keep the rows that are the switched. for example row 1 has values 5 and 13 respectively and row 3 has values 13 and 5 respectively, I want to get rid of row 3.
I tried sorting at first, but because I have other columns the sort is mixing up all the columns together. For example:
data.frame(unique(t(apply(df, 1, sort))), stringsAsFactors = F)
In this table I could see that Pkinase_Tyr was now in column X1.


text:
Q: How can I check my post data in Zend? I am a beginner and I am creating some forms to be posted into MySQL using Zend, and I am in the process of debugging but I don't really know how to debug anything using Zend. I want to submit the form and see if my custom forms are concatenating the data properly before it goes into MySQL, so I want to catch the post data to see a few things. How can I do this?

A: The Default route for zend framework application looks like the following
http://www.name.tld/$controller/$action/$param1/$value1/.../$paramX/$valueX

So all $_GET-Parameters simply get contenated onto the url in the above manner /param/value
Let's say you are within IndexController and indexAction() in here you call a form. Now there's possible two things happening:

*

*You do not define a Form-Action, then you will send the form back to IndexController:indexAction()

*You define a Form action via $form->setAction('/index/process') in that case you would end up at IndexController:processAction()
The way to access the Params is already defined above. Whereas $this->_getParam() equals $this->getRequest()->getParam() and $this->_getAllParams() equals $this->getRequest->getParams()
The right way yo check data of Zend Stuff is using Zend_Debug as @vascowhite has pointed out. If you want to see the final Query-String (in case you're manually building queries), then you can simply put in the insert variable into Zend_Debug::dump()

A: you can use $this->_getAllParams();.
For example: var_dump($this->_getAllParams()); die; will output all the parameters ZF received and halt the execution of the script. To be used in your receiving Action.
Also, $this->_getParam("param name"); will get a specific parameter from the request.

A: The easiest way to check variables in Zend Framework is to use Zend_Debug::dump($variable); so you can do this:-
Zend_Debug::dump($_POST);

A: Zend framework is built on the top of the PHP . so you can use var_dump($_POST) to check the post variables.
ZF has provided its own functions to get  all the post variables.. Zend_Debug::dump($this->getRequest()->getPost())
or specifically for one variable.. you can use Zend_Debug::dump($this->getRequest()->getPost($key))

A: You can check post data by using zend
$request->isPost()
and for retrieving post data
$request->getPost()
For example
if ($request->isPost()) {
$postData = $request->getPost();

Zend_Debug::dump($postData );

}


text:
Q: Timoshenko beam coercivity: $A((w,\beta),(v,\eta)):=\int^1_0\beta'\eta'dx+\int^1_0(w'-\beta)(v'-\eta)dx=\int^1_0fvdx \forall(v,\eta)\in H^1_0(0,1)^2$ I want to show coercivity of the following bilinear form from Timoshenko beam theory:
For t<<1 and $(w,\beta)\in H^1_0(\Omega)$ with $\Omega=(0,1)\times(-t/2,t/2)$
$A((w,\beta),(v,\eta)):= \displaystyle\int^1_0\beta'\eta'dx+\int^1_0(w'-\beta)(v'-\eta)dx=\int^1_0fvdx \forall(v,\eta)\in H^1_0(0,1)^2$
Showing that $A((w,\beta),(w,\beta))\ge0$ is trivial as $A$ just consists of L2 norms but I need to show that A is coercive. I do not know how to continue.

A: Coercivity is shown e.g. in this paper: Discretization by finite elements of a model parameter dependent problem, Douglas N. Arnold, Numerische Mathematik 37, pages 405–421 (1981).
Hint: use Poincaré inequality (also known as Wirtinger's inequality in 1D) and the triangle inequality.


text:
Q: Shorten js script using $.each function I have the following .js code which reads a json file to update the values in the html every minute.
$(document).ready(updateData);
function updateData() {
    $.ajaxSetup({ cache: false });
    $.getJSON("data/data.json", function(result){
        $('#id1').empty();
        $('#id1').append(result.id1);
        $('#id2').empty();
        $('#id2').append(result.id2);
        $('#id3').empty();
        $('#id3').append(result.id3);
        $('#id4').empty();
        $('#id4').append(result.id4);
        $('#id5').empty();
        $('#id5').append(result.id5);
        $('#id6').empty();
        $('#id6').append(result.id6);
        $('#id7').empty();
        $('#id7').append(result.id7);
        $('#id8').empty();
        $('#id8').append(result.id8);
        $('#id9').empty();
        $('#id9').append(result.id9);
    });
    setTimeout(updateData, 60000);
}

Can this be rewritten in a shorter way using the $.each() function?

A: You can use a loop:
var i;
for (i = 1; i <= 9; i++) {
    $('#id'+i).html(result['id'+i]);
}

A: It can be improved using a simple for loop:
$.ajaxSetup({ cache: false }); // 1
$(document).ready(updateData);

function updateData() {
  $.getJSON("data/data.json", function(result) {
    for (var i = 1; i<= 9; i++) {
      $('#id' + i).empty().append(result['id' + i]); // 2
    }

    setTimeout(updateData, 60000); // 3
  });
}

However, accessing the DOM by concatenated IDs does not look good.
For example, you can try to implement it using CSS classes and data-attributes.
Some minor improvements:

*

*ajaxSetup can only be initialized once, you don't need to call it every time.

*You probably don't need to empty() and append() at the same time. If it is a text, you can simply use .text(), or .html() for HTML.

*It is a good idea to call setTimeout in your getJSON callback so that it updates data in 60 seconds after a previous request is completed, better in .always() handler. Imagine that one of your clients has very slow connection and it takes more than 60 seconds to load this JSON. It will lead to unexpected results.

A: for(var i =1;i<=9;i++){
$('#id'+i).empty();
$('#id'+i).append(result.id+1); }

This going to work

A: A little more jQuery'ish, using $.each
$(document).ready(updateData);

function updateData() {
    $.ajaxSetup({
        cache: false
    });
    $.getJSON("data/data.json", function(result) {
        $.each("123456789".split(""), function(_,i) {
            $('#id'+i).html(result['id'+i));
        });
    });

    setTimeout(updateData, 60000);
}


text:
Q: Does JMeter or Rest Assured give any suggestion to improve the performance of the API or suggestion to the response we get from API? I am looking into if JMeter or Rest Assured give any suggestion to improve the performance of the API or suggestion on the response we get from API.

A: No, both of them are basically http client tools. You can't count on them for any suggesstions.


text:
Q: Cannot see notification sent with firebase I have a mobile device that is registering with topic using FirebaseMessaging.instance.subscribeToTopic("newTopic")
I am using OAuth 2.0 Playground to get an access token. I am sending a POST request as follows but not seeing any notifcation on the device registered to that topic. The CURL request returns a status code of 200 OK.
curl -X POST -k -H 'Authorization: Bearer access_token_goes_here' -H 'Content-Type: application/json' -i 'https://fcm.googleapis.com/v1/projects/projectId/messages:send' --data '{
  "message":{
    "topic" : "newTopic",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

Just to know if im receiving the notification, im handling the notification as follows:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });

A: Initial notification configuration:
await Firebase.initializeApp();
FlutterLocalNotificationsPlugin flutterNotificationPlugin =
    FlutterLocalNotificationsPlugin();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'channel ID',
  'channel name',
  playSound: true,
  importance: Importance.max,
);
await flutterNotificationPlugin
    .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
    ?.createNotificationChannel(channel);
var initializationSettingsAndroid =
    const AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = const DarwinInitializationSettings();
var initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await flutterNotificationPlugin.initialize(
  initializationSettings,
);

//LocalNotification show
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
  await FirebaseMessaging.instance
      .setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
}
 FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
    RemoteNotification? notification = message.notification;
    //AndroidNotification? android = message.notification?.android;
    if (notification != null) {
      log("On message: $notification");
      log(message.data.toString());

      if (Platform.isAndroid) {
        FlutterLocalNotificationsPlugin().show(
            0, notification.title, notification.body, notificationDetails);
      }
    }
  });


text:
Q: Possible to check if imagecreatefromjpeg is going to cause memory exhausted fatal error before I run it? I've done some searching for this and I understand that it is not possible to recover from an exhausted memory fatal error.    I have a script that runs imagecreatefromjpeg.  I tried catching the exception, I tried running the function with @ and then checking the return value for null or false,  I tried running it with 'die()'. Nothing works.   So I can't 'recover' from it.
So is it possible to anticipate it before I get to it?   Is it possible to check the uncompressed size of a jpeg and then die gracefully?   I want to sent a message to my users along the lines of "The image $image is too large to process. You will need to create a thumbnail manually".
My shared host won't allow me to increase memory size beyond 64mb so that's not an option.  My code is as follows...
function createthumb($section,$filename,$constrain=100)
{
    $dir = "$section/thumbs_$constrain";
    if(file_exists($workingdir."$section/thumbs_$constrain/$filename")) return 1;
    if(!file_exists($dir)) mkdir($dir);

    $src = imagecreatefromjpeg($workingdir."$section/$filename");
...

A: As a rule of thumb, you might use the size in pixels returned by getimagesize() :
list ($width, $height) = getimagesize($file);
$memory = $width * $height * 4; // 4 bytes per pixel

If this number is greater than a predefined limit (to be determined empirically, start with something like 32*1024*1024), then don't load it with imagecreatefromjpeg().

A: Have you thought about using ImageMagic instead of GD? ImageMagic is able to resize jpegs during load, so it doesn't consume copious amounts of PHP's memory. See this StackOverflow answer for details.

A: I think only error handler can help you  as exception handling may not work on memory exhausted
http://php.net/manual/en/function.set-error-handler.php

A: You can verify string source size before imagegreatefromjpeg.


text:
Q: Lazy infinite sequences in Clojure and Python Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:
Clojure:
(def fib-seq (lazy-cat [0 1]
 (map + fib-seq (rest fib-seq))))

sample usage:
 (take 5 fib-seq)

Python:
def fib():
 a = b = 1
 while True:
  yield a
  a,b = b,a+b

sample usage:
for i in fib():
  if i > 100:
    break
  else:
    print i

Obviously the Python code is much more intuitive.
My question is: Is there a better (more intuitive and simple) implementation in Clojure ?
 Edit
I'm opening a follow up question at
Clojure Prime Numbers

A: The Clojure code is intuitive to me (because I know Clojure).  If you want something that might look more like something you're familiar with, you can try this, an efficient and overly-verbose recursive version:
(use 'clojure.contrib.def)   ; SO's syntax-highlighting still sucks
(defn-memo fib [n]
  (cond (= n 0) 0
        (= n 1) 1
        :else   (+ (fib (- n 1))
                   (fib (- n 2)))))

(def natural-numbers (iterate inc 0))

(def all-fibs
  (for [n natural-numbers]
    (fib n)))

But to someone who doesn't know what recursion or memoization are, that isn't going to be intuitive either.  The very idea of "infinite lazy sequences" probably isn't intuitive to the majority of programmers.  I can't guess what's in your brain so I don't know what a more intuitive Clojure function would look like to you, other than "looks more like Python".
To someone who doesn't know programming, all of this stuff is going to look like gibberish.  What's a loop?  What's a function?  What is this yield thing?  That's where we all start.  Intuitiveness is a function of what you've learned so far.  Non-intuitive code is code you aren't familiar with yet.  Extrapolating from "I know this" to "It's inherently more intuitive" is wrong.

A: The wiki has an in depth treatment of various Fibonacci implementations in Clojure which may interest you if you haven't seen it already.

A: I agree with Pavel, what is intuitive is subjective. Because I'm (slowly) starting to grok Haskell, I can tell what the Clojure code does, even though I've never written a line of Clojure in my life. So I would consider the Clojure line fairly intuitive, because I've seen it before and I'm adapting to a more functional mindset.
Let's consider the mathematical definition, shall we?
       { 0                   if x = 0 }
F(x) = { 1                   if x = 1 }
       { F(x - 1) + F(x - 2) if x > 1 }

This is less than ideal, formatting wise - those three brackets lined up should be one giant bracket - but who's counting? This is a pretty clear definition of the Fibonacci sequence to most people with a mathematical background. Let's look at the same thing in Haskell, because I know it better than Clojure:
fib 0 = 0
fib 1 = 1
fib n = fibs (n - 1) + fibs (n - 2)

This is a function, fib, that returns the nth Fibonacci number. Not exactly what we had in Python or Clojure, so let's fix that:
fibs = map fib [0..]

This makes fibs an infinite list of Fibonacci numbers. fibs !! 1 is 1, fibs !! 2 is 1, fibs !! 10 is 55, and so on. However, this is probably quite inefficient, even in a language that relies on heavily optimized recursion such as Haskell. Let's look at the Clojure definition in Haskell:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

The first couple of characters are pretty simple: 0 : 1 : makes a list with elements 0 and 1, and then some more. But what's all the rest of that? Well, fibs is the list we've already got, and tail fibs calls the tail function on our list so far, which returns the list starting at the 2nd element (sort of like in Python saying fibs[1:]). So we take these two lists - fibs and tail fibs - and we zip them together with the + function (operator) - that is, we add the matching elements of each. Let's look:
fibs       = 0 : 1 : ...
tail fibs  = 1 : ...
zip result = 1 : ...

So our next element is 1! But then we add that back onto our fibs list, and look what we get:
fibs       = 0 : 1 : 1 : ...
tail fibs  = 1 : 1 : ...
zip result = 1 : 2 : ...

What we have here is a recursive list definition. As we add more elements to the end of fibs with our zipWith (+) fibs (tail fibs) bit, more elements become avaliable for us to work with when adding elements. Note that Haskell by default is lazy, so just making an infinite list like that won't crash anything (just don't try to print it).
So while this is perhaps theoretically the same as our mathematical definition before, it saves the results in our fibs list (sort of an auto-memoization) and we rarely have the problems that might be experienced in a naive solution. For completeness, let's define our fib function in terms of our new fibs list:
fib n = fibs !! n

If I didn't lose you yet, that's good, because that means you understand the Clojure code. Look:
(def fib-seq (lazy-cat [0 1]
 (map + fib-seq (rest fib-seq))))

We make a list, fib-seq. It starts with two elements, [0 1], just like our Haskell example. We do a lazy concatenation of these two initial elements with (map + fib-seq (rest fib-seq)) - assuming rest does the same thing that tail does in Haskell, we're just combining our list with itself at a lower offset, and then combining these two lists with the + operator/function.
After working this through your head a few times, and exploring some other examples, this method of generating fibonacci series becomes at least semi-intuitive. It's at least intuitive enough for me to spot it in a language I don't know.

A: You should always use a language that fits the problem*.  Your Python example is just lower level than the Clojure one -- easier to understand for beginners, but more tedious to write and parse for someone who knows the fitting higher level concepts.
* By the way, this also means that it is always nice to have a language that you can grow to fit.

A: Here is one solution.
(defn fib-seq [a b]
  (cons (+ a b) (lazy-seq (fib-seq (+ a b) a))))

(def fibs (concat [1 1] (fib-seq 1 1)))

user=> (take 10 fibs)
(1 1 2 3 5 8 13 21 34 55)

A: I like:
(def fibs
  (map first
       (iterate
           (fn [[ a, b       ]]
                [ b, (+ a b) ])
           [0, 1])))

Which seems to have some similarities to the python/generator version.

A: If you didn't know any imperative languages, would this be intuitive for you?
a = a + 5

WTF? a clearly isn't the same as a + 5.
if a = a + 5, is a + 5 = a?
Why doesn't this work???
if (a = 5) { // should be == in most programming languages
    // do something
}

There are a lot of things that aren't clear unless you've seen it before somewhere else and understood its purpose. For a long time I haven't known the yield keyword and in effect I couldn't figure out what it did.
You think the imperative approach is more legible because you are used to it.

A: (take 5 fibs)

Seems about as intuitive as it could possibly get.  I mean, that is exactly what you're doing.  You don't even need to understand anything about the language, or even know what language that is, in order to know what should happen.

A: Think about how would you write lazy-cat with recur in clojure.


text:
Q: Sonarqube ant IllegalStateException; not picking up properties file I'm testing out Sonarqube 5.3 and the Sonarqube Ant 2.4 jar but am running into a problem when calling the ant sonar target in my build script
Here is my build script (C:\dev\poc\sonarpoc\sonarpoc.xml):
<project name="sonarpoc" basedir="." default="init" xmlns:sonar="antlib:org.sonar.ant">
    ...
    <target name="sonar">
        <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml">
            <!-- Update the following line, or put the "sonarqube-ant-task-*.jar" file in your "$HOME/.ant/lib" folder -->
            <classpath path="/dev/jars/opensource/sonarqube/2.4/sonarqube-ant-task-2.4.jar" />
        </taskdef>
        <!-- Execute the SonarQube analysis -->
        <sonar:sonar />
    </target>
    ....
    <target name="build" depends="clean, compile, sonar, build-ear"/>

To execute from the command line I am calling:
C:\dev\poc\sonarpoc>ant -f sonarpoc.xml clean build

I have a sonar-project.properties defined in C:\dev\poc\sonarpoc which contains
# required metadata
sonar.host.url=http://localhost:9000
sonar.projectKey=dev:sonarpoc
sonar.projectName=DEV-sonarpoc
sonar.projectVersion=1.0
sonar.sources=source

So far, so good. I can run sonar-runner at this point and can see the analysis results at http://localhost:9000.
However, when I run the ant script as above, I'm getting this:
compile:

sonar:
[sonar:sonar] Apache Ant version 1.7.1 compiled on June 27 2008
[sonar:sonar] SonarQube Ant Task version: 2.4
[sonar:sonar] Loaded from: file:/C:/dev/jars/opensource/sonarqube/2.4/sonarqube-ant-task-2.4.jar
[sonar:sonar] User cache: C:\Users\john\.sonar\cache
[sonar:sonar] Load global repositories
[sonar:sonar] Load global repositories (done) | time=144ms
[sonar:sonar] User cache: C:\Users\john\.sonar\cache
[sonar:sonar] Load plugins index
[sonar:sonar] Load plugins index (done) | time=13ms
[sonar:sonar] Default locale: "en_IE", source code encoding: "windows-1252" (analysis is platform dependent)
[sonar:sonar] Process project properties

BUILD FAILED
java.lang.IllegalStateException: Unable to load component class org.sonar.batch.scan.ProjectLock
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:62)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at org.sonar.core.platform.ComponentContainer.getComponentByType(ComponentContainer.java:262)
    at org.sonar.batch.scan.ProjectScanContainer.doBeforeStart(ProjectScanContainer.java:109)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:130)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:117)
    at org.sonar.batch.task.ScanTask.execute(ScanTask.java:55)
    at org.sonar.batch.task.TaskContainer.doAfterStart(TaskContainer.java:86)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:132)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:117)
    at org.sonar.batch.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:122)
    at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:119)
    at org.sonar.runner.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.sonar.runner.impl.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:61)
    at com.sun.proxy.$Proxy0.execute(Unknown Source)
    at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:274)
    at org.sonar.runner.api.EmbeddedRunner.runAnalysis(EmbeddedRunner.java:165)
    at org.sonar.runner.api.EmbeddedRunner.runAnalysis(EmbeddedRunner.java:152)
    at org.sonarsource.scanner.ant.SonarQubeTask.launchAnalysis(SonarQubeTask.java:72)
    at org.sonarsource.scanner.ant.SonarQubeTask.execute(SonarQubeTask.java:55)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:357)
    at org.apache.tools.ant.Target.performTasks(Target.java:385)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
    at org.apache.tools.ant.Main.runBuild(Main.java:758)
    at org.apache.tools.ant.Main.startAnt(Main.java:217)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
Caused by: java.lang.IllegalStateException: Unable to load component class org.sonar.api.batch.bootstrap.ProjectReactor
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getCompoent(ComponentContainer.java:62)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:60)
    ... 39 more
Caused by: java.lang.IllegalStateException: You must define the following mandatory properties for 'Unknown': sonar.projectKey, sonar.projectName, sonar.projectVersion, sonar.sources
    at org.sonar.batch.scan.ProjectReactorBuilder.checkMandatoryProperties(ProjectReactorBuilder.java:323)
    at org.sonar.batch.scan.ProjectReactorBuilder.defineRootProject(ProjectReactorBuilder.java:179)
    at org.sonar.batch.scan.ProjectReactorBuilder.execute(ProjectReactorBuilder.java:124)
    at org.sonar.batch.scan.MutableProjectReactorProvider.provide(MutableProjectReactorProvider.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.picocontainer.injectors.MethodInjector.invokeMethod(MethodInjector.java:129)
    at org.picocontainer.injectors.MethodInjector.access$000(MethodInjector.java:39)
    at org.picocontainer.injectors.MethodInjector$2.run(MethodInjector.java:113)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.MethodInjector.decorateComponentInstance(MethodInjector.java:120)
    at org.picocontainer.injectors.CompositeInjector.decorateComponentInstanceCompositeInjector.java:58)
    at org.picocontainer.injectors.Reinjector.reinject(Reinjector.java:142)
    at org.picocontainer.injectors.ProviderAdapter.getComponentInstance(ProviderAdapter.java:96)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.sonar.core.platform.ComponentContainer$ExtendedDefaultPicoContainer.getComponent(ComponentContainer.java:60)
    ... 53 more

Total time: 5 seconds
C:\dev\poc\sonarpoc>

The
Caused by: java.lang.IllegalStateException: You must define the following mandatory properties for 'Unknown': sonar.projectKey, sonar.projectName, sonar.projectVersion, sonar.sources

line from above is where the problem lies. It looks like the ant task can't recognize that there is a sonar-project.properties file in the current directory like sonar-runner can.
I'm thinking that there is additional path configuration needed to tell the ant task to look in the current directory for the sonar-project.properties file and to use it but I can't figure out what that is.
I tried adding:

to C:\dev\poc\sonarpoc\sonarpoc.xml but no joy.
EDIT:
The ant script with the build target runs successfully when I specify the sonar properties on the command line i.e.
C:\dev\poc\sonarpoc>ant -f sonarpoc.xml -Dsonar.projectKey=dev:sonarpoc -Dsonar.projectName=DEV-sonarpoc -Dsonar.projectVersion=1.0 -Dsonar.sources=source clean build

so that reinforces my thoughts that there is some additional path configuration for the ant target to pickup the properties file is needed.
Has anyone come across this before?

A: The SonarQube Scanner for Ant does not support "sonar-project.properties" file out of the box. Is you take a look at the documentation page, you'll see that you have to provide those properties inside the Ant file:
<!-- Define the SonarQube project properties -->
<property name="sonar.projectKey" value="org.codehaus.sonar:example-java-ant" />
<property name="sonar.projectName" value="Simple Java Project analyzed with the SonarQube Ant Task" />
<property name="sonar.projectVersion" value="1.0" />
<property name="sonar.java.binaries" value="build" />
<property name="sonar.java.libraries" value="lib/*.jar" />

If you still want to use a properties file to house those settings, I guess that you could invoke the LoadProperties Ant task for that purpose. But I've never tried this so I can't guarantee this works.

A: On SonarQube 5.1.2 I can to set property file for ant analysis with parameter -propertyfile sonar-project.properties.

A: The solution is simple, Please verify that you are pointing to correct directory
Somtimes in cmd, it points to C:\
To move to another directory you need to add D:
So always verify in cmd, if you are pointing to the directory of right directory.


text:
Q: How to remove a node in a pointer to linked list? I'm trying to remove the last node of a linked list while returning its value. But all this pointers is confusing, like am I really removing it by calling p = NULL??
typedef struct node {
    ElemType val;
    struct node *next;
} NODE;

struct list_struct {
    NODE *front;
    NODE *back;
};

/**
If list is empty, do nothing and return arbitrary value
otherwise, the last element in the list is removed and its value is returned.
**/
ElemType popBack(LIST *l) {
    NODE *p = l->front;
    NODE *previous = NULL;
    while (p != NULL) {
        if (p->next == NULL) {
            ElemType value = p->val;
            p = NULL;
            l->back = previous;
            return value;
        }
        previous = p;
        p = p->next;
    }
    return DEFAULT;
}

A: For starters to use a singly-linked list to remove its last element is not an efficient approach. Instead you should use in this case a doubly-linked list.
Nevertheless in any case you need to free the memory occupied by the deleted node and correctly update not only the pointer back but also the pointer front of the list and the data member next of the pointer previous.
The function can look the following way
ElemType popBack( LIST *l)
{
    ElemType value = DEFAULT;

    if ( l->front != NULL )
    {
        if ( l->front->next == NULL )
        {
            value = l->front->val;
            free( l->front );
            l->front = l->back = NULL;
        }
        else
        {
            node *current = l->front;

            while ( current->next->next != NULL )
            {
                current = current->next;
            }

            value = current->next->val;

            free( current->next );
            current->next = NULL;

            l->back = current;
        }
    }

    return value;
}


text:
Q: Keeping a track of duplicate inserts in a Map (Multithreaded environment) I am looking for a way to keep a track of the number of times the same key insert is attempted into a Map in a multithreaded environemnt such that the Map can be read and updated by multiple threads at the same time. If keeping a track of duplicate key insert attempts is not achievable easily, an alternate solution would be to kill the application at the first sign of a duplicate key insert attempt.
The following user defined singleton Spring bean shows a global cache used by my application which is loaded using multiple partitioned spring batch jobs (one job for each DataType to be loaded). The addResultForDataType method can be called by multiple threads at the same time.
public class JobResults {

    private Map<DataType, Map<String, Object>> results;

    public JobResults() {
        results = new ConcurrentHashMap<DataType, Map<String, Object>>();
    }

    public void addResultForDataType(DataType dataType, String uniqueId, Object result) {
        Map<String, Object> dataTypeMap = results.get(dataType);
        if (dataTypeMap == null) {
            synchronized (dataType) {
                dataTypeMap = results.get(dataType);
                if (dataTypeMap == null) {
                    dataTypeMap = new ConcurrentHashMap<String, Object>();
                    results.put(dataType, dataTypeMap);
                }
            }
        }
        dataTypeMap.put(uniqueId, result);
    }

    public Map<String, Object> getResultForDataType(DataType dataType) {
        return results.get(dataType);
    }

}

Here :

*

*DataType can be thought of as the table name or file name from
where the data is loaded. Each DataType indicates one table or file.

*uniqueId represents the primary key for each record in the table or file.

*result is the object representing the entire row.

*The above method is called once per record. At any given time, multiple threads can be inserting a record for the same DataType or a different DataType.

I thought of creating another map to keep a track of the duplicate inserts :
public class JobResults {

    private Map<DataType, Map<String, Object>> results;
    private Map<DataType, ConcurrentHashMap<String, Integer>> duplicates;

    public JobResults() {
        results = new ConcurrentHashMap<DataType, Map<String, Object>>();
        duplicates = new ConcurrentHashMap<DataType, ConcurrentHashMap<String, Integer>>();
    }

    public void addResultForDataType(DataType dataType, String uniqueId, Object result) {
        Map<String, Object> dataTypeMap = results.get(dataType);
        ConcurrentHashMap<String,Integer> duplicateCount = duplicates.get(dataType);
        if (dataTypeMap == null) {
            synchronized (dataType) {
                dataTypeMap = results.get(dataType);
                if (dataTypeMap == null) {
                    dataTypeMap = new ConcurrentHashMap<String, Object>();
                    duplicateCount = new ConcurrentHashMap<String, Integer>();
                    results.put(dataType, dataTypeMap);
                    duplicates.put(dataType, duplicateCount);
                }
            }
        }
        duplicateCount.putIfAbsent(uniqueId, 0);
        duplicateCount.put(uniqueId, duplicateCount.get(uniqueId)+1);//keep track of duplicate rows
        dataTypeMap.put(uniqueId, result);
    }

    public Map<String, Object> getResultForDataType(DataType dataType) {
        return results.get(dataType);
    }

}

I realize that the statemet duplicateCount.put(uniqueId, duplicateCount.get(uniqueId)+1); is not implicitly thread safe. To make it thread-safe, I will need to use synchronization which will slow down my inserts. How can I keep a track of the duplicate inserts without impacting the performance of my application. If keeping a track of duplicate inserts is not easy, I would be fine with just throwing an exception at the first sign of an attempt to overwrite an existing entry in the map.
Note I am aware that a Map does not allow duplicate keys. What I want is a way to keep a track of any such attempts and halt the application rather than overwrite entries in the Map.

A: Try something like this:
    ConcurrentHashMap<String, AtomicInteger> duplicateCount = new ConcurrentHashMap<String, AtomicInteger>();

Then when you're ready to increment a count, do this:
final AtomicInteger oldCount = duplicateCount.putIfAbsent(uniqueId, new AtomicInteger(1));
if (oldCount != null) {
    oldCount.incrementAndGet();
}

So, if you do not have a count in the map yet, you will put 1, if you have, you will get the current value and atomically increment it. This should be thread safe.

A: If you want to keep track of the number of inserts, you can change the outer map type to something like Map<String, Pair<Integer, Object>> (or, if you don't use Apache Commons, just Map<DataType, Map.Entry<Integer, InnerType>>, where the Integer value is the number of updates:
DataType key = ...;
Map<Integer, Object> value = ...;
dataTypeMap.compute(key, (k, current) -> {
    if (current == null) {
        /* Initial count is 0 */
        return Pair.of(0, value);
    } else {
        /* Increment count */
        return Pair.of(current.getFirst(), value);
    }));

If all you care about is ensuring that there is no duplicate inserts, you can simply use computeIfAbsent:
DataType key = ...;
Map<Integer, Object> value = ...;
if (dataTypeMap.computeIfAbsent(key, k -> value)) != null) {
    /* There was already a value */
    throw new IllegalStateException(...);
});


text:
Q: How to calculate available space in a Teradata database I want to report on various statistics on a specific Teradata database, particularly "free space".  Should table skew be included in the calculation?  For example, someone suggested the following query:
SELECT databasename
     , SUM(maxperm)/1024/1024/1024 (DECIMAL(10,2))     AS space_allocated
     , SUM(currentperm)/1024/1024/1024 (DECIMAL(10,2)) AS space_Used
     , (MAX(currentperm)*COUNT(*)-SUM(currentperm))
        /1024/1024/1024 (DECIMAL(10, 2)) AS skew_Size

     , (space_used + skew_size) AS total_space_used

     , (MIN(maxperm-currentperm)/1024/1024/1024) * COUNT(*) (DECIMAL(10,2))
        AS free_Space

     ,  CAST(total_space_used AS DECIMAL(10,2)) * 100
      / CAST(space_allocated AS DECIMAL(10,2)) AS pct_used

FROM   DBC.diskspace
WHERE  databasename = 'MyDatabase'
   AND maxperm > 0
GROUP   BY 1;

I'm particularly curious about the calculation of total_space_used and pct_used.  Is it "proper" to account for skewed tables like this?

A: Definitely keep skewing into account. Your column free_space gives you exactly the free space with skewing of all existing tables considered.
Also the free_space assumes that all future tables are perfectly distributed. Without skewing.


text:
Q: Trying to launch a new FXML file in javaFX using a method call I am trying to call another fxml page using a method but getting the error below.

java.lang.IllegalStateException: Not on FX application thread;
  currentThread = AWT-EventQueue-0  at
  com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236) at
  com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236)     at
  com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
    at javafx.stage.Stage.(Stage.java:241)    at
  javafx.stage.Stage.(Stage.java:227)     at
  thebio.MainController.StudentRegistration(MainController.java:134)

The method below is the one i used in carrying out this event, i don't know where i am getting it wrong please, and any assistance will definitely be well appreciated.
public void StudentRegistration(){
    try {
        Platform.setImplicitExit(false);
        Parent root1;
        root1 = FXMLLoader.load(getClass().getResource("Student.fxml"));
        Stage stage = new Stage();
        stage.setTitle("ABC");
        stage.setScene(new Scene(root1));
        stage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Thanks.

A: Use Platform#runLater to update the GUI from a non-GUI thread.
Platform.runLater(()->{
    Parent root1;
    root1 = FXMLLoader.load(getClass().getResource("Student.fxml"));
    Stage stage = new Stage();
    stage.setTitle("ABC");
    stage.setScene(new Scene(root1));
    stage.show();
});


text:
Q: Is possible change priority to task create_snapshot from NORMAL to HIGH or URGENT? I has a cluster elasticsearch with 6 data nodes and 3 master.
When execute the snapshot I receive the error "process_cluster_event_timeout_exception".
I look in my cluster "/_cat/pending_tasks" it has 69 tasks with priority HIGH and source put-mapping
My cluster is for centralized log and have this process to put data in cluster:

*

*logstash - collect from Redis and put to Elasticsearch

*apm-server

*filebeat

*metricbeat

I stay removing beats and some applications from apm-server
Is possible change priority to task create_snapshot from NORMAL to HIGH or URGENT?
It is not a solution, how to I check the correct size for my cluster?
*Normally i keep 7 days the indice in my cluster because the backup.
But because the error, I removed the process to exclude the old data
GET _cat/nodes?v&s=node.role:desc

ip
heap.percent
ram.percent
cpu
load_1m
load_5m
load_15m
node.role
master
name

10.0.2.8
47
50
0
0.00
0.00
0.00
mi
-
prd-elasticsearch-i-020

10.0.0.7
14
50
0
0.00
0.00
0.00
mi
-
prd-elasticsearch-i-0ab

10.0.1.1
47
77
29
1.47
1.72
1.66
mi
*
prd-elasticsearch-i-0e2

10.0.2.7
58
95
19
8.04
8.62
8.79
d
-
prd-elasticsearch-i-0b4

10.0.2.4
59
97
20
8.22
8.71
8.76
d
-
prd-elasticsearch-i-00d

10.0.1.6
62
94
38
11.42
8.87
8.89
d
-
prd-elasticsearch-i-0ff

10.0.0.6
67
97
25
8.97
10.45
10.47
d
-
prd-elasticsearch-i-01a

10.0.0.9
57
98
32
11.63
9.64
9.17
d
-
prd-elasticsearch-i-005

10.0.1.0
62
96
19
10.45
9.53
9.31
d
-
prd-elasticsearch-i-088

My cluster definitions:
    {
      "_nodes": {
        "total": 9,
        "successful": 9,
        "failed": 0
      },
      "cluster_name": "prd-elasticsearch",
      "cluster_uuid": "xxxx",
      "timestamp": 1607609607018,
      "status": "green",
      "indices": {
        "count": 895,
        "shards": {
          "total": 14006,
          "primaries": 4700,
          "replication": 1.98,
          "index": {
            "shards": {
              "min": 2,
              "max": 18,
              "avg": 15.649162011173184
            },
            "primaries": {
              "min": 1,
              "max": 6,
              "avg": 5.251396648044692
            },
            "replication": {
              "min": 1,
              "max": 2,
              "avg": 1.9787709497206705
            }
          }
        },
        "docs": {
          "count": 14896803950,
          "deleted": 843126
        },
        "store": {
          "size_in_bytes": 16778620001453
        },
        "fielddata": {
          "memory_size_in_bytes": 4790672272,
          "evictions": 0
        },
        "query_cache": {
          "memory_size_in_bytes": 7689832903,
          "total_count": 2033762560,
          "hit_count": 53751516,
          "miss_count": 1980011044,
          "cache_size": 4087727,
          "cache_count": 11319866,
          "evictions": 7232139
        },
        "completion": {
          "size_in_bytes": 0
        },
        "segments": {
          "count": 155344,
          "memory_in_bytes": 39094918196,
          "terms_memory_in_bytes": 31533157295,
          "stored_fields_memory_in_bytes": 5574613712,
          "term_vectors_memory_in_bytes": 0,
          "norms_memory_in_bytes": 449973760,
          "points_memory_in_bytes": 886771949,
          "doc_values_memory_in_bytes": 650401480,
          "index_writer_memory_in_bytes": 905283962,
          "version_map_memory_in_bytes": 1173400,
          "fixed_bit_set_memory_in_bytes": 12580800,
          "max_unsafe_auto_id_timestamp": 1607606224903,
          "file_sizes": {}
        }
      },
      "nodes": {
        "count": {
          "total": 9,
          "data": 6,
          "coordinating_only": 0,
          "master": 3,
          "ingest": 3
        },
        "versions": [
          "6.8.1"
        ],
        "os": {
          "available_processors": 108,
          "allocated_processors": 108,
          "names": [
            {
              "name": "Linux",
              "count": 9
            }
          ],
          "pretty_names": [
            {
              "pretty_name": "CentOS Linux 7 (Core)",
              "count": 9
            }
          ],
          "mem": {
            "total_in_bytes": 821975162880,
            "free_in_bytes": 50684043264,
            "used_in_bytes": 771291119616,
            "free_percent": 6,
            "used_percent": 94
          }
        },
        "process": {
          "cpu": {
            "percent": 349
          },
          "open_file_descriptors": {
            "min": 429,
            "max": 9996,
            "avg": 6607
          }
        },
        "jvm": {
          "max_uptime_in_millis": 43603531934,
          "versions": [
            {
              "version": "1.8.0_222",
              "vm_name": "OpenJDK 64-Bit Server VM",
              "vm_version": "25.222-b10",
              "vm_vendor": "Oracle Corporation",
              "count": 9
            }
          ],
          "mem": {
            "heap_used_in_bytes": 137629451248,
            "heap_max_in_bytes": 205373571072
          },
          "threads": 1941
        },
        "fs": {
          "total_in_bytes": 45245361229824,
          "free_in_bytes": 28231010959360,
          "available_in_bytes": 28231011147776
        },
        "plugins": [
          {
            "name": "repository-s3",
            "version": "6.8.1",
            "elasticsearch_version": "6.8.1",
            "java_version": "1.8",
            "description": "The S3 repository plugin adds S3 repositories",
            "classname": "org.elasticsearch.repositories.s3.S3RepositoryPlugin",
            "extended_plugins": [],
            "has_native_controller": false
          }
        ],
        "network_types": {
          "transport_types": {
            "security4": 9
          },
          "http_types": {
            "security4": 9
          }
        }
      }
    }

Data Nodes: 6 instances r4.4xlarge
Master Nodes: 3 instances m5.large

A: No It is not possible to change priority of task create_snapshot.
As you have 69 pending tasks, it seems you are doing too many mapping updates.
Regarding correct size of cluster, I would recommend you to go through following blog posts :

*

*https://www.elastic.co/blog/found-sizing-elasticsearch

*https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/sizing-domains.html


text:
Q: Sklearn train_test_split() equivalent in pyspark This is the Sklearn version function to split data
sklearn.model_selection.train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)

I need the Sklearn train_test_split() equivalent in PySpark which can be given arguments to stratify on the target, has option whether to shuffle the data or not and things like that.
The train_test_split() is a fantastic handy function and it would be best to have its closest possible implementation.
randomSplit() function doesn't match.

A: I found a solution to the stratification problem in Pyspark data splitting function.
Stratified sampling in pyspark can be achieved by using sampleBy, lets say the column on which you want to stratify the sample is "colname" sampled = df.sampleBy("colname", fractions={4: 0.2, 6: 0.4, 8: 0.2}, seed=0)
Also did a little search and found out that it is without replacement.
https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.DataFrame.sampleBy.html


text:
Q: How can I get a partial response for Method: instances.aggregatedList Compute API in GCP I am trying to get specific response from Compute API method instances.aggregatedList by setting the fields request param as per https://cloud.google.com/resource-manager/docs/performance#partial-response
But I am getting 400 BAD REQUEST.
Is there a sample which I can refer for getting partial response for aggregated methods?

A: If you use the following CURL command:
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) "https://compute.googleapis.com/compute/v1/projects/[CHANGE-FOR-YOUR-PROJECT-ID]/aggregated/instances?maxResults=1"

You'll notice that the result will have a similar form to:
{
  "id": "projects/[PROJECT-ID]/aggregated/instances",
  "items": {
    "zones/us-central1-a": {
      "instances": [
        {
          "id": "[INSTANCE-ID]",
          "creationTimestamp": "2020-09-21T06:22:21.604-07:00",
          "name": "instance-1",
          "description": "",
          "tags": {
            "items": [
              "http-server",
              "https-server"
            ],
            "fingerprint": "XXXXXX"
          },
          "machineType": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/zones/us-central1-a/machineTypes/e2-medium",
          "status": "RUNNING",
          "zone": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/zones/us-central1-a",
          "canIpForward": false,
          "networkInterfaces": [
            {
              "network": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/global/networks/default",
              "subnetwork": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/regions/us-central1/subnetworks/[SUBNETWORK_NAME]",
              "networkIP": "10.8.0.13",
              "name": "nic0",
              ... with a lot more fields

As you can see the result is a little bit different as the response body explained in the documentation:
{
  "id": string,
  "items": [
    {
      "scopeName": string,
      "instances": [
        {
          "id": string,
          "creationTimestamp": string,
          "name": string,
          "description": string,
          "tags": {
            "items": [
              string
            ],
            "fingerprint": string
          },
          "machineType": string,
          "status": enum,
          "statusMessage": string,
          "zone": string,
          "canIpForward": boolean,
          "networkInterfaces": [
            {
              "network": string,
              "subnetwork": string,
              "networkIP": string,
              "ipv6Address": string,
              "name": string,
              .... with a lot more fields

Notice that if you compare both results, the actual response that you receive has an additional "zones/us-central1-a": field before the instances: field that I believe is causing the behavior you experience.
If you are interested in working with partial resources and get only some particular fields on the response you simply need to respect the syntax rules explained on the documentation you've shared and use the escape characters accordingly on your query parameters.
E.g. if you are only interested in getting the id of your project as well as the instances' name, machineType and status I tested the following curl command from the Cloud Shell with my GCP project and it worked without issues:
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) "https://compute.googleapis.com/compute/v1/projects/[PROJECT-ID]/aggregated/instances?fields=id,items/zones%2Finstances(name,machineType,status)"

where I see that something similar to the following is returned:
{
  "id": "projects/[PROJECT-ID]/aggregated/instances",
  "items": {
    "zones/us-central1-a": {
      "instances": [
        {
          "name": "instance-1",
          "machineType": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/zones/us-central1-a/machineTypes/e2-medium",
          "status": "RUNNING"
        },
        {
          "name": "instance-2",
          "machineType": "https://www.googleapis.com/compute/v1/projects/[PROJECT-ID]/zones/us-central1-a/machineTypes/e2-medium",
          "status": "TERMINATED"
        }
      ]
    }
  }
}


text:
Q: How many ways are there to select a pair of cards from a standard deck of cards such that one of the cards is red and the other one is black? Suppose that a pair of cards are selected from a standard deck of 52 cards. And since there are 26 black cards and 26 red cards, so I'm wondering if my thinking is right?
${26!/25! * 26!/25!}$ so it would be ${26*26 = 676}$

A: As @TonyK highlighted in the comment, there is another (and I would argue, more natural) interpretation of the question - where the order of draw matters.
Pick the first card - its colour doesn't matter. There are $52$ cards in the deck, so $52$ ways to do this. Then you're restricted to the other colour for the second pick, and there are $26$ such cards, giving you $26$ ways to pick the second card. Hence the number of ways in total is $(52)(26) = 1352$.
If the order of the hand (of two cards) that you've picked doesn't matter - for example, if you having picked the seven of hearts and then the ace of spades is considered the same pick as the ace of spades first then the seven of hearts, then you need to divide the possibilities by $2! = 2$ (to remove the extra possibilities from permuting the two cards in your hand). So the answer is $\frac 12 (52)(26) = 26^2 = 676$, as you originally calculated.
If you want to be complete, you can give both answers with an explanation, and I would do this with an open-ended answer, but if had to choose one interpretation, it would be the former and the answer would be $1352$.
By the way, your computation was a little obscure because you didn't explain why you multiplied such and such factorial and divided this and that factorial. This is a common failing in students who just apply formulae blindly, and that leads them to think combinatorics is harder than it really is. It's actually more productive to try to parse the problem with basic common sense and only then apply the math that you need. I'm sure you'll agree the above is easier to understand and explain to others.


text:
Q: To count X of imgs, create n°X of divs and append imgs to divs created Morning guys,
i've a problem with divs and imgs..
so, i've, for example, a number X of imgs into a div (in this case, #content_project), now i want create number X (from number of imgs) of div (in this case, #content), append it one by one (each) of the previously called img, append all of this created (#content) into #contenitore_project and, the end, remove the old img from div #content_project.
so, this is the before code:

and i want to happen this with jquery:

i hope that you've understand.
Frank

A: Here's a one-liner:
$('#content_project img').unwrap().wrap('
').parent().appendTo('#contenitore_project');

*

*$('#content_project img') selects your image tags.

*.unwrap() gets rid of their parent  tags.

*.wrap() wraps each one with its own
 element.

*.parent() selects the
, not the  tag.

*.appendTo('#contenitore_project') moves them all to that other element.

Demo: http://jsfiddle.net/QyYeX/


text:
Q: How do I select the first object in an array of Objects If I log an array to the console with console.log(array) it looks like this:
[]
0: {Entry: '1', 0006332: '000593-1', OLDRS: '16.91', RANK: '1', RS: '100', …}
1: {Entry: '1', 0006332: '000605-1', OLDRS: '16.91', RANK: '1', RS: '100', …}
2: {Entry: '1', 0006332: '000641-1', OLDRS: '20.87', RANK: '1', RS: '100', …}
3: {Entry: '1', 0006332: '0000643-1', OLDRS: '15.91', RANK: '1', RS: '100', …}
4: {Entry: '1', 0006332: '0000608-1', OLDRS: '1.00', RANK: '1', RS: '100', …}
5: {Entry: '1', 0006332: '0004463-1', OLDRS: '1.02', RANK: '1', RS: '100', …}
6: {Entry: '1', 0006332: '0004466-1', OLDRS: '1.02', RANK: '1', RS: '100', …}
7: {Entry: '1', 0006332: '000627-1', OLDRS: '13.27', RANK: '1', RS: '100', …}
length: 8
[[Prototype]]: Array(0)

Looks like and array of objects to me. If I try to select the first object, with console.log(array[0]) the output is undefined
What am I doing wrong and how can I select the first ojbect of the array above?


text:
Q: How can I get the path to the current target directory in my build.sbt In my build.sbt I want to know the current target file. Something like this:
val targetFile = ??? // /home/fbaierl/Repos/kcc/scala/com.github.fbaierl/target/scala-2.12/myapplication_2.12-1.2.3-SNAPSHOT.jar

With target.value I only get the directory up until /target. Is there any way to get the full path to the resulting jar?

A: What you need is the return value of compile:package.
Run sbt "show compile:package" to see that it prints full path to the artifact you are building.
If you just need the path without building the artifact, do sbt "show Compile / packageBin / artifactPath"
In order to use this value in build.sbt, you have to define a task or setting like this
val targetFile = taskKey[File]("shows target file")

targetFile := {
  val path = artifactPath.in(packageBin).in(Compile).value
  //same as val path = (Compile / packageBin / artifactPath).value
  streams.value.log.info(path.toPath.toString)
  path
}

A value of any task in sbt cannot be directly assigned to a val like val someFile: File. You have to write your custom logic in terms of settings and tasks.

A: In most recent 1.x style, it should be something like
  val targetFile: File = (Compile / packageBin / artifactPath).value


text:
Q: how to write aggregate conditional SQL query to get individual column counts and total counts by passing date arguments I did some thing like this:
with q1 as
(
  select x, count(*) as A from T1 where .. condition group by x
 ),
q2 as ( select x, count(*) AS B  from T2 where .. condition group by x),
q3 as ( select x, count(*) AS C from T3 where .. condition group by x),
Q4 AS ( select x, count(*) AS D from T4 where .. condition group by x)

SELECT Q1.X, Q1.A, Q2.B, Q3.C, Q4.D FROM Q1,Q2,Q3,Q4

I only get blank results.. also i'm passing date as input arguments for each select.
column x exists in 4 different tables. All i have to do is show the count of x from each table for a particular date range.

A: You can use union all and then conditional aggregation as following:
Select x,
       Coalesce(sum(case when tab ='Q1' then cnt end),0) As a,
       Coalesce(Sum(case when tab ='Q2' then cnt end),0) As b,
       Coalesce(Sum(case when tab ='Q3' then cnt end),0) As c,
       Coalesce(Sum(case when tab ='Q4' then cnt end),0) As d
From
     (Select 'Q1' as tab, x, count(*) cnt from t1 Where ... group by x
      Union all
      Select 'Q2' as tab, x, count(*) from t2 Where ... group by x
      Union all
      Select 'Q3' as tab, x, count(*) from t3 Where ... group by x
      Union all
      Select 'Q4' as tab, x, count(*) from t4  Where ... group by x)
Group by x;

Cheers!!

A: Conditional Aggregation can be used through JOIN Clauses by x columns which are common in name :
select t1.x,
       count(case when t1.y=1 then 1 end ) as A,
       count(case when t2.z=0 then 1 end ) as B,
       count(case when t3.a=0 then 1 end ) as C,
       count(case when t4.b=0 then 1 end ) as D
  from t1
  join t2 on t2.x = t1.x
  join t3 on t3.x = t1.x
  join t4 on t4.x = t1.x
 group by t1.x

Conditions in WHERE Clauses are assumed to be t1.y=1, t2.z, t3.a, t4.b respectively.


text:
Q: How to convert php template to Timber (Wordpress) I'm fine creating a brand new Timber template, but I need to override a plugin template (MEC Events) - the plugin support give help with that but its in php, which works and brings in the header and footer from my base twig template, but doesn't include the post.thumbnail and post.title on those which it should.
In any case I'd like to keep the whole site in Timber/Twig ideally, but don't have a clue where to start turning this into a Timber template. Here's the php template, any help greatly appreciated:
<?php
/**
 * The Template for displaying all single events
 */

get_header();

$single = new MEC_skin_single();
$single_event_main = $single->get_event_mec(get_the_ID());
$single_event_obj = $single_event_main[0];

// Date Widget
$single->display_date_widget($single_event_obj);
// Time Widget
$single->display_time_widget($single_event_obj);
// Location Widget
$single->display_location_widget($single_event_obj); // Show Location
// Label Widget
$single->display_label_widget($single_event_obj);
// Export Widget
$single->display_export_widget($single_event_obj);
//Social
$single->display_social_widget($single_event_obj);

get_footer();

A: I'm not familiar with the MEC events calendar, but from looking at your code snippet, I think you could make it work, at least to a certain level.
You have these three lines, that kind of prepare the data that should be displayed in a template.
$single = new MEC_skin_single();
$single_event_main = $single->get_event_mec(get_the_ID());
$single_event_obj = $single_event_main[0];

With Timber and Twig, you'll want to prepare your data in PHP and then pass it to your Twig template. Here's how I would do it.
<?php

$context = Timber::get_context();

$single            = new MEC_skin_single();
$single_event_main = $single->get_event_mec( get_the_ID() );

$context = array_merge( $context, [
    'single'           => $single,
    'single_event_obj' => $single_event_main[0],
] );

Timber::render( 'single-event.twig', $context );

single-event.twig
{% extends 'base.twig' %}

{% block content %}

    {# Date Widget #}
    {{ single.display_date_widget(single_event_obj) }}

    {# Time Widget #}
    {{ single.display_time_widget(single_event_obj) }}

    {# Location Widget #}
    {{ single.display_location_widget(single_event_obj) }}

    {# Label Widget #}
    {{ single.display_label_widget(single_event_obj) }}

    {# Export Widget #}
    {{ single.display_export_widget(single_event_obj) }}

    {# Social #}
    {{ single.display_social_widget(single_event_obj) }}

{% endblock }

In Timber, you usually have a base template that you extend. And in that base template, you define blocks where your content is going to be placed in. That's what the {% extend %} and {% block %} tags are for. With this, you can get rid of get_header() and get_footer().
Because $single is an object with display_*_widget() methods, we can access that function through the dot notation. The methods need a $single_event_obj as a parameter, so we make sure this variable is also passed to the template data.
In case you now need access to post.thumbnail and post.title, you can also prepare a post variable in your PHP template:
<?php

$context = Timber::get_context();

$single            = new MEC_skin_single();
$single_event_main = $single->get_event_mec( get_the_ID() );

$context = array_merge( $context, [
    'post'             => Timber::get_post(),
    'single'           => $single,
    'single_event_obj' => $single_event_main[0],
] );

Timber::render( 'single-event.twig', $context );


text:
Q: Instance variable changed when calling a method in Python I have problem with understanding what happens with the instance variable in the following case:
class Permutation:
    def __init__(self,cycles):
        self.cycles=cycles

    def inverse(self):
        c=self.cycles
        for i in c:
            r=math.ceil(len(i)/2)
            for j in range(r):
                i[j],i[-(j+1)]=i[-(j+1)],i[j]
        return c

p = Permutation([[1,5,2],[3, 7]])
print(p.cycles)
p.inverse()
print(p.cycles)

output:
>>>
[[1, 5, 2], [3, 7]]
[[2, 5, 1], [7, 3]]

I have a class named Permutation with instance variable cycles. When I want to calculate the inverse of the permutation, I define new variable c, which should be the same as self.cycles and then I calculate the inverse of variable c. When I create an instance p=Permutation(...) and call p.inverse(), p.cycles actually changes and I'm not sure why.
Could someone please explain what is happening with variable cycles?
Thank you!


text:
Q: Partial derivative of a complex number Given $n=(x + iy)/\sqrt{2}L$ and $\overline n=(x - iy)/\sqrt{2}L$.
$\partial_n=\partial/\partial n$, $\partial_x=\partial/\partial x$, $\partial_y=\partial/\partial y$
Show that $\partial_n$ = $L(\partial_x - i \partial_y)/\sqrt{2}$  and  $\partial_\overline n$ = $L(\partial_x + i \partial_y)/\sqrt{2}$.
I'm not sure on how to start proving these but should I use the definition for the Wirtinger derivatives?

If ever I use that, how can $\sqrt2 L$ be in the numberator? Any suggestions?

A: You do not need the Wirtinger derivatives, but do know that the Wirtinger derivatives are derived the same way when we do not have the $\sqrt{2}L$ factor present. Anyways, notice that we can redefine $x$ and $y$ in terms of $n$ and $\bar{n}$:
$$x(n,\bar{n}) = \frac{L}{\sqrt{2}}(n + \bar{n})$$
$$y(n,\bar{n}) = \frac{L}{\sqrt{2}i}(n - \bar{n})$$
We are going to need the partial derivatives:
$$\partial_nx = \frac{L}{\sqrt{2}}, \hspace{.5cm} \partial_\bar{n}x = \frac{L}{\sqrt{2}}$$
$$\partial_ny = -\frac{iL}{\sqrt{2}}, \hspace{.5cm} \partial_\bar{n}y = \frac{iL}{\sqrt{2}}$$
Now take any function in terms of $x$ and $y$ and parametrize it:
$$f(x,y) = f(x(n,\bar{n}),y(n,\bar{n}))$$
and find the derivatives using the chain rule:
$$\partial_nf = \partial_xf \partial_nx + \partial_yf \partial_ny = \frac{L}{\sqrt{2}}\partial_xf - i\frac{L}{\sqrt{2}}\partial_yf = \frac{L}{\sqrt{2}}(\partial_x - i\partial_y)f$$
$$\partial_\bar{n}f = \partial_xf \partial_\bar{n}x + \partial_yf \partial_\bar{n}y = \frac{L}{\sqrt{2}}\partial_xf + i\frac{L}{\sqrt{2}}\partial_yf = \frac{L}{\sqrt{2}}(\partial_x + i\partial_y)f$$
The last step is to notice that we are operating on the same scalar function on both sides. Therefore, the operators acting on both sides must be equivalent giving the desired result:
$$\partial_n = \frac{L}{\sqrt{2}}(\partial_x - i\partial_y)$$
$$\partial_\bar{n} = \frac{L}{\sqrt{2}}(\partial_x + i\partial_y)$$


text:
Q: any generalized functions for fadeIn fadeOut? Jquery:
$(document).ready(function () {
    $('#myfirstDiv').click(function () {
        $('#seconDiv').fadeIn("fast");
    });
    $('#closeBtn').click(function () {
        $('#seconDiv').fadeOut("fast");
    });
});

there is multiple usage of these functions in my site, with different ids for Div and Buttons.
How could I generalize these functions for every Div and Button?

A: *

*Define a class for the button div

*Define a class for the fading div

*Create a custom attribute data-target in the div button

*Create a custom attribute data-action in the div button

*Have your jQuery look for all button div elements (select by class) and link them to their targets, according to their actions (show/fadeIn or hide/fadeOut)

This way, no matter how many buttons or divs, your jQuery will "automagically" link them, if they are correctly set.
Sorry, no code for now, but this approach works.
Update
Some links to help you achieve this approach:

*

*Jquery custom attributes

*jQuery's class selector

*jQuery's bind

A: Here's a plugin that takes in the second div and the button to close it:
(function($) {
    $.fn.extend({
        FadeInOut: function(divTwo, closeBtn) {
            return this.each(function() {
                $(this).click(function() {
                    $(divTwo).fadeIn("fast");
                });
                $(closeBtn).click(function() {
                    $(divTwo).fadeOut("fast");
                });
            });
        }
    });
})(jQuery);

DEMO

A: i have found a solution to generalize these fadeIn and fadeOut functions.
you can see this Example

may be it would help any other.


text:
Q: Form based and Certificate based authentication in Spring Framework / Spring Security is it possible in spring framework to have 2 login implementation at the same time for the login page? Form login and Certificate based login (x509). I've tried either one of these method but combining them at the same time, it is hard for me to do it. Any idea how to enable these two methods? Any book or site reference that I can refer to regarding this?
Thanks

A: Yes, it is possible, by making the SSL client-auth optional.
Here on Baeldung is a good tutorial on enabling SSL client authentication with X.509 certificates, with forced client-auth (not good for your case, with login form fallback)
Follow that tutorial and pay attention in the application.properties file to make the client-auth want instead of need. This will make the client-server SSL handshake attempt to ask for a certificate.
server.ssl.client-auth=want

*

*If the browser does not provide a certificate (does not have any configured or the user clicks on cancel when prompted to select a certificate from a list), the SSL handshake will be done without the client certificate, and the user will have to login with username+password

*If the user chooses a certificate, the SSL handshake is done with the client certificate. The server then verifies the given certificate in the trust-store. If the certificate is valid, the SSL handshake is successfully established. Otherwise, the connection is refused by the server.

Pay attention that

*

*only the authentication is done with the x.509 certificate. For authorization, you must provide the X509Configurer an UserDetailsService implementation, to retrieve the UserDetails for the user that just authenticated via x.509

*thus, if you have a database of users with their assigned roles, even if the certificate is in the trust-store, the user might not be in the user database, so you will have to treat this possibility in your application logic. I.e. when the SSL connection is mutual, but the user is not present in the user database.

A: Yes it is possible. All you need is to declare x509 support in your http config:
<http ...>
    ...
    <x509 ... />
    ....
</http>

and configure SSL in Tomcat.
See this entry and this thread.


text:
Q: replacing 6000+ strings in >2GB text file I'd like to search and replace more than 6000 strings in a > 2GB text file.
sed -i "s/search/replace/g" 2gbfile.log

is taking forever. Especially if you have to do it 6000+ times.
So I came up with a script that splits the 2 GB file into chunks so that I can parallelize the effort. I'm running 48 processes simultaneously (64 cores available), but still, it's taking rather long.
#!/usr/bin/env bash

echo "sorting..."
sort bigbigbigfile | awk -F, '{print $2,$1,$3}' > bigbigbigfile.work

CPUS=$(( $(lscpu |grep "On-line CPU(s) list"|grep -Eo '0-[0-9]+'|cut -f2 -d-) + 1))
CPUSUSABLE=$(echo "$CPUS*0.75" | bc | cut -f1 -d.)
NUMLINES=$(cat all-temperatures.sort | wc -l)
SPLIT=$(echo "$NUMLINES / $CPUSUSABLE" | bc | cut -f1 -d.)
echo "cutting..."
split -l $SPLIT bigbigbigfile.work chunkstoworkwith

mapfile -t REPLACEME < replace.list

echo "seding..."
for chunk in $(ls chunkstoworkwith*); do
        (
        for i in "${!REPLACEME[@]}"; do
                counter=$(( counter + 1 ))
                sed -i "s/ ${REPLACEME[$i]} / $counter /g" $chunk
        done
        ) &
done

This works. But I think it could be even faster when I search and replace in memory, rather than having sed replacing in-place and doing 6000+ replaces in 48 files. This sums up to almost 300k sed calls, which results in a lot of file opening/closing/writing/whatever.
Any idea on how to speed this up and do the replacements in memory and flushing out the data after everything has been changed?

A: Your script is parsing the entire chunk for every single replacement!
Meaning that for every chunk, the script opens, goes through all lines, possibly perform 1 replacement, closes the file and moves it the original file (due to the -i option).
Provided you want to replace the pattern with a counting number, here is a way to perform all replacements at once for every chunks:
sed -f <(awk '{print "s/ "$1" / "++c" /"}' replace.list) -i "$chunk"

The -f option allows to take a sed script as input and will be executed at once for all lines of the $chunk file.
This will likely reduce the overall timing...

A: I'm not entirely sure why your sed is going so slow, you would probably have to debug or watch it closer to really find out, but if it is trying to write 6,000 times and that's slowing it down, you could skip the -i and just have sed write the whole (changed) file out once:
sed "s/search/replace/g" 2gbfile.log > 2bgfile-AfterSed.log


text:
Q: Find external window Title I got this code:
using System.Runtime.InteropServices;

[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);
[DllImport("User32")]
private static extern int ShowWindow(int hWnd, int nCmdShow);
private const int SW_HIDE = 0;

int hWnd = FindWindow(null, Microsoft Excel - Book1);
if (hWnd > 0)
{
    ShowWindow(hWnd, SW_HIDE);
}

But sometimes im oppening Book1 with OpenOffice.org.. and my question is, how can i SW_HIDE different windows titles?
If Microsoft Excel - Book1 title exists
If Book1 - OpenOffice.org Calc title exists
Maybe it is possible to find windows title part "Book1"
Thank you very much!

A: Use the below code to get the list of all opened windows.
[DllImport("user32.dll")]
        static extern bool EnumWindows(EnumDelegate lpfn, IntPtr lParam);

then write the delegate function as below:
public string[] win_List = new string[50];
int i = 0;
public bool lpfn(IntPtr hWnd, int lParam)
{
    StringBuilder stbrTitle = new StringBuilder(255);
    int titleLength = GetWindowText(hWnd, stbrTitle, stbrTitle.Capacity + 1);
    string strTitle = stbrTitle.ToString();
    if (IsWindowVisible(hWnd) && string.IsNullOrEmpty(strTitle) == false)
    {
        win_List[i++] = strTitle;
    }
    return true;
}

public string[] GetWinList()
{
    EnumDelegate del_fun = new EnumDelegate(lpfn);
    EnumWindows(del_fun, IntPtr.Zero);
    return win_List;
}


text:
Q: Valgrind on FreeBSD Good day!
I'm playing around one C project. It is located on FreeBSD machine (it looks like Raspberry PI2, not sure)

The problem is I want to run project in Valgrind to find memory leakage. When I try to install Valgrind through ports, I get next error:
root@raspberry-2-55:/usr/ports/devel/valgrind # make
===>  valgrind-3.10.1.20160113,1 is only for i386 amd64, while you are running
armv6.
*** Error code 1

Stop.
make: stopped in /usr/ports/devel/valgrind

Please help to run valgrind on this platform.

A: The combination ARM6/FreeBSD is not supported.
Valgrind fully supports FreeBSD i386 and amd64. You can find information on the ports here FreeBSD stable port and here FreeBSD development port.
At a guess, Valgrind support for ARM won't be implemented until and if ARM becomes a Tier 1 platform or until someone steps forward to do the porting.
See also the Valgrind team's statement on porting:

Maintaining each port takes a lot of effort, more so than for most other programs. Valgrind is fragile due to the low-level nature of what it does. Also, each platform port has CPU-specific code, OS-specific code and platform-specific code, and testing all the combinations is difficult.

Update:
On FreeBSD you can use the very powerful dtrace tool for performance monitoring and debugging. It does have a steep learning curve, though.
My favorite debugging tool is still placing printf() in strategic locations. Say you suspect your program crashes in a large block of code. Place a printf in the middle, recompile and re-run. If you see the output, the error came after the printf. If you don't it was before the printf. You have now halved the size of the block containing the error. Now add another printf in the middle of the remaining suspicious code and repeat. This technique is called bisection. You can also use it to monitor the value of a variable.
I would suggest to wrap the debugging printf in a macro ([1], [2]), so you can leave them in the code but you can disable them for a release build.


text:
Q: Clojure : Documentation syntax, regarding when-let and if-let I've been looking at the if-let and when-let macros, Im having trouble determining what exactly it is that they "do".  In particular, the documentation sais :
clojure.core/when-let
([bindings & body])
Macro
  bindings => binding-form test

  When test is true, evaluates body with binding-form bound to the value of test

I thus am somewhat confused about the way macros are documented.
1) What does the "=>" symbol mean ?
2) What does "test" refer to ?

A: Direct answer to your questions:

*

*=> means "expands to", as in BNF notation. In this case it means that you need two forms: binding-form and the test.

*"test" means anything that can be evaluated as bool.

By the way, I  think that the docs are unclear or even maybe erroneous here. It is hard (or impossible) to deduce that the two forms constituting the bindings need to be enclosed in a vector. IMHO it should be either when-let ([[bindings] & body]) (the vector shown in the args) or bindings => [binding-form test] (the vector shown in the BNF-like expansion.)

A: It's often helpful when dealing with a macro to call macroexpand and see what the generated code is.
(macroexpand
    '(if-let [x (myfunc)]
       (foo x)
       (bar))

; expands to

(let* [temp__3695__auto__ (myfunc)]
   (if temp__3695__auto__ (clojure.core/let [x temp__3695__auto__]
     (foo x))
     (bar)))

; the generated symbols are necessary to avoid symbol
; capture but can confuse. The above is equivalent to:

(let* [ t (myfunc)]
    (if t
       (let [x t]
           (foo x))
       (bar))

So you can see that if-let is a shorthand for "bind local variable to the result of a function call and if that variable is truthy call the first form, else call the other form. The value returned by your function is only available in the 'truthy' branch."
wrt documentation convention
bindings => binding-form test

*

*=> reads something like 'is equivalent to'

*test is some form that returns a value

For most of these functions, clojuredocs is your friend, example usage often clarify things. If the clojuredocs example doesn't cut it for you, you can add your own

A: Consider the following code:
(if-let [x (a-function)]
  (do-something-with x) ;; (a-function) returned a truthy result
  (do-something-else)   ;; (a-function) returned nil or false

This is like let, in that x will be bound to the return value of (a-function). This function could return nil or false. In that case, the implicit test fails and (do-something-else) will be evaluated. If x is not nil and not false, (do-something-with x) will be evaluated.
A scenario where this could be useful:
(if-let [user (find-logged-in-user)]
  (do something with logged in user) ;; a user was found
  (redirect to login page)           ;; no user was found

I sometimes use something like the following, to conditionally add keys to a map of options:
(apply merge {:username "joe"
              :email "joe@example.com"}
             (when-let [name (find-full-name)] {:name name})
             (when-let [dob (find-date-of-birth)] {:dob dob}))

This results in a map with :username and :email keys, and a :name key if the users' full name was found, plus a :dob key if a date of birth was found.
I hope that makes the use of if-let and when-let clearer.


text:
Q: Determining the length of a UTF-8 response in an ASP script I have a number of PHP scripts that I am trying to port to ASP. These scripts query a database, and display the results in UTF-8 format. This works fine for PHP, but ASP seems to have problems with UTF-8, and IIS seems to have problems with content length in general.
On the ASP side, there is no simple way to get the size of a UTF-8 string in bytes. ASP only deals with UTF-16 and bytes. Given that VBA code runs as VBScript rather than VB6, I cannot make any Windows API calls either.
On the IIS side, the response gets truncated if the content length is too small, and the scripts crash if it is too large. But of course if I can work out the correct length, that will not matter.
I should point out that all other aspects of UTF-8 are functioning correctly. The scripts display the correct response, it is just that they do not have the correct content length. If I use only ANSI data, and the Len function to get the length, all is well.
Care for some code? Very well, here is a simplified version of what I have so far:
<% @CodePage=65001 Language="VBScript"
Dim data

'   set data to correct UTF-16 value
Response.Clear
Response.AddHeader "Content-Type", "text/plain"
Response.AddHeader "Content-Length", CStr(Len(data))
Response.Write(data)
Response.Flush
%>

A: From RFC

The Content-Length entity-header field indicates the size of the
  entity-body, in decimal number of OCTETs, sent to the recipient or, in
  the case of the HEAD method, the size of the entity-body that would
  have been sent had the request been a GET.

Number of octets.
EDITED - To explain my point
Wrong. I was wrong. Well, more or less.
utf-8 or not, Content-Length only represents the number of octets (the term bytes has different meanings in different systems) in the wire. Period.
BUT, what i was not seeing is that you are not sending the pure utf-8 data, but leaving to the webserver/scripting engine do the conversion to the corresponding charset/codepage on data output.
How to handle it? If you are doing it the way your sample code shows, you can change your Len(Data) with utf8Len(Data) with the following function:
Function utf8Len( text )
    utf8Len = 0
    ' Only strings with data
    If VarType( text ) <> 8 Then Exit Function
    If Len( text ) < 1 Then Exit Function

    ' Create an ADODB.Stream object to handle charset conversion
    With (CreateObject("ADODB.Stream"))
        ' Define characteristics of the stream
        .Type = 2 '( adTypeText )
        .Charset = "utf-8"

        ' Put data into the stream
        .Open
        .WriteText text
        .Flush

        ' Get the length of the stream without BOM
        utf8Len = .Size - 3

        ' Close the stream
        .Close
    End With

End Function

For a .Net alternative this can be used
Function utf8Len( text )
    utf8Len = 0
    ' Only strings with data
    If VarType( text ) <> 8 Then Exit Function
    If Len( text ) < 1 Then Exit Function

    utf8Len = LenB(CreateObject("System.Text.UTF8Encoding").GetBytes_4(text))

End Function


text:
Q: How to avoid a blink when UIWebView loads HTML I have a native iOS app that contains a tab bar. The view controller for each tab contains a UIWebView. When the user switches between tabs, I load the HTML in the corresponding web view. The HTML is fully cached on a device. Here is how I feed the HTML to UIWebView:
[self.webView loadHTMLString:htmlString baseURL:baseUrl];

baseUrl is a file URL pointing to a directory where all assets are located.
This works great in online and offline modes, however it takes time for the UIWebView to parse and render the HTML. As a result, the user sees a brief blink of a white background when switching between tabs. I'd like to remove it, because the user is able to tell that the UI is not native (native UI renders instantly).
I was thinking about taking a screenshot of the UIWebView once it's done rendering the HTML and caching it in memory. The next time the user navigates to that web view, the app displays the screenshot while the UIWebView is rendering the HTML in the background. Finally, the app swaps the screen shot with the actual UIWebView and takes a new screenshot. This is similar to how Google Chrome app works.
Does anyone know a better solution to this problem?

A: Depends on how you present that web view. I'm not really sure from your description how you do it, but since you're talking about a blink of white background, I'm going to assume there is a situation where you have a web view with a loaded html and then you switch it to another html. The solution for that case would be:

*

*create a second web view,

*load the new html to this new web view,

*when that web view finishes loading html (you can find out if you use UIWebViewDelegate) you can then quickly switch it with your old web view (meaning you finally add the new web view to the view hierarchy at THIS point, not when you created it).

This way you'll have an instant switch between old and new html, however user will be left waiting and it is your decision what to do with it. You could use UIActivityIndicatorView for example.

A: When webViewDidFinishLoad: gets called you can do any number of things, make the webview visible, remove something that you had on top of the webview etc...