text:
Q: I cannot start an XAMLX workflow via IIS I am writing a WF 4 service.  I can run it out of Visual Studio 2013 just fine but when I try otherwise, (e.g. via a browser) I am getting

[XamlObjectWriterException: 'Cannot create unknown type '{......

The  type it cannot create is one from a second, deployed assembly.   The second assembly is mentioned in the namespace line in the .xamlx file and that assembly is deployed.  However, IIS still cannot find it.
I have tried many strategies to resolve this but nothing budges the problem.  So, how can I get the IIS XAMLX handler to discover a type in the non-default assembly?

Note:  I understand that this question is very much like
WF4 RC - Cannot create unknown type when loading WF Service from loose Xaml with ActivityXamlServices
but in that case, the assembly was not named in the namespace definition within .xamlx and the poser of the question was manually creating a WF instance.  In my case, the alternate assembly is named and deployed.   The WF instance is supposed to be created directly by the WF infrastructure which reads the xamlx file.

A: I have since discovered the problem: it was my own--a case-sensitivity problem in a namespace caused the other class to not be found.  Fixing the namespace casing fixed the issue.


text:
Q: character encoding when transforming special characters in JSON into CSV (excel) I am currently trying to populate a .csv file from a json using
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

i've read the default encoding they use is utf-8, some of my JSON has special characters, emoji, or chinese letters in it.. here's an example
[ { username: 'jung.y00n',
    name: '정 윤',
    bio:
     'ғʀᴇᴇʟᴀɴᴄᴇʀᴍᴏᴅᴇʟ\nᴄᴏɴᴛᴀᴄᴛ  ᴅᴍ 사적/공구 연락 확인 못해요\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n바이오리 슬림/브이 스틱 (10/14-16)',
    pic_url: 'C:/Users/Administrator/Downloadsjung.y00n.jpg' } ]

[ { username: 'yujing.lai',
    name: '勇闖美利堅的美少女 * Miss.Amber',
    bio:
     'San Francisco,California USA\nAcademy of Art UniversityMaster of Fine Arts\nNational Taiwan University of ArtBFA\n✈',
    pic_url: 'C:/Users/Administrator/Downloadsyujing.lai.jpg' } ]

[ { username: 'rky_thitiworada',
    name: 'ฐิติวรดา จังจริง',
    bio:
     'Thitiworada Janjring\nDJ.Rky\nI\'m interested in music,mixing,EDM,DJ   \n ติดต่องาน ☎ 097-0922200 \nติดต่องาน ID line➡  djrky  \n#msrk  @mashiimx',
    pic_url: 'C:/Users/Administrator/Downloadsrky_thitiworada.jpg' } ]

[ { username: 'mimisayhihi',
    name: '米恩綺Mimi',
    bio:
     'Taipei \n工作聯繫窗口\nKaren :karen@cclfilm.com \n方慈/judy@ cclfilm.com \n活動邀約/hihifish1128@gmail.com',
    pic_url: 'C:/Users/Administrator/Downloadsmimisayhihi.jpg' } ]

however after exporting the JSON to csv and open it in ms excel in windows it looked like this

Any idea on what i need to do to make this encoded and shown correctly ?

A: You can prepend a Byte order mark to the file to tell Excel to decode the characters correctly, this should do the trick:
const users = [ { username: 'jung.y00n',
    name: '정 윤',
    bio:
    'ғʀᴇᴇʟᴀɴᴄᴇʀᴍᴏᴅᴇʟ\nᴄᴏɴᴛᴀᴄᴛ  ᴅᴍ 사적/공구 연락 확인 못해요\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n바이오리 슬림/브이 스틱 (10/14-16)',
    pic_url: 'C:/Users/Administrator/Downloadsjung.y00n.jpg' }
,
{ username: 'yujing.lai',
    name: '勇闖美利堅的美少女 * Miss.Amber',
    bio:
    'San Francisco,California USA\nAcademy of Art UniversityMaster of Fine Arts\nNational Taiwan University of ArtBFA\n✈',
    pic_url: 'C:/Users/Administrator/Downloadsyujing.lai.jpg' }
,
{ username: 'rky_thitiworada',
    name: 'ฐิติวรดา จังจริง',
    bio: 'Thitiworada Janjring\nDJ.Rky\nI\'m interested in music,mixing,EDM,DJ   \n ติดต่องาน ☎ 097-0922200 \nติดต่องาน ID line➡  djrky  \n#msrk  @mashiimx',
    pic_url: 'C:/Users/Administrator/Downloadsrky_thitiworada.jpg' }
,
{ username: 'mimisayhihi',
    name: '米恩綺Mimi',
    bio:
    'Taipei \n工作聯繫窗口\nKaren :karen@cclfilm.com \n方慈/judy@ cclfilm.com \n活動邀約/hihifish1128@gmail.com',
    pic_url: 'C:/Users/Administrator/Downloadsmimisayhihi.jpg' }
];

const fs = require("fs");
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

const outputFile = "users.csv";
const csvWriter = createCsvWriter({
    path: outputFile,
    header: Object.keys(users[0]).map(key => { return {id: key, title: key} })
});

function prependBOM(file) {
    let fileContents = fs.readFileSync(file);
    fs.writeFileSync(file, "\ufeff" + fileContents);
}

async function writeCSV() {
    await csvWriter.writeRecords(users);
    // Prepend BOM to file so Excel will display characters correctly.
    prependBOM(outputFile);
}

writeCSV();

If you don't want to do this, you can import UTF-8 data manually into Excel:

*

*Start Excel.

*Import your csv data using Data->Import External Data->Import Data

*Select file type "csv", browse to your file and select it.

*In the import wizard change the File_Origin to "65001 (UTF-8)".

*You can then click "Transform data" to see your data.

*You can select close and load to create a new worksheet with your imported data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update multiple progress bar with gtk c++ I need to output the i progress bars and update them all. But only the last one updates i times. This is the code:
static void calculaPi (GtkButton * boton,  Datos * dDatos){
    const char * threads;
    GtkWidget * barra, *bot2, *button, *progress, *vbox;
    threads = gtk_entry_get_text(GTK_ENTRY(dDatos->dthreads ));
    gint ithreads  = 1;
    ithreads = atoi(threads);
    barra = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title((GtkWindow *) barra, "Loteria de Threads");
    gtk_window_set_default_size(GTK_WINDOW(barra), 300, ithreads*30);
    gtk_window_set_position(GTK_WINDOW(barra), GTK_WIN_POS_CENTER);
    button = gtk_button_new_with_label ("Click me!");
    vbox = gtk_vbox_new (FALSE, 5);
    gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 5);
    gtk_container_add (GTK_CONTAINER (barra), vbox);
    for (gint i = 1 ; i <=  ithreads; i++) {
       progress = gtk_progress_bar_new ();
       gtk_box_pack_start (GTK_BOX (vbox), progress, FALSE, FALSE, 5);
       g_object_set_data (G_OBJECT (barra), "pbar", (gpointer) progress);
       g_signal_connect (G_OBJECT (button), "clicked",
                   G_CALLBACK (button_clicked), (gpointer) barra);
    }
    bot2 = gtk_button_new_with_label("Salir");
    gtk_box_pack_start (GTK_BOX (vbox), bot2, FALSE, FALSE, 5);
    gtk_widget_set_size_request(bot2, 100, 35);
    g_signal_connect (G_OBJECT (bot2), "clicked",
    G_CALLBACK (destroy),
    G_OBJECT (barra));
        gtk_widget_show_all(barra);
    gtk_main();
}
static void
button_clicked (GtkButton *button,
                GtkWidget *barra)
{
  GtkProgressBar *progress;
  gdouble percent = 0.0;
  gtk_widget_set_sensitive (GTK_WIDGET (button), FALSE);
  progress = GTK_PROGRESS_BAR (g_object_get_data (G_OBJECT (barra), "pbar"));
  while (percent <= 100.0)
  {
    gchar *message = g_strdup_printf ("%.0f%% Complete", percent);
    gtk_progress_bar_set_fraction (progress, percent / 100.0);
    gtk_progress_bar_set_text (progress, message);

    while (gtk_events_pending ())
      gtk_main_iteration ();

    g_usleep (500000);
    percent += 5.0;
  }

}

A: With this line:
g_object_set_data (G_OBJECT (barra), "pbar", (gpointer) progress);

you override previous value of "pbar" data entry on each loop iteration.  When you later retrive it in button_clicked() you get the last set value, i.e. the last progress bar.
In this particular case you can just pass progress widget as user data (and drop g_object_[gs]et_data() calls) for button_clicked() callback: the function doesn't use current barra window for anything else anyway.
In a more general way, you should learn how to use your own structures for user data parameters.  A common way is to declare and use one structure for given toplevel type and store pointers to widgets you need to access from callbacks in it.


text:
Q: Reconnct to database isn't happening after Mule starts I am trying the Reconnection configuration in Mule for database connection. My goal is to make Mule retry the connection if the database is down, or at least keep the message somewhere so that I can post the message again later.
So I configure the Reconnection in the jdbc connector as followed:
<jdbc-ee:connector name="MyDatabase" dataSource-ref="DB2_Data_Source" validateConnections="true" queryTimeout="-1" pollingFrequency="0" doc:name="Database">
    <reconnect frequency="6000" count="8"/>
</jdbc-ee:connector>

It works if I start Mule when database is down. I can see in the log that Mule is retrying the reconnect.
The problem comes when the database is down after Mule has already started. I tried by shutting down my database after I ran the flow. I don't see Mule trying to reconnect to the database. When I post a message that hits the database endpoint, it just throws a SQLException and doesn't try to reconnect. Thus my message is lost.
Is there a way to make Mule retry the connection if database is down after Mule starts and log the error somewhere if the retry fails?


text:
Q: Use differential form to prove meromorphic function on compact riemann surface has same zeros and poles I am reading mine's modular form note, proposition 1.12 states that the sum of residues of a differential form on compact Riemman surface is 0. Then he states that applies this to $df/f$, then we can prove meromorphic function on compact riemann surface has same zeros and poles.
I can not follows this, can someone help? I apologize if this question is too elementary.


text:
Q: Sitecore check if Rendering item initialized I have a master layout which contains header and footer information. Also, I have pages using specific rendering items with the master layout. If the page using specific rendering items renders, the Title in master layout should be changed from default Title value.
This is my pseudo-code.

namespace renderingItem1

public override void Initialize(Rendering rendering)
{
    //code here
}

public string anotherMethod()
{
    string str = "";
    if (Initialized == true) {
        str = "Rendering Item is called in this page";
    }
    return str;
}

// In another project, added 'renderingItem1.dll' into references in abother project
// this is masterLayout.cshtml

@using renderingItem1

@string pageTitle = "";
@if (redneringItem1.anotherMethod() is NOT empty) {

    pageTitle = redneringItem1.anotherMethod();
}

In masterLayout.cshtml, it always outputs the default which is str = ""

A: Add Initialized property to your class and set it in Initialize to true:
public bool Initialized { get; set; }

public override void Initialize(Rendering rendering)
{
    Initialized = true;
    ...
}

And by the way, your anotherMethod cannot be static - if it's static, you cannot access non-static Initialized property and you won't be able to detect what is the status of the current instance of your rendering.


text:
Q: Visual studio 2022 perform search into .xsd designer I have a big project with an .xsd file that contains the dataset of all the tables of the database.
I use the .xsd designer integrated with visual studio to add query to table adapter and other stuff.
Due to the large amount of tables in the .xsd file is hard to locate a specific table, and i can't find a way to perform a search in this file; the common ctrl+f is doing nothing in this kind of file.

I've also tried to open the .xsd file with XML Schema Explorer, here i can perform a search, but i can't link back to the .xsd designer, because the search is performed in the xml schema.

Is there a way to perform a search in the .xsd designer?

A: What version of visual studio are you using? in VS2022 there is a 'Show in Graph View' right click option in the XML Schema Explorer.
So you can use the search box in the explorer and then jump to it in the graph view?
XML Schema Explorer right-click


text:
Q: How to pass an object as an argument in order to store data to a database? I am relatively new to Android and I'm a little bit stuck as fighting my way through databases, so any guidelines are much appreciated! Here it goes~
    //Random Fragment that inserts data to the databaase
    mWorkoutData = new WorkoutData();
    mDBTools = new DBTools(getActivity());

    HashMap<String, String> queryValuesMap =  new HashMap<String, String>();

    queryValuesMap.put("comments", mWorkoutData.getComments());

    mDBTools.insertWorkoutData(queryValuesMap);

The WorkoutData is the model class, however it does not manage to insert any data to the database while in case I pass an Edittext for example as an argument everything is fine!
Any guidelines or insights on how to solve this would be much appreciated!
EDIT:
DBTools
    public void insertWorkoutData(HashMap<String, String> queryValues) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put("comments", queryValues.get("comments"));

    db.insert("workouts", null, values);

    db.close();
}

