Quando e por que devo utilizar classes templates Class  em Java?

Question: Eu quando vejo que uma classe ela recebe isso, eu acho assustador.
Comment: Até alguém responder... [Usando Generics em java](http://www.devmedia.com.br/usando-generics-em-java/28981)
Comment: Isso é `Generics`. Há aplicações interessantes, mas realmente nunca parei pra pensar em que casos é recomendado.
Comment: Uhum class Generics...
Comment: Isso. Não são templates. Template é uma coisa relacionada que existe em C++ (mas bem diferente)
Comment: Ops achava que era a mesma coisa.
Comment: Acho que pode dar uma luz: [Diferenças entre  e ](http://pt.stackoverflow.com/q/68554/3117)
Answer: Em C++ isto pode se chamar template, mas em Java estas classes são chamadas de genéricas.
Isso é necessário quando uma classe pode usar a mesma estrutura básica e os mesmo algoritmos com diversos tipos de dados. Pense em algo que pode ser feito igualzinho com Boolean, Integer, Long, Float, etc. Tudo é igualzinho, só muda o tipo do dado que será usado para armazenar na classe. Como você resolve isto? Faz uma classe para cada tipo desses, copiando elas e só mudando o tipo?
Quando tiver que dar manutenção vai lembrar de fazer em todas igualzinho? Não tem condições, certo?
Aí você pode usar o tal do generics. Com isto pode variar o tipo do dado básico que será usado na classe de acordo com a forma que ela for instanciada. Então esse T aí é uma espécie de "super-variável", que será substituído por um tipo específico quando a classe for instanciada.
class Exemplo<T> {
    private T x;
    Exemplo(T x) => this.x = x;
    public T getValue() => x;
}

Depois usa:
Exemplo<String> teste1 = new Exemplo<String>("teste");
teste1.getValue();
Exemplo<Boolean> teste2 = new Exemplo<Boolean>(true);
teste2.getValue();

Coloquei no GitHub para referência futura.
Tudo funciona. No primeiro exemplo, todos os lugares que tinha o T, vai virar String. E no segundo onde tinha T vira Boolean, ficaria algo assim:
class Exemplo<String> {
    private String x;
    Exemplo(String x) {
        this.x = x;
    }
    public String getValue() {
        return x;
    }
}

Assim uma única classe resolve o problema para todos os tipos sem ter que ficar copiando código, que vai causar problemas de manutenção.
O Java está repleto dessas classes. As coleções de dados costumam se beneficiar muito disto. No começo Java não tinha esse recurso, então você tinha um ArrayList "pelado" assim mesmo. Então ele aceitava qualquer coisa. Até funciona, mas imagine que você pode misturar números, com Strings, com Clientes (uma classe que você definiu), com qualquer outra coisa. Quando se criou o tal do ArrayList<T>, você cria uma variável que guarda ArrayList<Cliente> e esta lista só pode guardar Clientes. Fica mais seguro. Basicamente esta é uma coleção que pode ser usado com qualquer tipo já existente no Java ou criado pelos programadores.
Simplificadamente é isso. Tem maneiras de usar de forma mais avançada, fazer restrições de que tipos podem ser usados em T, ter outros slots para generalizar outras partes com um tipo diferente, enfim... vai perguntando conforme for usando e for surgindo novas dúvidas.
Documentação (continue acompanhando as páginas do tutorial).
Comment: Sim, claro, vou melhorar.
Comment: `ArrayList` é um exemplo disso correto?
Comment: Muito boa resposta! Eu sempre procurei uma boa forma de explicar isso.
Comment: Entendi! Agora sim faz sentido para mim e do jeito que você explica fica tudo muito fácil, bigown.
Answer: Os Generics também são muito úteis em métodos nesse exemplo :
    public static <T> List<T> asList(T... objects) {
       return ...
    }

você receberá uma lista do tipo T baseado em seus parâmetros;


Free mail server support multiple IP for windows

Question: I am using hmailserver, its good mail server but only support one IP on my server. do you khnow any FREE mail server support multiple IP for outgoing emails?
mail.example.com : 220.127.116.11 mail2.example.com : 18.104.22.168
smartermail support this, but its not free for multiple domain
Comment: This is a shopping question which is off-topic here (see the [FAQ]).
Answer: Depending on your actual needs, the free version of Axigen Mail Server might be suitable.
It has the ability to create listeners for different IPs using it's admin interface.
http://www.axigen.com
Comment: not sure exactly what you mean, Axigen is supported on Windows:
http://www.axigen.com/mail-server/download/
http://www.axigen.com/mail-server/features/#aPlatforms
Comment: its not windows mail server
Answer: Just use the integrated smtp server bundled with Windows.
http://www.itsolutionskb.com/2008/11/installing-and-configuring-windows-server-2008-smtp-server/
Comment: It can. But you can use one server for ingoing, and another for outgoing. Or you use hmailserver for both, but he pipes to the integrated mail server for outgoing.
Comment: can i receive email with this mail server?


Error creating file using new File(directory).mkdir()

Question: I used new File(directory).mkdir() to create a new folder.
When i setdirectory = "C:\\Users\\livw\\Desktop\New folder\\5b27233480c016706f62a30a",
it works.
But when i add one more child folder to the directory: directory = "C:\\Users\\livw\\Desktop\\New folder\\5b27233480c016706f62a30a\\Samples",it doesn't create the folder.
How can i fix it?
Comment: Does `C:\\Users\\livw\\Desktop\New folder\\5b27233480c016706f62a30a` exist BEFORE hand? (and is `5b27233480c016706f62a30a` a directory and not a file?)
Comment: use mkdirs() instead of mkdir(), unlike mkdir() ,  mkdirs() garauntees the creation of any non existing parent directories also.
Answer: Short and sweet,
Use mkdirs() instead of mkdir().
Hope it helps
Please in future refer to documentation.
Comment: It worked. Thank you for your advice.
Comment: @TanNguyen if it helped then you could mark this as an accepted answer this helps the community to help others.
Comment: Yes, i'm waiting to do it :)
Answer: directory = "C:\Users\livw\Desktop\New folder\5b27233480c016706f62a30a"
kindly check the directory address as file separator is not properly given before new Folder
import java.io.File;`
public class FileCreation {
    public static void main(String[] args) {
        new  File("C:\\Users\\Master\\Desktop\\Horse\\demo\\devil").mkdir();
        new File("C:\\Users\\Master\\Desktop\\Horse\\demo\\devil"+File.separator+"a").mkdir();
    }
}


Php mysql fetch array repetitive index problem

Question: I want to remove the number indexes in the following output

Array ( [0] => 7593 [id] => 7593 [1] => Atakan [ad] => Atakan [2]

intended

Array ([id] => 7593 [ad] => Atakan [2]

my code
     global $durum;
 $array = Array();
 $sql="select * from bird_table_uye order by id desc";
 $query=phpmkr_query($sql,$durum);
 $i=0;

 while ($row=phpmkr_fetch_array($query)) {
  $array[$i]=$row;

   $i++;
 }
 print_r($array);

Answer: You can use
mysqli_fetch_array()

rather using
mysqli_fetch_assoc()

Comment: Your welcome it would be very nice of you if you accept the answer also :)
Comment: Yes of course there are number of libraries to make this job easier one of them is PHPExcel


Androidx RecycleView Not showing items with parse server

Question: This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {

private Context mcontext;
private List<Food> mData;
RequestOptions option;

public CategoryRAdapter(Context mcontext, List<Food> mData) {
    this.mcontext = mcontext;
    this.mData = mData;

    option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);

    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Food current = mData.get(position);
    holder.tv_Name.setText(current.getName());
    holder.tv_Rating.setText(current.getRating());
    holder.tv_Descip.setText(current.getDescrip());
    holder.tv_Category.setText(current.getCateg());
    Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}

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

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView tv_Name;
    TextView tv_Rating;
    TextView tv_Descip;
    TextView tv_Category;
    ImageView img_Thumbnail;

    public MyViewHolder(View itemView) {
        super(itemView);

        tv_Name = itemView.findViewById(R.id.food_name);
        tv_Rating = itemView.findViewById(R.id.rating);
        tv_Descip = itemView.findViewById(R.id.desc);
        tv_Category = itemView.findViewById(R.id.category);
        img_Thumbnail = itemView.findViewById(R.id.thumbnail);
    }
}
}

This is my model
Food Class
public class Food {
    String Name;
    String Images;
    String Descrip;
    String Rating;
    String Categ;

public Food() {
}

public Food(String name, String images, String descrip, String rating, String categ) {
    this.Name = name;
    this.Images = images;
    this.Descrip = descrip;
    this.Rating = rating;
    this.Categ = categ;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getImages() {
    return Images;
}

public void setImages(String images) {
    Images = images;
}

public String getDescrip() {
    return Descrip;
}

public void setDescrip(String descrip) {
    Descrip = descrip;
}

public String getRating() {
    return Rating;
}

public void setRating(String rating) {
    Rating = rating;
}

public String getCateg() {
    return Categ;
}

public void setCateg(String categ) {
    Categ = categ;
}
}

My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_categoria);
    recyclerView = findViewById(R.id.recycle_id);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    dbObjects = new ArrayList<>();
    ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
    query.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> objList, ParseException e) {

            if (e == null) {

                for (ParseObject obj : objList) {
                    Food food = new Food();
                    food.setName(obj.getString("Name"));
                    food.setDescrip(obj.getString("Descrip"));
                    food.setRating(obj.getString("Rating"));
                    food.setCateg(obj.getString("Categ"));
                    food.setImages(obj.getString("Images"));
                    dbObjects.add(food);
                }
            } else {
                FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
            }
        }
    });

    adapter = new CategoryRAdapter(this, dbObjects);
    recyclerView.setAdapter(adapter);

    FloatingActionButton fab = findViewById(R.id.shoppingFlot);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            carritopop();
        }
    });
}

private void carritopop() {
    dialogBuilder = new AlertDialog.Builder(this);
    View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
    l_finalizar = view.findViewById(R.id.l_finalizar);
    l_finalizar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pago();
        }
    });

    dialogBuilder.setView(view);
    dialog = dialogBuilder.create();
    dialog.show();
}

private void pago() {
    Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
    startActivity(intent);
}
}

I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Answer: Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
    for (ParseObject obj : objList) {
          ...
    }
    adapter.notifyDataSetChanged();
}

Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");

Answer: I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.


Selecting a parent element (without using Jquery)

Question: I just need to access the parent div where I have a button changing his siblings divs.
A code example can explain better:

trololo A

trololo B

    <button onClick="toggleThem(this)">This button will toggle above divs</button>

function toggleThem(a){  // something like this, BUT without Jquery
    $(a).closest(".parent").find(".divA").hide();
}

Answer: That's what parentNode is for:
a.parentNode.querySelectorAll('.divA');

Comment: What is "a" in this example:?
Comment: @zero_cool it follows the original question, in which case `a` is the `button` element.
Answer: function toggleThem(elem) {
    elem.parentNode.getElementsByClassName('divA')[0].style.display = 'none';
}

Comment: `TypeError: Cannot read property 'display' of undefined`. Don't forget that `getElementsByClassName` returns a `nodeList`.


Header region causing the page to be too wide

Question: When viewing my website on Internet Explorer there seems to be a big space on the right where the page has scroll bars to take in the full width. I think its to do with my header image. It seems ok in Firefox and chrome. Can anyone suggest a way to get this working on IE?
Comment: May you add a screenshot? It would help to see what you are seeing. Plus, the question would be helpful to future readers, even if the site is down.
Answer: Its because of your fb_reset facebook iframes.

If you remove the css rules in the style and change to

Add to css:
.fb_reset {
display:none;
}

Comment: And its only ie7. The others manage to figure it out.
Comment: exactlly .Its becasue Iframes


My hooks are not invoked by Drupal

Question: I am developing a module, but the hooks I am adding are not invoked from Drupal. It happens with more than one hook.
I read the documentation for the hooks, and I cannot find anything that would explain why this happens. I verified I am using the correct parameters, and returning the correct value.
What am I doing wrong? Is there anything I am missing?
Comment: This question is thought as canonical question for those questions about hooks not being invoked by Drupal.
Answer: When developing a module, you should keep in mind the following notes.

The implementation of a hook done from a module is a function whose name is prefixed with the module short name (also called the machine name); from the hook name, take off the hook part, and replace it with the module machine name. For example, the implementation of hook_menu() done from example.module is example_menu(). If the module is example_menu.module, and the function is example_menu(), that is not considered the hook_menu() implementation for example_menu.module.
This also means, for example, that the hook_form_alter() implementation in example_form.module is not example_form_alter(), but example_form_form_alter(). As another example, the implementation of hook_form_FORM_ID_alter() done for altering the form returned from user_register_form() from example.module is not example_form_user_register_alter(), but example_form_user_register_form_alter(). (The form ID is user_register_form.)
Generally speaking, using uppercase characters in the module machine name doesn't create problems: PHP doesn't make differences between myModule_get_value(), and mymodule_get_value(), and $value = myModule_get_value() would call either myModule_get_value(), or mymodule_get_value().
Although, there is a case where using upper case characters in a module machine name would cause problems: when defining the update hooks for a module. drupal_get_schema_versions(), the function that returns a list of available updates, contains the following code.
// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

The last line executed from drupal_get_schema_versions() is the following one.
return empty($updates[$module]) ? FALSE : $updates[$module];

If the module name is myModule.module, drupal_get_schema_versions('myModule') will return just the functions with a name that starts with myModule_update, and ends with a number; functions like mymodule_update_7120() will not be included because the regular expression used from drupal_get_schema_versions() is case sensitive. This still applies to Drupal 8, as the regular expression is still the same used in Drupal 7.
Some hooks are called in specific moments. For example, hook_menu(), and hook_menu_alter() are called from Drupal 7 after a module has been enabled/disabled, or when the cache for the router information is cleared; hook_init() is not invoked for cached pages.
Once the hooks are invoked because a specific event happened, they will not called again until a similar event doesn't happen. They are not called in two successive page requests.
Drupal caches the list of hooks implemented from a module. If you are editing the code of an enabled module to add new hooks, you first need to disable and  re-enable the module, or Drupal will not notice there are new hooks.
Ensure that a return statement didn't sneak its way into one of your hook functions during a refactoring. It has the potential to break not only the hook that it appears in, but to cause a chain reaction that breaks other hooks as well, making the problem difficult to locate.
Comment: Also maybe worth to mention my mistake for the sake of others in the future: do NOT define a namespace in your .module (or any other "flat", non-class PHP) file. Otherwise Drupal will not recognize your file, therefore won't discover the hooks defined in them.

My hooks are not invoked by Drupal


Criptografar XML com chave publica do TJMG


Custom Web Service With InfoPath

Question: I am facing issue with accessing a custom web service deployed to _vti_bin of SharePoint Site. The web service is being called from the InfoPath 2007 browser enabled form template. Everything works fine if the call originates on the same machine as the web service host. It's an anonymous web service with no auth needed.
When I access the form from an external environment, it throws "Error accessing data source". There's nothing in logs or event viewer.
Any idea is welcome as it is becoming cryptic considering there are no logs.
Answer: In the end, point number 2 in the following post served as the solution - http://sharepointconnoisseur.blogspot.com/2011/04/how-to-resolve-401-unauthorized-error.html

Custom Web Service With InfoPath


Registro de usuario com Vue js e laravel

Question: Criei uma pagina de login com vue.js.
Mandei as informações para um controller no laravel para criar um usuário.
Depois de criar o usuário, estou tentando redirecionar para home,com o usuário autenticado, mas quando redireciona para home, cai na tela de login.
Requisição Vue
register(){

        axios.post('/api/register', this.form)
            .then(response => {
                window.location.href = "/home";
            });
    }

Rota API
Route::post('register', 'Api\RegisterController@register');

Controller Laravel
 public function register(Request $request){

    $data = $request->validated();

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    Auth::login($user);
    Auth::guard()->login($user);
     // Auth::loginUsingId($user->id);

    return response()->json(['message' => 'Salvo com sucesso.','user' => $user]);
}

Rota WEB, que esta acessando após o registro:
Route::group(['middleware' => ['auth']], function () {
  Route::get('/home', function(){
      return view('home')
  });
});

Eu tentei com o código redirecionar para a home autenticado, mas esta indo para a tela de login, por causa do middlware.
Tem algum jeito de ir para a tela home autenticado automatico após o registro, sem ter que se logar?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Ao invés de retornar uma mensagem de sucesso sempre, use uma condicional para verificar se, de fato, o login foi realizado e aí sim poderá retornar uma mensagem de erro ou sucesso.
Comment: Certo, mas tem algum jeito de ir para a tela home autenticado automatico após o registro?
Answer: Um possível motivo é porque quando você usa rotas dentro do prefix "api", a sessão não está iniciada. O que você pode fazer:
No arquivo: app/Http/Kernel.php, procure pelo $middlewareGroups "api".
Adicione os middleware para iniciar sessão e relacionados com cookies.
Vai ficar +- assim:
// ...

        'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,

            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
// ...

https://laravel.com/docs/8.x/middleware#middleware-groups
O seu guard, provavelmente (se default), está utilizando "web", no auth.php - que utiliza sessions/cookies.
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

E o middleware de "api" não tem sessions por padrão (no RouteServiceProvider, você vai ver que para rotas /api, é utilizado o middleware group "api" - que só utiliza dois middleware definidos no kernel: throttle:api e SubstituteBindings).
Sugestões:
Apenas Auth::loginUsingId($user->id); é suficiente. Não precisar chamar os outros métodos de login.
Comment: Obrigado Eduardo.
Funcionou colocando, \Illuminate\Session\Middleware\StartSession::class, dentro do, protected $middleware.


Load different database in library file codeigniter

Question: I am trying to load a different database based on the session variable in codeigniter, But I get an error An Error Was Encountered You have not selected a database type to connect to. Below I have my admin_init_elements library file

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database type. ie: mysql.  Currently supported:
     mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
| ['dbprefix'] You can add an optional prefix, which will be added
|     to the table name when using the  Active Record class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
|     NOTE: For MySQL and MySQLi databases, this setting is only used
|      as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
|     (and in table creation queries made with DB Forge).
|      There is an incompatibility in PHP with mysql_real_escape_string() which
|      can make your site vulnerable to SQL injection if you are using a
|      multi-byte character set and are running versions lower than these.
|      Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['autoinit'] Whether or not to automatically initialize the database.
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
|       - good for ensuring strict SQL while developing
|
| The $active_group variable lets you choose which connection group to
| make active.  By default there is only one group (the 'default' group).
|
| The $active_record variables lets you determine whether or not to load
| the active record class
*/

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'pass';
$db['default']['database'] = 'latestdb';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

$db['latestdb']['hostname'] = 'localhost';
$db['latestdb']['username'] = 'root';
$db['latestdb']['password'] = 'pass';
$db['latestdb']['database'] = 'latestdb';
$db['latestdb']['dbdriver'] = 'mysql';
$db['latestdb']['dbprefix'] = '';
$db['latestdb']['pconnect'] = TRUE;
$db['latestdb']['db_debug'] = TRUE;
$db['latestdb']['cache_on'] = FALSE;
$db['latestdb']['cachedir'] = '';
$db['latestdb']['char_set'] = 'utf8';
$db['latestdb']['dbcollat'] = 'utf8_general_ci';
$db['latestdb']['swap_pre'] = '';
$db['latestdb']['autoinit'] = TRUE;
$db['latestdb']['stricton'] = FALSE;

$db['sit']['hostname'] = 'localhost';
$db['sit']['username'] = 'root';
$db['sit']['password'] = 'pass';
$db['sit']['database'] = 'sit';
$db['sit']['dbdriver'] = 'mysql';
$db['sit']['dbprefix'] = '';
$db['sit']['pconnect'] = TRUE;
$db['sit']['db_debug'] = TRUE;
$db['sit']['cache_on'] = FALSE;
$db['sit']['cachedir'] = '';
$db['sit']['char_set'] = 'utf8';
$db['sit']['dbcollat'] = 'utf8_general_ci';
$db['sit']['swap_pre'] = '';
$db['mappsit']['autoinit'] = TRUE;
$db['mappsit']['stricton'] = FALSE;

$db['fold']['hostname'] = 'localhost';
$db['fold']['username'] = 'root';
$db['fold']['password'] = 'pass';
$db['fold']['database'] = 'fold';
$db['fold']['dbdriver'] = 'mysql';
$db['fold']['dbprefix'] = '';
$db['fold']['pconnect'] = TRUE;
$db['fold']['db_debug'] = TRUE;
$db['fold']['cache_on'] = FALSE;
$db['fold']['cachedir'] = '';
$db['fold']['char_set'] = 'utf8';
$db['fold']['dbcollat'] = 'utf8_general_ci';
$db['fold']['swap_pre'] = '';
$db['fold']['autoinit'] = TRUE;
$db['fold']['stricton'] = FALSE;
/* End of file database.php */
/* Location: ./application/config/database.php */

I know the error is in the constructor line $DB2 = $CI->load->database($DB, TRUE); , I have to insert , update and delete from the selected db otherwise it takes default db and inserts there.
Comment: have you checked $DB is populated with correct value?
Comment: yes, its populating correctly @siddhesh
Comment: Share your database.php file from config folder and please remove your controlller code except __construct it is just useless
Comment: @siddhesh , modified the question
Comment: your ci version pelase?
Answer: You can load the database every time you perform a query, in the $ load-> database ('localhos or latestdb or sit ...', TRUE) function, the first parameter can be a variable or a function.
function myfuntion{

 $SomeDataBase = $this->load->database('localhost for example', TRUE);

    $result=$SomeDataBase->query('SELECT...');

}


Using Feign in a standalone library vs a Springboot application

Question: I want to create a client for Some-Micro-Service as a library (Some-Micro-Service-Client) that way it can easily be included in the pom of Some-Other-Micro-Service.
I would like to use Feign because it makes things easier, but I am not sure if this is possible with my architecture. All of the Feign examples that I see start with using the @EnableFeignClient annotation on the SpringBootAppplication class, but since I don't want the client library to have to be "started up" I want to know if it is possible just to include it in the library without using the EnableFeignClient annotation.
Answer: Yes, you can use feign without @EnableFeingClient annotation. Assume, we want to receive data from this API. In below example I used Feign Core and Feign Gson dependencies.
First of all we need to create class, in which we will get the json result:
public class TODO {
    private long id;
    private long userId;
    private String title;
    private boolean completed;

    \\ getters and setters ...
}

After that we declare the interface with the future rest-client methods:
public interface TaskApi {

    @RequestLine("GET /todos/{id}")
    TODO getTODO(@Param("id") int id);
}

And in conclusion let's build desired rest client and make test request:
public class FeignTest {

    private static final String API_PATH = "https://jsonplaceholder.typicode.com";

    public static void main(String[] args) {
        TaskApi taskApi = Feign.builder()
                .decoder(new GsonDecoder())
                .target(TaskApi.class, API_PATH);
        TODO todo = taskApi.getTODO(1);
    }
}

For more information and possibilities you can read in official repository.
Comment: This was really helpful, but as I'm unit testing FeignTest class, i am unable to mock the TaskAPI normally (with @Mock on the declaration and then doReturn when taskApi.getTODO(any()). Any help on this?
Comment: FeignTest is a pretty sample class for demonstrating how to create and use feign. In practice, you can create TaskApi object in another place and put it as a constructor parameter of FeignTest class. As result, you will have the possibility to mock the TaskApi object in unit tests.


Changeover from Garage Band to Logic Pro

Question: Currently,i am using Garage Band to do my arrangements for the songs I've composed. I have four songs completed with all the arrangements and accompaniment. The only thing left is to record the vocals.
I use Musescore to notate this score and export each instrument in midi format and import in GB and also use GB drum kits for beats and drum loops.i have presonus home recording kit for recording vocal using Garage Band.
My questions are if I purchase Logic Pro -

Will the same GB file work in Logic Pro or do I need to start with the beginning with all arrangements from scratch?
If I am able to move to Logic Pro from GB - is there is any possibility of degrade of sound quality?
What will be the key benefits I can get by migrating from GB to Logic
Pro?
Is Logic Pro as user friendly as GB?
Answer:

Will the same GB file work in Logic Pro or do I need to start with the beginning with all arrangements from scratch?

You don't have to start from scratch. You can import your Garage Band files into Logic Pro and they should open up pretty much exactly how they were in Garage Band. Note: You can't go back. Once you make changes in Logic, you won't be able to easily open that file up in Garage Band.

If I am able to move to Logic Pro from GB - is there is any possibility of degrade of sound quality?

No, more likely the opposite. Logic Pro is Apple's top of the line audio editing software. It has all of their best features and sound.

What will be the key benefits I can get by migrating from GB to Logic
  Pro?

You will have a lot more power for recording, editing and mixing. You will have access to many more effect plugins and virtual instruments. You'll have extended professional capabilities like alternate tunings, clock synchronization, etc.

Is Logic Pro as user friendly as GB?

Sort of, but not really. Your first day in Logic Pro will probably not be too hard. There are a lot of similarities with Garage Band. Once you start looking at using the more advanced features that Logic Pro has that are not in Garage Band, you'll find there is a learning curve. Some people find the menu locations and layout of features in Logic to be very intuitive, others do not. There isn't really a way to find out without using the software.
The Apple documentation that I've read on Logic Pro is usually pretty brief and doesn't do a good job of explaining all the details of each function and feature. I find that very disappointing for "professional" software. At the same time, there are many great videos on YouTube about how to use advanced features in Logic Pro.
On a personal note, once I got Logic Pro, I never wanted to go back to Garage Band. It is definitely an upgrade.


React router Prompt history push query params change Prompt location

Question: I have a problem using react-router Prompt component.
I want to warn users when they reload or leave page except for 1 case when I add query param to the url.
I already did it but when I refresh the page after making changed. I go back to the path "/" not the current page I'm working on.
Example: I'm working on path "create-contract".  Then I want to add query ?screen={screen} if users click on a button.
Now I have "create-contract?screen={screen}" Then if I refresh page and confirm or go back to previous url "create-contract" and refresh.
I will go to path "/". What I think is wrong.
I want it still in the current page when I refresh.
Here the code:
useEffect(() => {
        if (shouldBlockNavigation) {
            const existingHandler = window.onbeforeunload;
            window.onbeforeunload = (event) => {
                if (existingHandler) existingHandler(event);
                return true;
            };
        } else {
            if (screen) {
                history.push("?screen=" + screen);
            } else {
                history.push(RouteConstant.Contract.CreateContract.path);
            }
        }
        return () => {
            window.onbeforeunload = null;
        };
    }, [shouldBlockNavigation, screen]);

return (
        <>
            <Prompt
                when={shouldBlockNavigation}
                message="作成中の書類を破棄します。よろしいですか?"
            />
            ...
       </>
)

Anyone help me please. Thank you!
Answer: There is no information what is screen variable.
Seems for me that after reload it goes to this part:
else {
   if (screen) {
      history.push(RouteConstant.Contract.CreateContract.path + "?screen=" + screen);
   } else {
      history.push(RouteConstant.Contract.CreateContract.path); // goes here
   }
}

To solve this you can try to get current location, parse it, and if it contains ?screen=screen get screen from this url and use it
To get current location, you can use useLocation() from react-router-dom
Comment: Thank you for answer my question.

No. when reload it go to case if (shouldBlockNavigation).
"screen" variable just a number 1, 2, 3.
I try not to show the alert if I click on a button that add the query such as "?screen=1".
But after that if I reload the page it will go to the path "/" not the current path I'm working on


How can i auto get form's data for perl6?

Question: a form like this:
<form action='1.php' method='post'>
u:<input name='u' type='text'/>

p:<input name='p' type='password'/>

<input value='submit' type='submit'/>
</form>

and how can i auto get the form data use perl6?
lkie this:
my $form = xxx($the_form_url)

and the result like this:
$form.Str
#output like that:
#u=username&p=password&submit=submit

have shome modules in perl6?
please..
Comment: I'm not up to date on P6 webdev, but at the time of writing this the #1 place to browse P6 modules that folk have shared is [modules.perl6.org (mpo)](http://modules.perl6.org/). (CPAN / metaCPAN support is work in progress.) A [search of mpo for 'params'](http://modules.perl6.org/#q=params) lists [HTTP::ParseParams](https://github.com/retupmoca/P6-HTTP-ParseParams). It looks like you'd need to use it with something that handles requests. I see modules matching 'http', 'request', 'cgi', 'web'. I know szabgab et al are currently fleshing out [Bailador](https://github.com/Bailador/Bailador).
Comment: Are you looking for a [`WWW::Mechanize`](https://metacpan.org/pod/WWW::Mechanize) like module in Perl 6?
Answer: Bailador is indeed a good tip.
But if you want a more CGI-line approach, have a look at SCGI;
https://github.com/supernovus/SCGI


SharePoint Nested If Statement to add days to a date if condition is met

Question: I have a SharePoint Document library and need a calculated column to store a due date.
My existing columns are "Requires Follow Up?" which is a Yes/No field, and a "JPE Date" which is a date field.  If Requires Follow Up? is equal to Yes, I want the due date to be 7 days after the JPE Date. If Requires Follow Up? is equal to No or null I don't want a date in this field and would accept a blank, null or hyphen instead of a date.
I have tried many iterations of the following formulas:
IF(OR([Requires Follow Up?]="No",ISBLANK([Requires Follow Up?])),"-",IF([Requires Follow Up?]="Yes",[JPE Date]+7,"-")
=IF(([Requires Follow Up?])="No","-",IF(([Requires Follow Up?])="Yes",DATE(YEAR([JPE Date]),MONTH([JPE Date]),DAY([JPE Date])+7),IF(ISBLANK(([Requires Follow Up?])),"","")))
I feel like my reference to "Yes" is the issue, but replacing "Yes" with TRUE also doesn't work. I also tried to employ  <>"Yes" but am not certain if this means "not equal to" in this context.
I have been working from an Excel formula that performs perfectly every time: =IF(E5="No","-",IF(E5="Yes",D5+7,IF(ISBLANK(E5),"0","1")))  where E5 is the Required Follow Up? and D5 is the JPE date.
I am working in Notepad and copying into the SharePoint formula field so I think my quote marks are the correct characters.
Can anyone suggest better or improved syntax or other approaches to accomplish same? My research thus far tells me I need the square brackets because my column headers contain spaces, but this is new to me so I may not have understood that correctly.
Many thanks!
Answer: I found a solution that works:
<code>=IF(([Requires Follow Up?]),DATE(YEAR([JPE Date]),MONTH([JPE Date]),DAY([JPE Date])+7),"")
</code>
thanks to Ryan at Pentalogic
http://blog.pentalogic.net/2015/06/sharepoint-calculated-column-formula-with-yes-no-boolean-fields/


chamando Enum pelo value

Question: Criei uma enum:
 public enum EnumTipoBoleto
    {
        VazioErro=0,
        ConfigInicial = 1,
        Mensalidade = 2,
        Outros =3,
        DifMensal =4
    }

Agora em alguns lugares eu tenho o número e quero converter para enum

var variavel = 2;
var valorEnum = EnumTipoBoleto[variavel]; //Como faço?

'EnumTipoBoleto' is a type, which is not valid in the given context

Answer: Tenta fazer um cast
Por exemplo:
var variavel = 2;
var valorEnum = (EnumTipoBoleto)variavel;

Comment: uhahuahua era isso mesmo..aff que vacilo meu..rs

chamando Enum pelo value


google tango / opencv android camera app crashes/hangs

Question: I am developing a prototype app, utilizing the tango depth camera for template matching. So far, I have been able to solve all problems with the help of already answered questions, documentation etc.
However, now I seem to have come to a stop. Last major change I made, was to draw a contour on the camera preview image, before displaying it. No matter what I do now, the app works for a while, before it crashes.
I have looked at heap dumps and allocation tracking in Android Studio. The only possibly weird thing there is that there can be a lot of memory on FinalizerReference objects in the heap dump...
I also tried moving the processing to an AsyncTask, and just skip every color frame until the task was done (so that only one task was running at a time) and the processed frame was displayed, but the problem remained.
I am using Google Tango for getting color and depth camera data and opencv in java for analyzing the data and doing the template matching.
Does someone have a clue of what these logcat messages mean?
Logcat errors:

E/lowmemorykiller: Error opening /proc/10173/oom_score_adj; errno=2
  E/mm-camera-isp2: abf40_trigger_update:587 aec_ratio.ratio = 0.039062
  W/ActivityManager: Scheduling restart of crashed service
  com.lenovo.lsf.device/com.lenovo.lsf.push.service.PushService in 68068ms
  W/ActivityManager: Scheduling restart of crashed service com.qualcomm.qti.modemtestmode/.MbnSystemService in 88020ms
  E/InputDispatcher: channel '478a66c com.android.documentsui/com.android.documentsui.DocumentsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
  E/lowmemorykiller: Error writing /proc/10113/oom_score_adj; errno=22
  E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 76)
  E/lowmemorykiller: Error writing /proc/32408/oom_score_adj; errno=22
  E/InputDispatcher: channel '85c4188 com.android.launcher3/com.android.launcher3.Launcher (server)' ~ Channel is unrecoverably broken and will be disposed!
  E/mm-camera-isp2: abf40_trigger_update:587 aec_ratio.ratio = 0.000000
  E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ id=332, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED] ]
  E/mm-camera: mct_util_timer_handler:Error Backend stuck during HAL Command Raising SIGABRT
  E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 76)
  E/lowmemorykiller: Error writing /proc/32437/oom_score_adj; errno=22
  E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 308)
  E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 76)
  E/lowmemorykiller: Error writing /proc/32437/oom_score_adj; errno=22
  E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 76)
  E/mm-camera: mct_util_timer_handler:Error Backend stuck during HAL Command Raising SIGABRT  E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -32
  E/Surface: queueBuffer: error queuing buffer to SurfaceTexture, -32
  E/mm-camera: cpp_module_send_buf_divert_event:545] buffer event received with no divert config
  E/mm-camera: cpp_module_send_buf_divert_event:545] buffer event received with no divert config
  E/Camera3-OutputStream: getBufferLocked: Stream 0: Can't dequeue next output buffer: Broken pipe (-32)
  E/Camera3-OutputStream: returnBufferCheckedLocked: Stream 0: Error queueing buffer to native window: Broken pipe (-32)
  E/Camera3-Device: RequestThread: Can't get output buffer, skipping request: Broken pipe (-32)
  E/Camera3-Device: Can't return buffer to its stream: Broken pipe (-32)
  E/Camera3-OutputStream: getBufferLocked: Stream 0: Can't dequeue next output buffer: Broken pipe (-32)
  E/Camera3-Device: RequestThread: Can't get output buffer, skipping request: Broken pipe (-32)

Code for displaying camera preview:
mTango.experimentalConnectOnFrameListener(TangoCameraIntrinsics.TANGO_CAMERA_COLOR, new Tango.OnFrameAvailableListener() {
    byte[] imageByteArray = new byte[colorCameraIntrinsics.height * colorCameraIntrinsics.width * 3 / 2];
    Mat yuvMat = new Mat( colorCameraIntrinsics.height + colorCameraIntrinsics.height/2, colorCameraIntrinsics.width, CvType.CV_8UC1 );
    Bitmap bitmapDisplay = Bitmap.createBitmap( colorCameraIntrinsics.width, colorCameraIntrinsics.height, Bitmap.Config.ARGB_8888 );
    Mat colorMatDisplay;

    @Override
    public void onFrameAvailable(TangoImageBuffer imageBuffer, int cameraId) {
        Log.d(TAG, "onFrameAvailable: color frame available");
        if (colorFrameCounter < 3) { //only use every 3rd frame
            Log.d(TAG, "onFrameAvailable: skipping frame " + colorFrameCounter);
            colorFrameCounter++;
        } else {
            colorFrameCounter = 0;
            if (!stopCameraView.get()) { // Only view frame if camera view is not stopped

                // convert image buffer data to byte array
                imageBuffer.data.get(imageByteArray);

                // byte array to Mat object with YUV coding (NV21)
                yuvMat.put(0, 0, imageByteArray);

                // locking access to lastColorFrameMat
                synchronized (lockVar) {
                    Log.d(TAG, "onFrameAvailable: converting to bitmap");
                    // convert from YUV (NV21) Mat to RGBA Mat and place in lastColorFrameMat (global)
                    Imgproc.cvtColor(yuvMat, lastColorFrameMat, Imgproc.COLOR_YUV2RGBA_NV21, 4);
                    colorMatDisplay = lastColorFrameMat.clone();
                }

                if (templateContours != null) {
                    Imgproc.drawContours(colorMatDisplay, templateContours, templateContourMaxIdx, new Scalar(0, 255, 0, 255), 5);
                }

                // convert colorMatDisplay to bitmap, for display in imageview
                Utils.matToBitmap(colorMatDisplay, bitmapDisplay);

                Log.d(TAG, "onFrameAvailable: view lastColorFrameMat on phone display");

                // View colorImage in imageViewer on UI thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageViewer.setImageBitmap(bitmapDisplay);
                    }
                });
            }
        }

    }
});

Answer: There are two things potentially happened here:

the buffer for camera image went out of scope.

With current Tango's SDK, the callee of onFrameAvailable callback only have control to imageBuffer within the scope of the callback. That means if you reference imageBuffer in an AsynTask, you could potentially get a null buffer, and result in a crash. The way Tango solve it is to always deep copy out the data from the callback, and process it in another thread.

the process is blocking Tango's thread for too long.

Without the AsyncTask, what's likely happened is that the processing blocked Tango's thread for too long, and this is know to be bad for Tango as well.


reactjs map and css class toggle

Question:

    {this.props.data.map((res, index) => {
      return (

          {response.testData}
 this.showExtraLine(index)}><span className={`btn-green ${this.state.showExtraLine ? 'active' : ''}`}>
          { this.state.showExtraLine ?
            {res.abc[0].def}
           : '' }

      );
    })}

 showExtraLine(e){
    this.setState({
      showExtraLine: !this.state. showExtraLine,
    });
  }

Need to toggle the {res.abc[0].def} part on click of anchor - toggle works, but not sure how to handle toggling only the corresponding span - right now it is hiding all the rows..how to handle css toggle when using .map?
Answer: Right now you are maintaining the state for all of the mapped elements in your component, so they all reference the same value. You should instead create a component that will be used to render each of your mapped elements individually with their own state.
class Parent extends React.Component {
  render() {
    return (

        {this.props.data.map((res, index) => <Child key={index} {...res} />)}

    );
  }
}

class Child extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      showExtraLine: false
    };
    this.showExtraLine = this.showExtraLine.bind(this);
  }

  render() {
    return (

          {this.props.testData}

            <span className={`btn-green ${this.state.showExtraLine ? 'active' : ''}`}>

          { this.state.showExtraLine ? {this.props.abc[0].def} : '' }

    );
  }

  showExtraLine(e){
    this.setState({
      showExtraLine: !this.state.showExtraLine
    });
  }
}

Comment: Does not sole my problem, I need to use map here and also for 1 line I don't think I should be mKing it a separate child component
Comment: Map would still be used by the parent component. Creating a child component just cleans up your code and allows you to maintain a separate visible state for each element in your data array.
Answer: I think the problem is in your state variable, you are using a single state variable and printing the  on the basis of state of that variable.
Instead of that use an array in state showExtraLine = [],
in showExtraLine() function you are passing index, use that index to toggle only that element.
Try this it should work:
{this.props.data.map((res, index) => {
  return (

      {response.testData}
       this.showExtraLine(index)}><span className={`btn-green ${!this.state.showExtraLine[index] ? 'active' : ''}`}>
      { !this.state.showExtraLine[index] ?
         {res.abc[0].def}
      : '' }

  );
})}

showExtraLine(index){
    let showExtraLine = this.state.showExtraLine.slice(0);
    showExtraLine[index] = !showExtraLine[index];
    this.setState({
       showExtraLine: showExtraLine,
    });
 }

reactjs map and css class toggle


How to prevent or remove duplicate value(s) in a ValueListBox

Question: Our gwt app uses ValueListBox,
records.setValue(model);
records.setAcceptableValues(models);

Where model is a subset of models. The problem I'm having is that the ValueListBox contains duplicated value. How do I prevent or remove it?
Comment: Try using this. records.setAcceptableValues(new HashSet(models);  If it is a user defined object other than string etc, then you have to implement hashcode and equals.
Comment: @bgth put it as answer. Its correct. I have just done same thing.
Comment: There is just one difference between your answer and my answer. I have suggested to override this method in place of taking care every time when `setAcceptableValues()` is called.
Comment: Yes. that will also work. But by definition override is used for changing the way something behaves. Here, override will not change the way setAcceptableVales works or behaves. It will be used just for doing this particular reason(remove duplicates) which can be achieved without override.
Answer: Try using the below.
records.setAcceptableValues(new HashSet<String>(models);

If it is a user defined object other than string etc, then you have to implement hashcode and equals.
Answer: Override setAcceptableValues methods
@Override
public void setAcceptableValues(Collection<T> newValues) {
   super.setAcceptableValues(new HashSet<T>(newValues));
}

Sample code:
ValueListBox<Integer> semester = new ValueListBox<Integer>(new Renderer<Integer>() {
    public String render(Integer object) {
        String s = "";
        if (object != null) {
            s = object.toString();
        }
        return s;
    }

    public void render(Integer object, Appendable appendable) throws IOException {
        String s = render(object);
        appendable.append(s);
    }
}) {
    @Override
    public void setAcceptableValues(Collection<Integer> newValues) {
        super.setAcceptableValues(new HashSet<Integer>(newValues));
    }
};

semester.setAcceptableValues(Arrays.asList(1, 1, 3, 3, 2, 2, 3, 4, 5, 7, 8, 9, 1, 3, 2));
semester.setValue(2);

--EDIT--
As per your last comment try this one
class MyModel {
    private String id;
    private String name;

    public MyModel(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        return this.id.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof MyModel) {
            return this.id.equals(((MyModel) obj).id);
        }
        return false;
    }
}

ValueListBox<MyModel> semester = new ValueListBox<MyModel>(new Renderer<MyModel>() {
    public String render(MyModel object) {
        String s = "";
        if (object != null) {
            s = object.getName();
        }
        return s;
    }

    public void render(MyModel object, Appendable appendable) throws IOException {
        String s = render(object);
        appendable.append(s);
    }
}) {
    @Override
    public void setAcceptableValues(Collection<MyModel> newValues) {
        super.setAcceptableValues(new HashSet<MyModel>(newValues));
    }
};

semester.setAcceptableValues(Arrays.asList(new MyModel("1", "a"), new MyModel("1", "a"),
        new MyModel("2", "b"), new MyModel("3", "c")));
semester.setValue(new MyModel("1", "a"));

Comment: You have to override  `hashCode()` and `equals()` to implement your logic how the objects are unique from others.
Comment: Even with the override the ValueListBox is still showing up at least one duplicated value :-(
Comment: Sorry only one. How is it possible? What's the type of your model object?
Comment: Is it a POJO class? If yes then you have to override `hashCode()` and `equals()` as per `HashSet` rule.
Comment: I have updated my post. Please have a look at EDIT section. I have used a POJO as model object.
Answer: There is no method to prevent or remove duplicate options in ListBox or ValueListBox. You have to remove duplicate values before you pass them to your ValueListBox.
Comment: Actually there's no problem with the list values, there is no duplicate on it, actually when its rendered then there's the duplicate
Comment: This means you add them twice.
Comment: Yes, but my question was specific to ValueListBox problem with duplicating items.


Block changes do not save in admin/structure/block/ page

Question: I have a large number of blocks in a Drupal website. Now I can not save changes in region and order of blocks in admin/structure/block/ page.
There is no message at the top of the page, no Javascript error in console and no error in the error log of my cpanel.
I have increased max_input_vars in php.ini file to 5000 or upper and checked the changes in admin/reports/status/php/ to be sure about it but still block changes does not save.
How can I get out of this problem?
Answer: From my experience, this happens when you disable the Main page content block and save the changes. After doing this, clicking save will not do anything.
The simple fix is to enable the Main page content block, you should put it back under the Content region.
Comment: The main page content block is enable and in content region.
Comment: @shekoufeh try checking the Drupal error log `admin/reports/dblog`
Comment: there is nothing about it in error log of drupal!
Comment: Do you know **why** such disable may cause this? Maybe you're aware of some issue about it on D.O?
Comment: @Pierre.Vriens I learned this from experience/experimenting, so I do not know why, feel free to shed some light on this if you know something.
Comment: Aha, that's what you mean ... As per your "***This is known to happen***", I thought you knew about some issue about it somewhere. Maybe you should change that intro to something like "*I learned from experience/experimenting*"?
Answer: I had the same issue with Drupal 7. How to understand the issue? This happens when in a given region, you have used all allowed weight numbers from -55 to 55. Number 0 can be used for multiple blocks but the system will not behave the right way. Some people suggest you remove few blocks. That works, but what if you do not want to delete blocks?
In my case, I went to admin/structure/block then Show row weights. I manually started the numbering from -500 to 500 leaving free large slots between rows. After saving the page, you will notice the changes. Let me know if this solves your issue. Cheers.


Load a file entity by URI

Question: Is there a way to load a file by URI in Drupal 8?
In Drupal 7, it is possible using the following code.
$uri = 'public://file.xyz';

// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files); // If empty, $file will be false, otherwise will contain the required file

Taken from here https://www.drupal.org/forum/support/module-development-and-code-questions/2012-06-06/load-a-file-by-uri#comment-6493610
Answer: There is the loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface that allows to define required condition in searching the file entity by the given file URI:
/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;

Comment: To exactly match the code example in the original question, add `$file = reset($files);` again.

Load a file entity by URI


Term meaning "unintended overlaps between notes" in piano playing

Question: What is the proper or usual term that names the following problem in piano playing?
Problem:  The finger, after striking a note, does not release the key on time but overstays (typically by about 50 to 100 milliseconds).  As a result, the note sounds longer than it should and bleeds into the beginning portion of the next note.
The person in the video calls it "finger pedaling." But he is referring to it as a technique, something you do on purpose, for an effect:

I am talking about overlaps that happen unintentionally (because you are being sloppy), a problem.
(I am finding that my generic descriptions, e.g. "unintended overlaps," are no proper search terms and don't turn up anything useful.  Once I know the term, I may come back here and ask substantive questions, e.g. how to solve.)
Add later:  Just so I don't mislead, I should add that the unintended overlaps happen to me even when I am not being sloppy but on the contrary am trying my best not to have them, especially when going from finger 4 to 3.
Comment: I guess I'd call it *muddy*.
Answer: Overlap between notes is simply an extreme form of articulation - the legatissimo. For obvious reasons, this is possible only on the piano and related instruments, but it's a valid stylistic choice.
Doing it unintended, by sloppiness rather than on purpose, is an error, but I wouldn't expect this specific playing error to have a specific name, any more than unintended staccato or unintended portato does.
Answer: You've answered your own question. When it's unintentional, it's just called sloppy playing. There's no "official" term for it. I've heard it called "lazy fingers", "delayed release", "blurry" playing, and no doubt there are a whole raft of other terms people have come up with.
Comment: @poppycat It sounds like what you really want to know is how to fix the problem of not fully releasing a key after it's been played. Why don't you just ask that question?
Comment: That's bad news for me. I tried your terms, and "blurry" returns vision problem after piano practice, and "delayed" keys that get stuck. If you have any idea on how one may do searches and find helpful material I would appreciate hearing about it.
Comment: I will, and am formulating the question in my head. Thanks for the encouragement.
Answer: I don't know if what you are explaining is necessarily a problem as much as it may be a style.  I used to play organ in a church with a four second delay.  No matter how crisp I tried to play, the sound of the organ would, you could actually hear it, roll down the length of the building, hit the wall and tumble backward over itself.
Some pianists will play a fast scale but instead of keeping it crisp will pedal it.  I personally don't like it because as an organist we don't have sustain pedals but it is a style.  It could be that instead of thinking that your playing is sloppy, maybe your brain desires a more reverberant sound and instructs your fingers to make it so.
Comment: Thanks for your charitable thought. But I actually want to play crisp (at least the "conscious" part of me does). I even like recordings that don't reverberate, e.g. Budapest String Quartet, James Brown. But it was very kind of you to think I was actually pursuing a style.
Comment: Often it is not that we lack talent or need more practice or exercises but it is moving improperly which holds us back.  We either use the wrong muscles, are not using the correct ones or are combining them.  I would suggest contacting Edna Golandsky in NYC and find out if she has a teacher near you who can assess your playing and can suggest adjustments to free you up and minimize muscular co-contractions if they exist.
Answer: Musical terms describe a kind of execution and there is really no difference between "described" and "prescribed".  So you typically need to add a descriptor for the lack of consistency in execution.
You can add a qualifier to the intended articulation, most likely "leggiero" and call it "inconsistent leggiero" or use other attributes on "leggiero", like "unconvincing", "intermittent", "botched".
Another possibility is to intentionally use a non-formal term.  Instead of "legato" you can try "slurred" or "slurry".  This is reminiscent of the musical term of the notation element "slur" without suggesting its intentional implementation as "legato" phrasing.
"legato articulation" sounds deliberate, "slurred articulation" doesn't.


Sun Java keytool importing EV certificates into a single keystore

Question: At my current job we are using tomcat, customers have custom web portals setup on their own local machines. EV certs are new to me, they have 2 part intermediary and a primary certificate. For our product to work it appears I need to get all three parts installed under a single keystore entry. How can I roll all three parts into a single x.509 compliant file for import?
They syntax I am using is as follows:
/blah/system/j2sdk/bin/keytool -import -alias foo -keystore /zix/system/jdk1.5.0_06/jre/lib/security/cacerts -file certname.pem -trustcacerts
where foo = the keystore name and certname.pem is the main cert.
I have tried importing the intermediate certs under their own names into the keystore and I don't know if it's just the product I have to work with (not vanilla tomcat) or what but it doesn't see those. I have seen a working system and all three certs were under the single keystore alias. Anyone have any ideas?
Answer: It appears the way to do this is to put all the files in a single text file with a .pem extension you can then import them into a keystore under a single keystore name.


prove $a c^{-1} \equiv b d^{-1} \bmod m$

Question: if $a \equiv b \bmod m$ and $c \equiv d \bmod m$ and $gcd(c,m) = 1$ prove that $a c^{-1} \equiv b d^{-1} \bmod m$ .
Answer: If $\gcd(c,m)=1$, then there exists $c^{-1}$ such that $cc^{-1}=1\pmod{m}$. Since $c\equiv{d}\pmod{m}$, $\gcd(d,m)=1$ and $dc^{-1}=1\pmod{m}$, and it's clear that $c^{-1}=d^{-1}\pmod{m}$. Then, it's obvious that $ac^{-1}=bd^{-1}\pmod{m}$.


Comparing Kendall's Tau values

Question: I have a single ordinal outcome called RATING, and a series of continuous covariates (P1, P2, P3, etc). I have used Kendall's Tau statistic to assess the concordance/correlation between RATING and each covariate as per below.
#load Kendall package
library(Kendall)

#create example data
RATING<-sample(1:4,200,replace=TRUE)
P1<-RATING+rnorm(200,0,2.5)
P2<-RATING+rnorm(200,0,3)
P3<-RATING+rnorm(200,0,3.5)

#Calculate Kendall's Tau for each predictor
Kendall(RATING,P1)
Kendall(RATING,P2)
Kendall(RATING,P3)

The resulting Tau statistics will differ in size and significance obviously. My question though is whether there a way to determine which are significantly different from others? For example, can I use the results of these tests to say P1 is significantly more strongly correlated with RATING than P3, or that P3 is significantly less correlated with RATING than all other covariates?
I've found discussion of a method to compare Pearson's R values here How to compare the strength of two Pearson correlations? but I believe it assumes the compared R values are from independent samples, its not clear if it can be applied to Kendall's tau values, and its not clear whether its suitable for multiple comparisons.
Any suggestions greatly appreciated
Answer: Here's a rough and ready approach using bootstrapping, borrowing a method from Guillame Rousselet.
First I'll replicate your data, modifying P1 slightly such that it will have a strong relationship with the Rating just to illustrate. I'm using the the cor function from the default stats package with the method = "kendall" argument throughout.
set.seed(6000)
Rating <- sample(1:4, 200, replace=TRUE)
df <- data.frame( Rating,
                  P1 = Rating + rnorm(200, 0, .8),
                  P2 = Rating + rnorm(200, 0, 3.5),
                  P3 = Rating + rnorm(200, 0, 3))

#Check the 3 Kendall Tau values
sapply(2:4, function(x) cor(df[ , 1], df[ , x], method = "kendall"))
# [1] 0.6535829 0.1738252 0.2347800

So far so good.
Now we'll want to iteratively resample observations in the dataset, calculate the three overlapping Kendall's $\tau$ values, and take the differences between each pair ($\tau_i-\tau_j)$. Determining whether the bootstrapped distributions of these differences overlap zero provides your test.
library(boot)
library(broom)

#Create Bootstrap Function
compKendall <- function(data, indices){
  df <- data[indices, ] #Resample over rows

  #Calculate all 3 overlapping correlations
  ks <- sapply(2:4, function(x) cor(df[ , 1], df[ , x], method = "kendall"))

  #Arrange pairwise combinations of correlations
  kPairs <- combn(ks, 2)

  #Return the differences
  return( kPairs[1 , ] - kPairs[2 , ] )
}

#Run the bootstrap with 1000 resamples
kDiff <- boot(df, statistic = compKendall, R = 1000)

#Use broom to get a neat dataframe of differences w/ 95% CI's
broom::tidy(kDiff, conf.int = TRUE, conf.method = "perc")

##  A tibble: 3 x 5
#   statistic     bias std.error conf.low conf.high
#      <dbl>    <dbl>     <dbl>    <dbl>     <dbl>
# 1    0.480   0.00102    0.0533    0.378    0.591
# 2    0.419  -0.00308    0.0525    0.312    0.518
# 3   -0.0610 -0.00410    0.0694   -0.205    0.0720

The dataframe shows the estimated differences between Kendall's $\tau$ values, organised as $\tau$ number 1 - 2, 1 - 3, and 2 - 3.
As expected, the first correlation ($\tau_1 = .65$) appears larger than the other two - CI's for the differences exceed zero. However we couldn't conclude there is a significant difference between the second ($\tau_2 = .17$) and third ($\tau_3 = .23$) overlapping correlations.
Comment: That is a good question - multiplicity adjustments for CI's are hard to come by. Perhaps you could treat each difference estimate divided by its SE as the test statistic Z. You might save the broom::tidy dataframe as `results` and determine the p-value for each by `2 * pnorm( -abs(results$statistic / results$std.error) )`. From there you could apply a `p.adjust()` of your choice to the results. But I don't feel 100% confident recommending this without checking the assumptions of the bootstrap.
Comment: Thanks so much awhug. I will try this out. I don't see anything in the Rousselet link about adjustments for cases where there are many covariates (eg P1, P2, ... P27) and so multiple comparisons. Do you have any thoughts on the necessity of adjusting this method for that circumstance?
Comment: Missed that last comment when it came in, but thankyou, I will investigate

Comparing Kendall's Tau values


Show that a closed dense set E of R must be R

Question: This was a question on my exam and I'm not sure how I'm supposed to prove this. I had the following reasoning:
If we assume E' is not R, then there are points in R that are not in E'. If it is one point, then E' can be represented by the union of open sets, which already contradicts our assumption the E' is closed, but I will continue. Take a to be the point that isn't in E, then $E' = (-\infty,a) \cup (a,\infty)$, if we take the complement of this we get $\mathbb{R}-E = \{a\}$. This is obviously not an open set, therefore E is not closed. This contradicts our assumption that it is closed and dense, therefore E is R.
But this doesn't even use the denseness of E, and it seems really handwavy, so I assume there's a more rigorous way to do this but I don't know what it is.
Comment: Dense means that the closure of $E$ is $\mathbb R$. Closed means that the closure of $E$ is $E$. Thus…
Comment: What is the definition of a dense set?
Comment: We use the definition of dense that given a set E, $\forall x \in \mathbb{R}, \epsilon > 0, \exists y \in E, E \cap B(y;\epsilon) \ne \phi$.
Comment: Closed means the closure of E is E, thus a closed dense set must have that E is $\mathbb{R}$. It's that simple?
Answer: According to the definition that you are using, a set is dense in $\Bbb{R}$ iff each point of $\Bbb{R}$ is an adherent point of the set. If in addition you are using the definition that the closure of a set is the set of all adherent points of the set, then a set is dense in $\Bbb{R}$ iff its closure equals $\Bbb{R}$.
If $E$ is closed in $\Bbb{R}$, then by definition (if you are using) or by proof (if you are using some definition else) we have $E = \overline{E}$; we have $\overline{E} = \Bbb{R}$ by assumption, so $E = \Bbb{R}$.


$\Gamma(U,\cdot)$ is a left-exact functor $\mathfrak{Ab}(X)\to\mathfrak{Ab}$

Question: Exercise 1.8 in Hartshorne, Chapter II:

Let $0\to\mathcal{F}'\xrightarrow{\phi}\mathcal{F}\xrightarrow{\psi}\mathcal{F}''$ be a left-exact sequence. Then for any open set $U\subseteq X$, the sequence $0\to\Gamma(U,\mathcal{F}')\to\Gamma(U,\mathcal{F})\to\Gamma(U,\mathcal{F}'')$ is left-exact.

Here is the way I tried to prove this: Let $U\subseteq X$ be open. Since $\phi$ is injective, $\phi_U:\Gamma(U,\mathcal{F}')\to\Gamma(U,\mathcal{F})$ is injective. So it remains to show that $\ker(\psi_U)=\operatorname{im}(\phi_U)$. Then I looked at the diagram
$$\begin{array}{cccccc}
0 & \rightarrow & \Gamma(U,\mathcal{F}') & \xrightarrow{\phi_U} & \Gamma(U,\mathcal{F}) & \xrightarrow{\psi_U} & \Gamma(U,\mathcal{F}'')\\
& & \downarrow & & \downarrow & & \downarrow\\
0 & \rightarrow & \mathcal{F}'_p & \xrightarrow{\phi_p} & \mathcal{F}_p & \xrightarrow{\psi_p} & \mathcal{F}^{''}_p
\end{array}$$
which commutes for every $p\in U$ and with bottom row exact. Now if $s\in\Gamma (U,\mathcal{F}')$, we have $\psi_U(\phi_U(s))_p=\psi_p(\phi_p(s_p))=0$ for every $p\in U$, hence $\psi_U(\phi_U(s))=0$. The inclusion left to show is $\ker(\psi_U)\subseteq\operatorname{im}(\phi_U)$.
For this, take $t\in\ker(\psi_U)$. $\psi_U(t)=0$ implies $\psi_p(t_p)=\psi_U(t)_p=0$ for every $p$. Since $\ker(\psi_p)=\operatorname{im}(\phi_p)$, there exist $s'_p\in\mathcal{F}'_p$ such that $t_p=\phi_p(s'_p)$, hence also a section $s\in\Gamma(U,\mathcal{F}')$ with $s_p=s'_p$ (bad notation there, I didn't know how to name those germs). We have $\phi_U(s)_p=\phi_p(s_p)=t_p$ for every $p\in U$, so $\phi_U(s)=t\in\operatorname{im}(\phi_U)$.
Now my question is: is this proof correct? I usually look up some solutions in the internet after doing such an exercise, and for this one I found two solutions which both took a different approach from mine, which made me a bit insecure about my 'solution', since I took the 'direct approach' from my point of view.
Thank you in advance!
Answer: In my opinion, you need to reason why the $s'_P$ do glue to some $s'\in\mathcal{F}'(U)$. However, this is not that tough. We pick neighborhoods $V_P\subseteq U$ for each point $P$ such that $s'_P=(f_P,V_P)$ with $f_P\in\mathcal{F}'(V_P)$. For $W:=V_P\cap V_Q\ne 0$, we have $\phi_W(f_P|_W)=t|_W=\phi_W(f_Q|_W)$ and we know that $\phi_W$ is injective.
PS: That little nitpicking aside, I don't see anything wrong with the proof.
Comment: Hello @rattle! I just suppressed that little step so my question wouldn't be that lenghty, since it's an argument that was used in the exercises before already ;) Thanks for proof-reading!


Do All Drupal themes support subtheming?

Question: I heard that only some themes can have a subtheme.
Is this true?
Comment: I would read https://drupal.org/node/225125 for *tons* of information on subthemes
Comment: And, you may want to consider renaming or rephrasing this question because the answer to the title is YES but the answer to the content is NO.
Comment: I would prefer changing title, as my answer starts with NO ;)
Answer: No, of course it isn't true. All themes can be subthemed. Subtheming is a part of Drupal's core and themes cannot simply turn it down. You can always create a theme, name it's parent theme and override some CSS.
Fun starts when you want to override things from template.php, or if parent theme provides advanced configuration - not all themes are built in a way that makes subtheming easy. But even if it's not easy, it's not really blocked.
Comment: @Drupalizeme if theme author discourages subtheming or publish it with a licence that says you can't subtheme, then you probably shouldn't try as it may be a wasted effort (or legal problems). But it's still possible.
Comment: I was searching and i found some comments on templates that saying if the can have a subtheme and was answer as you can't make a subtheme with this template. This wasn't clear for me and i need it some help clear that out. Thank you again.


Exibir dados numa tela de pesquisa C# ASP.NET

Question: Trazer informações para a View()
Pessoal, boa tarde.
Estou com a seguinte dificuldade: Tenho uma tela de pesquisa de um helpDesk e preciso exibir os dados do banco, que é uma lista de chamados, porém nessa mesma tela eu tenho alguns inputs que serão usados para pesquisar no banco e retornar essa mesma listagem, dentre eles alguns <selects/> como, Categoria, Status e NivelPrioridade que na minha ideia eu desejo preencher com dados do próprio banco, já que cada um é uma tabela. Consegui trazer os dados para os inputs através de uma ViewModel, porém não consigo listar os chamados a partir da ViewModel, nem criar uma ViewBag com a lista retornada do banco para fazer essa listagem e aparentemente nem trazer mais de um dado como parametro pela View().
Então minha duvida seria:

Como passar mais de um parametro pra view ou
Como listar os meus chamados e ao mesmo tempo preencher os selects com a própria viewModel

Eu não sei se estou sendo claro o suficiente, peço desculpas desde já, está confuso pra mim também.
Segue o código para exemplificar:
//Codigo referente a minha View
@model AppHelpDesk.Models.ViewModels.ChamadoViewModel

@{
   }

        <input asp-for="Chamado.Id" value="" placeholder="Id do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Titulo

        <input asp-for="Chamado.Titulo" value="" placeholder="Titulo do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Data Inicial

        <input asp-for="Chamado.DataInicial" class="form-control" type="date" value="" id="example-date-input">

            Data Final

        <input asp-for="Chamado.DataFinal" class="form-control" type="date" value="" id="example-date-input">

            Categoria

        <select asp-for="Chamado.CategoriaId"
                asp-items="@(new SelectList(Model.Categoria, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Status

        <select asp-for="Chamado.StatusId"
                 asp-items="@(new SelectList(Model.Status, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Prioridade

        <select asp-for="Chamado.NivelPrioridadeId"
                asp-items="@(new SelectList(Model.NivelPrioridade, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

        <button type="submit" class="btn btn-primary">Pesquisar</button>

        Chamados pendentes

   @*

                    @Html.DisplayNameFor(model => model.Titulo)

                    @Html.DisplayNameFor(model => model.Descricao)

                    @Html.DisplayNameFor(model => model.DataInicial)

                    @Html.DisplayNameFor(model => model.DataFinal)

            @foreach (var i in Model)
            {
                if (i.StatusId == 1)
                {

                        @Html.DisplayFor(modelItem => i.Titulo)
                        @Html.DisplayFor(modelItem => i.Descricao)
                        @Html.DisplayFor(modelItem => i.DataInicial)
                        @Html.DisplayFor(modelItem => i.DataFinal)

                }

            }

*@

...
// Codigo da minha controller
namespace AppHelpDesk.Controllers
{
    public class HomeController : Controller
    {
        private readonly DashboardService _dashboardService;

        public HomeController (DashboardService dashboardService)
        {
            this._dashboardService = dashboardService;
        }

        // GET: Dashboard
        public IActionResult Index()
        {
            var list = _dashboardService.FindAll();
            ViewBag.pedingCount = list.Where(x => x.StatusId == 1).Count();
            ViewBag.SolvedCount = list.Where(x => x.StatusId == 2).Count();
            ViewBag.priorityCount = list.Where(x => x.NivelPrioridadeId == 3).Count();
            return View();
        }

        public IActionResult Create(Chamado chamado)
        {
            _dashboardService.Insert(chamado);
            return RedirectToAction(nameof(Index));
        }

        public IActionResult Pending(Chamado chamado)
        {
            var status = _dashboardService.FindAllStatus();
            var prioridade = _dashboardService.FindAllPrioridade();
            var categoria = _dashboardService.FindAllCategoria();
            var setor = _dashboardService.FindAllSetor();

            var viewModel = new ChamadoViewModel
            {
                Categoria = categoria,
                Chamado = chamado,
                NivelPrioridade = prioridade,
                Setor = setor,
                Status = status
            };

            ViewBag.listaChamados = _dashboardService.FindAll();
            return View(viewModel);
        }

        public IActionResult Solved()
        {
            var list = _dashboardService.FindAll();
            return View(list);
        }

        public IActionResult Priority()
        {
            var list = _dashboardService.FindAll();
            return View(list);
        }
    }
}

// Codigo da minha ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppHelpDesk.Models.ViewModels
{
    public class ChamadoViewModel
    {
        public Chamado Chamado { get; set; }
        public ICollection<Categoria> Categoria { get; set; }
        public ICollection<Status> Status { get; set; }
        public ICollection<Setor> Setor { get; set; }
        public ICollection<NivelPrioridade> NivelPrioridade { get; set; }
    }
}

Answer: Como passar mais de um parâmetro pra View
R: Não é possível passar mais de 1 parâmetro para o método View é justamente por isso que utilizamos as ViewModels para Isso.
Como listar os meus chamados e ao mesmo tempo preencher os Selects com a própria ViewModel
R: Basicamente sua ViewModel vai possuir Um pouco mais de Responsabilidade que ela possui hoje. Pelo oque eu entendi você quer fazer um filtro e listar os registro filtrados, basicamente isso vai ficar assim.
Controller
public IActionResult Pending(ChamadoViewModel viewModel)
{
    return View(viewModel.Get());
}

View Model
public class ChamadoViewModel
{
    #region Dependency Injection

    private readonly IRepository _repository;

    public ChamadoViewModel(IRepository repository)
    {
        _repository = repository;
    }

    #endregion

    #region Handlers

    public ChamadoViewModel Get()
    {
        var query = _repository.FindAllChamados()
                                .AsQueryable();

        Categorias = _repository.FindAllCategorias();
        Status = _repository.FindAllStatus();
        Setores = _repository.FindAllSetores();
        NivelPrioridades = _repository.FindAllPrioridades();

        if (Id != null)
            query = query.Where(x => x.Id == Id);
        if (string.IsNullOrEmpty(Titulo))
            query = query.Where(x => x.Titulo == Titulo);
        if (DataInicial != null && DataFinal != null)
            query = query.Where(x => x.DataInicial >= DataInicial && x.DataFinal <= DataFinal);
        if (CategoriaId != null)
            query = query.Where(x => x.CategoriaId == CategoriaId);
        if (StatusId != null)
            query = query.Where(x => x.StatusId == StatusId);
        if (SetorId != null)
            query = query.Where(x => x.SetorId == SetorId);
        if (NivelPrioridadeId != null)
            query = query.Where(x => x.NivelPrioridadeId == NivelPrioridadeId);

        Chamados = query.ToList();
        return this;
    }

    #endregion

    #region Data

    public Chamado Chamado { get; set; }
    public ICollection<Chamado> Chamados { get; set; }
    public ICollection<Categoria> Categorias { get; set; }
    public ICollection<Status> Status { get; set; }
    public ICollection<Setor> Setores { get; set; }
    public ICollection<NivelPrioridade> NivelPrioridades { get; set; }

    #endregion

    #region Helper

    // Essa é a região de Filtro é nessas propriedades que serão feito os Binds ou Asp-For

    public int? Id { get; set; }
    public int? CategoriaId { get; set; }
    public int? StatusId { get; set; }
    public int? SetorId { get; set; }
    public int? NivelPrioridadeId { get; set; }
    public string Titulo { get; set; }
    public DateTime? DataInicial { get; set; }
    public DateTime? DataFinal { get; set; }

    #endregion
}

View
@model AspNetCore.Controllers.ChamadoViewModel

@{
}

        <input asp-for="Id" value="" placeholder="Id do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Titulo

        <input asp-for="Titulo" value="" placeholder="Titulo do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Data Inicial

        <input asp-for="DataInicial" class="form-control" type="date" value="" id="example-date-input">

            Data Final

        <input asp-for="DataFinal" class="form-control" type="date" value="" id="example-date-input">

            Categoria

        <select asp-for="CategoriaId"
                asp-items="@(new SelectList(Model.Categorias, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Status

        <select asp-for="StatusId"
                asp-items="@(new SelectList(Model.Status, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Prioridade

        <select asp-for="NivelPrioridadeId"
                asp-items="@(new SelectList(Model.NivelPrioridades, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

        <button type="submit" class="btn btn-primary">Pesquisar</button>

        Chamados pendentes

                        @Html.DisplayNameFor(model => model.Chamado.Titulo)

                        @Html.DisplayNameFor(model => model.Chamado.Descricao)

                        @Html.DisplayNameFor(model => model.Chamado.DataInicial)

                        @Html.DisplayNameFor(model => model.Chamado.DataFinal)

                @foreach (var i in Model.Chamados)
                {
                    if (Model.StatusId == 1)
                    {

                            @Html.DisplayFor(modelItem => i.Titulo)
                            @Html.DisplayFor(modelItem => i.Descricao)
                            @Html.DisplayFor(modelItem => i.DataInicial)
                            @Html.DisplayFor(modelItem => i.DataFinal)

                    }
                }

Espero que isso esclareça todas as suas duvidas, e se ficar alguma em aberto fico a disposição para tentar esclarecê-la.


Como listar os telefones de todos os contatos?

Question: Estou querendo saber: Como listar todos os contatos(numero do telefone e nome do contado) do celular?
Comment: Acho que este artigo pode te ajudar http://www.frameworksystem.com/blog/mobile-lendo-lista-de-contatos-do-android/
Comment: @DaniloOliveira obrigado, se você quiser postar como resposta para ganhar pontuação fique a vontade.
Answer: Espero que este artigo tenha lhe ajudado @PedroRangel, boa sote com o desenvolvimento :)
http://www.frameworksystem.com/blog/mobile-lendo-lista-de-contatos-do-android/


Node.JS/MongoDB I can't access an object value

Question: I need some help with my NodeJs project.
I'm trying to check the seller's name and then get it's internal 'support' to set the newOrder.support as the seller.support.
For some reason, it is not working and I have no idea why.
The console.log(support) inside of the findOne() it is showing the correct value, but the console.log(support) that I have just before my newOrder = new Order({}) is showing that the value/datatype is 'undefined' so my database is storing data without the support value.
Could you guys help me out with it?
Thank you in advance.
    let support;
    User.findOne({
        fullName: seller
    }, function (err, user) {
        support = user.support;
        console.log(support);
    })

Comment: You didn't paste the whole code snippet, but it looks like you just need to wait for the promise returned from `findOne` before continuing.
Answer: ⚠ You can't set value support inside the Promise and than access them in outside("From your code").
 So, if you want to access your value where you're using findOne, try to use async/await
If you're using in MongoDB, you can try this code below.
 Option 1: Inside mongoDB connection
From mays, it's working with this code below: Only add async/await.
MongoClient.connect('mongodb://localhost:27017', async (error, client) => {
  if(error) throw new Error(error);

  const db = client.db('blog_dev');
  const collection = db.collection('users');

  // start from here your async await
  let support = await collection.findOne({ fullName: 'Seller'});

  // you can get support now
  console.log(support);
})

 Option 2: From your code
An example your code inside yourFunction(), then you can use code below:
async function yourFunction() {
  const support = await User.findOne({ fullName: 'seller'});
  console.log(support);
}

I hope it's can help you.
Comment: This was 3 years ago haha but I never came back to check the answer! But that was definitely the right answer! Thanks Titus!
Comment: Thank you for come back to see this answer. It's mean after 3 years, you still alive. Hahaha, just kidding


How to include column names along with field in oracle table

Question: I am trying to insert  the column header and corresponding field into another table .
Table1 :

col1    col2   col3   col4
1       2       3      4

output should look like this :
COL_A   COL_B   COL_C     COL_D    COL_E     COL_F      COL_G    COL_H

col1    1       col2       2       col3       3         col4     4

I tried to apply unpivot , but unpivot gives me the column names vertically not horizontally .
Please help !!
Comment: select 'col1 ' || col1, ...etc
Comment: Hi!!. I can't hardcode the column names as i dont know what the column names would be
Comment: Also want to have column header as a separate field/column Not just appending the column name with record
Answer: UNPIVOT and then PIVOT
SQL Fiddle
SELECT *
FROM (
    SELECT *
    FROM Table1
    UNPIVOT(val FOR col IN (
                COL1
                ,COL2
                ,COL3
                ,COL4
                ))
    )
PIVOT(MAX(COl || ' ' || VAL) FOR COL IN (
             'COL1' as VAL1
            ,'COL2' as VAL2
            ,'COL3' as VAL3
            ,'COL4' as VAL4
            ))

Results:
|   VAL1 |   VAL2 |   VAL3 |   VAL4 |
|--------|--------|--------|--------|
| COL1 1 | COL2 2 | COL3 3 | COL4 4 |

Comment: ,thanks for the answer ..is it possible to do something like this col1| 1| col2 |  2  |  col3  |  3  |  col4  |  4
Comment: @joe : That was not your original question. Editing a question after someone has answered is considered rude. Remove the edit and  accept this answer or ask another question.
Comment: I realised the output was perceived in a different way ,yes it was my mistake ,let me ask a new question ,I am marking your answer as useful


Conditional Fields module with Google Maps

Question: I'm trying to initially hide a geofield created with Geofield module using Conditional Fields that uses the Geolocation Field Google Maps Input Widget.
If I click on one of my conditional fields to show the Google Map Input Widget, it shows the Google Map Input with a grey background.  If you resize the browser, the map tiles show again.
Does anyone know of a way to hook into the javascript somehow to reinitialize the Google Map when it is shown?
Answer: I added a possible solution at https://www.drupal.org/node/1277888#comment-11680473.  Hope that helps someone.


Limited Node References

Question: I am building a site for a client where each page has 3 other pages associated with it.
I know how to create node references but I would like to find a way to limit the user to creating just 3 node references per page.
So each page only allows the creation of 3 references and whrn all of them are created the "add reference" link is removed ( until perhaps one or more of the references is deleted ).
Can anyone suggest a potential solution?
Thanks
Answer: In node reference field settings page (content type -> manage fields -> name of field) in "global settings area" set "number of values" to 3.
Thats it.
Hope this helps.
Comment: Thank you! It didn't even occur to me it could be that simple.
Comment: Simple solution is usually the best one. :)
Comment: Just realized the issue which prompted my original post (which I had forgotten :-). Node References offer the 'Global Settings' area but the 'number of values' dropdown list is not included ???
Comment: You'll find it under Home » Administration » Structure » Content types » [Your Content Type Name] » Manage fields

Limited Node References


Updating value into database

Question: I have problem in updating the value into my database. The problem here is that the when i am updating the data for all rows, the data from last row will be updated into the first row. Other rows will not be updated including the last row.
Below is my code for updating...
<code>$sql = "SELECT * FROM product where username = '$username'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$rows = mysqli_fetch_array($result);
$id = $rows['pro_id'];
$boxid = $rows['box_id'];
$name = $_POST['pro_name'];
$quan = $_POST['pro_quan'];
$sold = $_POST['pro_sold'];
for ($i = 0; $i < count($_POST['pro_name']); $i++)
{
    $sql = "UPDATE product
            SET pro_name = '" . $name[$i] . "',
            pro_quan = " . $quan[$i] . ",
            pro_sold = " . $sold[$i] . "
            WHERE pro_id = " . $id . "
            AND box_id = '" . $boxid . "' ";

    $results=mysqli_query($con, $sql);
}
</code>
So, i have no ideas what have gone wrong. Thanks for helping
Comment: means that if i want to update all the rows in the database using the query, the data in the last rows of the table will be updated to the first row. Which means the first row od data will be replace by the updated data of the last row
Comment: As per your requirement, I got this : "When you are updating the last record data is getting updated into the first record in the DB. Is this what you wanted to say? Is this your problem?" Clarify so that one can provide solution for the same. Your question is not so clear.
Comment: Yes, this is the problem i am facing. And the others rows data are not updated too
Comment: Previously, this code worked, but after i edited something and change it back, it doesn't work anymore.
Answer: You need to place the result in a loop.
Something like that:
<code>    $sql = "SELECT * FROM product where username = '$username'";
    $result = mysqli_query($con, $sql) or die(mysqli_error($con));

    while ($rows = mysqli_fetch_array($result))
    {
        $id = $rows['pro_id'];
        $boxid = $rows['box_id'];
        $name = $_POST['pro_name'];
        $quan = $_POST['pro_quan'];
        $sold = $_POST['pro_sold'];
        for ($i = 0; $i < count($_POST['pro_name']); $i++)
        {
            $sql = "UPDATE product
                SET pro_name = '" . $name[$i] . "',
                pro_quan = " . $quan[$i] . ",
                pro_sold = " . $sold[$i] . "
                WHERE pro_id = " . $id . "
                AND box_id = '" . $boxid . "' ";

            $results = mysqli_query($con, $sql);
        }
    }
</code>
Comment: my result is located in the loop
Comment: you need to fetch rows in while loop, look at my code.

Updating value into database


sqlite python - create new table by multiplying values from existing tables

Question:
I need to create a new table 'nutrition_consumed'
I want to create this table from existing tables 'nutritional_values' and 'food_consumption'
Where the new table 'nutrition_consumed' has the same number of rows as the table 'food_consumption'
And the rows of 'nutrition_consumed' are generated by multiplying the consumed 'amount' value by values for calories, total fat and protein in the 'nutritional_values' table.
import  sqlite3
conn = sqlite3.connect('food.db')

c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS nutritional_values
                (item, calories, total fat, protein)''')

items = [       ('Broccoli Chinese',    22,     0.7,    1.1),
                ('chia seeds',          490,    30.8,   15.6),
                ('blueberries',         57,     0.3,    0.7),]

c.executemany('INSERT INTO nutritional_values VALUES (?,?,?,?)',items)

c.execute('''CREATE TABLE IF NOT EXISTS food_consumption
                (date, item, amount)''')

consumed = [    ('24/8/2019', 'Broccoli Chinese',    1.5),
                ('24/8/2019', 'chia seeds',          0.35),
                ('24/8/2019', 'blueberries',         0.4),
                ('25/8/2019', 'blueberries',         0.8),]

c.executemany('INSERT INTO food_consumption VALUES (?,?,?)',consumed)

conn.commit()

conn.close()

To create a new table
c.execute('''CREATE TABLE IF NOT EXISTS nutrition_consumed
            (date, item, calories, total fat, protein)''')

which would look like
(u'24/8/2019', u'Broccoli Chinese', 33, 10.5, 1.65)
(u'24/8/2019',u'blueberries', 22.8, 1.3, 0.28)
(u'24/8/2019',u'chia seeds', 171.5, 10.75, 5.4)
(u'25/8/2019',u'blueberries', 45.6, 2.4, 0.56)

Is the some sort of SQLite hack to do this?
as a start ive tried
c.execute('''CREATE TABLE IF NOT EXISTS nutrition_consumed
                (date, item, calories, total fat, protein)''')

for row in c.execute('SELECT * FROM food_consumption'):
        item_nutritional_values = c.execute('SELECT calories, total fat, protein FROM nutritional_values WHERE item=?', row[1])
        print(item_nutritional_values)

this brings up the error
item_nutritional_values = c.execute('SELECT calories, total fat, protein FROM nutritional_values WHERE item=?', row[1])
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 16 supplied.

Answer: you need to supply you row as a tuple:
item_nutritional_values = c.execute('SELECT calories, total fat, protein FROM nutritional_values WHERE item=?', (row[1],))


Moving Laravel Core Files to private_html Directory

Question: As a security precaution, my boss has requested I move my Laravel 7 app outside the public_html folder and into private_html.
So my directory structure looks like this:
public_html/public/

private_html/ <-- All the rest of the Laravel core files, app, config, routes, .env, etc.

Now, as expected since I moved the files, I'm getting an HTTP ERROR 500 when I visited the the website.
How do I tell Laravel where my public folder is so can get back to serving my web pages? Which configuration files do I need to edit?
Thanks for any help.
Edit 1: After trying Youssef's suggestion, everything worked great except when I run
php artisan storage:link

I get:

Edit 2:
I was able to fix "php artisan storage:link" by opening config/filesystems.php and changing:
'links' => [
    public_path('storage') => storage_path('app/public'),
],

To:
'links' => [
    '/new/directory/public_html/public/storage' => storage_path('app/public'),
],

Then, when I type:
php artisan storage:link

A new symlink is created.
Comment: in public/index.php  change path of required files to load them from your private_html directory
Comment: Can you show an example please?
Answer: In public/index.php change path of this two files to current path of them.
first line path of autoload.php
__DIR__.'/../vendor/autoload.php';

to
require __DIR__.'/../../private_html/vendor/autoload.php';

second line path of app.php
$app = require_once __DIR__.'/../bootstrap/app.php';

to
$app = require_once __DIR__.'/../../private_html/bootstrap/app.php';

and put this in the \App\Providers\AppServiceProvider register() method to set path of public directory.
**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    // ...

    $this->app->bind('path.public', function() {
        return base_path().'/../public_html/public';
    });
}

finally reassign path of storage directory if you need access to stored files directly, using command :
php artisan storage:link

you can also move all files from public_html/public to public_html and adjust paths I mentioned above