text:
Q: ¿Cómo evitar la carga de parámetros de un método a otro? Mi clase:
    class vista{

    private $_rutaCss = URL . 'public/css/';
    private $_rutaJs = URL . 'public/js/';
    private $_rutaImg = URL . 'public/img/';
    private $_rutaIcon = URL . 'public/img/favicon/';
    private $_rutaConf = DIR . 'protected/include/';
    private $_link;
    private $_archivo;
    private static $instancia;

    public function setCss(array $filecss) {
        foreach ($filecss as $css) {
            $this->_archivo = $this->_rutaCss . $css . ".css";
            if (@file_get_contents($this->_archivo, FILE_USE_INCLUDE_PATH)) {
                $this->_link .= '<link rel="stylesheet" href="' . $this->_archivo . '" />';
            } else {
                echo "Archivo Css " . $css . ".css no encontrado
";
                echo '_rutaCss . $css . '.css">' . $css . '
';
            }
        }
        return $this->_link;
    }

    public function setJs(array $filejs) {

        foreach ($filejs as $js) {
            $this->_archivo = $this->_rutaJs . $js . ".js";
            if (@file_get_contents($this->_archivo, FILE_USE_INCLUDE_PATH)) {
                $this->_link .= '';
            } else {
                echo "Archivo Js " . $js . ".js no encontrado
";
                echo '_rutaJs . $js . '.js">' . $js . '
';
            }
        }
        return $this->_link;
    }
 public function header($titulo = FALSE) {
        $cabecera = '';
        $titulo = isset($titulo) ? $titulo : 'Sin titulo';
        $cabecera .= "<title>" . $titulo . "</title>";
        $cabecera .= $this->setCss(['bootstrap.min', 'font-awesome.min']);
        return $cabecera;
    }

    public function footer(array $adicional = []) {
        $pie = '';
        $pie .= "
 © " . date("Y") . " - " . ((int) date("Y") + 1) . "
";
        $pie .= $this->setJs(['jquery-3.1.1.min', 'bootstrap.min']);
        return $pie;
    }

}

Así incluyo el archivo con la clase:
<?php
require_once './protected/include/config.php';
require_once './protected/include/vistaClass.php';
$vista = new vista();
?>

<!DOCTYPE html>

    <?php

    echo $vista->header('prueba');

    ?>

    <?php
    echo $vista->footer();
    ?>

Si los métodos se incluyen una sola vez, ¿por qué en el html se muestra así?:
     <!DOCTYPE html>

                <meta charset="UTF-8">

                <title>prueba</title>
    <link rel="stylesheet" href="http://localhost/pagina/public/css/bootstrap.min.css" />
    <link rel="stylesheet" href="http://localhost/pagina/public/css/font-awesome.min.css" />

 © 2016 - 2017

<link rel="stylesheet" href="http://localhost/pagina/public/css/bootstrap.min.css" />
        <link rel="stylesheet" href="http://localhost/pagina/public/css/font-awesome.min.css" />

A: $this->_link es una variable que tiene un scope dentro de toda tu clase y tu estás agregando datos a ella, debes limpiarla antes de volver a usarla para otra cosa si no quieres que tenga los datos anteriores:
public function setJs(array $filejs) {
    $this->_link = ''; //limpiamos la variable antes de usarla en este llamado...
    foreach ($filejs as $js) {
        $this->_archivo = $this->_rutaJs . $js . ".js";
        if (@file_get_contents($this->_archivo, FILE_USE_INCLUDE_PATH)) {
            $this->_link .= '';
        } else {
            echo "Archivo Js " . $js . ".js no encontrado
". // no es necesario un doble echo
             '_rutaJs . $js . '.js">' . $js . '
';
        }
    }
    return $this->_link;
}

Espero te ayude.


text:
Q: Noun Project CSS wrapper? I can't find the link anywhere, and I searched all over Hacker News (where I recall seeing the project), with no luck.
Instead of having to download the images from The Noun Project and such, you just included a css file and specified the name of the noun as a class under the  tag, or something.  Is this out there?!

A: You might be thinking of the Font Awesome, the pictographic font with 150 icons, that can be used with twitter bootstrap.
With Fort Awesome, you link to FontAwesome in a CSS tag. Then you add the class of the icon you want to an HTML element.
In my jsFiddle example, I have a camera and play circle beside some text.
Nick

A: Maybe you mean: http://nounpack.com ?
They have a sprite with many icons taken from the noun project and then you can include them as icons with css.

A: Agree with @Nick Silva that Font Awesome is undoubtedly the best place to start for effortless 'noun project-esque' css.
That said, to answer your question, to use Noun Project icons directly you would need to wrap your own. The best way to do this (IMHO) is to use Font Custom
Font Custom is a command line tool used to generate custom icon webfonts (CSS) from SVGs (Noun Project icons)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterate over json Array using Power shell This is what I have tried so far:
$Path="C:\Users\Desktop\test.json"
$json=(Get-Content $Path | ConvertFrom-Json).parameters.FileArray
//FileArray is array name in json file
$demo=$json.GetType().FullName //System.Object[]

foreach($file in Get-ChildItem "D:\A\DF\ls\" -Include $json|ForEach Object{$_} -Recurse){

Write-Output $file.BaseName
Write-Output $file.FullName

Set-AzureRmDataFactoryV2LinkedService -DataFactoryName "adfg1" - ResourceGroupName "bgc" -Name $file.BaseName -DefinitionFile $file.FullName -Force
}

Json I am using test.json:
    {
    "parameters":
    {
    "FileArray": [
    "ABC.json",
    "DEF.json"]
    }
    }
Exception I am getting is:
    ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert
    the "-Recurse" value of type "System.String" to
    type "System.Management.Automation.ScriptBlock".
What I am expecting(Names of files):
ABC.json
DEF.json
Any help how it can be handled.
How I can iterate over array values from json.
P.S: I am beginner in powershell

A: foreach($file in (Get-ChildItem "D:\A\DF\ls\" -Include $json -Recurse)) {

$file.BaseName
$file.FullName

}

I don't see why you would need ForEach Object{$_} , the -include accepts an array
Example code:
$jsonfile = '{"parameters":
             { "FileArray": [ "ABC.json", "DEF.json"] } }' | ConvertFrom-Json
$json = $jsonfile.parameters.FileArray

foreach($file in (Get-ChildItem "c:\temp" -Include $json -Recurse)) {
    $file.BaseName
    $file.FullName
}

Example output:
ABC
C:\temp\example-folder\ABC.json
DEF
C:\temp\example-folder\DEF.json


text:
Q: Feathers Js Restrict Access To Page on Server Side I'm using feathers.js and am trying to restrict access to the payment-info.html page to users that are logged in.
const app = feathers();

app.configure(configuration(path.join(__dirname, '..')));

app.use(compress())
  .options('*', cors())
  .use(cors())
  .use(favicon( path.join(app.get('public'), 'favicon.ico') ))

  .use('/payment-info.html', function(req,res,next){
  if(req.isAuthenticated()){
    next();
  } else {
    // 401 Not Authorized
    next(new Error(401));
  }
  })

  .use('/', serveStatic( app.get('public') ))
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(hooks())
  .configure(rest())
  .configure(socketio())
  .configure(services)
  .configure(middleware);

module.exports = app;

However, req.isAuthenticated() returns false, even if the user is logged in. Is there a way to restrict access to a page in the public directory to only users that are logged in?

A: To do restriction in a page-load scenario, you'll need to first make sure that the token is in a cookie.  Check out the feathers-authentication documentation for how to enable cookies.  But it's super important that you are careful to not expose yourself to CSRF attacks through the cookie.
With the current version of the feathers-authentication plugin, you'll have to set this up manually.  You'll need to read the token out of the cookie for the rendering middleware to use:

const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use('/payment-info.html', function(req, res, next) {
  let token = req.cookies['feathers-jwt'];
  if (token) {
    // Get the JWT secret to verify the token.
    let secret = app.get('auth').token.secret;
    jwt.verify(token, secret, function(err, decoded) {
      if (err) {
        return res.status(401).send('You are not authorized to view that page.');
      }
      return next();
    });
  } else {
    return res.status(401).send('You are not authorized to view that page.');
  }
});

It's important that you never allow any services to directly use the token from the cookie.  It's fine for the rendering middleware to pull the token and use it to make service requests as though it is just another client, but you would never want to pull it from the cookie and colocate it on the req.feathers object for authorization inside of a service.  That's how you open your API up to CSRF attacks.
Also, if you're enabling CORS at all, you'll more than likely want to make sure that CORS are disabled for the rendering middleware.  Only enable CORS just before your Feathers services.
Another drawback of feathers-authentication@0.7.x is that the cookie expiration is not matched up with the token's expiration. You'll need to manually set the cookie's maxAge expiration to match how long you want your tokens to be valid, as explained in the docs.
feathers-authentication@1.x.x (which is currently in pre-release), will include better support for server side rendering, so you won't have to wire it up yourself.  It will also take care of making the cookie expire with the token.


text:
Q: MySQL Min(), MAX() using the IDs from another table I have two very simple MySQL tables: Table1 with a list of unique item_ids and the second one Table2 with records using the the item ids form the first table.  Table2 contains also the date the record was made. To recap here is how the tables look like:
Table1
columns: item_id <---these are unique IDs
Table2
columns: item_id, item_title, time_stamp
What I need is a MySQL query that will give me a list with the date of the first and last record have been made for each item_id in Table2.  It's imperative that Table2 will look just for the item_id in Table1 because Table2 contains item_ids that are not contained in Table1. So in other words I'm using Table1 just for sorting based on item_id.
Your help is greatly appreciated.

A: SELECT  t2.item_id, MIN(t2.time_stamp), MAX(t2.time_stamp)
FROM    table2 t2
JOIN    table1 t1
ON      t1.item_id = t2.item_id
GROUP BY
        t1.item_id
ORDER BY
        t1.ordering_column

In MySQL, you can use ungrouped and unaggregated expressions in SELECT and ORDER BY.

A: select item_id, maxts.ts, mints.ts
from (select item_id, max(time_stamp) as ts from Table2 group by item_id) maxts
join (select item_id, min(time_stamp) from Table2 group by item_id) mints on maxts.item_id=mints.item_id
join Table1.item_id t1 on t1.item_id=mints.item_id;


text:
Q: Exception in laravel 5.8 : Trying to get property of non-object when trying to edit data Recently I've started with Laravel 5.8 and I'm trying to make the edit button which will update the row from the database. and when the edit button click, Laravel raise an error like this

this is my Controller:
    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',['book'->$book]);
    }

    public function UploadEdit(Request $request){
        DB::table('books')->where('id_book',$request->id_book)->update([
            'judul' => $request->judul,
            'gambar' => $request->gambar,
            'kategori' => $request->kategori,
            'deskripsi' => $request->deskripsi,
            'ketersediaan' => $request->ketersediaan,
            'lokasi' => $request->lokasi
        ]);

        return redirect()->back();
    }