This is the respective method from DBTools to insert this specific data, I believe that the DBTools class is working properly, since I am able to see data on my listview in case I pass something like
 queryValuesMap.put("comments", EditText.getText().toString());

instead of
queryValuesMap.put("comments", mWorkoutData.getComments());

which was described above.
EDIT2
   //Random Fragment number 2 prior to random Fragment of the code above
   mWorkoutData.setComments(mTrainingEditText.getText().toString());

A: You constructed a workoutData object and then called getComments on it, but I would assume at that point that comments is null. You need to set value for comments before you try to read it back out.

A: Not really an answer to your question, but a suggestion I want to make to you that is longer than I can do in comments.
Whenever you're working with databases, you should use a contract class to store the constants. This will make your code easier to write and less prone to errors from typos. This might even be your problem. But basically you just make a class something like
public class WorkoutDatabaseContract {
    public static final String DB_NAME = "fitness"

    public static final String TABLE_WORKOUTS = "workouts"
    ...
    public static final String FIELD_COMMENTS = "comments"
    ...
}

Then your calls to your database look like
values.put(WorkoutDatabaseContract.FIELD_COMMENTS, queryValues.get(WorkoutDatabaseContract.FIELD_COMMENTS));
-or-
queryValuesMap.put(WorkoutDatabaseContract.FIELD_COMMENTS, workoutData.getComments);

It's less compact, but you do less typing because it Idea will auto complete for you, and you don't have to rely on your typing ability to get the field right everywhere. Plus if you ever change anything, you only have to change it in one place.


text:
Q: Cant connect to wifi when bluetooth is on I am using Ubuntu 20.04 LTS, and when using my Bluetooth headphones I cant connect to my home wifi, but somehow I can connect to a mobile hotspot, what do you think is causing this problem?

A: Did the first two answers, don't know which one fixed it, but now it works
wi-fi and bluetooth not working simultaneously


text:
Q: How convert date format in php hello guys i have date like this
25 March 2014 - 16:45

i want to convert this date in to this format how to do that please Help
2014-03-25 16:45:00

i try this  $creation = date('Y-m-d H:i:s',strtotime('25 March 2014 - 16:45'));
but it's not work

A:
i try this $creation = date('Y-m-d H:i:s',strtotime('25 March 2014 - 16:45')); but it's not work

The reason your code doesn't work is because '25 March 2014 - 16:45' is not in a format that strtotime() can parse.
strtottime() is good at handling a wide range of formats, but it can't cope with absolutely anything; there's just too much variation possible.
I suggest that you try PHP's DateTime class instead. This class has a method called createFromFormat() which allows you to specify the format of the incoming date string. This makes it easier for it to parse, and allows for formats that might not be recognised otherwise, like yours.
Try this:
$date = DateTime::createFromFormat('j F Y - H:i', '25 March 2014 - 16:45');
echo $date->format('Y-m-d H:i:s');

A: Use PHP DateTime
You have "-" in "25 March 2014 - 16:45"  in the string so it not be able to read by DateTime
So work around would be
$str = "25 March 2014 -16:45";

$date = new DateTime(str_replace("-","",$str));
echo $date->format('Y-m-d H:i:s');

A: I've successfully tried the following with your string:
$a = strptime('25 March 2014 - 16:45', '%d %B %Y - %R');
$time = mktime(
    $a["tm_hour"],
    $a["tm_min"],
    $a["tm_sec"],
    $a["tm_mon"]+1,
    $a["tm_mday"],
    $a["tm_year"]+1900
);
$converted = date('Y-m-d H:i:s',$time);

A: Try this:
$creation = date('Y-m-d H:i:s',strtotime('25 March 2014 16:45'));


text:
Q: PHPMailer: Subject name in arabic (non-English) characters I am using PHPMailer API for sending emails. I was wondering how can I send the subject in Arabic (non-English) language
$mail->CharSet  =  'utf-8';
$array=  FetchTable('cos');
$subject =  $_POST['subject'];
$body    =  $_POST['body'];

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host     = "host";
$mail->SMTPAuth = true;
$mail->Username = "yaz@enfaltourism.com";
$mail->Password = "*******";
$mail->Port     = "587";
$mail->From     = "yaz@enfaltourism.com";
$mail->FromName = "Enfaltourism";
$mail->Subject  = $subject;
$mail->AddAddress($email);
$mail->Send();`

The email is being successfully sent, but the problem is in sending subject in Arabic language. The email message body is displayed properly in Arabic after I set the char encoding but the the subject is being displayed in weird characters
Update
include("../mail/class.phpmailer.php");
$array=  FetchTable('cos');
$subject =  $_POST['subject'];
$body    =  $_POST['body'];
    $mail = new PHPMailer();
    $mail->CharSet  =  'utf-8';
    $mail->IsSMTP();
 $mail->Host     = "mail.enfaltourism.com";
 $mail->SMTPAuth = true;
 $mail->Username = "yaz@enfaltourism.com";
 $mail->Password = "*****";
 $mail->Port     = "587";
 $mail->From     = "yaz@enfaltourism.com";
 $mail->FromName = "Enfaltourism";
 $mail->Subject  = $subject;

i fixed as u told but the subject still weird character like this

A: I had this same problem with Japanese characters, both in the body and in the subject line:
I resolved it (email looks outstanding now) by doing:
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';

There really isn't any need to encode the subject separately so long as the object has the CharSet property set to UTF-8.

A: you can try using this code. Let me know if it helps
$phpmailer->Subject = "=?UTF-8?B?".base64_encode($subject)."?=";

A: Try encoding subject with base64_encode
$subject = '=?UTF-8?B?'.base64_encode('سلام علیکم').'?=';
However with setting the issue must be solved.
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';

A: Try this:
$mail->CharSet = 'UTF-8';
$mail->Subject = html_entity_decode("Recuperación de contraseña");

I did use this in my code and it worked!
Results


text:
Q: count the matching elements between two dataframes df1.location = 'United Arab Emirates',
 'Bahrain',
 'Luxembourg',
 'Malta',
 'Denmark',
 'Israel',
 'Iceland',
 'Russia',
 'United States',
 'Australia'

df2.location ='Qatar',
 'Bahrain',
 'Panama',
 'Chile',
 'San Marino',
 'Aruba',
 'Kuwait',
 'Peru',
 'Brazil',
 'United States'
 ```
And i have to find the number of matching elements between two pandas dataframes.

