text:
Q: данные из активити в Button navigation у меня есть панель button navigation с 5 кнопками снизу и несколько активити. Пользователь на второй кнопке начинает заполнять данные, там он вписывает в 4 активностях данные. На последней активности отображается его номер и фио,после чего снизу есть кнопка перехода на главную страницу ( это первая из 5 кнопок), как мне сделать чтобы при нажатии на эту кнопку пользователь оказался на главной странице и потом,при его желании он мог нажать на 5 кнопку где бы появились эти данные. То есть он переходит с 4 активности где все данные на главный экран и потом переходит на 5 кнопку и экраном, где все данные. Как это можно сделать? желательно для переноса использовать intent, его я уже хорошо изучил...

A: Если вы хотите всерьез заняться мобильной разработкой, то всё это не подойдет, нужно делать иначе.
Активити должна быть одна, в ней только меню и пустой контейнер (FrameLayout), в котором будут запускаться фрагменты, содержащие экраны приложения.
Как это правильно сделать, хорошо описано здесь:
https://coderlessons.com/articles/mobilnaia-razrabotka-articles/kak-kodirovat-nizhniuiu-panel-navigatsii-dlia-prilozheniia-dlia-android
Что касается передачи данных, интенты как раз не желательны.
Ключевое слово для вас: viewmodel, изучите эту тему обязательно, без нее нет современной мобильной разработки.
Вам нужно завести одну общую для всех фрагментов вьюмодель, в которой будут храниться данные и доступ к которой будет с любого экрана.


text:
Q: Nginx alongside apache in PLESK 9.3 Does anyone know how to set up Nginx alongside Apache in Plesk 9.3. I want to serve my dynamic content from Apache and the static content from Nginx.
I read that there is a new configuration setting in Plesk 9.3 where you can do that, but I can't find an explanation on how to do so.
I run CentOS 5.

A: "Apache Port Change" chapter of "Advanced Administration Guide" from Plesk documentation should get you started.
It's not just a simple setting which can be enabled though - requires quite a bit to reconfigure/check.
update: it would help if you let us know what exactly is the problem now? which step are you stuck on?

*

*nginx installation

*changing HTTP/HTTPS ports which are generated by Plesk using websrvmng, i.e. moving Apache to the back-end - described in the document

*nginx configuration and setting up event handlers in Plesk  - see examples in the document

this blog post might be useful as well, without part "3. Configuring Apache" - because this can now be done automatically in Plesk 9.3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make eclipse refer to workspace in the same folder as exe file? How to make eclipse refer to workspace in the same folder as eclipse.exe file without asking me every time. I use eclipse on usb stick on several computers (different labs around campus + my own laptop), and drive letter always changes, so is there a way to make eclipse... more portable?

A: See this answer about starting Eclipse with a specific workspace
There is a command-line argument -data you can give Eclipse for the location of the workspace.  You could create a batch file called 'runeclipse.bat' and give it the current directory as the location of the workspace.  I would create a subdirectory named 'workspace' though.
eclipse.exe -data .\workspace

A better idea would be to edit the eclipse.ini, which is in the same directory as the executable, and put the -data argument there. Make sure the -data argument appears before any JVM arguments
For example, here is my eclipse.ini file
-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms40m
-Xmx384m

I would add the -data argument like so, I've left empty lines to show what was added since there is no HTML or Markdown formatting in a code block, remember that the blank lines should not be in the actual eclipse.ini file.
-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile

-data
.\workspace

-vmargs
-Xms40m
-Xmx384m


text:
Q: Docker: problem with run a file jar in docker I'm new in the community and i'm new in docker's world. i have to virtualize a leshan server through docker and I have to do this with the option "--redis" that leshan makes avaible. so I decided to take a dockerfile from docker hub and modify the last "CMD" operation adding the option "--redis". The Build of images is successful but when i try to run the image in a container the error is "Invalid or corrupt jarfile". This problem show up also without the option "--redis" (with the no modify dockerfile). The strange thing is that if I pull the image from dockerhub and run the server build through same dockerfile, it works!
This is the docker file:
FROM linarotechnologies/alpine:edge

RUN apk add --no-cache openjdk8-jre-base ca-certificates shadow curl
runit

RUN mkdir -p /opt/leshan-server-demo && \
    curl -o /opt/leshan-server-demo/leshan-server-demo.jar \
    https://hudson.eclipse.org/leshan/job/leshan/lastSuccessfulBuild/artifact/leshan-server-demo.jar
RUN useradd -r -d /opt/leshan-server-demo -s /sbin/nologin -U leshan

CMD cd /tmp && chpst -u leshan java -jar /opt/leshan-server-demo/leshan-server-demo.jar $LESHAN_ARGS

this is the build:

Sending build context to Docker daemon  7.294MB
Step 1/5 : FROM linarotechnologies/alpine:edge
 ---> 7463224280b0
Step 2/5 : RUN apk add --no-cache openjdk8-jre-base ca-certificates shadow curl runit
 ---> Using cache
 ---> ebe6e6280cdf
Step 3/5 : RUN mkdir -p /opt/leshan-server-demo &&     curl -o /opt/leshan-server-demo/leshan-server-demo.jar         https://hudson.eclipse.org/leshan/job/leshan/lastSuccessfulBuild/artifact/leshan-server-demo.jar
 ---> Using cache
 ---> 52b61160e8c5
Step 4/5 : RUN useradd -r -d /opt/leshan-server-demo -s /sbin/nologin -U leshan
 ---> Using cache
 ---> 53419af60e36
Step 5/5 : CMD cd /tmp && chpst -u leshan java -jar /opt/leshan-server-demo/leshan-server-demo.jar $LESHAN_ARGS#
 ---> Running in 52cb5fc95ffb
Removing intermediate container 52cb5fc95ffb
 ---> 68acab7c306e
Successfully built 68acab7c306e
Successfully tagged leshan-server:latest

And this is the error when i run:

sudo docker run --rm -ti --name leshan-server leshan-server
  Error: Invalid or corrupt jarfile /opt/leshan-server-demo/leshan-server-demo.jar

Any ideas? Thank you for help!

A: https://hudson.eclipse.org/leshan/job/leshan/lastSuccessfulBuild/artifact/leshan-server-demo.jar

This url has redirect with 302. You have to use -L parameter with curl to follow the link.

A: ~# curl -o test.jar https://hudson.eclipse.org/leshan/job/leshan/lastSuccessfulBuild/artifact/leshan-server-demo.jar

~# cat leshan-server-demo.jar

<title>302 Found</title>

302 Found

nginx

curl is downloading the html redirect page.
You can tell curl to follow the redirects using -L option.
/opt/leshan-server-demo # curl -L -o test.jar https://hudson.eclipse.org/leshan/job/leshan/lastSuccessfulBuild/artifact/leshan-server-demo.
jar
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   138  100   138    0     0    316      0 --:--:-- --:--:-- --:--:--   315
100 7618k  100 7618k    0     0   622k      0  0:00:12  0:00:12 --:--:--  481k
/opt/leshan-server-demo #


text:
Q: Modify @RequestBody object in Controller From Filter I want to modify an object that has already been populated with JacksonMapper and add the IP and Referrer URL to it automatically, but the request is always null because it isn't found in the attributes array.  Am I doing something wrong?
ApiController.java
@RequestMapping(value="/member/follow")
    public @ResponseBody IHttpResponse follow(@RequestBody FollowRequest request) {
        return request.getHttpResponse();
    }

ApiRequestWrapper.js
public class ApiRequestWrapper extends HttpServletRequestWrapper
{
    public ApiRequestWrapper(HttpServletRequest request) {
        super(request);

        if(this.getAttribute("request") instanceof IHttpRequest)
        {
            IHttpRequest httpRequest = (IHttpRequest) this.getAttribute("request");

            if(httpRequest != null)
            {
                httpRequest.setIp(request.getRemoteAddr());
                httpRequest.setReferrer(request.getLocalName());
            }
        }
    }
}

Web.xml
<filter>
    <filter-name>apiFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>apiFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

A: The object corresponding to the RequestBody is created just before the method is invoked - there is no way to get hold of it in the filter.  You can achieve what you want to do by implementing an Aspect.


text:
Q: TeamCity Visual Studio plugin with Git We'd like to implement CI using TeamCity.
We use Git for source control and would like to make use of the "pre tested commits" or "personal builds" feature of TeamCity.
Does anyone have experience with the VS plugin for Teamcity?
As far as I've seen, it only supports Subversion, no word about Git.
Anyone used this setup with any success?

A: As explained in Pre-tested "Commits" using Git by JoergM, you can emulate a solution similar to the TeamCity6.x "Personal builds on branches", by using personal repos:
.

There is one central Git-repository that only contains pre-tested changes. I call this "Green Repository" because it should only contain changes that lead to green builds.
  Every developer pulls from this repository but nobody is allowed to push to it.
Instead everybody has a personal repository (think fork if you were on GitHub). The CI Server watches those personal repositories. After a commit it starts the compile and test. If that was successful it pushes the changes to the Green Repository.

JoergM adds:

The question is whether we will continue using our own solution or switch to the new feature of Teamcity.
  So far I can't see any advantage of the Teamcity feature.
  With our solution we are even more flexible in regard of branch design.

This kind of setup is similar to what I described in "What is the cleverest use of source repository that you have ever seen?".

A: TeamCity 6.5 has new feature: remote run on a branch. It works for Git and Mercurial and does not require IDE, see more here: http://confluence.jetbrains.net/display/TCD65/Branch+Remote+Run+Trigger

A: Note that support for Git branches has been considerably improved in TeamCity 7.1. In my opinion, this is far better than the personal build feature.
The relevant docs are available here: http://confluence.jetbrains.net/display/TCD7/Working+with+Feature+Branches


text:
Q: Asp.net Mvc ,Crystal Reports and Azure I have few question regarding to Crystal reports and Azure VM

*

*Is crystal reports is free if I am designing Reports in the Visual studio 2013,

*If I want to deploy my application on Azure Virtual Machine having Crystal reports, so is there is any extra charges for Crystal reports.

*Is Crystal Reports Runtime is free on Azure
Thank you

A: *

*Based on this link
Crystal reports is free and will only work if your version of Visual Studio is not the express edition.

*No, there would not be any charges

*Runtime is not on azure, SAP purchased crystal reports and the developer runtime is free to download.

A: kindly please check this link,
it was free before 2011 but not after 2011, you have to use there designing tool, or you have to buy license if you are exposing you application on the internet.
Crystal report license


text:
Q: Rails 7 respond_to ActionController::UnknownFormat error I've been playing around with Ruby on Rails 7 and I want to update a div element rendering a partial with format.js but an error arise when the execution reaches this line.
This is my controller:
class StocksController < ApplicationController
  def search
    if params[:stock].present?
      @stock = Stock.new_lookup(params[:stock])

      if @stock
        respond_to do |format| # <-------------------- Here is the error
          format.js { render partial: 'users/result' }
        end
      else
        flash[:alert] = 'Please enter a valid symbol to search'
        redirect_to my_portfolio_path
      end
    else
      flash[:alert] = 'Please enter a symbol to search'
      redirect_to my_portfolio_path
    end
  end