this is my models:
    class Books extends Model
    {
        protected $table = "books";
        protected $primaryKey = "id_book";

       protected $fillable = [
           'judul',
           'gambar',
           'kategori',
           'deskripsi',
           'ketersediaan',
           'lokasi'
       ];
    }

I was trying to solve this problem with change edit function in the controller:
from this
    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',['book'->$book]);
    }

to this
    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',compact('book'));
    }

and this:
    public function edit($id_book){
         $book = Books::find($id_book);
         return view('/books')->withBooks('$book');
    }

but it doesn't work

A: I think error shows id_book is wrong.
You should use findOrFail() method.
public function edit($id_book){
    $book = Books::findOrFail($id_book);
    return view('/books',compact('book'));
}

A: Change your line 58 (edit() function's return statement) to:
return view('/books',compact('book'));

A: It seems you used -> instead =>  to assign value
Change
return view('/books',['book'->$book]);

to
return view('/books',['book' => $book]);

A: Try this:
 public function edit($id_book){
        $book = Books::where('id_book', $id_book)->first();
        return view('/books', compact('book'));
    }

A: Try this
public function edit($id_book) {
   $book = Book::find($id_book);

   return view('books.edit', compact('book'));
}


text:
Q: Dozer map a List inside a Map I'm using Dozer to Map from one object to another. I know Dozer can do a recursive mapping, but maybe i'm putting too much pressure on Dozer :p I want to map from class A to B
class A {
  private Map<String, List<ObjectA>> myMap;
  // getters and setter for myMap
}

class B{
  private Map<String, List<ObjectB>> myMap;
  // getters and setter for myMap
}

When I map from A to B I get an instance of B, but inside the Map I got a List of ObjectA. To be clear, I get an instance of this (imaginary) object:
class B{
  Map<String, List<ObjectA>> myMap;
}

How can I make dozer to perform this mapping correctly?
Note: ObjectA and ObjectB have the same properties (and int and a String).

A: You could specified hint:
<field>
    A
    B
    ObjectA
    ObjectB
</field>


text:
Q: Dimension Mismatch in VGG Keras I want to create VGG model with Keras.
However, following error was displayed:

expected lstm_input_2 to have 4 dimensions, but got array with shape
  (60000, 10)

I created the following sequential model:
model = Sequential()
model.add(Conv2D(16, kernel_size=(3, 3),
                     padding='same',
                     input_shape=input_shape))
model.add(Activation('relu'))
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dense(50, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Dropout(0.5))
model.add(Activation('softmax'))

Please tell me why this error created.

A: You just need to add a Flatten layer like so:
…
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # <-- this layer is missing in your code

model.add(Dense(50, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Dropout(0.5))
model.add(Activation('softmax'))
…

This transforms your last 2d layer (MaxPooling2D) to a 1-dimensional shape that you than can feed into your Dense layer.


text:
Q: Printing a list with string.format rounding for float members If I have a list of the format ['ABC',0.1234,'DEF'] and I wanted to print it out doing something like
l = ['ABC',0.1234,'DEF']
print('\t'.join(map(str, l)))

But I would also like to round the float so that the output would be ABC\t0.12\tDEF.
I can do it with something like:
a,b,c = l
print('{}\t{:.2f}\t{}'.format(a,b,c))

But since l is just one member of a much larger list, I would like to be able to do this with a list comprehension or something more pythonic.

A: You could use:
print('\t'.join("{:.2f}".format(x) if isinstance(x, float) else str(x) for x in l))

A: You could define a function for this:
def float_or_str(x):
    try:
        return '{:.2f}'.format(x)
    except ValueError:
        return '{}'.format(x)

l = ['ABC',0.1234,'DEF']
print('\t'.join(map(float_or_str, l)))

yields
ABC 0.12    DEF

A: As mentioned in the comment, you can simply do this for a big list:
print('{}\t{:.2f}\t{}'.format(*l))

Note that .format() also supports indexing the list. Something like:
print('0[0] 0[1] 0[2]'.format(l))

Edit:
"The data structure here is a list of triplet lists. Is there any straightforward way to do string formatting on a unknown size list?"
You can try:
>>> print('\t'.join("{:.2f}".format(x) if isinstance(x, float) else str(x) for k
 in l for x in k))


text:
Q: cf dev start fails - failed to reach Pivotal Network I just started to use pcf.
Today i have installed pcf dev v0.17 as well as virtual box 5.1 in Red Hat 6.5.
Unfortunately I can't start the cf dev.
I receive the following error:
[root@dpavqlxrh6-02 ~]# cf dev start
Please retrieve your Pivotal Network API from:
https://network.pivotal.io/users/dashboard/edit-profile

API token>
FAILED
Error: failed to reach Pivotal Network: Post https://dtb5pzswcit1e.cloudfront.net/product_files/pcfdev/pcfdev-v0.136.0.ova?Expires=1468505522&Signature=bqxaC76GvYNLN7HvrEVrlz%!E(MISSING)53brSM6tlnSi%!E(MISSING)JhoTESIg3cIOWm5YMldT8BY-%!E(MISSING)G7ofWbbS22pUOrdqvucCE1074iyiMaNRqiyGAg5U%!E(MISSING)%!E(MISSING)C5BxXJzEjZnB1hvwsXPWyBvpNRdl6SMnG4PGhnaJPBRF0gypfJIm7qaX9nbjWob4Awng_&Key-Pair-Id=APKAJLAM6FL65BYZP7UQ&filename=pcfdev-v0.136.0.ova: x509: certificate signed by unknown authority

Any help would be great! :)

A: Before getting into a PCF DEV installation , you just try to create a free account on Pivotal cloud Foundry that will give you the API Token.


text:
Q: Query count base on date groupBy Type - Laravel My goal is to construct this data.

753
It works now, but it did so many queries to get what I need.

I've tried
$logs = BabyLog::where('babyId',$baby->id)->get();
$graphData = [];
foreach($logs as $i => $log){

    if(strtotime($log->updated_at) < strtotime(date('Y-m-d H:i:s'))){

        $logTime = strtotime($log->updated_at);
        $logDate = date('Y-m-d', $logTime );

        $logsOnThatDay = BabyLog::whereDate('updated_at', '=', $logDate)->where('babyId',$baby->id)->get();
        // dd($logsOnThatDay,$logDate);

        $pee      = 0;
        $poop     = 0;
        $feed     = 0;
        $medicine = 0;
        $sleep    = 0;

        foreach($logsOnThatDay as $j => $logOnThatDay){

                // dd($logOnThatDay);

            if($logOnThatDay->type == 'pee'){
                $pee++;
            }

            if($logOnThatDay->type == 'poop'){
                $poop++;
            }

            if($logOnThatDay->type == 'feed'){
                $feed++;
            }

            if($logOnThatDay->type == 'medicine'){
                $medicine++;
            }

            if($logOnThatDay->type == 'sleep'){
                $sleep++;
            }

        }

        $graphData[$logDate]['pee']      = $pee;
        $graphData[$logDate]['poop']     = $poop;
        $graphData[$logDate]['feed']     = $feed;
        $graphData[$logDate]['medicine'] = $medicine;
        $graphData[$logDate]['sleep']    = $sleep;

    }

    // dd($graphData);
}

I've tried to enhance it like this
$logs = BabyLog::whereDate('updated_at', '=', date('Y-m-d H:i:s'))
->whereIn('type', ['feed', 'pee', 'poop','medicine','sleep'])
->selectRaw('type, count(type) as count')
->groupBy('type')
->get()
->keyBy('type');

I'm kind of stuck now.
How do I optimize my query?

A: You can do a grouping on the PHP end:
$logs = BabyLog->where('babyId',$baby->id)->get()->groupBy(function ($log) {
   return $log->updated_at->format('y-m-d');
});

foreach($logs as $date => $logsOnThatDay) {
   // here on you can probably use the code you already have but this below might be shorter
   $graphData[$date] = $logsOnThatDay->reduce(function ($acc, $log) {
      if (array_key_exists($log->type, $acc)) { $acc[$log->type]++; }
       return $acc;
   }, [
      'pee' => 0,
      'poop' => 0,
      'feed' => 0,
      'medicine' => 0,
      'sleep' => 0,

   ]);

}


text:
Q: Delphi firemonkey Mac OSX modal form moves behind main form when closing file dialog Delphi 10.2 Tokyo, firemonkey framework.
I am experiencing a weird issue with Mac OSX and file dialogs.
I have a form, lets say "Form1".
This form open another form "Form2" modal via a buttonclick.
"Form2" has a button, which open a file dialog (for example selectdirectory, or NSOpenPanel etc.), and when I close this file dialog, "Form2" will move iun z-order behind the main form, stays active, and cannot brought back to front.
This happen only on Mac, not with Windows as target platform.
I first thought that I might have something somewhere in my code causing that, so I created a new test project, with the 2 forms I mentioned, and it does exactly the same.
What am I doing wrong? Is there something I need to take care of on Mac OSX regarding file dialogs?
Here you see the settings dialog in the background, above the main form. The settings dialog has a button, which calls SelectDirectory(...), all is normal so far.

When I now close the file dialog, the Settings form moves behind the main form, stays active, and I cannot bring the form back to front.


text:
Q: Spring Security java.lang.IllegalArgumentException: Non-hex character in input I deployed an existing Maven project in my Tomcat Server on Windows7 environment. I'm using tomcat7 , spring-security-core 3.1.0 .
However, everytime I'm logging in my webapp, I received an error
java.lang.IllegalArgumentException: Non-hex character in input

The code is working perfectly fine in Linux environment. So I was thinking it's because I'm using windows7 in my local environment. When I look into the internet I saw that's it's a encoding issue between linux and windows.
I tried setting up

JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8

but haven't succeeded. Please help me out. Thanks in advance!

A: Most likely, when you login, events happen is such order:

*

*Spring selects an entity from DB by username.

*Spring must check inputted password for match with stored encoded password.

To check for a match, Spring uses PasswordEncoder, which you have most likely configured.
Your password encoder expects that stored encoded password is a hexidecimal char sequence (previously encoded by this PasswordEncoder). Thus, it tries to decode CharSequence into byte[], but fails (source).
The solution is to persist users with previously encoded password, e.g. by BCryptPasswordEncoder.

A: Answer Alex Derkach is right for me!
In my case i have DB with straight store password(develop) looks like User=roor, psw=root.
So when i comment(delete) .passwordEncoder(new StandardPasswordEncoder("53c433t")); ! its work
!!But is wrong, password must be stored in encrypted form!!!

A: A possible reason for this is mixing password encoders. There're different implementations of PasswordEncoder. And, for example, if you use SymmetricPasswordEncoder for encoding and StandardPasswordEncoder for decoding you may get this exception.


text:
Q: force $_POST to list all fields, even if the field contains no data/value I have a multiselect drop-down field called "holds".
When nothing is selected, the holds name does not show up in $_POST
The only fields that display in the $_POST array are fields that are selected or have data in the text field.
How do I force $_POST to list all input fields (whether they contain data or not)?

A: If the browser doesn't send the value to the server, $_POST won't contain it. Period.

A: The problem isn't with the POST, it is with the original form field. If the browser does not have some value (even if that value is blank), then it will not submit the input with the request. There is nothing which can be done about this on the server end.

A: It may be a waste of space, but you might be able to send the post with an additional field which is a serialized array of the post fields (with or without data).
-Just a thought


text:
Q: How to get the view or component object using its name in Vue js? Javascript code:
    var main = new Vue({
        el: "#main",
        data: {
            currentView: "top",
        },
    });

   var topComponent = Vue.component('top', Vue.extend({
    template: "#top",
   }));

Now when I access main.currentView, I get "top". But with this string 'top', how do i get the component topComponent?

A: It's easy. You can access the topComponent just using Vue.component.
var topComponent = Vue.component('top');

Now you have topComponent, you can do a lot of things with its methods.
cid
options
super
extend
directive
filter
partial
transition
component

A: From the VueJS guide

Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using ref. For example:

var parent = new Vue({ el: '#parent' })
// access child component instance
var child = parent.$refs.profile
<div id="parent">
     <user-profile ref="profile"></user-profile>
</div>

A: You may want to check out this example:
http://jsbin.com/wikeb/1/edit
It uses the v-view directive in the html, which takes a string to change the viewmodel displayed. Some sweet transitions going on as well.
Comes from: https://github.com/yyx990803/vue/blob/master/test/functional/fixtures/routing.html


text:
Q: Data structure for saving whole sentences in several languages I am planing to save big amount of sentences in a certain language such that every element has a pointer to the translation of that sentence to different languages.
By sorting the sentences I can create a balances binary tree and add/delete/search in O(logn).
Is there a way to save the elements in a hash table? What would the hash function look like in this situation?
I want to be able to search a sentence in any language and return the translation of it in any other language.
If I have K languages, using a balanced tree I get O(klogn) search time for k trees.
Is there a better way?

A: Yes, trie is better suitable for string search. Also I'd store all sentences in all languages in single trie, with value being the list of all available translations.
The search in this case will be O(k) where k is the length of the searched sentence.
UPD
If you are searching only for known language and translating to another known in advance language, then:
Make each the value of the trie  Map<(Source Language) → Map<(Target language) → Translation>>
You'll have following workflow: Find value, that corresponds to the given sentence in the trie. In the found Map search for the source language. If found, this means that sentence is in target language (assuming there can be collisions between languages). At this point found Map (inner) represents all available translations to target languages. Search it for desired one.
The most performance-efficient way to implement both Maps will be plain array. Where i-th element represent value for i-th translation (assuming you have finite number of translations and you can assign distinct index to each of them). The search for known translation will be O(1) — just accessing known index in array. But this approach will also be most memory consuming, as if you have sparse values in the Map, your backing array will still consume fixed amount of memory (proportional to the number of all possible translations).
But this approach will work for the inner Map (where, as I understood, translation for all possible languages are stored).
For the outer map, which I can expect to be sparse, you have several options:

*

*If the average number of collisions between sentences in different languages is small (1-2), you can just store Key→Value pairs in the list. Average search time will be constant.

*If the average number of collisions is significant, but still not big enough to go with array (approach for the inner Map), then back this Map by a Hashtable, which size will be the expected number of values in the Map — the average number of collisions. Then again you'll get amortized O(1) search time.

*Map appears to be dense — go with array approach, as for inner Map.

UPD2 Example:
Suppose you have next sentences that translates to each other:
Hello [en]
Hola  [es]
Hallo [nl]
Hallo [de]
You should add all of them into trie, with following values:
Hello -> Map([en] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo))
Hola -> Map([es] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo))
Hallo -> Map([nl] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo),
             [de] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo))