A: Assuming df1 and df2 to be:
df1 = pd.DataFrame({'location': ['United Arab Emirates', 'Bahrain', 'Luxembourg', 'Malta', 'Denmark', 'Israel', 'Iceland', 'Russia', 'United States', 'Australia']})
df2 = pd.DataFrame({'location': ['Qatar', 'Bahrain', 'Panama', 'Chile', 'San Marino', 'Aruba', 'Kuwait', 'Peru', 'Brazil', 'United States']})

If you want the number of elements matching on the same row/index:
df1['location'].eq(df2['location']).sum()

output: 1 (only row index 1 matches)
If you want the number of matching unique elements, independently of their position:
len(set(df1['location'])&set(df2['location']))

output: 2 ('Bahrain' and 'United States' are common)


text:
Q: There is any way to configure Rails so it uses another public location for different domains? I have the following folder structure:
/rails
  /public
    /images

And I have 2 domains:
long_domain.com
short.one
I want that when long_domain.com is loaded it uses the /public folder as public, and when short.one is loaded it uses the /public/images
The problem is that I don't want it to load the routes, it should act as the original public folder.
Can this be done with Rails? Would it be better to use another "static" and lightweight server?

A: There's a few ways you could do this.
If you have your images hosted offsite, you'll have to use full URLs in your image tags.  Relative links would go to your CDN or site where your images are.  The advantage here is that you have explicit control over your app and it's likely to work.  I'd define some constant in my config for the image hosting location so I could easily change it later.
Outside of that, you could use mod_passenger to proxy back to Rails and use a mod_rewrite rule to rewrite your image tags on the fly.  The advantage here is that you wouldn't have to change your app (although the changes probably aren't too bad).  The problem is that mod_rewrite is regex's so it might take some playing to figure out the right rule (and testing all the weird cases).
A third option is to use a gem.  If you are really trying to scale out your image handling, you should just switch to Dragonfly which can store a secondary copy of the image anywhere you want.  It has lots of options and features.  It sounds like you would be interested in this aspect of it:
http://markevans.github.com/dragonfly/file.DataStorage.html
Hope this gives you some ideas.


text:
Q: Why is this true of a submartingale? Suppose $(X_n, \mathbb F_n)$ is a submartingale. A proof that I am currently reading seems to use that
$$EX_n \geq E X_0$$
Is that true in general? If so, how does it follow from the submartingale property?

A: If $X_n$ is a submartingale, then $\mathbb{E}[X_n\mid \mathbb{F}_{n-1}] \geq X_{n-1}$. Taking the expectation of both sides, we have
\begin{align*}
\mathbb{E}[\mathbb{E}[X_n \mid \mathbb{F}_{n-1}]] &\geq \mathbb{E}[X_{n-1}]\\
\mathbb{E}[X_n] &\geq \mathbb{E}[X_{n-1}].
\end{align*}
This holds for all $n$, so stringing these inequalities together gives
$$\mathbb{E}[X_n] \geq\mathbb{E}[X_{n-1}] \geq \cdots \geq \mathbb{E}[X_1] \geq \mathbb{E}[X_0].$$


text:
Q: Why doesn't `eval` work inside my loop? Using eval on a string that contains a command that defines a function works without problem:
$ eval "p4() { echo 4; }"
$ p4
4

However, when I do it like this it no longer works:
$ echo 'p3() { echo 3; }' | while read line ; do eval "$line"; done
$ p3
-bash: p3: command not found

Why doesn't this work?

A: It is happening due to a sub-shell being spawned due to your pipeline after echo. That is declaring function p3 in sub-shell, not accessible from current (parent) shell.
You can avoid it by using here-string instead of pipeline:
while read line ; do eval "$line"; done <<< 'p3() { echo 3; }'

p3
3

A: What anubhava is saying is correct and you should always keep that in mind. Let me just suggest an alternative: you may use process substitution and source:
source <(echo 'p3() { echo 3; }')
p3

The question is, why do you want to do that?

A: From man bash:

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

Since variables aren't transferred to the subshell, p3 isn't accessible there.
As an aside: zsh executes the second example exactly the way you expected, that is, it outputs 3.


text:
Q: Is there any way to find next similar tag without querying all tags at once? I'm trying to implement my own link hinting script for surf browser, and
I've been bumping into noticeable performance issues on pages with a
huge number of links. For example, it takes about 2 seconds to hint all
visible links on https://gunther.suckless.org/patches/ and 3 seconds on
https://en.wikipedia.org/wiki/Japan. I think, the problem is that I'm
trying to find all the link tags using querySelectorAll("a") (or
getElementsByTagName("a") - it has almost the same performance in my
case) and then filtering all these tags through the function that checks
whether a link is in the viewport or not (in other words, a link finding
procedure wastes most of the time on links that won't be displayed
anyway):
var all_elems = document.body.querySelectorAll("a");
for (var i = 0; i < all_elems.length; i++) {
  if (isHintDisplay(all_elems[i])) {
    hint_elems.push(all_elems[i]);
  }
}

I'd thought that, probably, a "manual" link tags iterations, that process one link tag at a time and stop when invisible links would found, would be a more optimal solution.
I've tried to implement these iterations using querySelector("a") / parentElement / nextElementSibling, but ended up with ugly and absolutely non-robust code...
Is there any other way to find previous/next similar tags without using
querySelectorAll / getElementsByTagName? Or these performance issues is inherent to Javascript itself and there is not much can be done to
improve situation?
P.S. It is assumed that processed tags won't contain any IDs and classes.
ADDED
Implementation of isHintDisplay:
function isHintDisplay(elem) {
  var pos = elem.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight,
                            window.innerHeight);
  return !(pos.bottom < 0 || pos.top - viewHeight >= 0);
}


text:
Q: What is this white trace on this PCB? I saw this image where the "white trace" is (I think) trying to separate high current 220VAC.
Do you know what is that white paint made of?

EDIT:
Image source: Shelly Facebook Page
While trying to find an answer to this, I looked (without much success) at several sites talking about PCB protection, isolation, and high voltage PCB design. Most of them focus in cutting your PCB, get wider clearance and traces, paint the entire PCB with silicon, etc. I could not find any reference to a colored paint/coating that is used in between traces like the image:

*

*CALCULATING SPACING BETWEEN PCB TRACES FOR VARIOUS VOLTAGE LEVELS

*PCB INSULATION MATERIALS

*MetaLine isulation coatings

*Electrical isulation materials

*Silicone Conformal Coating

*Essential guide to Conformal Coating

*How to protect your PCB?

*Altium: High Voltage PCB Design for Arc Prevention

*High Voltage PCB Design for Arc Prevention (video)

A: It looks like normal silkscreen print. It is quite typical to have two narrow lines at edges of isolation area for visual marking, but I haven't seen such wide fill before.
This seems like a bad idea and a potential violation of standards. Isolation materials are rated by their Comparative Tracking Index, which specifies how easily current will start forming a carbonized path along the surface of the insulator. It is easy to order a PCB with soldermask with specified CTI that is at least as good as the PCB material itself. But most manufacturers do not specify CTI for the silkscreen paint, so it could be  a worse insulator.

A: It's a visual indication of where the separation is. It makes it easy to visually inspect that there's 8 mm creepage distance with no components or tracks in the 'keep out' zone.
That's the charitable view. The cynical possibility is that it might be camouflaging a piece of copper intruding into that region. We can't tell from a picture, you would need close inspection to discover that.

A: Look to the PCB very carefully. The white area is made with the same silkscreen legend print as used for part numbers and part outlines. It is a paint cured by UV light or heat in order to be resistant to soldering.
So no additional production step is needed and the PCB is cheaper.
It is only a marking of the isolation gap but it does not improve the isolation.


text:
Q: Scrapy website crawler returns invalid path error I'm new to Scrapy and am following the basic documentation.
I have a site I'm trying to scrape some links from in order to then navigate some links within those. I'm specifically trying to get Cokelore, College, and Computers and I'm using my code below
import scrapy

class DmozSpider(scrapy.Spider):
    name = "snopes"
    allowed_domains = ["snopes.com"]
    start_urls = [
            "http://www.snopes.com/info/whatsnew.asp"
    ]

    def parse(self, response):
            print response.xpath('//div[@class="navHeader"]/ul/')
            filename = response.url.split("/")[-2] + '.html'
            with open(filename, 'wb') as f:
                    f.write(response.body)

This is my error
2015-10-03 23:17:29 [scrapy] INFO: Enabled item pipelines:
2015-10-03 23:17:29 [scrapy] INFO: Spider opened
2015-10-03 23:17:29 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-10-03 23:17:29 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-10-03 23:17:30 [scrapy] DEBUG: Crawled (200) <GET http://www.snopes.com/info/whatsnew.asp> (referer: None)
2015-10-03 23:17:30 [scrapy] ERROR: Spider error processing <GET http://www.snopes.com/info/whatsnew.asp> (referer: None)
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/Gaby/Documents/Code/School/689/tutorial/tutorial/spiders/dmoz_spider.py", line 11, in parse
    print response.xpath('//div[@class="navHeader"]/ul/')
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scrapy/http/response/text.py", line 109, in xpath
    return self.selector.xpath(query)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scrapy/selector/unified.py", line 100, in xpath
    raise ValueError(msg if six.PY3 else msg.encode("unicode_escape"))
ValueError: Invalid XPath: //div[@class="navHeader"]/ul/
2015-10-03 23:17:30 [scrapy] INFO: Closing spider (finished)
2015-10-03 23:17:30 [scrapy] INFO: Dumping Scrapy stats:

The error I'm getting I think has to do with the /ul in my xpath() but I can't figure out why. //div[@class="navHeader"] works fine on it's own, and it starts breaking once I start adding attributes after that.
The part of the website I'm trying to scrape is structured like so