end

I created a view where I created a div to modify only that div which id is 'results'.
  <%= form_tag search_stock_path, remote: true, method: :get do %>

        <%= text_field_tag :stock,
          params[:stock],
          placeholder: 'Stock ticker',
          autofocus: true,
          class: 'form-control form-control-lg' %>

        <%= button_tag type: :submit, class: 'btn btn-success' do %>

        <% end %>

  <% end %>

I have a partial name users/result.js.erb and when I submit the search I receive this error:
ActionController::UnknownFormat - ActionController::UnknownFormat:
  app/controllers/stocks_controller.rb:7:in `search'

This is my directory for more details:

And this is my routes.rb
Rails.application.routes.draw do
  devise_for :users
  root "welcome#index"
  get 'my_portfolio', to: 'users#my_portfolio'
  get 'search_stock', to: 'stocks#search'
end

Anyone knows what's going on here when respond_to is executed?
Why this ActionController::UnknownFormat error?


text:
Q: ¿Cómo sumar valores repetidos en PHP? Tengo un pequeño inconveniente. Estoy en el desarrollo de una Tabla de Goleadores de Futbol, es una tabla que debe mostrar dos campos: el nombre del jugador y el numero de goles. En PHP programe esto:
public function getTablaGolLP() {
    $response = array();
    $stmt = $this->conn->prepare("SELECT * FROM resultados_partidos WHERE estado = 'A'");
    //$stmt->bind_param("s", $id_resultado);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $response[] = array(
            'id_partido' => $row["id_partido"],
            'jugadores' => $this->getJugadorByLocalANDVisitante($row["id_resultado"]),
        );
    } return $response;
}

public function getJugadorByLocalANDVisitante($id_resultado) {
    $response = array();
    $stmt = $this->conn->prepare("SELECT * FROM resultados_partidos WHERE id_resultado = ? AND estado = 'A'");
    $stmt->bind_param("s", $id_resultado);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_array(MYSQLI_ASSOC)) {

        $jugadorloc = explode(',', $row['jugadores_local']);
        $arreglo_jugadores = array();

        //array_unique(devuelve todos los valores de un array)
        //count(cuenta todos los elementos de un arreglo u objeto)
        //validar que no se repita el jugador, tanto local como visitante
        //contar el numero de goles segun el numero de veces que se repite el id del jugador y guardarlo en una variable acumuladora
        //in_array — Comprueba si un valor existe en un array
        ///si ya existe el id se suma 1(gol) en una arreglo

        if ($jugadorloc != ""){
            $cantidadgoles = array_count_values($jugadorloc);
            //var_dump ($cantidadgoles);
            //var_dump($jugadorloc);
            $lista_simple = array_values(array_unique($jugadorloc, SORT_REGULAR));
            //var_dump($lista_simple);
            foreach($lista_simple as $key){
                $arreglo_jugadores[] = array(
                    'name_jugador' => $this->getJugadorById2($key),
                    'goles_local' => $cantidadgoles,
                );
                //var_dump($arreglo_jugadores);
            }
        }
        $response = array(
            'jugadoresloc' => $arreglo_jugadores,

        );
        return $response;
    } else return RECORD_DOES_NOT_EXIST;
}

Este código arma mi respuesta en el servidor. El problema es que no encuentro manera para que los jugadores de futbol que tienen su id no se repitan, puesto hay que los jugadores se dividen en jugadores_local y jugadores_visitante, en muchos casos se va a repetir el nombre del jugador ya que un jugador en un partido hizo gol de local, y después en otro partido hace algún gol de visitante. Cuando hago el append en JavaScript me lista todos los jugadores que hacen gol sin importar si es local o visitante.
El otro problema que tengo es que muchas veces esos jugadores van a hacer mas de un gol en el partido, así que no se como filtrarlo para que me aparezca una sola vez. Finalmente en la columna de numero de goles, debo ubicar la veces que ese jugador hizo gol, y la manera de obtener ese valor, es contar el numero de veces que se repite el id del jugador y luego pintarlo en la tabla.
Este es mi código JavaScript:
$.get('../API/public/tablaGolLP/JugadorByEquipo/', {}, function(returnedData){
    if(returnedData["error"] == false){
        returnedData["tablaGolLP"].forEach(function(tablaGolLP){
            //console.log(tablaGolLP["jugadorLoc"]["jugadores"][0]);
            if(tablaGolLP["jugadores"]["jugadoresloc"][0]["name_jugador"] != 3){
                tablaGolLP["jugadores"]["jugadoresloc"].forEach(function(jugador){
                    temporal = Object.assign([],jugador["name_jugador"]);  ///push
                    repetidos.push(jugador);
                $("#tablaGoleadores").append("
" + jugador["name_jugador"]["jugador"]
            + "	" + "" + "
");
            })
        }
        });
    }else{
        SweetAlert("error", returnedData["msg"]);
    }
}).done($(function(){
    $('#goleadores-data').DataTable({
        paging: false,
        searching: false,
        ordering: true,
        info: false,
        retrieve: true,
        responsive: true,
        order: [[ 1, "desc"]],
        });
    }));

A. Cedano, esta es la foto de la tabla de donde extraigo los id de los jugadores que anotaron gol

esta es la imagen de la respuesta que me da el servidor, me gustaria que el id 5 que pertenece a un jugador x apareciera solo con el name del jugador, y no me imprima el 5 y el 11 que es del otro jugador que anoto gol

Les pido que por favor me ayuden!
Gracias de antemano.


text:
Q: Calling jQuery function by var reference I'm trying to change the jQuery function called using the value of the switch. In this particular case It will grab the selector then use whatever the value of 'direction to call on jQuery function.
$('#'+the_name).value_of_switch(options.speed_up);

How can I accomplish this?
switch(direction){
    case 'up':   direction = 'slideDown';
    break;

    case 'down':  direction = 'slideUp';
    break;
}

$('#'+the_name).slideDown(options.speed_up);

A: Not too sure this is what you mean, does that help?
$('#'+the_name)["YOUR STRING VALUE HERE"](options.speed_up);

A: $(document).ready(function(){
var direction = 'up';
var theName = $('#the_name');
  var options = {speed_up:'slow'};
switch(direction){
      case 'up':
            direction = 'slideUp' ;
      break;

      case 'down':
            direction = 'slideUp' ;
      break;
}

theName[direction](options.speed_up);

});
http://jsfiddle.net/VrPxd/32/


text:
Q: Passport strategy for authenticating with LinkedIn using the OAuth 1.0a API return undefined email on save User I am beginner in node.js development and trying to build an application based on Express framework. I implemented passport-local passport-facebook and passport-linkedin for the users to sign up and log in to the application as well as linking multiple social account to a single user account in mongoDb (from this tutorial).
My problem is that I always get undefined e-mail field when using passport-linkedin even if i can get firstname and lastname with a correctly authenticated user.
passport.js
passport.use(new LinkedinStrategy({
consumerKey     : configAuth.linkedinAuth.consumerKey,
consumerSecret  : configAuth.linkedinAuth.consumerSecret,
callbackURL     : configAuth.linkedinAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
  function(req, token, tokenSecret, profile, done) {
  // asynchronous
  process.nextTick(function() {
   // check if the user is already logged in
   if (!req.user) {
    User.findOne({ 'linkedin.id' : profile.id }, function(err, user) {
    if (err)
        return done(err);
      if (user) {
        // if there is a user id already but no token (user was linked at one point and then removed)
        if (!user.linkedin.token) {
        [...]
        } else {
         // if there is no user, create them
         var newUser                  = new User();
         newUser.linkedin.id          = profile.id;
         newUser.linkedin.token       = token;
         newUser.linkedin.firstname   = profile.name.givenName;
         newUser.linkedin.lastname    = profile.name.familyName;
         newUser.linkedin.email       = profile.emails;
         newUser.save(function(err) {
            if (err)
                return done(err);
            return done(null, newUser);
         });
        }
      });
    } else {
    // user already exists and is logged in, we have to link accounts
    [...]
  }
 });
}));

routes/accounts.js
// linkedin --------------------------------
// send to linkedin to do the authentication
app.get('/auth/linkedin', passport.authenticate('linkedin', { scope: ['r_basicprofile', 'r_emailaddress'] }));

// handle the callback after linkedin has authenticated the user
app.get('/auth/linkedin/callback',
  passport.authenticate('linkedin', {
    successRedirect : '/profile', // redirect to the secure profile section
    failureRedirect : '/signup', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

I could find firstname and lastname to save into my User database from looking at Passport-LinkedIn/lib/strategy.js, then I did the same with profile.emails bit still remains "undefined" after authenticating proprely the user.
Thank you in advance for your help.
Edit: From LinkedIn Developer FAQ

While we have not announced the official deprecation of OAuth 1.0a in
  conjunction with LinkedIn's APIs, we no longer actively encourage or
  support its use.
Existing applications built with OAuth 1.0a will continue to
  functional normally until such time as we officially announce its
  sunset.
Using or transitioning to OAuth 2.0 is strongly encouraged for all
  applications.

A: Had the same issue a while back and now got it working. Have you tried with oauth2? If you have already implemented passport-linkedin then this should be minor changes for your passport.js file.
OAuth 1.0 was deprecated by Linkedin, hence why it may causes some issues to retrieve some information. I guess you're facing the same situation. Try this and you should be good to go!


text:
Q: Ignore minimum values from distincts rows in pandas I've below pandas dataframe
Name    |  Value1 |  Value2
User 1  |  1      |  15
User 1  |  2      |  35
User 1  |  3      |  35
User 1  |  3      |  35
User 2  |  4      |  23
User 2  |  5      |  25
User 3  |  6      |  45
User 3  |  7      |  50

I want to select only those rows which have largest value in Value2 column using pandas dataframe
Like this:
Name    |  Value1 |  Value2
User 1  |  2      |  35
User 1  |  3      |  35
User 1  |  3      |  35
User 2  |  5      |  25
User 3  |  7      |  50

Code with description will help me more as pandas are new for me.
Thanks in Advance :)

A: Use GroupBy.transform with max for Series filled by max values per groups, compare by column Value2 with Series.eq and filter by boolean indexing:
df1 = df[df.groupby('Name')['Value2'].transform('max').eq(df['Value2'])]
print (df1)

     Name  Value1  Value2
1  User 1       2      35
2  User 1       3      35
3  User 1       3      35
5  User 2       5      25
7  User 3       7      50

Details:
print (df.groupby('Name')['Value2'].transform('max'))
0    35
1    35
2    35
3    35
4    25
5    25
6    50
7    50
Name: Value2, dtype: int64

print (df.groupby('Name')['Value2'].transform('max').eq(df['Value2']))
0    False
1     True
2     True
3     True
4    False
5     True
6    False
7     True
Name: Value2, dtype: bool


text:
Q: Auto suggest wordpress.stackexchange.com when wordpress tag selected
Possible Duplicate:
This question may belong to <Another site>, consider migrating - feature request

I saw several questions in the past several days that related to wordpress and more appropriate to be asked on wordpress.SE. The latest one is this How can I add my own contact form in wordpress
Most of the time, this kind of questions is came from newcomers who doesn't even know that there is Wordpress.SE exist. I would like to suggest to add some sort of auto suggest, just like Questions with similar titles that pop up just below title, when asking question.


text:
Q: How to take info from particular amount of elements with the same class name? I have a lot of tables on the same screen. And i need to take tex from only one of it
Simple example:
    Table:Phone
div id="phone_type" type-id="pass" class="panel panel-default sort_table">

PHONE

Home

          Edit

          Delete

Work

          Edit

          Delete

    </form>

Table:Condo

CONDO

Limited

          Edit

          Delete

Free

          Edit

          Delete

</form>

And i need to take text of col-md-8 col-xs-8 increase_padding
But the problem is that when i am using:
table_content = driver.find_elements_by_css_selector('.col-md-8.col-xs-8.increase_padding')

it also takes info from tables that i am currently don't need.
But i need to take text only from 1 particular table.
Those tables are dynamic, so I can't take particular amount from
table_content

and append it to another list.
Is it a way to address to particular table and work with its outer HTML?

A: Just make context-specific searches. E.g. If you need this element from a "phone type" table:
phone_type = driver.find_element_by_id("phone_type")
print(phone_type.find_element_by_css_selector('.col-md-8.col-xs-8.increase_padding').text)

Or, in one go:
print(driver.find_element_by_css_selector('#phone_type .col-md-8.col-xs-8.increase_padding').text)


text:
Q: Android - why lost values EditText when scrolled RecyclerView? I am using from bellow code for converting numbers to currency format when text changes but when I scrolled the recyclerView I lost true data. What can I do :
public class ManagePriceProductsAdapter extends RecyclerView.Adapter<ManagePriceProductsAdapter.ViewHolder> {
    private List<ManagePriceProductsModel.DataValue> managePriceProductsModelList;
    private Context context;
    private getListDiscountInterface getListDiscountInterface;
    private int vendorId = -1;

    public ManagePriceProductsAdapter(Context context,
                                      List<ManagePriceProductsModel.DataValue> managePriceProductsModelList,
                                      getListDiscountInterface getListDiscountInterface,
                                      int vendorId) {
        this.context = context;
        this.managePriceProductsModelList = managePriceProductsModelList;
        this.getListDiscountInterface = getListDiscountInterface;
        this.vendorId = vendorId;
    }

    @Override
    public ManagePriceProductsAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(context)
                .inflate(R.layout.list_item_manage_price_products, viewGroup, false);

        return new ManagePriceProductsAdapter.ViewHolder(view,
                new DiscountNumberTextWatcherWithSeperator(),
                new OriginalNumberTextWatcherWithSeperator());
    }

    public void getListDiscount() {
        getListDiscountInterface.sendGetListDiscountToActivity(managePriceProductsModelList);
    }

    public void backButton() {
        getListDiscountInterface.backButtonForListDiscount(managePriceProductsModelList);
    }

    public void resetAdapter() {
        this.managePriceProductsModelList.clear();
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(final ManagePriceProductsAdapter.ViewHolder viewHolder, int position) {

        viewHolder.discountNumberTextWatcherWithSeperator.updatePosition(viewHolder.getAdapterPosition(),
                viewHolder.discountPriceEdittext,
                viewHolder.originalPriceEdittext);

        viewHolder.originalNumberTextWatcherWithSeperator.updatePosition(viewHolder.getAdapterPosition(),
                viewHolder.originalPriceEdittext);

        try {
            if (managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getTitle() != null) {
                if (!TextUtils.isEmpty(managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getTitle().trim())) {
                    String productName = managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getTitle().trim();
                    viewHolder.titleTextview.setText(productName);
                } else {
                    viewHolder.titleTextview.setText("----");
                }
            } else {
                viewHolder.titleTextview.setText("----");
            }
        } catch (Exception ex) {
            if (vendorId != -1) {
                Throwable t = new Throwable(ex + ", vendorId: " + vendorId).fillInStackTrace();
                FirebaseCrash.report(t);
            } else {
                Throwable t = new Throwable(ex + ", vendorId: empty").fillInStackTrace();
                FirebaseCrash.report(t);
            }
        }

        try {
            if (managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getPrice() != null) {
                Long productPrice = managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getPrice();
                if (productPrice != null && productPrice != 0 && productPrice > 0) {
                    viewHolder.originalPriceEdittext.setText(String.valueOf(productPrice));
                } else {
                    viewHolder.originalPriceEdittext.setText("");
                }
            }
        } catch (Exception ex) {
            if (vendorId != -1) {
                Throwable t = new Throwable(ex + ", vendorId: " + vendorId).fillInStackTrace();
                FirebaseCrash.report(t);
            } else {
                Throwable t = new Throwable(ex + ", vendorId: empty").fillInStackTrace();
                FirebaseCrash.report(t);
            }
        }

        try {
            if (managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getDiscountedPrice() != null) {
                Long discountPrice = managePriceProductsModelList.get(viewHolder.getAdapterPosition()).getDiscountedPrice();
                if (discountPrice != null && discountPrice != 0 && discountPrice > 0) {
                    viewHolder.discountPriceEdittext.setText(String.valueOf(discountPrice));
                } else {
                    viewHolder.discountPriceEdittext.setText("");
                }
            }
        } catch (Exception ex) {
            if (vendorId != -1) {
                Throwable t = new Throwable(ex + ", vendorId: " + vendorId).fillInStackTrace();
                FirebaseCrash.report(t);
            } else {
                Throwable t = new Throwable(ex + ", vendorId: empty").fillInStackTrace();
                FirebaseCrash.report(t);
            }
        }

    }

    @Override
    public int getItemCount() {
        return managePriceProductsModelList.size();
    }

    public interface getListDiscountInterface {
        void sendGetListDiscountToActivity(List<ManagePriceProductsModel.DataValue> managePriceProductsModelList);

        void backButtonForListDiscount(List<ManagePriceProductsModel.DataValue> managePriceProductsModelList);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        //region ViewBinding
        @BindView(R.id.title_textview)
        TextView titleTextview;
        @BindView(R.id.original_price_edittext)
        EditText originalPriceEdittext;
        @BindView(R.id.discount_price_edittext)
        EditText discountPriceEdittext;
        DiscountNumberTextWatcherWithSeperator discountNumberTextWatcherWithSeperator;
        OriginalNumberTextWatcherWithSeperator originalNumberTextWatcherWithSeperator;

        //endregion
        ViewHolder(View view,
                   DiscountNumberTextWatcherWithSeperator discountNumberTextWatcherWithSeperator,
                   OriginalNumberTextWatcherWithSeperator originalNumberTextWatcherWithSeperator) {
            super(view);
            ButterKnife.bind(this, itemView);
            this.discountNumberTextWatcherWithSeperator = discountNumberTextWatcherWithSeperator;
            this.discountPriceEdittext.addTextChangedListener(discountNumberTextWatcherWithSeperator);
            this.originalNumberTextWatcherWithSeperator = originalNumberTextWatcherWithSeperator;
            this.originalPriceEdittext.addTextChangedListener(originalNumberTextWatcherWithSeperator);
        }
    }

    private class DiscountNumberTextWatcherWithSeperator implements TextWatcher {

        private EditText discountEditText;
        private EditText originalEditText;
        private int position;

        private String getDecimalFormattedString(String value) {
            StringTokenizer lst = new StringTokenizer(value, ".");
            String str1 = value;
            String str2 = "";
            if (lst.countTokens() > 1) {
                str1 = lst.nextToken();
                str2 = lst.nextToken();
            }
            String str3 = "";
            int i = 0;
            int j = -1 + str1.length();
            if (str1.charAt(-1 + str1.length()) == '.') {
                j--;
                str3 = ".";
            }
            for (int k = j; ; k--) {
                if (k < 0) {
                    if (str2.length() > 0)
                        str3 = str3 + "." + str2;
                    return str3;
                }
                if (i == 3) {
                    str3 = "," + str3;
                    i = 0;
                }
                str3 = str1.charAt(k) + str3;
                i++;
            }

        }

        public void updatePosition(int position,
                                   EditText discountEditText,
                                   EditText originalEditText) {
            this.position = position;
            this.discountEditText = discountEditText;
            this.originalEditText = originalEditText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            if (charSequence.length() > 0) {
                originalEditText.setPaintFlags(originalEditText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                ManagePriceProductsModel.DataValue dataValue = new ManagePriceProductsModel.DataValue();
                dataValue.setTitle(managePriceProductsModelList.get(position).getTitle().trim());
                dataValue.setId(managePriceProductsModelList.get(position).getId());
                dataValue.setPrice(managePriceProductsModelList.get(position).getPrice());
                dataValue.setDiscountedPrice(Long.parseLong(charSequence.toString().replace(",", "")));
                managePriceProductsModelList.set(position, dataValue);
            } else if (charSequence.length() == 0) {
                originalEditText.setPaintFlags(originalEditText.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                ManagePriceProductsModel.DataValue dataValue = new ManagePriceProductsModel.DataValue();
                dataValue.setTitle(managePriceProductsModelList.get(position).getTitle().trim());
                dataValue.setId(managePriceProductsModelList.get(position).getId());
                dataValue.setPrice(managePriceProductsModelList.get(position).getPrice());
                dataValue.setDiscountedPrice(null);
                managePriceProductsModelList.set(position, dataValue);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            try {
                discountEditText.removeTextChangedListener(this);
                String value = discountEditText.getText().toString();

                if (!value.equals("")) {

                    if (value.startsWith(".")) {
                        discountEditText.setText("0.");
                    }
                    if (value.startsWith("0") && !value.startsWith("0.")) {
                        discountEditText.setText("");

                    }

                    String str = discountEditText.getText().toString().replaceAll(",", "");
                    if (!value.equals(""))
                        discountEditText.setText(getDecimalFormattedString(str));
                    discountEditText.setSelection(discountEditText.getText().toString().length());
                }
                discountEditText.addTextChangedListener(this);
            } catch (Exception ex) {
                ex.printStackTrace();
                discountEditText.addTextChangedListener(this);
            }
        }
    }

    private class OriginalNumberTextWatcherWithSeperator implements TextWatcher {

        private EditText editText;
        private int position;

        private String getDecimalFormattedString(String value) {
            StringTokenizer lst = new StringTokenizer(value, ".");
            String str1 = value;
            String str2 = "";
            if (lst.countTokens() > 1) {
                str1 = lst.nextToken();
                str2 = lst.nextToken();
            }
            String str3 = "";
            int i = 0;
            int j = -1 + str1.length();
            if (str1.charAt(-1 + str1.length()) == '.') {
                j--;
                str3 = ".";
            }
            for (int k = j; ; k--) {
                if (k < 0) {
                    if (str2.length() > 0)
                        str3 = str3 + "." + str2;
                    return str3;
                }
                if (i == 3) {
                    str3 = "," + str3;
                    i = 0;
                }
                str3 = str1.charAt(k) + str3;
                i++;
            }

        }

        public void updatePosition(int position,
                                   EditText editText) {
            this.position = position;
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            if (charSequence.length() > 0) {
                ManagePriceProductsModel.DataValue dataValue = new ManagePriceProductsModel.DataValue();
                dataValue.setTitle(managePriceProductsModelList.get(position).getTitle().trim());
                dataValue.setId(managePriceProductsModelList.get(position).getId());
                dataValue.setPrice(Long.parseLong(charSequence.toString().replace(",", "")));
                dataValue.setDiscountedPrice(managePriceProductsModelList.get(position).getDiscountedPrice());
                managePriceProductsModelList.set(position, dataValue);
            } else if (charSequence.length() == 0) {
                ManagePriceProductsModel.DataValue dataValue = new ManagePriceProductsModel.DataValue();
                dataValue.setTitle(managePriceProductsModelList.get(position).getTitle().trim());
                dataValue.setId(managePriceProductsModelList.get(position).getId());
                dataValue.setPrice(null);
                dataValue.setDiscountedPrice(managePriceProductsModelList.get(position).getDiscountedPrice());
                managePriceProductsModelList.set(position, dataValue);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            try {
                editText.removeTextChangedListener(this);
                String value = editText.getText().toString();

                if (!value.equals("")) {

                    if (value.startsWith(".")) {
                        editText.setText("0.");
                    }
                    if (value.startsWith("0") && !value.startsWith("0.")) {
                        editText.setText("");

                    }

                    String str = editText.getText().toString().replaceAll(",", "");
                    if (!value.equals(""))
                        editText.setText(getDecimalFormattedString(str));
                    editText.setSelection(editText.getText().toString().length());
                }
                editText.addTextChangedListener(this);
            } catch (Exception ex) {
                ex.printStackTrace();
                editText.addTextChangedListener(this);
            }
        }
    }
}

A: As the comments above it is not recommended to use edittext in recyclerview.
If you have to do this can you try to use
 viewHolder.setIsRecyclable(false);

in your onBindViewHolder method

A: You can use this library to support this

*

*Create a ViewState

new ViewState<>() {
    private String savedValue; /* here will be saved a value for each item by createViewStateID() */

    @Override
    public void clear(@NonNull final ViewHolder<ViewFinder> holder) {
        holder.getViewFinder().setText(R.id.text, "");
    }

    @Override
    public void save(@NonNull final ViewHolder<ViewFinder> holder) {
        savedValue = holder.getViewFinder().<EditText>find(R.id.text).getText().toString();
    }

    @Override
    public void restore(@NonNull final ViewHolder<ViewFinder> holder) {
        holder.getViewFinder().setText(R.id.text, savedValue);
    }
};

*Set that ViewState to your ViewRenderer

adapter.registerRenderer(new ViewRenderer<>(
    R.layout.your_item_layout, //your layout
    YourItemModel.class, //your model
    (model, finder, payloads) -> finder.setText(R.id.text, model.getValue()), //your binding
    getYourViewStateProvider() // here is your ViewState
));

More info you can find here

A: You can use the code below to keep hold of your dynamic values.
Paste this code inside your adapter. This allows to assign a unique id to your items. Just make sure the id assigned to all the items in the recyclerview must be unique.
override fun getItemViewType(position: Int) = position

override fun getItemId(position: Int) = position.toLong()


text:
Q: How to fill a ListView with a string-array? I want to show these itens at my ListView
<string-array name="bookmark_titles">
    <item>Google</item>
    <item>Bing</item>
    <item>Gmail</item>
</string-array>

I have a method that gets these values.
public static Collection getBookmarks(Context context) {
    Collection bookmarks = new Collection();

    String[] titles  = context.getResources().getStringArray(R.array.bookmark_titles);

    for (int i = 0; i < titles.length; i ++) {
        bookmarks.add(titles[i]);
    }

    return bookmarks;
}

How can I call the method getBookmarks in my main.java to fill the ListView?
I have already created a ListView. It is:
<ListView
    android:id="@+id/my_listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="#ECECEC"
    android:dividerHeight="1sp" />

main.java
I am trying to do something like this:
ListView lv = (ListView) findViewById(R.id.my_listView);

ArrayList<Bookmark> my_array = BookmarkCollection.getTestBookmarks(context);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, my_array);
lv.setAdapter(adapter);

A: You can do this with an ArrayAdapter and have it use either an Array or a List to give it data
lv.setAdatper(new ArrayAdapter<String>(context, R.layout.some_layout_to_use, R.id.some_textview_in_layout, listData);

A: You can create your adapter with a one liner, check out the static method  ArrayAdapter createFromResource(Context context, int textArrayResId, int textViewResId)
The first argument will probably be your Activity, the second is R.array.bookmark_titles, and the third is a layout to use.
To clarify based on the comments, the method accepts int, which is exactly what the constants in your generated R class are stored as.
Here's a complete example, assuming this is being called from an Activity:
ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this, R.array.bookmark_titles, android.R.layout.simple_list_item_1);
myListView.setAdapter(aa);

In this case, android.R.layout.simple_list_item_1 refers to an XML layout that is provided by the Android SDK.  You can change this if needed.


text:
Q: Javascript-only wordwrap function on whitespace? Most wordwrap functions I've found are bound to css and/or a browser dom.
I'm working in a javascript environment (rhino) and need to find or design a better word wrap that breaks on whitespace before a given line length value.
My current solution just searches for the last white space before the given character, then clips  the left side, storing it as a line of output (in an array return).  Repeat until no more text remains.
Hoping someone has seen something elegant.

A: You could write something like:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();

That will replace \s+ with \n after at-least-one,-at-most-eighty,-preferably-as-many-as-possible characters. (Note: if there are more than eighty characters in a row without whitespace, then there will be a line-break before and after them, but no wrapping will take place inside them.)
See it in action:

// generate random sequence of 500 letters and spaces:
let original = String.fromCharCode.apply(String, Array.from({length: 500}, () => 64 + Math.floor(Math.random() * 27))).replace(/@/g, ' ');

// perform word-wrapping:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();

// show the results in the
 elements:
document.getElementById('ruakh-original').innerText = 'original:\n' + original;
document.getElementById('ruakh-word-wrapped').innerText = 'word-wrapped:\n' + wordwrapped;

A: This regex will wrap every 0-width character and respect whitespaces and hyphens also cuts words longer than width characters. Try it out on regexr.
/**
 * Wrap every 0-`width` character and respect whitespaces and hyphens also cuts words longer than `width` characters.
 * @param str The string to wrapped
 * @param width The maximum length a string can be
 */
function wordwrap(str, width) {
    return str.replace(new RegExp(`(?:\\S(?:.{0,${width}}\\S)?(?:\\s+|-|$)|(?:\\S{${width}}))`, 'g'), s => `${s}\n`).slice(0, -1);
}

function wordwrap(str, width) {
    return str.replace(new RegExp('(?:\\S(?:.{0,' + width + '}\\S)?(?:\\s+|-|$)|(?:\\S{' + width + '}))', 'g'), function (s) {return s + '\n'}).slice(0, -1);
}

console.log(wordwrap('This is my regular-expression. It will wrap every 0-20 character and respect whitespaces and hyphens, also cuts reallylongwordslikethis.', 20));

A: RegEx is really the way to go. /.{0,79}(?:\s|$)/g will grab the longest line under 80 characters ending with a character or the end of the file.  Calling exec multiple times will extract each line.
var text = "";
var regex = /.{0,79}(?:\s|$)/g;
var lines = [];
var line;

while (line = regex.exec(text)) {
    lines.push(line);
}


text:
Q: MySQLi: Advance query to limit the number of products for the price range Is this possible to make in the MySQLi query parameter to set the following thing:
For example: I have a product table with various products with different prices
Table: products
id  name     price
1   pen      10
2   banana   50
3   potato   10
5   apple    20
6   guaba    30
7   papa     30
8   salt     80
9   butter   25
10  cheese   10

I want to limit the price range and product range in the MySQLi statement.
For example: When I want to show 5 products those prices are accumulative to 100 or near 100, it will fetch any 5 products from database that's price accumulative to 100.
Again, when I want to show 2 products those price are accumulate to 100 or near 100, it will fetch any two products those prices match to accumulative 100 or near 100.
I have learned that it is possible to make the price range by following way; But I am not sure if I also can limit the product number for those price range.
For price range; I can do by:
SELECT id, name, price
FROM (
   SELECT id, name, price,
          @cumSum:= @cumSum + price AS cumSum
   FROM products, (SELECT @cumSum:=0) var
   ORDER BY id ) t
WHERE cumSum <= 100

But how can I limit the number of products for the price range?

A: I think you want to find 5 prices that sum of them is nearest to 100:
SQL Fiddle
SELECT *
FROM t
WHERE (
SELECT
    CONCAT('|', t1.id, '|', t2.id, '|', t3.id, '|', t4.id, '|', t5.id, '|')
FROM
    t t1
    JOIN
    t t2 ON t1.id <> t2.id
    JOIN
    t t3 ON t1.id <> t3.id AND t2.id <> t3.id
    JOIN
    t t4 ON t1.id <> t4.id AND t2.id <> t4.id AND t3.id <> t4.id
    JOIN
    t t5 ON t1.id <> t5.id AND t2.id <> t5.id AND t3.id <> t5.id AND t4.id <> t5.id
ORDER BY
    ABS(t1.price + t2.price + t3.price + t4.price + t5.price - 100)
LIMIT 1) LIKE CONCAT('%|', id ,'|%');

Result is:
id  name    price
1   pen     10
2   banana  50
3   potato  10
5   apple   20
10  cheese  10

And for 2 prices:
SELECT *
FROM t
WHERE (
SELECT
    CONCAT('|', t1.id, '|', t2.id, '|')
FROM
    t t1
    JOIN
    t t2 ON t1.id <> t2.id
ORDER BY
    ABS(t1.price + t2.price - 100)
LIMIT 1) LIKE CONCAT('%|', id ,'|%');


text:
Q: How to query the Cognito Group of a logged in user? I am using AWS Amplify. I have a Cognito Auth with 2 groups. Using Auth.currentAuthenticatedUser, I can tell the email address of the logged-in user but is there a way to determine the group of the user?

A: There are two alternative solutions: either establish Amplify Auth Admin Queries API (to use listGroupsForUser query) or use AWS SDK Cognito Identity Provider Client to use AdminListGroupsForUserCommand.

*

*Enabling Admin Queries API

*Using AWS SDK Cognito Identity Provider Client


text:
Q: Phonegap/Cordova how to remove floating action button on Android? I am running Phonegap on Android 5.1.1 device and it has this Floating Action button sitting in the corner. How would i remove it??
I have not seen other threads about this for Cordova. Would i remove it from the config.xml??

A: Set the android target SDK to version 22
 <preference name="android-targetSdkVersion" value="22" />


text:
Q: How to move CCLayer in cocos2d Can any one tell me how to move a CClayer. Like DoodleJump when object will move upward the background will also move upward.Plz Explain me with some sample code.

A: Use CCFollow actions.
Make your background sprite height some 1000 px.
[self runAction:[CCFollow actionWithTarget:(u r hero) worldBoundary:CGRectMake(0,0,480,1050)]];

A: This tutorial will teach you how to make a game very similar to doodle jump:
Tutorial Part 1
Hope it helps :)
P.S.
Check out this guys' channel he has the solution to your background problem.

A: Look at the tile maps code from the cocos2d sample code that is included with cocos2d.

A: The most basic answer to the question in the title is:
a CCLayer is a CCNode and can be moved by repositioning it:
myLayer.position = ccp(x,y);

A: use ccaction like ccmoveby or ccmoveto , etc.,


text:
Q: Python xml install not working When i try 'import xml' in IDE is get the error missing module. When i use 'pip list' in command prompt xml is missing from my pip installs list. When i try a fresh install i get the following error. Any help would be greatly appreciated, thanks.

I have installed ez-setup and upgraded setuptools through pip and pip is up to date (version 10.0.1).

A: xml is a module from stdlib so import xml must always succeed. If it doesn't you have a rather broken Python installation. Also pip list never lists stdlib modules, it only lists modules managed by pip.
py-xml works only with Python 2, not 3. The code open('README.md', 'r', 'utf-8') is a complete mess, it works with neither Python 2 nor 3.
If you're not satisfied with standard xml I recommend to install lxml.

A: In my case I had another xml.py in my working directory. So, I renamed it. Now, it's working


text:
Q: I used wget to download html files, where are the images in the file stored? Firefox was loading very slow, so I decided to use wget to save HTML files.I used the following command,
wget http://textbook.s-anand.net/ncert/class-xii/chemistry/hello-this-first-chapter

The files have been saved in my home folder.But I don't know where the images are stored.I need them to use in Anki.
So where are the images stored?

A: I prefer to use --page-requisites (-p for short) instead of -r here as it downloads everything the page needs to display but no other pages, and I don't have to think about what kind of files I want.
Actually I'm usually using something like
wget -E -H -k -p http://textbook.s-anand.net/ncert/class-xii/chemistry/hello-this-first-chapter

This means:

*

*-E: Append .html to the file name if it is an HTML file but doesn't end in .html or similar

*-H: Download files from other hosts, too

*-k: After downloading convert any link in it so they point to the downloaded files

*-p: Download anything the page needs for proper offline viewing

A: using the -r parameter should enable wget to download the whole folder, including your images.
wget -r http://textbook.s-anand.net/ncert/class-xii/chemistry/hello-this-first-chapter

A: Downloading the image files separately as well
I think this command could get you started.
 wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://textbook.s-anand.net/ncert/class-xii/chemistry/hello-this-first-chapter

It allows you to specify the location to save the images and which types of files you wants. Maybe downloading the images as such is easier.
Source:

-r enables recursive retrieval. See Recursive Download for more information.
-P sets the directory prefix where all files and directories are saved to.
-A sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.

Copying the image files from your folder
I have noticed that the website uses PNG image files. You can just copy those from your folder. This should be run in the folder where you stored the webpage.
find . -name "*.png" -exec cp '{}' ./some_dir/somewhere/ \;

A: wget simply downloads the HTML file of the page, not the images in the page, as the images in the HTML file of the page are written as URLs. To do what you want, use the -r (recursive), the -A option with the image file suffixes, the --no-parent option, to make it not ascend, and the --level option with 1.
Specifically wget -r -A .jpg,.png,.gif --no-parent --level <url>
Even better, most browsers have methods for saving pages for offline viewing.


text:
Q: How to insert data into SQL Server in a C# ASP.NET website? The code in the code behind file (.aspx.cs):
protected void Page_Load(object sender, EventArgs e)
{
    con.ConnectionString = "server=localhost;user id=root;password=Welcome@123database=login;";
}

protected void Button2_Click(object sender, EventArgs e)
{
    try
    {
        con.Open();

        SqlCommand cmd = new SqlCommand("insert into user(userid,username,password) values('" + txtuserid.Text + "','" + txtusername.Text + "','" + txtpassword.Text + "')", con);

        cmd.Parameters.AddWithValue("@user_id", txtuserid.Text);
        cmd.Parameters.AddWithValue("@username", txtusername.Text);
        cmd.Parameters.AddWithValue("@password", txtpassword.Text);

        cmd.ExecuteNonQuery();

        Response.Write("<script>alert('User Added Successfully')</Script>");
        con.Close();
    }
    catch (Exception ex)
    {
        Response.Write("<script>alert('User registration was unsuccessful')</Script>");
    }
}

A: You've totally misunderstood how parameters are supposed to be used. What you're doing is SQL injection-prone string concatenation of SQL statements - do NOT do this!
Use this code instead:
SqlCommand cmd = new SqlCommand("insert into user (userid, username, password) " +
                                "values (@userId, @userName, @password);";

cmd.Parameters.AddWithValue("@userId", txtuserid.Text);
cmd.Parameters.AddWithValue("@userName", txtusername.Text);
cmd.Parameters.AddWithValue("@password", txtpassword.Text);


text:
Q: How to generate tests based on data in nunit framework using C# So i have this code:
[TestFixture]
[Category("MyTestSet")]
public class MyTests
{
    [Test]
    public void TestCase12()
    {
        ExecuteTestCase(12);
    }

    [Test]
    public void TestCase13()
    {
        ExecuteTestCase(13);
    }

    [Test]
    public void TestCase14()
    {
        ExecuteTestCase(14);
    }
}

The ExecuteTestCase gets test parameters from my web server and executes the test case with these settings.
Each time i add a new test case parameters on my web server i need to add a new test in my C# code and pass the ID of test case parameters i have in my web server database and compile my code.
Is there any way to do it automatically? Like say, C# gets from my server ID's of all test case parameters and creates tests for them on the fly?
What is important, test cases change frequently. I was thinking about running all test cases in one test case on a loop, but than i'd be unable to run my test cases separately for example in Nunit  IDE.
So my question is: how to run multiple test cases depending on data i receive on run time.

A: You can use TestCaseSourceattribute in order to get parameters from web service and have your test cases auto generated
[TestFixture]
[Category("MyTestSet")]
public class MyTests
{
    [Test, TestCaseSource(nameof(GetTestParameters))]
    public void TestCase(int parameter)
    {
        ExecuteTestCase(parameter);
    }

    static int[] GetTestParameters()
    {
        //call web service and get parameters
        return new[] { 1, 2, 3 };
    }
}

documentation


text:
Q: Google Appmaker: Update form based on selected dropdown option I have an AppMaker app that has a from based off of one address table/datasource.  I can get a form with next/prev buttons, but replaced the key field (name) with a dropdown list of all names (a user can start typing names to jump there, with the dropdown showing).
My hope is that when a user selects from the dropdown, the entire form updates and the next/prev buttons work properly as well (there too many records to page thru with next/prev only).  I don't have to have next/prev functionality if it complicates things too much.
Currently the dropdown is working, but I cannot get the index for the next/prev buttons set or the rest of the form to reflect the selected dropdown record.
I've tried to set the "onValueEdit" event to something like this...
var selected = widget.value;
var idx      = widget.options.indexOf(selected);

console.log("Selected: "+selected+", index = "+idx+"\n");
if(idx < 0) {                      //...this error is never hit
  console.log("Index error - setting to zero!\n");
  idx = 0;
}
widget.datasource.loadPage(idx);   //...update form?

Two observations via console logging:

*

*The "idx" var is never set to the selected dropdown index reliably, and is
often "0" (tho no error msg ever shows), so the "indexOf()" function
isn't working as expected.

*The "selected" var (name) is always correct.
If I call widget.datasource.loadPage(...) with a fixed value (say 5) it has no effect on what is shows in the form either (previous loaded data remains) - obviously not the way to do it :v/
Can you steer a noob in the right direction?

A: If you are using default App Maker form, then you can see that so-called pager, doesn't actually paginate. It triggers prevItem/nextItem datasource methods, in other words it navigates through datasource items, not pages. Here is a quote from App Maker docs:

nextItem: Selects the next item. For Query Datasources, if the current item is the last item on the page, then this loads the next page and selects the first item on the newly loaded page.

So, if you already have all your items loaded(you set query page size for your datasource to 0), then you need just to change selected item within datasource:
// onValueEdit dropdown event
// assuming, that form and dropdown share same datasource
widget.datasource.selectKey(newValue._key);

If you really have lots of items and it is not feasible to load all of them in one call... then it will be all another story...

A: I deleted this page and started again, and replaced the default business name data field with a drop down, I set the dropdown as:
Options: @datasources.Addresses.items

Value: @datasources.Addresses.item

It works fine?!  Not sure what happend in my original page!
UPDATE:
So it seems you need to delete both the Value and Options and then re-enter these.  The OK will light up when you do.
Also, my original take on App Maker was to build the UI and attach data. That was my first mistake.  You build the data then have App Maker build edit/add pages for you.

A: UPDATE:
It's important that Options and Value are set as shown in the image below!

However, I had trouble setting them that way (read: wasted hours!) until I wiped them both completely using More options in the binding picklist, and tried again (I had even tried on a brand new app!). I was being forced to choose ..projections.. and then a final field before the OK button would be available.
Not sure if AppMaker is buggy here or there is something simple I'm not understanding!
None of the coding in my original question is required.
Once set this way, binding just works as you would expect it!!
All other fields are set as @datasource.item. and are bound to whatever item is chosen.  No Events settings are necessary for the dropdown either, as I thought they might be.


text:
Q: Next.js app with mongo db database showing error on my login on local host but not on deployed version I am trying to make changes to a deployed web app locally. The app is built in next.js with mongodb and hosted on vercel. I am able to use my credentials to login to the app on the deployed version but when i do my run dev command in terminal and navigate to localhost:3000 and try to login to the app, i get an alert saying that "username and password combination incorrect" I am wondering why i am having this issue. Is it an issue with vercel and or does it sound like a mongo issue?
I have tried to login locally and i expected to get into the app but all that resulted was a error


text:
Q: Convert html file in node.js to pdf and write the same in disk In my application I have one html template which brings dynamic data from DB. I need to convert that html file(template) to PDF. Is there any package to convert the raw html to PDF in node.js? I go through with pdfcrowd and livedocx. Both using some webservices for conversion which does not suits for my specification. please suggest some package for converting HTML to PDF in local machine..?

A: Go through this link..
Here u can convert HTML file to PDF or HTML content to PDF
import NDHTMLtoPDF.h and NDHTMLtoPDF.m from above source link
pass HTML file path to generate PDF here..
NSURL *targetURL = [NSURL fileURLWithPath:HTMLPath];

Converting HTML to PDF
self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:targetURL
                                     pathForPDF:[[NSString stringWithFormat:@"~/Documents/Sample.pdf"] stringByExpandingTildeInPath]
                                       delegate:self
                                       pageSize:kPaperSizeA4
                                        margins:UIEdgeInsetsMake(20, 5, 90, 5)];

pass HTML Content to generate PDF here..
NSString *str_PDFName_path = [NSString stringWithFormat:@"~/Documents/Sample.pdf"];
self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:str_HTML pathForPDF:[str_PDFName_path stringByExpandingTildeInPath] delegate:self pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(20, 5, 90, 5)];


text:
Q: Custom Container for hosting OpenLDAP in Bluemix I am trying to create custom container for hosting OpenLDAP in Bluemix.
I am following the steps mentioned in the link:
https://console.ng.bluemix.net/catalog/images/add-your-own/
At Step 6, where I need to tag the docker image, I receive the below error:
D:\>docker tag openldap registry.ng.bluemix.net/devopstest/openldap:aa9f496f321

FATA[0001] Error response from daemon: DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"
"<title>405 Method Not Allowed</title>"

 Method Not Allowed

 The method is not allowed for the requested URL.

Any help or pointers is much appreciated. Thanks.

A: registry.ng.bluemix.net/devopstest/openldap:aa9f496f321 should math the pattern:
registry.ng.bluemix.net/<namespace>/<image_name>:<tag>
In the Bluemix documentation, we find:

Namespace: A unique name to identify your private repository within the Bluemix registry. The namespace is assigned one time for an organization and cannot be changed after it is created.
To identify the namespace for your organization:

*

*From the Bluemix user interface:
Note: You can only identify the namespace from the Bluemix user interface if an image was added already to the private repository for the organization. You cannot find the namespace by clicking one of the IBM-provided images. Use the command line option instead.

*

*From the Bluemix Catalog, click an image. The container creation window opens.

*Under the image name, click Copy image URL. The namespace can be retrieved from the copied URL, which is in the following format: registry.ng.bluemix.net/<namespace>/<image_name>:<tag>

*From the command line:

*

*Cloud Foundry plug-in:
cf ic namespace get

*ICE:
ice namespace get
Combine your namespace with the Bluemix registry domain and the image name to get the private Bluemix repository URL for an image: registry.ng.bluemix.net/<namespace>/<image_name>:<tag>

Is devopstest matching your private Bluemix repository name?


text:
Q: Storing floating point numbers in struct in C I created a struct variable. An example of this is:
    struct numbers
    {
        float start;
        float end;
        int middle;
    }values;

    int main()
    {
        scanf("%f %f %d", &values.start, &values.end, &values.middle);
        printf("%f %f %d, &values.start, &values.end, &values.middle);
    }

When I try to read values into these variables through user input, such as "0 5.8 3". When I try to print, it looks like this
0.000000 0.0000000 -26148776 (The last number changes everytime I run the program, and the rest remain as 0)
How can I fix this issue?
Thanks in advance!

A: The scanf family of functions needs pointers so it knows where to store the results.
The printf family of functions prints values, so it does not need pointers.
When you have a mismatch between printf format specification and argument, then it leads to undefined behavior.
So the simple solution is to not use the address-of operator & for the arguments in your printf call.


text:
Q: How do I force a default gateway change? It seems stuck on 192.168.0.1 in Ubuntu This has me stumped. I am connected to a college network, which requires me to have my MAC registered (Done, windows works fine).
So, when I boot to Ubuntu, I try to access a page in Chromium, and I get an
Error 102(net::ERR_CONNECTION_REFUSED): Unknown error.
Firefox fails too.
Resolve.conf has several servers, all of which I can successfully ping, and I can ping digg.com and google.com using their names.
Also, there is constant network activity, but I can't tell what process/ports are downloading and uploading. (netstat -tupl didn't seem to show anything)
I don't have any network managers installed (for w/e reason).

Update: I randomly tried to update my system, and it of course failed, but I read the text.
The error states that: failed to fetch package blah blah at IP ADDRESS: 192.168.0.1:80 (connection refused).
Obviously, the ip addr of canonical is not 192... but I don't have a router between me and the internet now (I used dhclient to update my settings) so what is rerouting all my http requests to 192.168.0.1?
Using wicd, setting a static ip, dns, and gateway still results in all http traffic getting redirected to 192.168.0.1:80, using
ip route show | grep default | awk '{ print $3 }' shows a different ip than 192.168.0.1.

A: You're looking for the route command.  However, it sounds to me like there is a deeper issue going on with your setup.  What error did Firefox give you?
Also, dhclient has been absorbed into dhcp3-client.  Make sure that the version of dhclient you're using is from that package.

A: To manually input a default gateway you would run this at the command line:
~$ route add -net default gw xxx.xxx.xxx.xxx

Though, like someone mentioned above, seems like you're having other problems.  From what I can tell, it sounds like you're being routed through a proxy (configured by the school).  Similar to what you'd see when you connect to a public wifi access point and you're redirected to a webpage to accept terms/agreements before you can move onto to surfing the web.  Did firefox give you a specific error?


text:
Q: Is there a way to pass a param to a function called on jQuery .click? I know you can invoke a function on click by:
$(".foo").on("click", function);
// Assume 'function' is an actual function declared elsewhere.

But is there a way to pass a param into the function using that style? I know you can do:
$(".foo").on("click", {namespace: this}, function (e) {
    var that = e.data.namespace;

    that.function(that);
});

But this is not how I want to write it. I want to call an already created function on a .click event and pass params to it using the one-line notation of the top example. How do I do this?

A: Unfortunately you can't do what you're asking exactly, but you can come pretty close just by calling the function inside of the callback function:
$(".foo").on('click', function () { namedFunction.call(this, yourArguments); });

You can use .apply instead of .call if it suits you.

A: Besides you can also use bind:
function namedFunction(yourArgument, e) {
    console.log(yourArgument);
}

$(".foo").on("click", namedFunction.bind(this, yourArgument));

This method was added to ECMA-262, 5th edition and might have compatibility problems with old browsers. You may check MDN for possible workarounds.


text:
Q: Public GIS data for lots within sections of township and range for NM, USA Anyone know where to find a publicly available shapefile/fc of lot divisions within sections for township and range of New Mexico?
I've been to several government websites that offer this type of data but can't seem to find any files that are broken down all of the way to the lot level.  I.E. land grids for section and twp/rng seem easy enough to come by from these sites where as lots are eluding me.

A: Just found one right after I posted this.
http://www.blm.gov/nm/st/en/prog/more/geographic_sciences/spatial_data_metadata.html
Followed the link for "Survey LandNet" which is a download for very detailed survey data.


text:
Q: How to fetch Data from Array in Angular js I am on a project in which I want to display data from array into
 using Angular js
myid =[];
$scope.AddtoCart = function(){
myid.push( $scope.dataToCart);
srvaddtocart.addData(myid);
//console.log($scope.SharedCart);
}
  $scope.One = function(){
  $scope.AddtoCart();
  $scope.SharedCart = myid;
  console.log($scope.SharedCart);
  $("#close").click(function(){
    $(".oxy-product-cart").toggleClass("is-visible");
  });
}

this is my js code where SharedCart is storing multiple ID
the output of the SharedCart is something like this
[1190,902,123]

How to display this Array in my HTML page

*

*1190

*902

*123

A:

{{item}}

A: Here is a simple example you can add to your HTML view
{{myid}}

{{item}}


text:
Q: Writing a diffEQ as $P(x,y)dx + Q(x,y)dy = 0$ instead of in terms of $dy/dx$ I'm reading in Tenenbaum and Pollard's Ordinary Differential Equations where they introduce the concept of the differential. Suppose $y=f(x)$ is differentiable. He defines the differential by $dy(x, \Delta x)=f'(x)\Delta x$, and explains that if we think of $dx$ as the differential of the function $x\mapsto x$, then we can write $dy=f'(x)dx$, and this continues to hold when $x$ is a function of another variable, $t$. On page 51-52, he writes

The first-order differential equations we will study in this chapter
  can be written in the form $$Q(x,y)\frac{dy}{dx} +
 P(x,y)=0.\tag{6.6}$$ Written in this form, it is  assumed that $x$ is
  the independent variable and $y$ is the dependent variable. If we
  multiply (6.6) by $dx$, it becomes $$P(x,y)dx + Q(x,y)dy=0.$$ Written
  in this form, either $x$ or $y$ may be considered as being the
  dependent variable. In both cases, however, $dy$ and $dx$ are
  differentials, and not increments.

I'm a little shaky with the notion of dividing by $dx$ in the first place. I guess $dy/dx$ has a removable singularity at $dx=0$ which we can fill in, giving us $(dy/dx)(x)=f'(x)$ for all $x$, whether $x$ depends on some other variable(s) or not. Is that the way I should think of it?
Another thing that concerns me is the potential switching of the dependency. If a solution $y(x)$ is not injective, how can we arbitrarily decide to think of $y$ as the dependent variable? Or perhaps we'll get singularities in our solution where $y'(x)=0$?
I have actually worked with differential forms on smooth manifolds before, so I'm happy with an answer where we think of them as smooth covector fields (here I guess $\Delta x$ is an element of the tangent space at $x$). I would feel wrong dividing by a smooth covector field unless I knew it was nonzero!

A: Yeah, this seems like a common bit of voodoo.  We can't really multiply and divide by differentials, but we can do something like this:  imagine a vector-valued function $\ell(t)$, where $\ell: \mathbb R \mapsto \mathbb R^2$.  Let $V: \mathbb R^2 \mapsto \mathbb R^2$ be a vector field such that $V(x,y) = P(x,y) \hat x + Q (x,y) \hat y$.
Clearly, if we integrate the $V$ on $\ell$, we can get
$$\int V \cdot \frac{d\ell}{dt} \, dt$$
If we write $\ell(t) = \bar x(t) \hat x + \bar y(t) \hat y$, we get
$$\int P(\bar x, \bar y) \bar x'(t) + Q(\bar x, \bar y) \bar y'(t) \, dt$$
It's still important, I think, to distinguish between the coordinates $x, y$ and the scalar functions $\bar x(t), \bar y(t)$.
Now, the paramterization is arbitrary.  We can, for instance, choose as our parameterization $\bar x(t) = t$.  Or rather, we can just use $x$ itself for the parameter, and as such, $\bar x' = 1$, so we get
$$\int P(x, \bar y(x)) + Q(x, \bar y(x)) \frac{d \bar y}{dx} \, dx$$
So all of this can be phrased in terms of a rigorous set of ideas.  Usually, when integrating over curves, the distinction between a coordinate (like $y$) and a component function of the parameter (like $\bar y(t)$) is dropped completely.  Usually, we can understand that this is exactly what's meant, and so it feels redundant, but I think from a pedantic perspective, it's helpful to maintain the distinction.
Overall, there's no need to "divide" any differentials; all we have here are notations for derivatives.  Choosing to parameterize with respect to $x$ does have dangers:  not when $dy/dx = 0$ (these are well-handled) but when the derivative does not exist (is infinite).  Curves that might otherwise be smooth and differentiable can give problems when the derivative $dy/dx$ does not exist.  Still, since the thrust of this topic is ODEs, such issues should seldom crop up.

A: Here's what is really behind the differential equation. If you can write the differential form as an exact differential form after multiplying by (mostly) non-zero $R(x,y)$, then
$$
  R(Qdx + Pdy) = df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y} dy = 0
$$
gives an algebraic equation
$$
                   f(x,y) = C.
$$
By the implicit function theorem, you can solve for $y=y(x)$ locally near $x=x_{0}$ and $y=y_{0}$ if $f(x_{0},y_{0})= C$ and if
$$
               \frac{\partial f}{\partial y}(x_{0},y_{0}) \ne 0.
$$
In such a case,
$$
     \frac{\partial f}{\partial x}+\frac{\partial f}{\partial y}\frac{dy}{dx}=0,
$$
which gives
$$
             \frac{dy}{dx} = -\frac{\partial f/\partial x}{\partial f/\partial y}=-\frac{RQ}{RP}=-\frac{Q}{P}.
$$
Over some regions, you'll solve for $y=y(x)$ and over other others you'll solve for $x=x(y)$. It depends on the derivatives $\partial f/\partial x$, $\partial f/\partial y$, which are propotional to $Q$, $P$, respectively. So the end result is that it appears you can just divide by $dy$ or $dx$ and solve. I think this makes it clear that you are not actually just dividing by $dx$ or $dy$, even though the final result makes it look that way.
BTW: Such ODEs are sometimes called exact differential equations because of the technique of turning the differential equation into an algebraic equation through the use of exact differential forms.


text:
Q: php -l: suppress output on valid files When using the php -l myFile.php command (PHP 5.5.30), if the file has a syntax error then I get the proper warnings and stack trace, etc.
However, if the file has no syntax warnings I get the message

No syntax errors detected in myFile.php

Is there a way to have the command have no output when the syntax is valid? I only care if a file has invalid syntax - I don't need a message saying it's valid.

A: The "no syntax errors..." message is sent out on the stdout while the syntax errors are sent out on stderr. You can redirect those to somewhere like /dev/null if you don't want them.
php -l file.php 1> /dev/null

that will output the errors if there were any or nothing if no errors. You do lose the "Errors parsing..." message, but will get the errors if there was a problem.

A: You can use chronic to suppress all output if the command succeeds (returns 0):
chronic php -l myFile.php

DESCRIPTION
chronic runs a command, and arranges for its standard out and standard error to only be displayed if the command fails (exits nonzero or crashes).  If the command succeeds, any extraneous       output will be hidden.

On Debian, it's in the moreutils package.

A: Don't check the output, check the return code.
$ php -l good.php &> /dev/null; echo $?
0

$ php -l bad.php &> /dev/null; echo $?
255

So:
if ! php -l somescript.php &> /dev/null; then
  echo 'OH NOES!'
fi

Or if you're feelin fancy:
if ! foo=$(php -l somescript.php 2>&1); then
  echo $foo
fi

A: php -ln script.php >/dev/null || php -ln script.php

EDIT:
chronic php -ln script.php


text:
Q: Missing fonts in Xvfb I've installed Ubuntu 12.04.3 64-bit as a guest under VMplayer running on my Win7 host.
After Ubuntu installs, I launch and open a terminal.
I then enter the following:
sudo apt-get update
sudo apt-get install wine
sudo apt-get install xvfb
sudo apt-get install xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic

When I launch xvfb, I get the following error:
"[dix] Could not init font path element /var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType, removing from list!"

"x-ttcidfont-conf" should have been installed with "wine" as I got the same EULA when I install manually.  However, it never gets recognized and when I check font folders, they're empty.
I've tried these steps as well:

*

*Alternate attempt 1:

*

*sudo apt-get -y install x-ttcidfont-conf cabextract ttf-mscorefonts-installer

*sudo dpkg-reconfigure x-ttcidfont-conf

*Alternate attempt 2:

*

*Reset Ubuntu

*At login screen: Press CtrlAltF1

*Login

*kill x server: sudo service lightdm stop

*generate new xorg.conf file: sudo X -configure

*

*This will create a 'xorg.conf.new' file in your current dir

*return to GUI: sudo start lightdm

*Login through UI

*Open & edit xorg.conf.new and add the following two lines:

FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/CID"
    FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType"

*Save & exit

*Logout of UI

*At login screen: Press CtrlAltF1

*Login

*kill x server: sudo service lightdm stop

*rename and move: sudo mv xorg.conf.new /etc/X11/xorg.conf

*return to GUI: sudo start lightdm

I fully admit I'm a linux/ubuntu/xvfb noob...but I am good at Google searches and nothing seems to work.
What am I missing?

I've tried:
sudo apt-get -y install x-ttcidfont-conf
[sudo] password for <user>:
Reading package lists... Done
Building dependency tree
Reading state information... Done
x-ttcidfont-conf is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 17 not - upgraded.

and still get the same error message.

I've also tried:

*

*sudo apt-get upgrade

*Restarted ubuntu

*retried

Get same results.   :-(

There is an in-house shell script that launches Xvfb followed by an application and apparently just hangs as a result.  The first line in the shell script is:
Xvfb :2 &
And simply executing that command outside of the shell script causes the same error.
I've read in one of the many pages to help resolve this that I need an xorg.conf in a folder to point to font folders.  I tried to create this and for the other fonts such as xfont-100dpi, xfont-75dpi, etc. there is content in the folders.  Why am I not able to get any content in the equivalent font folder for x-ttcidfont-conf TrueType font?

A: You are missing the package x-ttcidfont-conf. A simple sudo apt-get -y install x-ttcidfont-conf should solve the problem.

A: I found that by executing the following command, I was able to resolve the problem:
mkfontdir

Thanks for your help.


text:
Q: Dataframe aggregate method passing list problem This maybe a bug, but what is your take on this pandas functionality:
df = pd.DataFrame(np.arange(20).reshape(10,-1), columns=[*'AB'])

def f(x):
    print(type(x))

df.agg(f)

Output:
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
A    None
B    None
dtype: object

However, if I wrap function call in the agg method in brackets passing a single function as a list.
df = pd.DataFrame(np.arange(20).reshape(10,-1), columns=[*'AB'])

def f(x):
    print(type(x))

df.agg([f])

Output:
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
      A     B
      f     f
0  None  None
1  None  None
2  None  None
3  None  None
4  None  None
5  None  None
6  None  None
7  None  None
8  None  None
9  None  None

All that changed was passing the custom function as a single value list.


text:
Q: pybbn InferenceController.apply takes too long to run I have created a bbn consisting of 12 nodes, with edges that connect the first 11 to the final node. Each of the 11 nodes have 3 or 2 possible outcomes (let's save 'Low', 'Med', 'High'), and the final node can take 4 cases.
I have created the bbn with known probabilities that I calculate from my input data. When I try to create a join tree the code takes too long and looks like there is nothing happening:
join_tree = InferenceController.apply(bbn)
I was wondering if this is because my network is too large or I am doing something wrong.
Thanks!
I tried calculating the probabilities beforehand and defining the BbnNode with known probabilities.


text:
Q: Two login forms share saved browser data, how to disable? I am developing a website which makes use of two login forms, one for regular users and one for administrators. Since administrators can also have an independent regular account, I would like to clear the form from any autosaved data from the browser. This way the admin panel won't have incorrect credentials that may have been filled out in the other form in an earlier stage.
Is this possible, if so, how?
Thanks in advance.

A: I see you tagged this question XHTML. I don't think there is any standards-compliant way to do that in XHTML. Maybe some JavaScript trickery, but it would be messy.
HTML5, however, defines the "autocomplete" option for forms, so you could write your <form> tag like this: <form action="..." autocomplete="off"> and HTML5-compliant browsers will not autofill the fields (remember to set the HTML5 doctype!) Doing this results in the user seeing something like this:
Edit based on OP's comment: changing the name of the fields would (in theory) prevent one field's values from autocompleting another's. If the fields in your user login form are username and password and you called the fields in your admin login admin_username and admin_password, the values of one would not be suggested for the other.


text:
Q: Distribute list of dictionaries by key evenly I have a list of dictionaries like this:
[{'User ID': '111',
  'Full Name': 'name a',
  'Role: Name': 'role a'},
 {'User ID': '222',
  'Full Name': 'name b',
  'Role: Name': 'role a'},
 {'User ID': '232',
  'Full Name': 'name c',
  'Role: Name': 'role b'},
 {'User ID': '223',
  'Full Name': 'name d',
  'Role: Name': 'role d'},
 {'User ID': '444',
  'Full Name': 'name e',
  'Role: Name': 'role d'}]

I have used the answer to this question to sort the roles evenly in a list. But I also need the their 'Full Name' as well.
So basically I need to sort the dictionary evenly by role, is this possible with the linked answer?
I don't want the dictionary roles ordered like [a, a, a, b, c, c], I want it like [a,b,a,c,a,c] or something like this anyway. Similar to how the linked question would do it.

A: Use the code as below:
import pprint
import random
from functools import partial
from operator import itemgetter

data = [{'User ID': '111',
         'Full Name': 'name a',
         'Role: Name': 'role a'},
        {'User ID': '222',
         'Full Name': 'name b',
         'Role: Name': 'role a'},
        {'User ID': '232',
         'Full Name': 'name c',
         'Role: Name': 'role b'},
        {'User ID': '223',
         'Full Name': 'name d',
         'Role: Name': 'role d'},
        {'User ID': '444',
         'Full Name': 'name e',
         'Role: Name': 'role d'}]

def optimize(items, quality_function, stop=1000):
    no_improvement = 0
    best = 0
    while no_improvement < stop:
        i = random.randint(0, len(items) - 1)
        j = random.randint(0, len(items) - 1)
        copy = items[::]
        copy[i], copy[j] = copy[j], copy[i]
        q = quality_function(copy)
        if q > best:
            items, best = copy, q
            no_improvement = 0
        else:
            no_improvement += 1
    return items

def quality_maxmindist(items, key=None):
    if key is None:
        def identity(e): return e

        key = identity

    s = 0
    for k, item in { key(item) : item for item in items}.items():
        indcs = [i for i in range(len(items)) if key(items[i]) == k]
        if len(indcs) > 1:
            s += sum(1. / (indcs[i + 1] - indcs[i]) for i in range(len(indcs) - 1))
    return 1. / s

quality_fun = partial(quality_maxmindist, key=itemgetter("Role: Name"))

res = optimize(data, quality_fun)
pprint.pprint(res)

Output
[{'Full Name': 'name a', 'Role: Name': 'role a', 'User ID': '111'},
 {'Full Name': 'name d', 'Role: Name': 'role d', 'User ID': '223'},
 {'Full Name': 'name c', 'Role: Name': 'role b', 'User ID': '232'},
 {'Full Name': 'name b', 'Role: Name': 'role a', 'User ID': '222'},
 {'Full Name': 'name e', 'Role: Name': 'role d', 'User ID': '444'}]

Basically, you add a key parameter to the function quality_maxmindist (from here), this key parameter is going to be use to determine how to items are equal.
In the particular case of your question, you could use operator.itemgetter on "Role: Name", this way items with the same role will be considered equal. See below the code changes with comments:
def quality_maxmindist(items, key=None):
    if key is None:
        def identity(e): return e

        key = identity

    s = 0
    # notice that you need to use a dictionary for finding unique items by key
    for k, item in { key(item) : item for item in items}.items():
        indcs = [i for i in range(len(items)) if key(items[i]) == k]  # notice
        if len(indcs) > 1:
            s += sum(1. / (indcs[i + 1] - indcs[i]) for i in range(len(indcs) - 1))
    return 1. / s

quality_fun = partial(quality_maxmindist, key=itemgetter("Role: Name"))
res = optimize(data, quality_fun)


text:
Q: Is it OK to trickle charge a disposable battery So I am playing around with designing a UPS when another question hit me.
If I have a source feeding a small amount of current into a non-rechargeable battery is this OK?
By OK, I mean is this acceptable as a circuit to be put into products.

The battery will self discharge and begin to receive very small amounts of leakage current. After reading a bit I was surprised to find that you can actually recharge non-rechargeable batteries(disposable).
What scared me: Wikipedia quotes, "manufacturers do not support recharging, and warn that it may be dangerous". So this of course makes me worry about using this simple circuit. My intention is for the consumer to not use a rechargeable battery.

A: It may not be acceptable, but with minor modifications it can be.
You must keep the current flowing into the battery within the limits specified by the battery manufacturer (not some random dude editing Wikipedia). For safety reasons, you should also ensure that no single point of failure can cause a high current (beyond the manufacturer-specified limit) to flow into the battery.
The only 3.6V primary cells that come to mind are those made by the Israeli company Tadiran, so just for an example, let's check their application information, page 22:

Maximum reverse (charging) currents are listed in the
  Tadiran Batteries Product Data Catalogue. To obtain
  full performance reverse currents should be kept below
  10 μA.

So there's a "maximum current", which varies by battery type (and may, presumably, affect the battery performance), and a general maximum of 10\$\mu\$A that will not affect the battery performance. The "maximum current" is safety-related, not lifetime related. A PN silicon diode such as a 1N4148 will not leak more than 10\$\mu\$A unless you get it really hot (over 100°C). A 200mA Schottky might be okay. But, that's only one constraint.
The Batteries Product Data can be found here. Page 4 contains safety information including the maximum reverse current by battery type (15mA to 100mA), and a number of other cautions.
According to the UL recommendations you should use two series diodes (in case one fails) OR a diode and a current-limiting resistor that will ensure the maximum current is never exceeded, even if the diode fails. That resistor could be just a few hundred ohms (or less, depending on battery type) and meet the requirements of the Tadiran cells listed. For a memory backup or other very low current situation (low tens of uA), the resistor is probably the best because it will drop little voltage compared to a diode.


text:
Q: Marshal int slice to string line I have a struct as this:
type Int64Slice []int64
type DataWrapper struct {
    ListId Int64Slice    `json:"listid" required`
    Domain string `json:"domain" required`
    Name   string `json:"name,omitempty"`
}

And I need it become:
{
    "listid": "1 2 3 4 5",
    "domain": "mydomain"
}

I have wrote custom MarshalJSON:
func (u Int64Slice) MarshalJSON() ([]byte, error) {
    var result string
    if u == nil {
        result = "null"
    } else {
        result = strings.Trim(strings.Join(strings.Fields(fmt.Sprint(u)), " "), "[]")
        Logger.Debugln(result)
    }
    return []byte(result), nil
}

func (d *DataWrapper) ToJSON() []byte {
    result, err := json.Marshal(d)
    if err != nil {
        log.Fatalln(err)
        panic(err)
    }
    return result
}

At the line Logger.Debugln(result), it prints this result:

20170830090317506 20170830090026319 20170830111023194 201708301043081 ...
json: error calling MarshalJSON for type models.Int64Slice: invalid
character '2' after top-level value

A: I think you have it backwards.
Use the bytes.Buffer type to incrementally build up the string representation of your data.
The program
package main

import (
    "bytes"
    "encoding/json"
    "os"
    "strconv"
)

type Int64Slice []int64

func (s Int64Slice) MarshalJSON() ([]byte, error) {
    if s == nil {
        return []byte("null"), nil
    }

    var b bytes.Buffer
    b.WriteByte('"')
    for i, v := range s {
        if i > 0 {
            b.WriteByte('\x20')
        }
        b.WriteString(strconv.FormatInt(v, 10))
    }

    b.WriteByte('"')
    return b.Bytes(), nil
}

func main() {
    var (
        a Int64Slice = nil
        b = Int64Slice{
            42,
            12,
            0,
        }
    )
    enc := json.NewEncoder(os.Stdout)
    enc.Encode(a)
    enc.Encode(b)
}

Prints:
null
"42 12 0"

Playground link.

A: 20170830090317506 20170830090026319 20170830111023194 201708301043081 is not a valid JSON value.  It is interpreted as a valid number (20170830090317506) followed by a valid space, followed by invalid data, beginning with the 2 character; thus the error you observed.
It needs quotes around it:
Try something like:
result = `"` + strings.Trim(strings.Join(strings.Fields(fmt.Sprint(u)), " "), "[]") + `"`


text:
Q: Increasing the text size of tikz-cd labels By default the arrow labels in tikz-cd are quite small. When the labels involve subscripts or superscripts, they can become unreadable. How can I increase the label text size for all tikz-cd diagrams in my document?

A: In your preamble, add
\tikzcdset{every label/.append style = {font = \small}}

The default font size appears to be \scriptsize. Other options include (from small to larger): \tiny, \scriptsize, \footnotesize, \small, and \normalsize.


text:
Q: Eclipse fix same error in many files I recently imported a large number of source files into an eclipse project. Unfortunately they all have the wrong package declaration. Is there a way to fix errors en masse across all of the files (1 error per file)?

A: Try Source / Refactor / Rename (or something similar, I don't have it in front of me right now) in the editor context menu.


text:
Q: How to apply StandardScaler on objective variable when using sklearn pipeline and GridSearch? I want to train ML model on Ames dataset using sklearn pipeline as below:
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn.model_selection import GridSearchCV
from sklearn.feature_selection import VarianceThreshold

# -----------------------------------------------------------------------------
# Data
# -----------------------------------------------------------------------------

# Ames
X, y = fetch_openml(name="house_prices", as_frame=True, return_X_y=True)

# In this dataset, categorical features have "object" or "non-numerical" data-type.
numerical_features = X.select_dtypes(include='number').columns.tolist()   # 37
categorical_features = X.select_dtypes(exclude='number').columns.tolist()   # 43

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=0)

# -----------------------------------------------------------------------------
# Data preprocessing
# -----------------------------------------------------------------------------

numerical_preprocessor = Pipeline(steps=[
    ('impute', SimpleImputer(strategy='mean')),
    ('scale', MinMaxScaler())
])

categorical_preprocessor = Pipeline(steps=[
    ('impute', SimpleImputer(strategy='most_frequent')),
    ('one-hot', OneHotEncoder(handle_unknown='ignore', sparse=False))
])

preprocessor = ColumnTransformer(transformers=[
    ('number', numerical_preprocessor, numerical_features),
    ('category', categorical_preprocessor, categorical_features)
],
        verbose_feature_names_out=True,
)

# -----------------------------------------------------------------------------
# Pipeline
# -----------------------------------------------------------------------------

model = Pipeline(
    [
        ("preprocess", preprocessor),
        ('selector', VarianceThreshold(0.0)),
        ("regressor", GradientBoostingRegressor(random_state=0)),
    ]
)

_ = model.fit(X_train, y_train)

print(f"R2 train: {model.score(X_train, y_train):.3f}")   #  0.974
print(f"R2 test : {model.score(X_test, y_test):.3f}")   # 0.861

# -----------------------------------------------------------------------------
# Grid Search
# -----------------------------------------------------------------------------

param_grid = {
    "regressor__n_estimators": [200, 500],
    "regressor__max_features": ["sqrt", "log2"],
    "regressor__max_depth": [4, 5, 6, 7, 8],
}

grid_search = GridSearchCV(model, param_grid=param_grid, cv=3)

grid_search.fit(X_train, y_train)

grid_search.score(X_test,y_test)

What I am doing:

*

*For numerical features : Imputing & MinMax scaling

*For categorical features : Imputing & One-hot encoding
Next step is feature selection and fitting model.
However, I would like to apply StandardScaler on objective variable (y). I would like to know how I can include this step in sklearn pipeline to be sure that there is no leakage of information in cross-validation loop.
I mean, I want to fit_transform on train subset and transform on test subset during cross-validation (in hyper-parameter tuning).
I am not sure if I can use TransformedTargetRegressor since it has only fit method but StandardScaler should be fit_transform on train subset.

A: Yes, you answered the question yourself. TransformedTargetRegressor performs targets transformation with the Transformer/Pipeline your provide.
This automatically performs a fit_transform in training phase on y.
Then, the model is fitted on the transformed version of y, and then inverse_transformed to be given as model output.
You are basically tranforming the target space (with an arbitrary operation, linear/nonlinear) and operating regression on it.
This tranformation is done automatically by this wrapper. You can use it in your code like this:
from sklearn.compose import TransformedTargetRegressor

param_grid = {
    "regressor__regressor__n_estimators": [200, 500],
    "regressor__regressor__max_features": ["sqrt", "log2"],
    "regressor__regressor__max_depth": [4, 5, 6, 7, 8],
}

grid_search = GridSearchCV(
    TransformedTargetRegressor(
        regressor = model,
        transformer = StandardScaler()
    ),
    param_grid=param_grid, cv=3)