Square brackets here have nothing to do with arrays, they are used to visually distinguish languages.
So, when you perform search in you trie, you don't know on which language is your sentence. When you get a value from the trie (Map of Maps) you can "map" the original language of your sentence to the translation in desired language.
Back to example, if you have sentence "Hallo" and you know it's in [de], you want to translate it into [en].
You search "Hallo" in the trie, and get:
Map([nl] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo),
             [de] -> Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo))

Now you get value for [de] from this map (as you think your sentence in in [de]). You'll get:
Map([en]->Hello, [es]->Hola, [nl]->Hallo, [de]->Hallo)

Now fetch search for target language in this map ([en]). You'll get "Hello".

Of course instead of  Trie->Map->Map  structure you can have Map->Trie->Map, where first Map will map source languages to corresponding dictionaries, represented by trie. But I think this is less memory efficient, as it seems that words in different languages often share the same prefix, and hence having them in single trie will preserve memory. But it's the same in terms of performance efficiency, so it's up to you.


text:
Q: How to keep a selection of column/rows while scrolling columns and rows on a rmarkdown HTML table? The goal is to imitate the "freeze columns and rows in Excel" in an HTML table within an RMardown document.
Here is an example:
---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
rmarkdown::paged_table(mtcars)
```

The ouput is a HTML document with this table:

When you click on "Next", to scroll rows, it keeps the column names on top of the table:

However, when you click on the triangle symbol on the right of the column names, to scroll the columns, the rownames disapear:

1. How to keep rownames while scrolling columns?
2. How to choose the row(s)/column(s) kept while scrolling?
I was not able to find this option in knitr::kable(), rmarkdown::paged_table() nor flextable, am I missing something?

A: Answer to the first question
you can use FixedColumns extension of DataTable (i.e. using the {DT} package) to fix the row names (1st column) while scrolling horizontally.
---
title: "fixed columns"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
DT::datatable(
  mtcars,
  extensions = 'FixedColumns',
  options = list(
    dom = 't',
    scrollX = TRUE,
    fixedColumns = TRUE
  )
)
```


text:
Q: MySQL combining table data The context here is migrating users from an existing Drupal 6 site to a new site that no longer uses Drupal - or any other CMS.  Drupal, at least in v6, used a rather complex mechanism for storing additional user data

*

*User data went into a users table

*you defined data keys in a separate table called profile_fields

*and the actual values in a table called profile_values.

profile_values and users shared a uid field.  In my new site I am using a single users table which is structured something like this
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`rname` varchar(64)...