CATEGORIES:

Autos

Business

Cokelore

College

Computers

Crime

Critter Country

Disney

Embarrassments

Fauxtography

A: You just need to remove the trailing /. Replace:
//div[@class="navHeader"]/ul/

with:
//div[@class="navHeader"]/ul

Note that this XPath would actually match nothing on the page. The ul element is a sibling of the navigation header - use following-sibling:
In [1]: response.xpath('//div[@class="navHeader"]/following-sibling::ul//li/a/text()').extract()
Out[1]:
[u'Autos',
 u'Business',
 u'Cokelore',
 u'College',
 # ...
 u'Weddings']


text:
Q: Multipart File to File InputStream How can I convert a MultipartFile to FileInputStream in memory?
I have tried to below , but i am facing the error as

org.springframework.web.multipart.commons.CommonsMultipartFile cannot
  be cast to java.io.File

My Code is
FileInputStream fis = new FileInputStream((File)file);

where file is a multipart file

A: Try using:
MultipartFile uploadedFile = ((MultipartHttpServletRequest)request).getFile('file_name')
InputStream inputStream = new ByteArrayInputStream(uploadedFile?.getBytes())

A: You can't create an instance of FileInputStream unless your file is not on file system.
You have to either first save the multipart file in temporary location on server using
file.transferTo(tempFile);
InputStream stream = new FileInputStream(tempFile);

But multipart file can also be read simply via basic streams methods such as
InputStream inputStream =  new BufferedInputStream(file.getInputStream());

A: Take look at MultipartFile
In that you can go with :
void    transferTo(File dest)

This method transfer the received file to the given destination file.

A: MultipartFile file;
InputStream inputStream = file.getInputStream();

A: To convert Multipart file to Input Stream
MultipartFile file;
InputStream inputStream = new InputStream(file.getInputStream());

This worked for me.

A: We may just cast and use like below
FileInputStream file = (FileInputStream) multipartFile.getInputStream();

A: For a multipart file eg:
FileMultipartData part =  new FileMultipartData();
InputStream inputStream = part.getFileMultipart().get(0).getByteStream();

This worked for me in my code. Please try it


text:
Q: Limit vs Derivative
I am learning Calculus and I am confused over the difference between Limit and Derivative.
In the screenshot below, both the blue and red boxes come to the same conclusion of 3x^2.
So, why do we have 2 representations of the same outcome? As far as I understand, the derivative allows us to find the slope of the tangent line, and it seems that the limit equation does the same thing as well.

A: The concepts of a limit and derivative are totally different. One represents the idea of moving infinitely close to some input of a function and observing its behavior. Informally, a derivative is what happens when you measure the rate of change between two infinitely close points.
In just so happens that someone is using the definition of a derivative to show that a certain limit is equal to the derivative of some function. The derivative is built upon the limit and is itself a limit:
$$\lim_{h\to 0} {f(x+h)-f(x)\over h} = f'(x)$$
$$\lim_{x\to a} {f(x)-f(a)\over x-a} = f'(x)$$
The two are inherently related because limits are a mathematical tool to encapsulate what we are actually doing with a derivative, but they are not the same conceptually.

A: The derivative is the limit formula. More so, the derivative is defined as$$\frac {df}{dx}=\lim\limits_{\Delta x\to0}\frac {f(x+\Delta x)-f(x)}{\Delta x}$$The reason why they produce the same answer is because they are the exact same formula. The derivative is calculated using the limit.

A: Note that

*

*the derivative at a point $x_0$ is defined by the limit (whether it exists) $$f'(x_0)=\lim_{\Delta x\to 0} \frac{f(x_0+\Delta x)-f(x_0)}{\Delta x}=3x_0^2$$

once we have defined the derivative at each point we can consider its value for all points of the domain such that the given limit exists and thus define the derivative function $f'(x)=3x^2$.


text:
Q: How to capture curl trace output into a log file I have the below shell script which execute a curl command with trace. I am able to capture the output(api response) of curl command into the log file, but unable to capture the trace logs into the log file. Please help.
#! /bin/bash

app_header="app_header:test_app"
cmd="curl -ivk —trace GET https://app.corp.com/api/state/1231231?id=21"
echo $cmd >> /log/call_app_service.log

for i in {1..2}
do
    echo "Running $i times" >> /log/call_app_service.log
    $cmd -H $app_header >> /log/call_app_service.log
    echo "\n" >> /log/call_app_service.log
    sleep 1
done

A:
I am able to capture the output(api response) of curl command into the log file, but unable to capture the trace logs into the log file.

The output you're capturing is from stdout.  The output you're missing is from stderr which is still going to the terminal instead of the file.
You can redirect standard error (fd 2) to standard output (fd 1)
$cmd -H $app_header >> /log/call_app_service.log 2>&1


text:
Q: CSS font-weight thicker than 900? I have a panel which can be expanded or minimised through a vertically centred link with a < or > symbol as the link text. At font-weight: 900 this does not stand out much, even with a large grey background around it. I do not want to use an image and, at the current font size, both symbols currently take up the maximum width of the panel.
Is there any way to thicken the line on the symbols beyond 900? Or is there another alternative I could use?
Thanks in advance.
Richard

A: You can use  text-shadow instead of font-weight
text-shadow: 0px 1px, 1px 0px, 1px 0px;

A: Unfortunately there's no font-weight thicker than 900, and specifying font-weight by number varies across browsers. Your best bet would be to use a thicker font - you haven't specified what you're using, but Impact is relatively thick and tall for its width while being web-safe. Otherwise you could use @font-face to load in a different font.

A: In CSS 3 there's another way to make the font size bolder:
color:#888888;
text-shadow: 2px 0 #888888;
letter-spacing:2px;
font-weight:bold;

EDIT:
For some sort of weird reason this doesn't look as pretty as it did over an year ago. It only works with text-shadow of 1px (on most common fonts, other thicker fonts might still work with 2px). And with text-shadow of only 1px, there's no need for such a large letter-spacing.
color:#888888;
text-shadow: 1px 0 #888888;
letter-spacing:1px;
font-weight:bold;

A: Adding to Gogutz answer. You can use the currentcolor keyword to use the color of the text and avoid hardcoding it.
Like this:
text-shadow: 0.5px 0 currentColor;
letter-spacing: 0.5px;

A: To add to Gogutz answer, you can go even bolder by stacking up the text-shadows in a grid. Comma separate each on the line:
.extra-bold {
  text-shadow: 0px 1px, 1px 0px, 1px 1px;
}

A: This is quite thick. But works only with webkit.
font-size: -webkit-xxx-large;
font-weight: 900;


text:
Q: Cloud foundry java buildpack - find out tomcat version I know there is documentation or release notes, but is there any way I can find out tomcat version that cloud foundry uses inside any env variables?
I don't see it in /actuator/env

A: From the Cloud Foundry side, you can see what's installed by the Java buildpack during staging. It show's you exactly what's been installed. This doesn't get saved anywhere though, unless you're sending your application logs to some form of permanent storage.
Ex:
   -----> Java Buildpack v4.19 (offline) | https://github.com/cloudfoundry/java-buildpack.git#3f4eee2
   -----> Downloading Jvmkill Agent 1.16.0_RELEASE from https://java-buildpack.cloudfoundry.org/jvmkill/bionic/x86_64/jvmkill-1.16.0_RELEASE.so (found in cache)
   -----> Downloading Open Jdk JRE 1.8.0_202 from https://java-buildpack.cloudfoundry.org/openjdk/bionic/x86_64/openjdk-jre-1.8.0_202-bionic.tar.gz (found in cache)
          Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (2.3s)
          JVM DNS caching disabled in lieu of BOSH DNS caching
   -----> Downloading Open JDK Like Memory Calculator 3.13.0_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/bionic/x86_64/memory-calculator-3.13.0_RELEASE.tar.gz (found in cache)
          Loaded Classes: 8166, Threads: 250
   -----> Downloading Client Certificate Mapper 1.8.0_RELEASE from https://java-buildpack.cloudfoundry.org/client-certificate-mapper/client-certificate-mapper-1.8.0_RELEASE.jar (found in cache)
   -----> Downloading Container Security Provider 1.16.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-security-provider/container-security-provider-1.16.0_RELEASE.jar (found in cache)
   -----> **Downloading Tomcat Instance 9.0.17** from https://java-buildpack.cloudfoundry.org/tomcat/tomcat-9.0.17.tar.gz (found in cache)
          Expanding Tomcat Instance to .java-buildpack/tomcat (0.6s)
   -----> Downloading Tomcat Access Logging Support 3.3.0_RELEASE from https://java-buildpack.cloudfoundry.org/tomcat-access-logging-support/tomcat-access-logging-support-3.3.0_RELEASE.jar (found in cache)
   -----> Downloading Tomcat Lifecycle Support 3.3.0_RELEASE from https://java-buildpack.cloudfoundry.org/tomcat-lifecycle-support/tomcat-lifecycle-support-3.3.0_RELEASE.jar (found in cache)
   -----> Downloading Tomcat Logging Support 3.3.0_RELEASE from https://java-buildpack.cloudfoundry.org/tomcat-logging-support/tomcat-logging-support-3.3.0_RELEASE.jar (found in cache)

If you're looking to get it from inside the container or inside the app, the suggestions in this SO post should work.
Hope that helps!


text:
Q: BlackBerry: Dozens of net_rim_services_impl Threads when debugging When debugging my application I see dozens of net_rim_services_impl. Is that normal behaviour or is my app causing that trouble.
Can some give me an explanation what is in net_rim_services_impl?
I use GPS/Geolocation with several LocationListeners and my app consists of a gui-thread and a background thread with a separate entry point that is auto-started. It is listening for push notifies within that thread.
Anybody?

A: That is normal behavior.
Here's a couple of links with people dealing with net_rim_services_impl errors.
But I don't think you are dealing with them. Aren't you?
http://supportforums.blackberry.com/t5/Java-Development/Application-net-rim-services-impl-14-is-not-responding-process/m-p/140453/highlight/true#M16090
http://supportforums.blackberry.com/t5/Java-Development/Process-net-rim-services-impl-14-queue-too-large-key-stylus/m-p/187664/highlight/true#M24680


text:
Q: rearrange javascript object I have an object with depth at most 3:
OBJ.T.V.E={...}

T and V are integers (like in OBJ[0][1]['String']={...} )
so a typical structure could be:
OBJ[0][0]['S1']={..}
OBJ[0][0]['S2']={..}
OBJ[0][1]['S1']={..}
OBJ[0][2]['S1']={..}

I want to rearrange and get somehow this:
OBJNEW['S1'][0][0]={...}

which would have the same value as in OBJ[0][0]['S1']
I'm struggling for hours with no luck. Any ideas? Jquery code is also welcome.
EDIT:
Right now I tried creating an array of objects like that:
OBJ2=[];
$.each(OBJ, function(name, value) {
  $(value).each(OBJ, function(name1, value1) {
    OBJ2[name1]=[];
    $(value1).each(OBJ, function(name2, value2) {
      OBJ2[name1][name2]={};
      OBJ2[name1][name2]['S1']={};
    })
  })

But this step fails since each ...['S1'] assignment overwrites the previous object (e.g. S2).
Please ignore any typos, I have just recreated the logic.

A: This should get you pretty far, unless I misunderstood.
function flipObject(o) {
  var i1, i2, i3, result = {};

  for ( i1 in o ) {
    if ( o.hasOwnProperty(i1) ) {
      for ( i2 in o[i1] ) {
        if ( o[i1].hasOwnProperty(i2) ) {
          for ( i3 in o[i1][i2] ) {
            if ( o[i1][i2].hasOwnProperty(i3) ) {
              if ( !(i3 in result) ) result[i3] = {};
              if ( !(i1 in result[i3]) ) result[i3][i1] = {};
              result[i3][i1][i2] = o[i1][i2][i3];
            }
          }
        }
      }
    }
  }
  return result;
}

It turns
{
    "0": {
        "0": {
            "s1": "s1.0.0",
            "s2": "s2.0.0"
        },
        "1": {
            "s1": "s1.0.1",
            "s2": "s2.0.1"
        }
    },
    "1": {
        "0": {
            "s1": "s1.1.0",
            "s2": "s2.1.0"
        },
        "1": {
            "s1": "s1.1.1",
            "s2": "s2.1.1"
        }
    }
}

into
{
    "s1": {
        "0": {
            "0": "s1.0.0",
            "1": "s1.0.1"
        },
        "1": {
            "0": "s1.1.0",
            "1": "s1.1.1"
        }
    },
    "s2": {
        "0": {
            "0": "s2.0.0",
            "1": "s2.0.1"
        },
        "1": {
            "0": "s2.1.0",
            "1": "s2.1.1"
        }
    }
}

A: Some of the problem in your original code is that you can't use a plain array [] as an associative array {}.  String keys can only be used in an associative array.  The next problem is that you can and should iterate over all your string keys instead of trying to hard-code them.
The simplest thing you can do is write for/in loops for each level of your original object's hierarchy, then flip the assignment when writing them to the new object.  You'll also have to check if the parent keys exist, and if they don't, create them.
var NEWOBJ = {};

for (var outerKey in OBJ) {
  for (var innerKey in OBJ[outerKey]) {
    for (var stringKey in OBJ[outerKey][innerKey]) {
      NEWOBJ[stringKey] = NEWOBJ[stringKey] || {};
      NEWOBJ[stringKey][outerKey] = NEWOBJ[stringKey][outerKey] || {};
      NEWOBJ[stringKey][outerKey][innerKey] = OBJ[outerKey][innerKey][stringKey];
    }
  }
}

console.log(NEWOBJ);

As far as I know, jQuery will do little to nothing to help you here.  It really isn't much simpler than the native Javascript that accomplishes the same thing.
Note that this doesn't do a deep copy of the objects you're moving around.  I believe if you change objects in NEWOBJ that they'll also be changed in OBJ.  I think it would be hard to solve this problem generically, and you'll probably have to resort to custom copy object for each object type.
Also note that I am not a Javascript GURU.  I know there are sometimes problems when iterating over properties in an object that hasOwnProperty can solve that might creep up in an example like this.  I don't know what those problems are off the top of my head, though.  For example I tried this code with a simple JSON object and it worked :)
http://jsfiddle.net/e9uST/ - use the Javascript console in your browser to see the output.


text:
Q: Powering a switching power supply with a CTE (centre tapped earth) transformer This question is an extension of a previous topic I posted regarding CTE transformers.
I plan to use a switching power supply for an upcoming project, and I want to supply power to it from a CTE transformer. See spec sheet for PSU.
As discussed in my last post, CTE transformers have no neutral output. Instead, they have three contacts, where one is ground, and the other two alternate between -55V and +55V such that the voltage difference between the two contacts is +/-110VAC. The PSU, on the other hand, has a "L" and "N" contact for power. Based on the PSU's spec sheet, 110VAC is well within the input range, and I'm assuming that as long as the voltage difference between the "N" and "L" contacts is in the specified range, the device will work.
Am I correct in this assumption? Or am I going to ruin my PSU?

A: The data sheet does specify neutral and line for the supply and doesn't mention twin hot supplies. The manufacturer's contact details are given at the end of the data sheet; ask them as no-one else can give a definitive answer.

A: You have one of 110V construction site safety isolation transformers that output 110 VAC that is center-tapped to earth potential so each leg is 55 VAC.
The 115 VAC can be used as usual for connecting into terminals of common equipment such as this power supply.
All it requires is 110 VAC to L an N terminals and the earth to earth terminal.

A: Electrical code mention dedicated wire. Where is some rules applied, like color, wire can not be interrupted. It becomes neutral the connected to ground at source. In your case the source is transformer. Output of transformer is voltage, just choose output you need. If it is 55-0-55 you can consider 0-55-110, that is the same. 0 considerably is earth, if nothing connected to earth,no 0. But for safety purpose earthing is required.


text:
Q: C++ Insertion operator overload (<<) I'm working through an assignment in which I must overload the insertion operator to take a Node object. I've created the operator overload function outside the class definition, but inside the node.h file. Everything compiles fine, but the overloaded operator is not called, instead I get simple the address of the object.
I'm prohibited from modifying the calling code, so any changes must be to the operator overload.
My code as it stands right now:
/** OPERATOR << ***********************************/
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> *& pHead)
{
    out << "INCOMPLETE";
    return out;
}

Right now, I just want to ensure the overloaded operator is called. I'll fix the output code once I know I'm calling the right operator.
The calling code:
// create
Node <char> * n = NULL;

// code modifying n

// display
cout << "\t{ " << n << " }\n";

A: Note that the parameter pHead's type is a reference to non-const, const Node<T>* is a non-const pointer to const, the argument n's type is Node<T>* (i.e. a non-const pointer to non-const). Their type doesn't match, Node<T>* need to be converted to const Node<T>*, which is a temporary and can't be bound to  reference to non-const.
In short, you can't bind a reference to non-const to an object with different type.
But reference to const could be bound to temporary, so you can change the parameter type to reference to const:
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> * const & pHead)
//                                                                      ~~~~~

Or change it to passed-by-value, Node<T>* will be implicitly converted to const Node<T>* when passing as argument. (Passing pointer by reference to const doesn't make much sense.)
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> * pHead)

At last, overloading operator<< with pointer type looks weird. The most common form with user-defined type would be:
template<class T>
std::ostream & operator << (std::ostream & out, const Node <T> & pHead)

A: The problem is that the inserter takes a parameter of type const Node<T>*, but it's called with an argument of type Node<T>*; there is no conversion from T* to const T*. So the "fix" is to remove the const from the stream inserter.
But, as hinted at in a comment, having an inserter that takes a pointer to a type is a bad idea. It should take a const Node<T>&, like all the other inserters in the world. I gather that this is a constraint imposed by an assignment; if so, it's idiotic. You're being taught badly.


text:
Q: How to print only the key values of a dictionary for a certain range based on the dictionary values? Suppose I am having a Dictionary in the following format.
new_dict = {'worry': [23, 667, 1692, 1940], 'win': [96, 200, 286], 'work': [833, 1458]}

I want to print only the key only keys based on the values between 0 to 100.
Output in this case:

{'worry', 'win'}

I have tried:
dict0100 = {k:v for (k,v) in new_dict.items() if new_dict.values(range(100))}

I am getting error like values take only 1 argument.
Note: The values range between 0 to 5000 in my case. I want only the key values between 0 to 100 only.
Any help is appreciated.

A: Try this:
dict0100 = {k: v for (k, v) in new_dict.items() if any(i <= 100 for i in v)}

If you want the list to be filtered too:
dict0100 = {k: l for k, l in [(k, [i for i in v if i <= 100]) for k, v in new_dict.items()] if l}

Note about < or range
About using the comparison operator < or the in range() expression, I would personnaly go for the x < 100 since here all of the lists items are said to be positive integers, and comparison is more performant:
import timeit

t1 = timeit.timeit(lambda: 3 in range(100))
print(t1) # 0.37976

t2 = timeit.timeit(lambda: 3 <= 100)
print(t2) # 0.08725

A: I'd use a range check with any. Here's a neat reusable generator function:
def get_keys_in_range(dct, lo=0, hi=100):
    rng = range(lo, hi)
    for key, lst in dct.items():
        if any(l in rng for l in lst):
            yield key