In the original Drupal profile_values table the rname entry for each user (distinct uid) is identified by that uid and an 'fid' of 14.
CREATE TABLE IF NOT EXISTS `profile_values` (
`fid` int(10) unsigned NOT NULL DEFAULT '0',
`uid` int(10) unsigned NOT NULL DEFAULT '0',
`value` text,...

What I need to do is execute a bit of SQL which will pick up the right value (for uid = UID & fid = 14) from the profile_values table and update the users table.  I vaguely suspect that this will require using INNER JOIN etc but that is well beyond my level of SQL skills (my poorest suite).  I would much appreciate any tips on how this can be accomplished.
An illustration of what I am after may help here
user Table (Before)
uid        name        rname
 1          Any         - empty prior to operation
 2          Eny         - empty prior to operation

profile_values Table
uid        fid      value
 1          13        v1-13
 1          14        v1-14
 2          11        v2-11
 3          14        v2-14

user Table (After)
uid        name        rname
 1          Any        v1-14
 2          Eny        v2-14

A: This is a very simple problem, and you need to learn how to join datas.
I will give you the example, but try looking around to learn about how to perform joins.
In this example, we are using a LEFT JOIN, in case of a user not having a rname, you still want to keep this users in the results.
SELECT user.uid, user.name, profile_values.value as rname
FROM user
    LEFT OUTER JOIN profile_values
        ON user.uid = profile_values.uid
WHERE profile_values.fid = 14

Look at some posts on stackoverflow :

*

*What is the difference between "INNER JOIN" and "OUTER JOIN"?

A: this will be the query
update user inner join profile_values on user.uid=profile_values.uid and profile_values.fid=14 set user.rname=profile_values.value


text:
Q: Plot values of one certain row in different columns of a table I have a huge table and I want to make a plot of lets say two different rows in this table.
Below you can see a small overview of my data set.
I want to plot now for country 4 the production of the years 1,2 and 3 so that someone can see the change over time
The same with country 6
On the X axis shoud be the years and on the  Y axis should be the values.
Can somebody help me?
Thanks in advance!
   country    year1        unit        year2        unit    year3
    1          5.1         tonnes       1.4         tonnes   5
    2          4.9         tonnes       1.4         tonnes   2
    3          4.7         tonnes       1.3         tonnes   3.5
    4          4.6         tonnes       1.5         tonnes   8
    5          5.0         tonnes       1.4         tonnes   8
    6          5.4         tonnes       1.7         tonnes   6

A: These are the steps to create the plot.
The data:
dat <- read.table(text="country    year1      unit      year2      unit    year3
   1          5.1         tonnes       1.4         tonnes   5
   2          4.9         tonnes       1.4         tonnes   2
   3          4.7         tonnes       1.3         tonnes   3.5
   4          4.6         tonnes       1.5         tonnes   8
   5          5.0         tonnes       1.4         tonnes   8
   6          5.4         tonnes       1.7         tonnes   6", header = TRUE)

*

*Choose a subset of the data:
subdat <- dat[dat$country == 4, c("year1", "year2", "year3")]

*Arrange the data in the long format:
subdat_l <- data.frame(Value = unlist(subdat), Year = factor(1:3))

*Plot:
plot(Value ~ Year, subdat_l)

If the actual data frame consists of the data of more than three years, you can use this general approach:
years <- grep("^year", names(dat), value = TRUE) # find the columns with the data
subdat <- dat[dat$country == 4, years]
subdat_l <- data.frame(Value = unlist(subdat),
                       Year = substr(years, 5, nchar(years)))


text:
Q: Vector of functions in APL What is the syntax for a vector (array) of functions in APL?
I have tried the following but these are interpreted as a 3-train and a 2-train, respectively:
{1},{2}

{1} {2}

PS. I am looking to do this with more complex (and possibly named) functions by the way, the {1} above is just so the example is short.

A: Arrays of functions can be obtained using ⎕OR (Object Representation) and the fact that such objects implicitly become reconstituted into functions when used as operands. (You can also do it explicitly using ⎕FX.) It is easiest to define some helper operators first:
      _Arrayify←{f←⍺⍺ ⋄ ⎕OR'f'}
      _Apply←{2=⎕NC'⍺':⍺ ⍺⍺ ⍵ ⋄ ⍺⍺ ⍵}

Now, let's define some sample functions:
      A←{2×⍵}
      B←{⍵÷2}
      C←{-⍵}

We create a 3-element vector of functions, and check that it is indeed a "normal" array:
      fnArray←(A _Arrayify⍬)(B _Arrayify⍬)(C _Arrayify⍬)
      ⍴fnArray
3

Let's extract the second function and apply it:
      (2⊃fnArray)_Apply 10
5

We can also create an application function, so we can use operators on it:
      Apply←{⍺ _Apply ⍵}
      fnArray Apply¨10
20 5 ¯10

A: Dyalog APL does not officially support function arrays, you can awkwardly emulate them by creating an array of namespaces with identically named functions.
      (a←⎕NS⍬).f←2∘×
      (b←⎕NS⍬).f←÷∘2
      (c←⎕NS⍬).f←-
      f←(a b c).f
      f 4
8 2 ¯4

Maria Wells suggested an operator to produce an array of functions


text:
Q: Map master/detail records after Dapper calls At work, we're considering using Dapper. In the existing code base, our master/detail objects are loaded separately. Typically, this means that there is one sql statement executed for all master records and one sql statement executed per detail record.
To improve performance and ease the transition, I'd like to make 2 calls using Dapper and stitch the results together:
public class Zoo
{
    Guid Id { get; set; }
    string Name { get; set;}
    IList<Monkey> Monkeys { get; set; }
}

public class Monkey
{
    Guid Id { get; set; }
    Guid ZooId { get; set; }
    string Name { get; set; }
    bool DeservesBanana { get; set; }
}

var sqlZoos = "SELECT * FROM Zoos"
var Zoos = connection.Query( sqlZoos )

var sqlMonkeys = "SELECT * FROM Monkeys"
var Zoos = connection.Query( sqlZoos )

foreach( var zoo in Zoos )
{
  zoo.Monkeys = Monkeys.Where( x => x.ZooId = zoo.Id ).ToList();
}

Is there a helper method or something in Dapper that I can use to replace the foreach. Should I use something like AutoMapper instead? Or is there a better way to achieve this (than the foreach loop) using the .NET library?

A: You could try something like this:
var zoos = new Dictionary<string, Zoo>();
var query = "SELECT * FROM Zoos LEFT OUTER JOIN Monkeys ON Monkeys.ZooId = Zoos.Id";

_connection.Query<Zoo, Monkey, Zoo>(query, (z, m) =>
{
    if (!zoos.TryGetValue(z.Id, out Zoo zoo))
        zoos.Add(z.Id, zoo = z);

    zoo.Monkeys.Add(m);
    return zoo;
});


text:
Q: Rollover calling image from array Working on a webpage where I would like multiple rollovers from the same base image (multiple black pixels distributed throughout the page - kind of like a popup effect). I figure the easiest way to do this is to have an array with all the rollover images and an array with the base image (pixel.png). Had lots of trouble even getting the images to display, and now that I have the background image displaying, I cannot get the rollover to work. Have tried trouble shooting in chrome using developer/debug but no dice - doesn't even show an error message. I'm guessing it's something simple like not calling the functions properly but I just can't see it..
<!DOCTYPE html>

A: It is simple but what you've posted was not even close:
Here's the working example: https://jsfiddle.net/tqw84trm/1/
if (document.images) {
  var flipped = new Array();
  for(i=0; i< inames.length; i++) {
    flipped[i] = new Image();
    flipped[i].src = "media/"+inames[i];
  }
}

function out (num) {
  if(document.images) {
    var rev = revert.slice();
    revert[num] = document.images[num].src;
    document.images[num].src = rev[num];
  }
}


text:
Q: Prove that $\lvert\frac{1}{n}-\frac{1}{2n}-\frac{1}{2n+2}\rvert<\frac{1}{n^2}$ Prove that $\lvert\frac{1}{n}-\frac{1}{2n}-\frac{1}{2n+2}\rvert<\frac{1}{n^2}$ and deduce that $1-\frac{1}{2}-\frac{1}{4}+\frac{1}{3}-\frac{1}{6}-\frac{1}{8}$ is convergent.
Using algebra, the absolute value becomes $\lvert\frac{1}{2n}-\frac{1}{2n-2}\rvert$ which is $\lvert\frac{-(n+1)}{2n(n+1)}\rvert$.
Not entirely sure how to proceed with this proof..
Edit: Incorrect third term, changed to $\frac{1}{2n+2}$.

A: $$\frac{1}{n}-\frac{1}{2n}-\frac{1}{2n+2}=\frac{1}{2n}-\frac{1}{2(n+1)}=\frac{1}{2n(n+1)}\leq \frac{1}{n^2}$$
Now we have
$$0\leq1-\frac{1}{2}-\frac{1}{4}+\frac{1}{3}-\frac{1}{6}-\frac{1}{8}+\cdots=\sum_{n=1,n \,\mathrm{odd}}^\infty\frac{1}{n}-\frac{1}{2n}-\frac{1}{2n+2}\leq\sum_{n=1}^\infty\frac{1}{n^2}$$
the series is positive and bounded above so it's convergent.

A: $$
\begin{array}{rcl}
\left| \frac{1}{n}-\frac{1}{2n}-\frac{1}{2n-2} \right| & < & \frac{1}{n^2} \\
\left| \frac{1}{2n}-\frac{1}{2n-2} \right|& < & \frac{1}{n^2} \\
\left| \frac{-2}{(2n)(2n-2)} \right|& < & \frac{1}{n^2} \\
\frac{1}{2n^2-2n}& < & \frac{1}{2n^2-n^2} \\
\end{array}
$$
True for all integer $n>1$.

A: For the inequality you ask about, use brute force:
$$ \frac{1}{n} - \frac{1}{2n} - \frac{1}{2n-2} = \frac{2(n-1) - (n-1) - n}{2n(n-1)} = \frac{-1}{2n(n-1)}$$
So, your inequality will follow from $2n(n-1) > n^2$, which is equivalent to $n^2 > 2n$, which is true for $n > 2$.
For convergence, you should use the inequality to bound pieces of your series by $\frac{1}{n^2}$ (in absolute value). Once you do this, from convergence of $\sum_n \frac{1}{n^2}$ it follows that the series converges.

A: I think you have it wrong there. The absolute value becomes $\dfrac{1}{2n^2-2n}$ which is $\dfrac{1}{2n^2-2n}=\dfrac{1}{n^2+n^2-2n}<\dfrac{1}{n^2}$ when $n^2>2n$.


text:
Q: Unregistering a COM dll using regsvr32 I've registered a COM dll using the regsvr32 command and I forgot the exact location of the assembly from where I did it. Now I'm facing trouble to unregister the dll. How I can unregister it? I tried using the /u switch from other locations of the assembly but that's not working.. the asp application is still using the assembly successfully.

A: Use this for getting path: http://support.softartisans.com/kbview_1294.aspx

A: Open command prompt with admin privilege and type:
regsvr32 -u dll name


text:
Q: dropdownlist get value from database using angularjs below i mentioned our code for dropdownlist value get from database but i got error. error means in angular code not call angular http method  url everthing so dropdown showing empty.
AngularJS
 $scope.product = function (e) {
        $http({
            method: "GET",
            url: "/Prescription/GeneratePrescriptions"
        }).
          then(function (response) {
              $scope.formulationlist = response.data;
          }, function () {
              alert("Error Occur");
          })
    }

Controller

 public ActionResult GeneratePrescriptions()
    {
        FDAGeneric_Bind();
        FDAFormulation_Bind();
        TestFDAFormulation_Bind();
        return View();
    }

 public JsonResult TestFDAFormulation_Bind()
        {
            DataSet ds = dFDA.Get_FDAFormulation();
            List<SelectListItem> Formulationlist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                Formulationlist.Add(new SelectListItem { Text = dr["Formulation"].ToString(), Value = dr["FormulationID"].ToString() });
            }
            //ViewBag.MasterFormulationID = Formulationlist;
            return Json(Formulationlist, JsonRequestBehavior.AllowGet);
        }
View

 <td>
                                    <select ng-model="r.formulationid" ng-change="" ng-options=" p.formulationid as p.formulation for p in formulationlist" class="form-control">
                                        <option value="">Select Product</option>
                                    </select>
                                </td>


text:
Q: regular expression for stop position in python 3 I have a string: "0x1.9999999afpap-4". I hope to have a regular expression to extract 1.9999999afpa from this string. I am looking for a regular expression solution to extract everything from a string except the "0x" and "p-4". At meanwhile, I hope this solution could be applied to other strings with random letters and length, such as extract"1.999999999pp" from "0x1.999999999ppp-4"
Thanks.

A: use a non-capturing group (note: you have to escape the dot to be accurate):
test ="0x1.9999999afp-4"
import re
new=re.search("1\.\w*(?=[$p])", test)
print (new.group())

now output is
"1.9999999af"


text:
Q: bash recursive function for counting files So I wanted to make a shell script that counts all hidden files, aliases and subdirectories in a folder. Problem is that it the recursive call of the function I created doesn't go beyond the first depth level:
function recursive_func()
{
    current=$1
    echo $current
    for thing in $(ls -A $current)
    do
        if [ -d $current/$thing ]
        then
            let subd++
            recursive_func $current/$thing
        elif [ -L $thing ] ; then
            let symlinks++
        elif [ -f $thing -a ${thing:0:1} == "." ] ; then
            let hidden++
        fi
    done
}

However, one of my colleague managed to do it and it looks like this:
function recursive_func()
{
    echo $1
    for thing in $(ls -A $1)
    do
        path=$1/$thing
        if [ -d $path ]
        then
            let subd++
            recursive_func $path
        elif [ -L $path ] ; then
            let symlinks++
        elif [ -f $path-a ${thing:0:1} == "." ]; then
            let hidden++
        fi
    done
}

I can't tell why the second version works but mine doesn't. Any help?
Edit:
The problem was that current was global and so after every recursive call the value was wrong for the rest of the iterations in the for loop. Fixed it by adding local in front of current, or by just using $1 instead.

A: Better use find to avoid the recursive call and count the output lines with wc -l.
Try this in the folder to search:
find -mindepth 1 -name '.*'
find -mindepth 1 -name '.*' | wc -l

A: current is a global variable and after every recursive call the value is wrong for the rest of the iterations in the for loop. Fixed it by adding local in front of current, or by just using $1 instead.
function recursive_func()
{
    local current=$1
    echo $current
    for thing in $(ls -A $current)
    do
        if [ -d $current/$thing ]
        then
            let subd++
            recursive_func $current/$thing
        elif [ -L $thing ] ; then
            let symlinks++
        elif [ -f $thing -a ${thing:0:1} == "." ] ; then
            let hidden++
        fi
    done
}

or
function recursive_func()
{
    echo $1
    for thing in $(ls -A $1)
    do
        if [ -d $1/$thing ]
        then
            let subd++
            recursive_func $1/$thing
        elif [ -L $1/$thing ] ; then
            let symlinks++
        elif [ -f $1/$thing -a ${thing:0:1} == "." ] ; then
            let hidden++
        fi
    done
}

A: Try this
recursive_func () {
    shopt -s dotglob
    for item in $1/*; {
        fname=$(basename $item)
        [[ -L $item ]] && ((symlinks++))
        [[ ${fname::1} = '.' ]] && ((hidden++))
        [[ -d $item ]] && { ((subd++)); recursive_func "$item"; }
    }
    shopt -u dotglob
}

A: ls -al | wc -l

The first command lists all files in the directory, and puts them in the long format, so that they occupy one line each.  The second command counts the lines.
Apologies; I just realised you wanted recursion.


text:
Q: Build table dynamically with PDFmake I found an example of how to fill the table with pdfmake dynamically, which has 2 columns. Now I tried add another column 'height' to the table but I don't know how to modify it.
function buildTableBody(data, columns) {
    var body = [];

    body.push(columns);

    data.forEach(function(row) {
        var dataRow = [];

        columns.forEach(function(column) {
            dataRow.push(row[column].toString());
        })

        body.push(dataRow);
    });

    return body;
}

function table(data, columns) {
    return {
        table: {
            headerRows: 1,
            body: buildTableBody(data, columns)
        }
    };
}

function Pdftest(){
  var externalDataRetrievedFromServer = [
    { name: 'Bartek', age: 34, height: 1.78 },
    { name: 'John', age: 27, height: 1.79 },
    { name: 'Elizabeth', age: 30, height: 1.80 },
  ];

    var dd = {
    content: [
        { text: 'Dynamic parts', style: 'header' },
        table(externalDataRetrievedFromServer, ['name', 'age', 'height'])
    ]
}
pdfMake.createPdf(dd).download();
}

Does anybody know what needs to be modified?

A: Error was anywhere else, the code above works perfectly fine


text:
Q: Where is the default QGIS Point layer style .qml file installed in Win 32? Where is the default QGIS Point layer style .qml file installed in a Windows 32 bit installation? I have done a search on *.qml and can only find four python plugins styles.

A: I think what you are looking for is a symbology file. The default would be
~/.qgis/symbology-ng-style.xml

QMLs are layer style files. Reusable symbol libraries are stored in XMLs which can be imported and exported using Style Manager.


text:
Q: How to add text on Isotope Image? I've build a sort of portfolio using Isotope and Jquery but I don't know how to put text on my pictures without destroying all the isotope portfolio.
I've tried a lot of thing : using position:relative for the pictures and position:absolute for the text but it doesn't work. What should I do ?
Thank you.

A: I know this problem and it happened to me. You can use HTML5 Tag which is figcaption. After using figcaption tag you can figure it via CSS.
<figcaption>example</figcaption>


text:
Q: Does Vue 3 + Inertia remove event listeners automatically when component is unmounted? I have an event listener inside script setup:

<template>

your element

</template>

Will it be removed when the component is unmounted or do I have to remove it manually?

A: The global event listener is not automatically removed, so your component will need to explicitly do that.
You should add the listener in the mounted hook, and remove it in the unmounted hook. Also, you'll need to store the function passed to addEventListener so that it could be passed to removeEventListener:

A: I found a way to automatically deregister event listeners:
import { getCurrentScope, onScopeDispose } from "vue";

export function addEventListenerWrapper(target, name, fn) {
    target.addEventListener(name, fn);
    if (getCurrentScope()) {
        onScopeDispose(() => target.removeEventListener(name, fn));
    }
}

Then you should be able to just register your listener inside of your component like this and it should deregister later automatically:
addEventListenerWrapper(window, "click", event => {
    if (!elementRef.value.contains(event.target)) {
        console.log("click outside element");
    }
})

Please refer to the following Vue SFC Playground to see it in action. You should see in the console that toggling the element with the button will cause the console to print event registration/deregistration messages.
See these links for more info:

*

*https://vuejs.org/api/reactivity-advanced.html#onscopedispose

*https://github.com/vuejs/pinia/blob/78ec9a186dcbce3d583db332ae22094a182358cc/packages/pinia/src/subscriptions.ts


text:
Q: First releasing iPhone only, later universal I' m working on an iOS app. I would like to release it first as a iPhone only app, and later (in a couple of months) update it to a universal app. I has to be the same app-id because it is a free game with in-app purchases.
Is this possible ?

A: Yes, that's not a problem at all, you'd just have to write additional code to support the iPad and submit it as a regular update to your iPhone app (which then becomes a Universal app).
When the iPad originally came out, a lot of iPhone apps did exactly that.


text:
Q: mysql import on Mac : second password asked? I'm trying to import a mysql database from my Mac with terminal under OSX Yosemite. I typed the mysql command with -u -p -h etc but when I hit enter, Terminal ask me :
"Enter password".
I tried to re-enter the one I put in the command line, the one of my Mac, and others but nothing worked.
What is this second password asked ?

A: http://dev.mysql.com/doc/refman/5.0/en/connecting.html
For password options, the password value is optional.
If you use a -p or --password option and specify the password value, there must be no space between -p or --password= and the password following it.
If you use a -p or --password option but do not specify the password value, the client program prompts you to enter the password.
mysql --user=user_name --password=your_password db_name
So if you typed -p passwd instead of -ppasswd, it will ask for the password.
If the password itself doesn't work, then you have it wrong.


text:
Q: Incorrect onPress Parameter Value When JSX views are Concatinated I have a small list of rows which I rendering in React Native. Each row contains some information and button which performs an operation on the object associated.
To render the rows, I iterate through a list and with each new row, add the JSX markup to an array.
for (i = 0; i < this.state.values.length; i++) {
  var theVariable = this.state.values[i].id;
  returnValue.push(
    <View style={{flexDirection: 'column', borderTopWidth: .5, borderColor: 'grey'}}
      <View style={[s.rowStyle, {justifyContent: 'center'}]}>
        <TouchableHighlight style={s.buttonOutlineActiveRental} underlayColor='transparent'  onPress={() => this._someFunction(theVariable)}>
          <Text style={s.buttonText}>
            Click me!
          </Text>
        </TouchableHighlight>
      </View>
    </View>
  );
}

The issue is the theVariable value of the on press function is incorrect. Through some debugging I've discovered that the theVariable is always equal to the theVariable in the final row. This leads me to believe that each row is always pointing to the newest version of the variable.
In this case, what is the proper method to pass the parameter through the on press function?

A: First of all I'd suggest changing var to let. Secondly move the declaration out of the loop.
Next create a new component for the "row". Pass the variable to the row as a prop. This should bind the current value to the component solving your issue.


text:
Q: Need Remote_User / Auth_user in Flask Application with Apache 2.4 I have a Flask Application and Apache 2.4 to serve API requests from Angular website. I need help to get windows username of whoever is visiting the website. I cannot show the login screen as my company has SSO authentication. Therefore, I need to find a way to get "REMOTE_USER"/"AUTH_USER" from the request headers or any other way.
I am getting None when I use
request.headers['REMOTE_USER'] and request.headers.get('X-Remote-User')
I hope someone can help me to understand how to achieve this.


text:
Q: Initializing using properties with Dependency keyword and UnityContainer I have a code sample which look something like this.
public class AdventureWorksRepository
{
    [Dependency]
    private AdventureWorksEntities Context
    {
        get; set;
    }

    public AdventureWorksRepository()
    {
         SelectDemo();
    }

    public void SelectDemo()
    {
        var productNames = Context.Products.Select(item => item.Name);

        foreach (var productName in productNames)
        {
           Console.WriteLine("Name : "productName);
        }
    }
}

and heres the main programe
private static void Main(string[] args)
{
    UnityProvider.Container = new UnityContainer();
    UnityProvider.Container.RegisterInstance<AdventureWorksEntities>(new AdventureWorksEntities());
    var repository = UnityProvider.Container.Resolve<AdventureWorksRepository>();
}

from what i've understood the Dependency keyword should tell Unity to initialize the the AdventureworksEntities property but I keep getting and null refrence exception  any tips what I'm doing or assuming wrong

A: I would recommend that you don't use the [Dependency] attribute. With them you have references to your container everywhere in your codebase. See this article for detailed explanation.
You can tell Unity that you want a dependency injected using InjectionProperty like this
container.RegisterType(typeof(IMyInterface), typeof(MyImplementation), new InjectionProperty("MyProperty"));

instead. If you want to inject a specific value into that property instead of letting Unity resolve that value you can also specify your own value in the constructor of InjectionProperty.
Btw.: Your property must be public. It won't work on private properties. If you don't want to make that property public you should instead go for constructor injection
public class AdventureWorksRepository
{
  private readonly AdventureWorksContext context;
  public AdventureWorksRepository(AdventureWorksContext context)
  {
    if(context == null) throw new ArgumentNullException("context");
    this.context = context;
  }
}


text:
Q: Resuming circle progress bar animation after pausing it I'm trying to create an application that uses a timer. And in addition to the timer I want to use a circular progress bar. The code is below. It's simple but looks good.
But then I need it to pause and resume from the point where I paused it.
And here I struggle.
Below is step-by-step implementation.
First, I've created a circle progress ar:
func createProgressBar() {

        let circularPath = UIBezierPath(arcCenter: progressBarImageView.center, radius: progressBarImageView.frame.size.width / 2, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
        shapeLayer.path = circularPath.cgPath

        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 3
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = .round
        shapeLayer.strokeEnd = 0
        view.layer.addSublayer(shapeLayer)

    }

Then I've created an animation, so at certain moment it starts filling the bar for passed duration. Duration in seconds.
BTW, if someone could explain why total filling time properly calculates only with speed of 0.8 and not 1, I'll be grateful.
func startAnimation(with duration: Int) {

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        basicAnimation.toValue = 1
        basicAnimation.duration = CFTimeInterval(duration)
        basicAnimation.fillMode = .forwards
        basicAnimation.isRemovedOnCompletion = false

        shapeLayer.add(basicAnimation, forKey: "usSoBasic")
        shapeLayer.speed = 0.8

        shapeLayer.timeOffset = 0
    }

Then I've created function that pause an animation.
func pauseAnimation() {
        let pausedTime = shapeLayer.convertTime(CACurrentMediaTime(), from: nil)
        shapeLayer.speed = 0.0
        shapeLayer.timeOffset = pausedTime
    }

And the only thing that left is to resume it. But turns out that it's the hardest part of all.
I've tried to use different "circularPath", delete all the previous animation and create a new one, tried to use different starting angles. All of it just doesn't work.
It's even not showing bar at all or starts from the beginning, or the bar has completely wrong starting and ending points.
Where should I look and how would you implement the solution?


text:
Q: Arnoldi iteration and minimal poly I'm working on Exercise 33.3 on Numerical Linear Algebra by Lloyd Trefethen. The problem is: if Arnoldi iteration runs to completion on matrix $A$, and $A$ is a $m$ by $m$ square matrix, then the minimal polynominal of $A$ is of degree $m$.
My thoughts are: If Arnoldi runs to completion, then $A$ has full rank, i.e., eigenspace of $A$ has degree $m$, therefore all eigenvalue of $A$ are distinct, hence minimal polynominal is the characteristics polynominal, so their degree are both m.
I'm not sure if the logic follow through, I'm not very familiar with minimal polynominal and characteristics polynominal. So can someone help me check on that please?
Thanks

A: As I note in my comment, your approach is incorrect.
The key is to note that Arnoldi iteration runs to completion with the initial vector $b$ if and only if the Krylov subspace generated by $b$ is equal to all of $\Bbb R^m$.
From there, one approach is to show that the matrix of $A$ relative to the basis $\{b,Ab,\dots,A^{m-1}b\}$ is a companion matrix; the fact about the characteristic polynomial follows. Alternatively, the fact that the vectors $b,Ab,\dots,A^{m-1}b$ are linearly independent implies that the matrices $I,A,\dots, A^{m-1}$ are linearly independent, and we can similarly deduce from this that the minimal polynomial of $A$ has degree $m$.


text:
Q: Element unidentifiable in Sikuli-Selenium Webdriver : NoClassDefFoundError My application has a Upload button, clicking on which opens the local file explorer. Tried to automate the window using Sikuli. Below is the Sikuli code snippet.
ImagePath.setBundlePath("C:\\TempFolder\\");
String imageName = "TextBox.PNG";
Screen s = new Screen();
Match m = s.find(imageName);
m.highlight();
s.click(imageName);

On execution, it is failing at
Match m = s.find(imageName);
and the error message is:

The snapshot of pom.xml


text:
Q: CSS & JS: ¿Se podria activar un codigo JavaScript desde CSS? A ver, me explico: Me gustaria crear un detector de cuando el cursor toca un elemento, pero el .onmousemove() es muy impreciso y quiero algo mas rapido, y se me ocurria usar el :hover de CSS, pero no se como (si es que se puede) conectar codigo JavaScript al activarse el :hover ¿Hay alguna forma?
Por ejemplo:
#elemento {
    /* ejecutarcodigojs */
}

¿Se podria llegar a hacer? O cualquier alternativa mas precisa al .onmousemove() me sirve tambien
Gracias.

A: No, no se puede, pero el mismo evento que aplica un estilo CSS sobre un elemento, se puede escuchar para ejecutar javascript. El nombre cambia, mientras en CSS es hover, en javascript el evento se llama mouseover:

document.querySelector('div').addEventListener('mouseover', () => console.log('Ratón sobre el div'))
div#hover {
  width: 200px;
  padding: 10px;
}
div:hover {
  background-color: navy;
  color: white;
}
<div id="hover"> Pon el ratón encima </div>