[*get_keys_in_range(new_dict, lo=0, hi=100)]
# ['worry', 'win']

It's worth mentioning that membership checks on range objects are constant time (O(1)) in python-3.x (but O(N) in python-2.x, so you may want to consider the other solutions using pure comparisons).
Note that the range is closed on the right interval, meaning you'd want to do range(lo, hi+1) if you want the upper bound to be inclusive.

This can be shortened to
lo, hi = 0, 100
[key for key, lst in new_dict.items() if any(l in range(lo, hi) for l in lst)]
# ['worry', 'win']

You can pre-cache range for a little more performance (as done inside the function).
rng = range(lo, hi)
[key for key, lst in new_dict.items() if any(l in rng for l in lst)]
# ['worry', 'win']

A: Try this:
dict0100 = {k:v for (k,v) in new_dict.items() if [x for x in v if all([x<100,x>0])]}

This will save both the key and the value, for key only remove the ":v"

A: your dict has keys of type str and values of type list (of ints)
your expected output is a set object (and not a dict).
try this:
new_dict = {'worry': [23, 667, 1692, 1940], 'win': [96, 200, 286], 'work': [833, 1458]}

set0100 = {k for k, arr in new_dict.items() if any(v in range(100) for v in arr)}

print(set0100)

this uses the nice fact that range objects implement the __contains__ method, which allows us to use in on them.

A: dict0100 = {k:v for (k,v) in new_dict.items() if all([v_e < 5000 for v_e in v])}


text:
Q: How to add LinearLayout with rows of imageView In NavigationDrawer Hi I have the following layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Add The mainmenu-->

    // add a linearLayout with 3 row of imagaeView

    <!-- The navigation drawer -->

    <Mvx.MvxListView
        local:MvxBind="ItemsSource MenuItems; ItemClick SelectMenuItemCommand"
        local:MvxItemTemplate="@layout/item_menu"
        android:id="@+id/left_drawer"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:choiceMode="singleChoice"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111" />
</android.support.v4.widget.DrawerLayout>

Problem:

*

*How to add a linearLayout with many rows into this Navigational drawer that using MvxListView.

The NavigationDrawer is on the left side.
Questions:

*

*Must I use FrameLayout?

*Can I replace FrameLayout with LinearLayout?

A: DrawerLayout only supports two child views.
The first element must always be the content view, the second will be what is in the drawer, and you must specify a gravity indicating whether the drawer is coming in from the left or the right.
If you want more than a ListView in the drawer, just wrap the contents in another layout such as RelativeLayout, FrameLayout or LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="240dp"
        android:layout_gravity="start"
        android:layout_height="match_parent">

        <!-- add other views here -->

        <Mvx.MvxListView
            local:MvxBind="ItemsSource MenuItems; ItemClick SelectMenuItemCommand"
            local:MvxItemTemplate="@layout/item_menu"
            android:id="@+id/left_drawer"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:choiceMode="singleChoice"
            android:layout_width="match_parent"
            android:layout_height="0"
            android:layout_weight="1"
            android:background="#111" />
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>


text:
Q: log4j2 configuration from file I am working on an existing system that uses log4j, I want to update to log4j2.
There is a custom spring bean that loads the configuration from a file. I need to keep this approach. I cannot use the "log4j.configurationFile" system property.
We have a properties file where the path to the current log4j.xml is specified ( NFS share )
The spring bean has this code ...
public class Log4jConfigurationBean implements ResourceLoaderAware,
    InitializingBean {

private ResourceLoader resourceLoader;

private boolean enabled;

private String location;

/**
 * Default, no argument constructor.
 */
public Log4jConfigurationBean() {
    enabled = true;
}

/**
 * Sets whether or not this bean should load an external configuration
 * defined by {@link #setLocation(Resource)}. If false, this
 * bean does nothing.
 *
 *

 * Default value is true.
 *

 *
 * @param enabled
 *            false causes this bean to do nothing
 */
public void setEnabled(final boolean enabled) {
    this.enabled = enabled;
}

/**
 * Sets the location of the external log4j configuration (xml or properties)
 * to be loaded.
 *
 * @param location
 *            the location of the external configuration to be loaded.
 * @throws IllegalStateException
 *             if there is a problem resolving the location resource
 * @throws NullPointerException
 *             if resource is null
 */
public void setLocation(final String location) {
    this.location = StringUtils.trimToNull(location);
}

@Override
public void setResourceLoader(final ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
}

/**
 * @throws IllegalStateException
 *             if enabled and no location has be set, or if the external
 *             configuration is neither xml or properties.
 */
@Override
public void afterPropertiesSet() throws Exception {
    URL configURL = null;
    if (null != location) {
        try {
            final Resource resource = resourceLoader.getResource(location);
            if (null != resource) {
                configURL = resource.getURL();
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    "Could not resolve configuration location due to error: ",
                    e);
        }
    }
    if (enabled && null == configURL) {
        throw new IllegalStateException(
                "Log4j configuration enabled, but configuration location is not set.");
    }
    if (enabled) {
        if (configURL.getFile().toLowerCase().endsWith(".xml")) {
            DOMConfigurator.configure(configURL);
        } else if (configURL.getFile().toLowerCase()
                .endsWith(".properties")) {
            PropertyConfigurator.configure(configURL);
        } else {
            throw new IllegalStateException(
                    "Configuration must be properties or xml: "
                            + configURL.getFile());
        }
    }
}

}
In log4j2 there is no PropertyConfigurator.
How can I load the log4j2.xml file the same way.
The file path to the log4j2.xml file is specified in a spring property file.
The goal is to have the war files contain a log4j2.xml file in the classpath. This will be used when developing on your local box.
When the web apps are deployed to a qa environment, there is a property file containing the following key/value pair...
# Should an external file be used for log4j configuration
log4j.enabled=true
log4j.location=file:/paht to log4j2.xml

A spring bean is using these values to decide if an external log4j2.xml file should be used instead of the one on the classpath.
I tried with a spring bean like this... the code is executed, but it still uses the configuration file on the classpath.
public class Log4j2ConfigurationBean implements ResourceLoaderAware, InitializingBean {
private static final Logger log = LoggerFactory.getLogger(Log4j2ConfigurationBean.class);
private ResourceLoader resourceLoader;
private boolean enabled;
private String location;

/**
 * Default, no argument constructor.
 */
public Log4j2ConfigurationBean() {
    enabled = true;
}

/**
 * Sets whether or not this bean should load an external configuration defined by {@link #setLocation(Resource)}. If false, this bean does nothing.
 *
 *

 * Default value is true.
 *

 *
 * @param enabled
 *            false causes this bean to do nothing
 */
public void setEnabled(final boolean enabled) {
    this.enabled = enabled;
}

/**
 * Sets the location of the external log4j configuration (xml or properties) to be loaded.
 *
 * @param location
 *            the location of the external configuration to be loaded.
 * @throws IllegalStateException
 *             if there is a problem resolving the location resource
 * @throws NullPointerException
 *             if resource is null
 */
public void setLocation(final String location) {
    this.location = StringUtils.trimToNull(location);
}

@Override
public void setResourceLoader(final ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
}

/**
 * @throws IllegalStateException
 *             if enabled and no location has be set, or if the external configuration is neither xml or properties.
 */
@Override
public void afterPropertiesSet() throws Exception {
    URL configURL = null;
    if (enabled) {
        if (StringUtils.isBlank(location)) {
            throw new IllegalStateException("Log4j2 configuration enabled, but configuration location is not set.");
        }
        try {
            System.out.println(this.getClass().getName() + " : Loading log4j2 configuration with " + location);
            final Resource resource = resourceLoader.getResource(location);
            if (null != resource) {
                configURL = resource.getURL();
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("Could not resolve configuration location due to error: ", e);
        }
        if (configURL.getFile().toLowerCase().endsWith(".xml")) {
            try {
                System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
                System.setProperty("AsyncLogger.RingBufferSize", "8192");
                ConfigurationFactory configurationFactory = XmlConfigurationFactory.getInstance();
                ConfigurationSource configurationSource = new ConfigurationSource(configURL.openStream(), configURL);
                Configuration configuration = configurationFactory.getConfiguration(configurationSource);
                configuration.start();
                log.info("Log4j2 configured with {}", location);
                log.info("System property Log4jContextSelector set to {}", System.getProperty("Log4jContextSelector"));
                log.info("System property AsyncLogger.RingBufferSize set to {}", System.getProperty("AsyncLogger.RingBufferSize"));
            } catch (Exception e) {
                System.out.println(this.getClass().getName() + " : Could not initialize log4j2 with resource " + location);
                System.out.println(e.getStackTrace());
            }
        } else {
            throw new IllegalStateException("Configuration must be xml: " + configURL.getFile());
        }
    } else {
        System.out.println(this.getClass().getName() + " : External log4j2 configuration not configured.");
    }
}

}
Thanks.

A: Check out the How do I configure log4j2 in code without a configuration file? section here - http://logging.apache.org/log4j/2.x/faq.html


text:
Q: Continuous differentiability implies Lipschitz continuity Here's a statement in Zygmund's Measure and Integral on page 17:

If $f$ has a continuous derivative on $[a,b]$, then (by the mean-value theorem) $f$ satisfies a Lipschitz condition on $[a,b]$.

This does not seem obvious to me. How can I show it?
Also, what does a continuous derivative imply? Can we conclude the function is differentiable? If so, how can I prove it?

A: Since $f'$ is continuous it is bounded on $[a,b]$. Choose $M\in \Bbb R$ such that $|f'(x)|\le M$ for all $x\in [a,b]$. If $x,y\in [a,b]$, then by the MVT there is $\xi\in [a,b]$ with $f(x)-f(y)=f'(\xi)(x-y)$, thus $|f(x)-f(y)|\le M|x-y|$. In fact you can show that a differentiable function on an open interval (not necessarily a bounded interval) is Lipschitz continuous if and only if it has a bounded derivative. This is because any Lipschitz constant gives a bound on the derivative and conversely any bound on the derivative gives a Lipschitz constant.
To your other question: Continuous derivative does not imply twice differentiable. In fact, we know that there are functions $f$ (such as the Weierstrass-function) which are continuous but not differentiable. Taking the antiderivative $F$ gives us a differentiable function with derivative $f$ (by the Fundamental Theorem of Calculus), so it has a continuous derivative, but as $f$ is not differentiable, $F$ is not twice differentiable.

A: By the mean value theorem,
$$f(x) - f(y) = f'(\xi)(x-y)$$
for some $\xi \in (y,x)$. But since $f'$ is continuous and $[a,b]$ is compact, then $f'$ is bounded in that interval, say by $C$. Thus taking absolute values yields
$$\lvert f(x) - f(y)\rvert \le C \lvert x-y\rvert$$


text:
Q: Symfony 2.0 Model relationships I am trying to model the following table structure in Symfony 2.0 using annotations.
   State
PK Code
   Name