text:
Q: Chart not updating properly I am trying to follow Mike Bostock's tutorial on d3js (http://mbostock.github.io/d3/tutorial/bar-2.html) to understand how to update charts dynamically but I am facing some hurdles.
In my chart, my bars on the left, rather than being simply removed, are sent behind my chart and I can't figure out why:
JS:
var t = 1297110663, // start time (seconds since epoch)
          v = 70, // start value (subscribers)
          data = d3.range(33).map(next); // starting dataset

          function next() {
            return {
              time: ++t,
              value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))
            };
          }

          setInterval(function(){
            data.shift();
            data.push(next());
            console.log(data);
            redraw();
          }, 1000);

          var w = 20,
              h =80;

          var x = d3.scale.linear()
                  .domain([0, 1])
                  .range([0, w]);
          var y = d3.scale.linear()
                  .domain([0, 100])
                  .rangeRound([0, h]);

          var chart = d3.select(".container").append("svg")
              .attr("class", "chart")
              .attr("width", w * data.length - 1)
              .attr("height", h);

          chart.selectAll("rect")
            .data(data)
          .enter().append("rect")
            .attr("x", function(d, i){ return x(i) - 0.5; })
            .attr("y", function(d) { return h - y(d.value) - .5; })
            .attr("width", w)
            .attr("height", function(d) { return y(d.value); });

          function redraw(){
            console.log(data);
            var rect = chart.selectAll('rect')
              .data(data, function(d){ return d.time; });

            rect.enter().insert("rect")
              .attr("x", function(d, i) { return x(i + 1) - .5; })
              .attr("y", function(d) { return h - y(d.value) - .5; })
              .attr("width", w)
              .attr("height", function(d) { return y(d.value); })

            rect.transition() // Shouldn't I use .update() here?
              .duration(1000)
              .attr("x", function(d, i) { return x(i) - .5; });

            rect.exit().transition()
              .duration(1000)
              .attr('x', function(d, i) { return x(i - 1) - .5})
              .remove();
          }