   County
PK State_Code -> FK State.Code
PK Code
   Name

   Muni
PK State_Code -> FK.State.Code
PK County_Code -> FK County.Code
PK Code
   Name

Modeling the fields and the state - county relationship is simple enough, but I cannot determine how to define the relationship for the Muni table.

*

*States have one or more counties.

*Counties have one or more Munis.

*Munis belong to one or more Counties.

The table structure is legacy and cannot be modified.

A: Here you go. Tested with Symfony 2.0.5 (Doctrine 2.1):
State.php
namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Entity
 */
class State
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="County", mappedBy="state_code")
     */
    private $counties;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="state_code")
     */
    private $munis;
}

County.php
namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * County
 *
 * @ORM\Entity()
 */
class County
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="counties")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="county_code")
     */
    private $munis;
}

Muni.php
namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Muni
 *
 * @ORM\Entity
 */
class Muni
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="County", inversedBy="munis")
     * @ORM\JoinColumn(name="County_Code", referencedColumnName="Code")
     */
    private $county_code;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="munis")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;
}

Don't forget to generate getters/setters. All relationships are bi-directional.


text:
Q: RadDataControl. Hide add new logical opearor button Is there a way to hide the add logical operator button?
The green one with three white dots at the end of each filter descriptor

A: You can modify the control template with Blend to achieve your goal.

A: Adding this attribute to the component does it
CanUserCreateCompositeFilters="False"


text:
Q: Can't get client's real IP when using Nginx in Docker I have configured Nginx reverse proxy with Docker in my project.
part of my docker-compose file:
version: "3"

# optional ports are specified throughout for more advanced use cases.

services:
  proxy-service:
    container_name: budi-nginx-dev
    restart: on-failure
    image: nginx:latest
    volumes:
      - ./.generated-nginx.dev.conf:/etc/nginx/nginx.conf
    ports:
      - "${MAIN_PORT}:10000"
    depends_on:
      - minio-service
      - couchdb-service
    extra_hosts:
      - "host.docker.internal:host-gateway"

I have add "X-Forwarded-For proxy_set_header" in "location /api/".
part of my nginx file:
user                    nginx;
error_log               /var/log/nginx/error.log debug;
pid                     /var/run/nginx.pid;
worker_processes        auto;
worker_rlimit_nofile    33282;

events {
  worker_connections  1024;
}

http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  proxy_set_header Host $host;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

  map $http_upgrade $connection_upgrade {
    default     "upgrade";
  }

  server {
    listen       10000 default_server;
    server_name  _;
    client_max_body_size 1000m;
    ignore_invalid_headers off;
    proxy_buffering off;

    location ~ ^/api/(system|admin|global)/ {
      proxy_pass      http://host.docker.internal:4002;
    }

    location /api/ {
      proxy_read_timeout 120s;
      proxy_connect_timeout 120s;
      proxy_send_timeout 120s;

      proxy_http_version  1.1;
      proxy_set_header    Connection          $connection_upgrade;
      proxy_set_header    Upgrade             $http_upgrade;
      proxy_set_header    X-Real-IP           $remote_addr;
      proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;

      proxy_pass      http://host.docker.internal:4001;
    }

    location /app_ {
      proxy_pass      http://host.docker.internal:4001;
    }

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;

      proxy_connect_timeout 300;
      proxy_http_version 1.1;
      proxy_set_header Connection "";
      chunked_transfer_encoding off;

      proxy_pass      http://minio-service:9000;
    }

    client_header_timeout 60;
    client_body_timeout   60;
    keepalive_timeout     60;
    gzip                  off;
    gzip_comp_level       4;
  }
}

When I request api that start with "api/", I get "127.20.0.1" of "X-Forwarded-For" property in the request header. Obviously it is not the real client ip.
I would like to known how to get the real client ip in this case.


text:
Q: Simple supremum/infimum proof Let $A$ and $B$ be non-empty  subsets of $\mathbb{R}$ with  $a\leq b$ for all $a\in  A, \space b \in B$ and suppose there exists a  unique number $\alpha$ such that $a\leq \alpha \leq b$ for all $a\in  A, \space b \in B.$ Then we have $\alpha  = \sup A = \inf B$.
Proof: Suppose $\alpha < \sup A.$ If $S = \sup A\in  A$ we are done so  assume  this is not the case. Choose  $k = \dfrac{\alpha +  S}{2}$ so $\alpha < k$ and $k < S.$ Now we can choose some $A\ni  a \geq k$ which yields a contradiction  since $\alpha <a$. One can similarly show that $\alpha \leq \inf B.$ We conclude that  $\sup A \leq \alpha \leq \inf B$ and since $\alpha$ is unique it follows that $\alpha  = \sup A = \inf B$.
Does my proof seem sound? If  not, what do I have to adjust?

A: Your argumentation is correct but I would add a bit more detail to the last sentence: Assume that $\sup A\neq \alpha \neq \inf B$ so we would obtain the inequality $\sup A < \alpha < \inf B$. Then we could choose a number
$t = \dfrac{
\alpha + \inf B}{2}$ (analogous to how you chose $k$ in your proof) so $\sup A < \alpha  < t < \inf B$ which would contradict the uniqueness of $\alpha.$ The same applies for $\sup A$. This makes your last conlcusion more clear in my opinion.
In general, it's good to try keeping the proof concise whereby one should not leave out details that make it "hard" to follow.

A: I was initially lost by your first two sentences. It is not super clear with what "we are done" if $\sup A$ belongs to $A$. In any case, we can take the given existence of $\alpha$
and apply just the definitions of supremum and infimum to say $\sup A \leq \alpha \leq \inf B$.
Your final statement is sound, although it took me some time to become convinced. Of course it is intuitively obvious. You might want to add some detail to make clear why "it follows".   As for myself,
I became convinced when I wrote it this way: $\,\,\,\,\alpha$ is unique $\,\,\implies\,\, \inf B \,\leq\, \sup A.$
Or, even more clear to me is: $\,\,\,\,\alpha$ is not unique  $\,\,\impliedby\,\, \sup A \,< \,\inf B.$


text:
Q: How to create a dataset from a select in the database? I have a database, postgresql and I make the select in the table iaconsultas.
conn = psycopg2.connect(host="10.1...", port="5432", database="dbname", user="username", password="pwd")
cur = conn.cursor()
cur.execute("SELECT dsobservacao,cid FROM iaconsultas limit 100")
col_names = [i[0] for i in cur.description]
# retrieve the records from the database
records = cur.fetchall()

#print(col_names) print columns name
#print(records) print data

The variable col_names shows me the names of the colunase records, the values entered in each one.
I am studying for machine learning and would like to create a dataset with the values of the columns and their respective names, for the labels.
DataSet for example:
dsoberservacao;cid
valueinserted;idcid

Is it possible to do that? How can I do it? Thank you!


text:
Q: DMOS values in LIVE IQA Database has negative values I'm working on Image Quality Assessment with LIVE Database. I'm validating a QA algorithm, which is non-linearly dependent on subjective scores (DMOS values). So, I'm trying to fit a curve to find the equation of a curve, I'm taking log on both x and y axes which gives me a linear fit.
But for JPEG Img14 and Img58 have negative DMOS values (-0.19 & -2.64 respectively).

*

*What does this mean? Does it mean that JPEG compressed image is better in quality than original image?

*This is causing me problem while taking log and then using power. How do I fix this issue?


text:
Q: Do you use Javadoc for every method you write? Should I be writing Doc Comments for all of my java methods?

A: When I write code for myself - NO. In this case, java doccing is a waste of my time.
When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a java doc at least stating its obvious purpose. For a good test - run the javadoc creation utility on your code (I forget the exact command line now). Browse through the webpage it generates. If you would be satisfied using a library with that level of documentation, you're golden. If not, Write more javadocs in your code.

A: There is another reason you should use javadocs. In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.

A: @Claudiu

When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.

@Daniel Spiewak

I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.

@Paul de Vrieze

For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter

/**
 * Get the current value of the foo property.
 * The foo property controls the initial guess used by the bla algorithm in
 * {@link #bla}
 * @return The initial guess used by {@link #bla}
 */
int getFoo() {
  return foo;
}

And yes, this is more work.
@VonC
When you break a huge complex method (because of high cyclomatic complexity reason) into:

*

*one public method calling

*several private methods which represent internal steps of the public one

, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.
Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.
And remember: limit values or boundary conditions should be part of your javadoc as well.
Plus, javadoc is way better than simple "//comment":