Here is the jsfiddle: http://jsfiddle.net/kkMR4/
Another thing I don't understand is why we dont use .update()? If I understand correctly .enter() is used to create the DOM element where data didnt find any match in the DOM and .exit() is used to find the DOM elements which are not in data, so shouldn't I use update() to move all the other column to the left?
Many thanks
Best

A: The problem is in this block:
        rect.exit().transition()
          .duration(1000)
          .attr('x', function(d, i) { return x(i - 1) - .5})
          .remove();

The third line (.attr), reassigns the coordinates. If you want them to truly exit, you can remove this line.
        rect.exit().transition()
          .duration(1000)
          .remove();


text:
Q: Stacked SQL Query error and complications I just learned you can stack SQL queries instead of running 4 different ones and combining the data. So I'm read tutorials and stuff but still can't figure this certain one out.
SELECT ID,
       (SELECT firstname
        FROM   user
        WHERE  ID = fundraiser.user_ID) AS firstname,
       (SELECT lastname
        FROM   user
        WHERE  ID = fundraiser.user_ID) AS lastname,
       (SELECT org_fund_id
        FROM   fundraiser
        WHERE  ID = fundraiser.ID)      AS org_fund_ID,
       (SELECT ref_ID
        FROM   fundraiser
        WHERE  ID = fundraiser.ID)      AS ref_ID
FROM   fundraiser
WHERE  1
ORDER  BY org_fund_ID ASC

Here's the basic setup for the database/tables being called:
[fundraiser] - (ID, ref_ID, user_ID, org_fund_ID) and
[user] - (firstname, lastname)
Basically, I want to pull all of the fields from "fundraiser" from the database but get the corresponding "user.firstname" and "user.lastname" where "fundraiser.user_ID" = "user.ID".
So it would come out something like this as a row:
fundraiser.ID, fundraiser.user_ID, fundraiser.ref_ID, user.firstname, user.lastname
I've tried like 30 different ways of writing this query and all have failed. The error I get is "#1242 - Subquery returns more than 1 row".
Not sure how I can give you more information so you can visualize what I'm talking about, but I will provide whatever data I can.
Thanks in advance.

A: to select ALL columns:
SELECT *
FROM   fundraiser f
       INNER JOIN user u
               ON u.ID = f.user_ID
ORDER  BY f.ord_fund_id ASC;

to select needed columns:
SELECT
    u.firstname,
    u.lastname,
    f.org_fund_id,
    f.ref_ID
FROM fundraiser f
INNER JOIN user u ON u.ID = f.user_ID
ORDER BY f.ord_fund_id ASC;

this should be, what you need. See this Wikipedia page.


text:
Q: Is there any point implementing my own file cache in a Windows app? I have a Delphi app that references a datafile of 28-byte records.  The file is written sequentially but read randomly.  The datafile is split into N physical files which are rolled over at 10 megs or so to provide some insurance against disk problems, and because we are only ever writing to the most recent one, and I found it became slower and slower to write to if it were allowed to grow to big.  On startup I read the entire file set and build an index so that I can quickly know which file to seek into given a virtual record number.
As part of the splitting into N files I implemented a read cache.  I realise now that Windows does a fair amount of caching on it's own, and I wonder if I'm gaining anything by sticking another cache between myself and the disk files.
Any thoughts appreciated.

A: No. Use file mappings to use the existing file cache more efficiently.


text:
Q: How do I pack a file together with the binary of a C++ application? I have a C++ application that takes configuration options from an XML file, and uses an XSD file to validate the information provided.
At the moment, I define the location of the XSD file in the makefile like this:
DEFINES := XSD_FILE_LOCATION=\"$(HOST_DIR)/share/$(strip $(COMPONENT_DIR))/xml\"

So from the source code I use 'XSD_FILE_LOCATION' to find the path to the XSD file.
I would like to package the XSD file together with the application's binary, so that the binary can be passed around and it already contains the XSD information, rather than demanding building it on every PC it's going to be used.
EDIT: I am thinking about embedding the XSD file as a string in the source code, but the solution does not convince me, I like the idea of having it as a separate file.

A: If you want it packaged inside the executable, you could consider simply creating a variable to hold it, something like (not really valid XML, the intent is just to show the method):
const char *xml =
    "<xml>"
    "  <tag>This is my XML.</tag>"
    "  <tag>There are many like it, but this one is mine.</tag>"
    "</xml>"
;

You could even have a build step which took the real XML file, and morphed it into a C++ source file for compilation, so that any funnies like character escapes could be done automatically. This allows you to manage the XML file in its raw form during development (as a separate file) while merging it with the executable at build time.
Then, once your program is running, you can do as you see fit. Use the in-memory copy contained in xml, write it to disk as part of start-up, or whatever else your heart desires.


text:
Q: Identity IQ does not start Currently, I am using a virtual machine in Oracle cloud. I have successfully installed Tomcat and IdentityIQ. The server is deployed correctly, but when I try to access through Google Chrome with the credentials, I get the following error.

I have disabled the firewall and when I try to test the connection with ping it does not respond.


text:
Q: How to use AppleScript application with "open file -a AppleScriptApp"? Some information about what I am trying to achieve
I am using emacs inside of terminal. I know about existence of cocoa versions of emacs (like GNU Emacs for OS X, Aquamacs and Emacs Mac Port). But I prefer to code inside of terminal.
Everything is fine in my setup except the fact that sometimes I want to open file inside of emacs from Finder or any other software. So I need find running process of emacs in terminal or create new one and open the fine inside of running emacs.
So basically I need to create an .app wrapper for opening files in terminal emacs.
Trying to get it done
As far as I understand, open -a my_emacs_app /path/to/file is the same as opening file in application from finder. So that's why I am testing my_emacs_app using open command.
My first attempt is to create application using AppleScript. Here is the code that process passed arguments:
on run argv
    if (count of argv) > 0 then
        -- get file path from argv
        -- and log to logfile for testing purposes
        return "defined"
    else
        -- no args means no file
        -- log to logfile that we can't extract file path
        -- from empty arguments
        return "failed"
    end if
end run

And actually it works when I try to run it using
$ osascript my_emacs_app.scpt /path/to/file

It opens the file and logs what expected to log file.
When I run it using
$ osascript my_emacs_app.scpt

It logs to file that no arguments were passed.
So I was happy with it. But remember, I need an .app wrapper. So I am exporting this script as application (and place it inside of /Applications/ folder). And then when I try to
$ open -a my_emacs_app /path/to/file

I see that application is executed for a short time and then is closed. But nothing good happens. I mean, file is not opened in emacs and nothing is logged into log file.
Does any one know, how to export such scripts?

A: After few different attempts and hacks I found good solution to solve my problem. First - implement the script. Then open the Automator.app and create new application. Then combine Get Specified Finder Items action and Run AppleScript. So now open -a my_automator_app /path/to/file will pass /path/to/file/ to my script. And that's cool.
P. S. in the argv will be stored the alias to the file, not the posix file path. To convert it from alias to posix you should use
set aliasPath to item 1 of item 1 of argv
set filePath to (the POSIX path of aliasPath)

Oh and don't forget that you might want to get the quoted form of filePath in case it contains some special characters (like space or ~).
You can get more information about alias/posix paths here

A: From man open in EXAMPLES section:

"open -a /Applications/TextEdit.app '/Volumes/Macintosh HD/foo.txt'" opens the document in the application specified (in this case, TextEdit).

So You can specify path to Your AppleScript application after -a argument.
I tested this and it works for me, path does not have to be absolute.


text:
Q: keyboard interrupt gives segmentation fault in sleep In my main.c file i have the code below. Everything works fine but when i create a signal by using ctrl+c; execution pauses at sleep(1), intHandler function works,  then program gives segmentation fault in sleep(1) line.
Any one has any idea what should cause this? I cant execute the last two lines in RunMe() and because of this i cant close my open sockets and threads properly.
volatile sig_atomic_t keepRunning = 1;

void intHandler(int exitCode)
{

    keepRunning = 0;
}

int RunMe()
{
    // some unrelated code runs in here
    // preperation of sockets and threads etc.

    while (keepRunning == 1)
    {
        printf("KR:%d\n",keepRunning);
        sleep(1); // here produces the segmentation fault.
        if (iLogger.stateRequested == ITRUE)
        {
            printState(&fp);
            iLogger.stateRequested = IFALSE;
        }

    }
    // both two below closes my sockets and threads
    iLogger.Destroy();
    fp.RemoveAll(&fp);
}

int main(int argc, char *argv [])
{
    signal(SIGINT, intHandler);
    RunMe();
}


text:
Q: Pandas rolling datetime not accepting datetime offset
My dataframe is presented above. The dtypes are
weekday               int64
date         datetime64[ns]
time                 object
customers             int64
dtype: object

I'd like to sum the customers column to be the count of customers arrived in the past 2 hours (stored in column date). However, using the Pandas Rolling functionality, I can only write
df['customers'] = df['date'].rolling(2).count()

This only counts the previous two date rows completely disregarding datetime values. I'd like to write
df['customers'] = df['date'].rolling('2H').count() #desired: 2H

to get the correct result. However, I'm getting ValueError: window must be an integer. Reading the rolling documentation from pandas, a datetime object should be able to receive a rolling time window (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html). I'm completely clueless why my datetime column cannot use this functionality.

A: Create sorted DatetimeIndex:
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date').sort_index()
df['customers'] = df['customers'].rolling('2H').count()


text:
Q: Database.EnsureCreated not working I'm playing around with Entity Framework 7 versions listed below
"EntityFramework.Core": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final"

My DatabaseContext class is very simple
public class WorldContext : DbContext
{
    public DbSet<Trip> Trip { get; set; }
    public DbSet<Stop> Stop { get; set; }

    public WorldContext()
    {
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = Startup.Configuration["Data:WorldContextConnection"];

        optionsBuilder.UseSqlServer(connectionString);
        base.OnConfiguring(optionsBuilder);
    }
}

I'm experiencing a problem when hitting the Database.EnsureCreated method in the constructor. As far as I can understand, this method is supposed to make ensure that the database is created if it does not exist, otherwise it is supposed to do nothing. When I debug through my DatabaseContext class code I hit the breakpoint set on the Database.EnsureCreated method, when execution continues the breakpoint is hit a second time (This was not expected), so the DatabaseContext constructor is entered into twice for some reason. On the second hit the following exception is thrown

Even if the database exist, shouldn't the EnsureCreated method ignore it? Am I missing something here?

A: Do not call ensure created in your constructor, but call it once during app start


text:
Q: How to specify RollingUpdate settings for Celery Beat on Kubernetes We have Celery Beat set up using the following deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: celery-beat
  labels:
    deployment: celery-beat
spec:
  replicas: 1
  minReadySeconds: 120
  selector:
    matchLabels:
      app: celery-beat
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 0 # Would rather have downtime than an additional instance in service?
      maxUnavailable: 1
  template:
    metadata:
      labels:
        app: celery-beat
    spec:
      containers:
        - name: celery-beat
          image: image_url
          command: ["/var/app/scripts/kube_worker_beat_start.sh"]
          imagePullPolicy: Always
          ports:
            - containerPort: 8000
              name: http-server
          livenessProbe: #From https://github.com/celery/celery/issues/4079#issuecomment-437415370
            exec:
              command:
                - /bin/sh
                - -c
                - celery -A app_name status | grep ".*OK"
            initialDelaySeconds: 3600
            periodSeconds: 3600
          readinessProbe:
            exec:
              command:
                - /bin/sh
                - -c
                - celery -A app_name status | grep ".*OK"
            initialDelaySeconds: 60
            periodSeconds: 30
          resources:
            limits:
              cpu: "0.5" #500mcores - only really required on install
            requests:
              cpu: "30m"

I have found the RollingUpdate settings tricky because with Celery Beat you really don't want two instances, otherwise you might get duplicate tasks being completed. This is super important for us to avoid since we're using it to send out push notifications.
With the current settings, when a deployment rolls out there is 3-5mins of downtime, because the existing instance is terminated immediately and we have to wait for the new one to set itself up.
Is there a better way of configuring this reduce the downtime whilst ensuring a maximum of one service is ever in service?


text:
Q: jQuery function not executed with new parameter My function was working as intended, but then I added an additonnal parameter to the function. I want to associate different XML files to different divs of my HTML. This is how I tried to do it:
function request(){
 rssRequest();
rssRequest2();
}
    function rssRequest(){
         let url = "https://news.google.com/rss?x=1571747254.2933&hl=en-US&gl=US&ceid=US:en";
                let idContent = "world";
                $.ajax(url, {
                        method: "GET",
                        type: 'xml',
                        success: useContent($, idContent)
                     }
            )
        }

        function useContent(xmlContent, id){
            let $items = $(xmlContent).find("item");

                $items.each(function(){
                    let title = $(this).find('title').text();
        let h3 = $("<'h3'>" +title+ "</'h3'>");
        article.append(h3)
        $("#"+id).append(article)
            })
        }