*

*It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a constant - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: regexp (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)

*It can be parsed by external tools (like xdoclet)

@Domci

For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]
In short, comment logic, not syntax, and do it only once, on a proper place.

@Miguel Ping

In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.

A: If the method is, obviously self evident, I might skip a javadoc comment.
Comments like
/** Does Foo */
 void doFoo();

Really aren't that useful. (Overly simplistic example, but you get the idea)

A: I thoroughly document every public method in every API class.  Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc.  I also document every protected method in every API class, though to a lesser extent.  This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit.  Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.

A: simply put: YES
The time you need to think about whether you should write a doc,
is better invested in writing a doc.
Writing a one-liner is better than spending time for not documenting the method at all in the end.

A: For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. There are a few guidelines:

*

*APIs, framework classes, and internal reusable static methods should be commented thoroughly.

*Logic in every complicated piece of code should be explained on two places - general logic in javadoc, and logic for each meaningful part of code in it's own comment.

*Model properties should be commented if they're not obvious. For example, no point in commenting username and password, but type should at least have a comment which says what are possible values for type.

*I don't document getters, setters, or anything done "by the book". If the team has a standard way of creating forms, adapters, controllers, facades... I don't document them, since there's no point if all adapters are the same and have a set of standard methods. Anyone familiar with framework will know what they're for - assuming that the framework philosophy and way of working with it is documented somewhere. In this cases, comments mean additional clutter and have no purpose. There are exceptions to this when class does something non-standard - then short comment is useful. Also, even if I'm creating form in a standard way, I like to divide parts of the form with short comments which divide the code into several parts, for example "billing address starts here".
In short, comment logic, not syntax, and do it only once, on a proper place.

A: Java doc should not be relied on, as it places a burden on developers making changes to maintain the java doc as well as the code.
Class names and function names should be explicit enough to explain what is going on.
If to explain what a class or method does makes its name too long to deal with, the class or method is not focused enough, and should be refactored into smaller units.

A: All bases covered by others already; one additional note:
If you find yourself doing this:
/**
 * This method currently launches the blaardh into the bleeyrg.
 */
void execute() { ... }

Consider changing it into this:
void launchBlaardhIntoBleeyrg() { ... }

This may seem a bit obvious, but in many cases the opportunity is easy to miss in your own code.
Finally keep in mind that the change is not always wanted; for instance the behaviour of the method may be expected to evolve over time (note the word "currently" in the JavaDoc).

A: For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter.
/**
 * Get foo
 * @return The value of the foo property
 */
int getFoo() {
  return foo;
}

Is not useful. Better do something like:
/**
 * Get the current value of the foo property.
 * The foo property controls the initial guess used by the bla algorithm in
 * {@link #bla}
 * @return The initial guess used by {@link #bla}
 */
int getFoo() {
  return foo;
}

And yes, this is more work.

A: No, do not comment every method, variable, class, etc..
Here's a quote from "Clean Code: A Handbook of Agile Software Craftsmanship":

It is just plain silly to have a rule that says that every function must have a
  javadoc, or every variable must have a comment. Comments like this just clutter
  up the code, popagate lies, and lend to general confusion and disorganization.

A comment should exist if, and only if, it adds important information for the intended user of the method, variable, class, etc.. What constitutes "important" is worth consideration and could be a reminder to myself when/if I come back to this method/class/etc., a consequence/side effect of the method, motivation for why the thing even exists (in the case where some code is overcoming a shortcoming/bug of some library or system), important information about the performance or when it is appropriate to call, etc..
What is not a good comment but indicates the code itself should be rewritten/modified is a comment explaining the details of a complex and obscure method or function. Instead, prefer shorter clearer code.

A: I feel there should at least be comments regarding the parameters accepted and return types in term of what they are.
One can skip the implementation details in case the function names describes it completely, for eg, sendEmail(..);

A: I make it a point to write javadoc comments whenever it is non-trivial, Writing javadoc comments when using an IDE like eclipse or netbeans isn't that troublesome. Besides, when you write a javadoc comment, you are being forced to think about not just what the method does, but what the method does exactly, and the assumptions you've made.
Another reason is that once you've understood your code and refactored it, the javadoc allows you to forget about what it does since you can always refer to it. I'm not advocating purposely forgetting what your methods do but it's just that I prefer to remember other things which are more important.

A: You should probably be documenting all of your methods really.  Most important are public API methods (especially published API methods).  Private methods are sometimes not documented, although I think they should be, just for clarity - same goes with protected methods.  Your comments should be informative, and not just reiterate what the code does.
If a method is particularly complex, it is advised that you document it.  Some people believe that code should be written clearly so that it doesn't require comments.  However, this is not always possible, so comments should be used in these cases.
You can automate the generation of Javadoc comments for getters/setters from Eclipse via the code templates to save on the amount of documentation you have to write.  another tip is to use the @{$inheritDoc} to prevent duplication of code comments between interfaces and implementation classes.

A: Javadoc can be really useful for libraries and reusable components. But let's be more practical. It is more important to have self explaining code than javadoc.
If you imagine a huge legacy project with Javadocs - would you rely on that? I do not think so... Someone has added Javadoc, then the implementation has changed, new feature was added (removed), so the Javadoc got obsolete.
As I mentioned I like to have javadocs for libraries, but for active projects I would prefer

*

*small functions/classes with names which describe what they do

*clear unit test cases which give explanation what the
function/classes do

A: at a previous company, we used to use the jalopy code formatter with eclipse. That would add javadoc to all the methods including private.
It made life difficult to document setters and getters. But what the heck. You have to do it -- you do it. That made me learn some macro functionality with XEmacs :-) You can automate it even further by writing a java parser and commenter like ANTLR creator did several years ago :-)
currently,  I document all public methods and anything more than 10 lines.

A: I try to at the very least document every public and interface property and method, so that people calling into my code know what things are.  I also try to comment as much as possible in line as well for maintenance sake.  Even 'personal' projects I do on my own time just for myself, I try to javadoc just because I might shelf it for a year and come back to it later.

A: You can run javadoc against code that does not have javadoc comments and it will produce fairly useable javadocs if you give thoughtful names to your methods and parameters.

A: Assumed in all the answers so far is that the comments will be good comments.  As we all know that is not always the case, sometimes they are even incorrect.  If you have to read the code to determine its intent, boundaries, and expected error behavior then the comment is lacking.  For example, is the method thread safe, can any arg be null, can it return null, etc.  Comments should be part of any code reviews.
This may be even more important for private methods since a maintainer of the code base will have to contend with issues that an API user will not.
Perhaps IDEs should have a feature that allows the use of a documenting form so that the developer can check off various properties that are important and applicable for the current method.


text:
Q: What is Proguard's obfuscated local variable naming convention? Proguard obfuscates local variables, unless told otherwise. From the manual:

ProGuard's obfuscation step does remove the original names entirely, unless you explicitly keep the LocalVariableTable or LocalVariableTypeTable attributes.

I am in possession of both the source code and the obfuscation map for an app, however there is no information I can see relating to the mapping for local variable names. I'm wanting to plug in a debugging agent to print out some variable names for some methods in a distribution of the app (I've made the agent using javassist), however this is not an easy task without knowing the variable names.
It's not the source code variable name, and my IDE's java decompiler says the variable's names are "var0", "var1" which are also not correct (and I suspect are just placeholders).


text:
Q: How to do a certain task only with the first output of a foreach loop? I want to output values of a list like this, but also I want to prepend another value to only the first element of the list, i.e. valuesInRow[0]. How do I do this while also outputting the other values in the list without the prepend?
<c:forEach var="valuesInRow" items="${valuesInRows}">
  ${idPrepend}${valuesInRow}
</c:forEach>

A: You can use varStatus: How to get a index value from foreach loop in jstl
It will give you some control about the loop.

A: Maybe you could get a hold onto the current index, and use aan if to check that you are on the first one ?
<c:forEach var="valuesInRow" items="${valuesInRows}" varStatus="loop">
  <c:if test = "${loop.index == 0}"></c:if>${idPrepend}${valuesInRow}
</c:forEach>


text:
Q: Filter based on NotNull criteria So I'm trying to filter out the jsonResponse based on some keys ... return that block if it has all the provided keys
The pseudo code is like this:
public Object filterSomething(String key1, String key2, String key3){

    for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
        if (singleBock.IncludesAllNotNullKeys) {
            return singleBlock
        }
    }

}

Note that any key could be Null (which is specified by the end-user), in that case I'm gonna filter the result based on the ones that are not null.
clearly I can check the check which ones are NotNull and then have multiple for loops (but that looks very messy! ) ... something like this:
public Object filterSomething(String key1, String key2, String key3){

    if (key1 != Null && key2 != Null && key3 != Null) {
        for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
            if (singleBock.IncludesAllKeys()) {
                return singleBlock
            }
        }
    }

    if (key1 != Null && key2 != Null) {
        for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
            if (singleBock.IncludesBothKeys()) {
                return singleBlock
            }
        }
    }

    ...

}

Is there any suggestion on how to handle this case properly?

A: I would just check the null in the logic when you check if a single block contains that keys: singleBock.IncludesAllNotNullKeys
The method could look like this:
private boolean includesAllNotNullKeys(Object singleBlock, String key1, String key2, String key3) {
    boolean check1 = key1 == null || singleBlock.contains(key1);
    boolean check2 = key2 == null || singleBlock.contains(key2);
    boolean check3 = key3 == null || singleBlock.contains(key3);
    return check1 && check2 && check3;
}

Of course, this is tailored exactly to your problem. For a more reusable, generic way you could handle the keys as var-args or List<String> and the method could iterate and break accordingly.