Adding an alert to my code, I found out that the code after  $items.each(function(){ is not executed. How can I execute it?

A: You are missing a semicolon and closing bracket on $.ajax({..}); (at the end, just before the function useContent). Your code should look like this:
let url = "https://news.google.com/rss?x=1571747254.2933&hl=en-US&gl=US&ceid=US:en";

let idContent = "world";

$.ajax(url, {
    method: "GET",
    type: 'xml',
    success: useContent($, idContent)
});

function useContent(xmlContent, id){
    let $items = $(xmlContent).find("item");

    $items.each(function(){
        let title = $(this).find('title').text();
        let h3 = $("<'h3'>" +title+ "</'h3'>");
        article.append(h3);
        $("#"+id).append(article);
    });
}

A: You are calling useContent() before AJAX request happens. So the function doesn't receive proper parameters.
My solution to solve the problem is that use an anonymous function to pass proper arguments.
function rssRequest() {
  let url =
    "https://news.google.com/rss?x=1571747254.2933&hl=en-US&gl=US&ceid=US:en"
  let idContent = "world"
  $.ajax(url, {
    method: "GET",
    type: "xml",
    success: function(content) {
      useContent(content, idContent)
    }
  })
}


text:
Q: In a C# Windows Forms application - how does the message pump use the main/form controls thread to update the form? From my understanding, the form and all of its graphical controls run on the main thread. The form is displayed by the main thread and the inputs from the keyboard and mouse are received via the message pump and are executed on that same main thread. I also believe that the code you write also runs on that same thread, unless you create other threads for it to run on. For example, the code you write in the Form1() constructor will run on that same thread. If you make a never ending loop on that thread then the GUI will never display.
How does the code you write for that thread plus the input events received from the message pump all run in the same thread? Also, when you use Invoke on a delegate for it to run on the main thread, how does it get run on the main thread when the main thread already has a list of instructions that it is running. I don't understand how a thread can have a list of instructions that it is executing and then receive some instructions from somewhere else to run also. Does it have code to go periodically check (between running other instructions) some queue? I can understand if 2 execution paths ran on different threads, but don't understand it being on the same thread.

A: The only way you can write code for the message pump thread, commonly called the User Interface (UI) thread, is to put your code into event driven callbacks. These are events in C# terminology. Some events besides mouse, keyboard, etc include the idle event (Application.Idle), which is called when there is no other input to be dispatched.
The delegate to be dispatched on the UI thread will be executed in a similar manner to an Application.Idle handler, or by blocking until the delegate completes. There is only one stack for the UI thread, so it can only execute one call stack at a time. The thread can be pre-empted for other threads to run, but this will not execute additional code for the UI thread.
That said, sometimes you will find reentrant code on windows forms applications. There are certain calls you can make that can cause this situation. Application.DoEvents() can cause event dispatching within the call stack of an event handler. This just deepens the stack; it does not involve any other threads.


text:
Q: change nested Keyed dictionaries into nested lists of just the keys KDB+/Q I have a (0h) list (named result) of keyed dictionaries, keyed on `RIC.
I want to extract the list of RICs for each entry of result and store it in a different list that simply has the nested lists of RICs for each index. I need to be able to apply a function to each list of RICs sequentially by index, and can't figure out how to do it since result has keyed dictionaries instead of lists (the keyed dictionaries have other columns too, but RIC is the only one I'm interested in)
Sorry if this explanation is poor, but I'm really not sure how to go about this. Any advice is greatly appreciated!

A: You have a list of keyed tables. Therefore, you can use qSQL to exec the RIC column from each:
{exec RIC from x}each result

A: You have a list of keyed dictionaries. Its type is 0, so we know the dictionary keys vary.
Index At Each is all you need:
q)show dd:(`one`two`three`four`five,'`RIC)!'(`bar;)each(2+5?5)?'`3
`one`RIC!(`bar;`oco`khd`dga`eob)
`two`RIC!(`bar;`iog`edg`kio)
`three`RIC!(`bar;`gme`iko`cje`ijj)
`four`RIC!(`bar;`dlm`klp`epj`bji`gph)
`five`RIC!(`bar;`lfm`mci`pal`eho`kgi`enf)
q)type dd
0h
q)dd@'`RIC
`oco`khd`dga`eob
`iog`edg`kio
`gme`iko`cje`ijj
`dlm`klp`epj`bji`gph
`lfm`mci`pal`eho`kgi`enf

q)(dd@'`RIC) ~ {exec RIC from x}each dd
1b
q)\ts:10000 {exec RIC from x}each dd
18 1456
q)\ts:10000 dd@'`RIC
5 736

(Will also work with a list of keyed tables.)


text:
Q: JQuery UI datepicker ( start weeks from Monday) I am using jQuery UI datepicker, I know I can customize this datepicker in this way:
$("#reserve_date").datepicker({
            beforeShowDay: no_disabled_Days
});

currently, my datapicker calendar start weeks from Sunday, I would like it starts weeks from Monday, how to do??

A: $( ".selector" ).datepicker({ firstDay: 1 });

jQuery UI Reference; see the link for a slightly more detailed explanation.
For inline reference:
Sunday     0
Monday     1
Tuesday    2
Wednesday  3
Thursday   4
Friday     5
Saturday   6


text:
Q: Formatting Kunkunshi: Okinawan sheet music I've gotten stuck trying to figure out a way to make Okinawan sheet music called "Kunkunshi" (see image below).

Basically, I'm trying to make a grid of Japanese Characters. There should be twelve squares in a column, separated by a gap about 66% of the width of the squares. The characters should be either centered in the square, or in a smaller font in the middle of two squares. Ideally, lyrics could be written along side the characters in the grid as shown in the image.
The closest help I could find was this question about Japanese handwriting templates.

A: The following will provide something to start with. There is a loop to draw the grid, and a rudimentary API to put letters at some cells, lines or "lyrics" places. Ask for clarification in the comments if needed.
\documentclass [border=2mm]{standalone}
\usepackage{tikz}

\begin{document}

\def\atcenter#1#2#3{
  % Puts #3 at cell (#1,#2)
  \path (#1,#2) +(.3,.5) node {#3};
}

\def\atline#1#2#3{
  % Puts #3 at the line between cells (#1, #2-0.5) and (#1, #2+0.5)
  \path (#1,#2) +(.3,.5) node[fill=white, font=\tiny, inner xsep=1mm, inner ysep=0] {#3};
}

\def\lyrics#1#2#3{
  % Puts #3 at the right side of the column #1, at fractional y-coordinate #2
  \path (#1,.5) +(.6,#2) node[font=\tiny,anchor=west, inner sep=0.5mm] {#3};
}

\begin{tikzpicture}[x=10mm,y=-6mm]

    % Draw the grid
    \draw[thick] (1,1) rectangle (11,13);
    \foreach \column in {1,...,10} {
      \foreach \row in {1,...,12} {
         \draw (\column,\row) rectangle +(0.6,1);
         }
    }

    % Some example letters in cells
    \foreach \letter [count=\i  from 1] in {A,B,C,D,E,F,G,H,I,J,K,L} {
      \atcenter{10}{\i}{\letter};
    }

    % Some example letters at lines
    \atline{10}{2.5}{a};
    \atline{10}{3.5}{b};

    % Another column with letter
    \foreach \letter [count=\i  from 1] in {M,N,O,P,Q,R} {
      \atcenter{9}{\i}{\letter};
    }

    % Example "lyrics". Note the expression used as #2
    \foreach \letter [count=\i from 1] in {f,o,o,b,a,r} {
      \lyrics{9}{3+\i*0.4}{\letter}
    }
\end{tikzpicture}
\end{document}

Above code produces:

Update
Just for fun, tried it with japanese characters, to see if it would work. It worked! (requires xelatex and AozoraMinchoRegular.ttf font, which is free).
Disclaimer I don't understand a word of Japanese :-)
Code:
\documentclass [border=2mm]{standalone}
\usepackage{xeCJK}
\setCJKmainfont{AozoraMinchoRegular.ttf}
\usepackage{tikz}

\begin{document}

\def\atcenter#1#2#3{
  % Puts #3 at cell (#1,#2)
  \path (#1,#2) +(.3,.5) node {#3};
}

\def\atline#1#2#3{
  % Puts #3 at the line between cells (#1, #2-0.5) and (#1, #2+0.5)
  \path (#1,#2) +(.3,.5) node[fill=white, font=\tiny, inner xsep=1mm, inner ysep=0] {#3};
}

\def\lyrics#1#2#3{
  % Puts #3 at the right side of the column #1, at fractional y-coordinate #2
  \path (#1,.5) +(.6,#2) node[font=\tiny,anchor=west, inner sep=0.5mm] {#3};
}

\begin{tikzpicture}[x=10mm,y=-6mm]

    % Draw the grid
    \draw[thick] (1,1) rectangle (11,13);
    \foreach \column in {1,...,10} {
      \foreach \row in {1,...,12} {
         \draw (\column,\row) rectangle +(0.6,1);
         }
    }

    % Some example letters in cells
    \foreach \letter [count=\i  from 1] in {中,中,工,上,四,合,四,五,中,中,工,上}
    {
      \atcenter{10}{\i}{\letter};
    }

    % Some example letters at lines
    \atline{10}{2.5}{五};
    \atline{10}{3.5}{中};

    % Another column with letter
    \foreach \letter [count=\i  from 1] in {四,合,四,五,中,中,工,上}
    {
      \atcenter{9}{\i}{\letter};
    }

    % Example "lyrics". Note the expression used as #2
    \foreach \letter [count=\i from 1] in {日,本,語,で} {
      \lyrics{9}{3+\i*0.5}{\letter}
    }
\end{tikzpicture}
\end{document}

Result:


text:
Q: When woken up from sleep, some Chrome windows are blurry I have a 2nd monitor attached to my Retina MBP. I was on OS X Mavericks and had this problem, where sometimes the displays would go to sleep and when I wake them, many tabs within Chrome look blurry on my main Retina screen.
When I move the tabs over to the non-retina monitor, it actually fixed it. i.e. the solution is to temporarily move the tab to the non-retina monitor (drop it there) and then bring it back and all of a sudden it looks crispy clear again.
Obviously this is a non-scalable/sustainable strategy.
I assumed that by upgrading to Yosemite that would take care of that, but it didn't. I am still seeing it.
Not all tabs are blurry, and the only ones that seem to be blurry are my Chrome tabs. I haven't tried Safari or anything else yet.
Any ideas for what may be causing this?
Here is a screenshot of a Chrome tab looking blurry.

A: Not 100% sure, but It looks like the latest stable release (39.0.2171.71, released 11/25), may have fixed this.

A: Is the external monitor always connected to your machine?
I'm not sure this will work or if this is a viable solution, but try to set the external monitor as your primary display and report back.


text:
Q: How I Delete File after uploading in ASP.net FileUpload Control string savePath = Server.MapPath("\\Upload_File\\");
// Get the name of the file to upload.
string fileName = email_attach.FileName;
string pathToCheck = savePath + fileName;

email_attach.SaveAs(pathToCheck);

string file = pathToCheck;
Attachment data = new Attachment(file);
mail.Attachments.Add(data);

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
email_attach.Dispose();
FileInfo file_Delete = new FileInfo(pathToCheck);
if (file_Delete.Exists)
{
    file_Delete.GetAccessControl();
    file_Delete.Delete();
}

when i did this it throws exception like

An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code
Additional information: The process cannot access the file 'C:\Users\User\Documents\Visual Studio 2013\WebSites\Email_Sent_Web\Upload_File\DMP.edx' because it is being used by another process.

how i solve plz help ,thanks in Advance

A: Try to write data.Dispose(); below  mail.Attachments.Add(data);


text:
Q: ListView and MapActivity under Tab using classes I am trying to put a MapActivity and a ListActivity in Tabs. I found a way of doing it, but I just don't like the way it looks like (I rather use some classes to make my code more modular)
Now, I have this code in my main activity:
Resources res = getResources(); // Resource object to get Drawables
TabHost.TabSpec spec;  // Resusable TabSpec for each tab
Intent intent;  // Reusable Intent for each tab
intent = new Intent().setClass(this, OptionsActivity.class);

 spec = tabHost.newTabSpec(OPTS_TAB_TAG).setIndicator("Options",
                          res.getDrawable(R.drawable.ic_tab_options))
                          .setContent(intent);
 tabHost.addTab(spec);

And this one in the OptionsActivity class:
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class OptionsActivity extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

String[] options = getResources().getStringArray(R.array.options_array);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options));

ListView lv = getListView();

lv = (ListView) findViewById(R.id.opt);
lv.setEmptyView((TextView) findViewById(R.id.options));

lv.setTextFilterEnabled(true);

lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, options));

}

}

and my layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/main">
                <ListView
                    android:id="@+id/list"
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight="1" />
                <TextView
                    android:id="@+id/empty"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

                <ListView
                    android:id="@+id/opt"
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight="1" />
                <TextView
                    android:id="@+id/options"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <RelativeLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/mainlayout"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
                <com.google.android.maps.MapView
                    android:id="@+id/mapview"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:clickable="true"
                    android:apiKey="0fFbO-eNMhj2lDaC6b4YBfpo1DikBMixPYiEJCw" />
            </RelativeLayout>

        </FrameLayout>
    </LinearLayout>
</TabHost>

But for some reason, when I select this "Options" tab, my application has a force close...
Can someone show me what I'm doing wrong here?

A: you are not using any layout so from where you are getting lv = (ListView) findViewById(R.id.opt); put code in try catch block like this
     try{
     ListView lv = getListView();
 lv = (ListView) findViewById(R.id.opt);
 lv.setEmptyView((TextView) findViewById(R.id.options));
 lv.setTextFilterEnabled(true);
 lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, options));
 }catch(Exception e){
 e.getMessage();       ///Put break point here to find error
  }

then debug it once


text:
Q: I want the tokenized sentences along with their positions The end result should be a dictionary in which the keys are the names of your texts and the values are lists of lists. Each embedded list should be a sentence, tokenized into words.
The dictionary should therefore look something like this:
{'Text1 Name':[['this', 'is', 'sentence', '1'], ['this', 'is', 'sentence', '2'], ...],
'Text2 Name': [['this', 'is', 'sentence', '1'], ['this', 'is', 'sentence', '2'], ...],
...}
I want the output to print its position along with the sentences.

from nltk import word_tokenize, sent_tokenize
sent_tokenize(text)
I have converted the text into sentences but i need it in the above form.

op:

['The Project Gutenberg EBook of On the Origin of Species, by Charles Darwin\r\n\r\nThis eBook is for the use of anyone anywhere at no cost and with\r\nalmost no restrictions whatsoever.',
'You may copy it, give it away or\r\nre-use it under the terms of the Project Gutenberg License included\r\nwith this eBook or online at www.gutenberg.org\r\n\r\n** This is a COPYRIGHTED Project Gutenberg eBook, Details Below \r\n     Please follow the copyright guidelines in this file.',
'\r\n\r\nTitle: On the Origin of Species\r\n\r\nAuthor: Charles Darwin\r\n\r\nPosting Date: May 7, 2011 [EBook #8205]\r\nRelease Date: June, 2005\r\nFirst Posted: July 2, 2003\r\n\r\nLanguage: English\r\n\r\nCharacter set encoding: ASCII\r\n\r\n* START OF THIS PROJECT GUTENBERG EBOOK ON THE ORIGIN OF SPECIES ***\r\n\r\n\r\n\r\n\r\nProduced by Steve Eccles\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nOn the Origin of Species\r\n\r\nby Charles Darwin\r\n\r\n\r\n\r\nAudio production Copyright (C) 2003 by Steve Eccles\r\n\r\n\r\n\r\nThis copyrighted audio performance is based on Project Gutenberg's\r\npublic domain eBook, "On the Origin of Species."',
'This file is for the Identification of the maker of this CD ROM Audio,\r\nComputer Read, Book: "On the Origin of Species" by Charles Darwin.',
'CD ROM: Completed on the 4th of April, 2003.',