问:
Looping jquery function load() using php mysql doesn't work it loop first row only
I need to show the posts count depend on topic id using auto load jquery load() after looping the result using php but unfortunately it shows the first row and uses that first row to show another count and change again
Any Help please!

index.php

```<code>    <?php
    foreach($t_all_rows as $row){
            ?>
         <tr>
             <td class="text-center hidden-xs hidden-sm">
                 <a class="font-w600" href="javascript:void(0)">
                    <script type="text/javascript">
                                    var auto_refresh = setInterval(
                                    function ()
                                    {
            $('#load_posts').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
                                    }, 1000); // refresh every 5000 milliseconds
                                    </script>

                                   <span id="load_posts"></span>
                </a>
          </td>
       </tr>
       <?php } ?>
</code>```

get_posts.php

```<code>    include('connection.php');
    $db=new DB();
    $conn=$db->db_connect();
    $my_t_id=$_GET['t_id'];
    $post_query = mysqli_query($conn,'SELECT * FROM post WHERE t_id = "'.$my_t_id.'"');
    $record_count=mysqli_num_rows($post_query);
    //Display count.........
    echo $record_count;
</code>```

答:
that is normal, because get only first div by ID, change the span id or add a new class with loop number

Adding $k

```<code>    foreach($t_all_rows as $k =>  $row){
</code>```

Adding new class

```<code><span id="load_posts" class="load_post<?=$k?>"></span>
</code>```

change jquery code:

```<code>$('.load_post<?=$k?>').load
</code>```

But importan, I am suggest to you, to upgrate the mysql query using JOIN and not use jquery

Body:
I need to show the posts count depend on topic id using auto load jquery load() after looping the result using php but unfortunately it shows the first row and uses that first row to show another count and change again
Any Help please!

index.php

    <?php
    foreach($t_all_rows as $row){
            ?>

       <?php } ?>

get_posts.php

    include('connection.php');
    $db=new DB();
    $conn=$db->db_connect();
    $my_t_id=$_GET['t_id'];
    $post_query = mysqli_query($conn,'SELECT * FROM post WHERE t_id = "'.$my_t_id.'"');
    $record_count=mysqli_num_rows($post_query);
    //Display count.........
    echo $record_count;

Body:
that is normal, because get only first div by ID, change the span id or add a new class with loop number

Adding $k

    foreach($t_all_rows as $k =>  $row){

Adding new class

<span id="load_posts" class="load_post<?=$k?>"></span>

change jquery code:

$('.load_post<?=$k?>').load

But importan, I am suggest to you, to upgrate the mysql query using JOIN and not use jquery


来源: stackexchange

问:
Casting, unboxing, conversion..?
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?</p>

```<code>int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting
</code>```

答:
A cast is one form of conversion, basically.

All the comments in your code are correct.

It's important to note the difference between a reference conversion and other conversions, however. The final conversion you've shown is a reference conversion - it maintains representational identity, so the values of X and R are both references to the same object.

Compare this with a double to int conversion (changes form significantly) and unboxing (copies the value from inside the box to the variable).

The difference is important for some topics such as generic variance - that only works with reference types because of the reference conversions available. Basically the CLR checks that it all the types are appropriate, and then runs the appropriate code without ever having to perform any actual conversions on the references themselves.

ContentLicense: CC BY-SA 2.5

Title: Casting, unboxing, conversion..?

Body:
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?

int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting


问:
Storing and processing a lot of tiny files
There are a lot of files with size from 1Kb to 5Mb on our servers. Total size of those files is about 7Tb.  Process algorithm - read and make some decisions about this file. Files may have several formats: doc, txt, png, bmp and etc. Therefore I can't merge those files to get bigger files.
How I can effectively store and process those files? What technology fits well to this task?</p>

答:
You can use various technologies to store and process these files. Below mentioned are the technologies that you can use.

1 Apache Kafka: You can create different topics for each format and push your data in these topics.
Advantage :

Based on your load you can easily increase your consumption speed.

2 Hadoop: you can store your data in hdfs the format and can design MR jobs to process.

3 You can use any document storage NOSQL database to store your data

Note: All the above solutions will store your data in distributed format and you can run it on commodity machines

Store your data in clouds(AWS, Google, Azure) and use there API to get and process the data. (If you want your data to be shared with the other applications also)

ContentLicense: CC BY-SA 3.0


问:
Getting the remaining energy of the battery?
Hy i am just developing and energy profiling application for which i need to have current energy of battery in nanowatt-hours. I have tried using Battery Manager API but the problem with it is that it requires a certain micro-chip called fuel-gauge to get these values. My question is that is there any other way of getting current energy of battery without using fuel gauge? Also i have managed to get current capacity of battery in percentage using BatteryManager API  which means that my code is working fine.</p>

答:
I have solution for your problem, use this code:

```<code>   BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
    int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

    double capacity = getBatteryCapacity(this);

    double remaining = (capacity*batLevel)/100;

    Log.d("Capapcity Remaining",remaining+" ");
</code>```

and getBatteryCapacity() implementation is here.

```<code>  public double getBatteryCapacity(Context context) {
    Object mPowerProfile;
    double batteryCapacity = 0;
    final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

    try {
        mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
                .getConstructor(Context.class)
                .newInstance(context);

        batteryCapacity = (double) Class
                .forName(POWER_PROFILE_CLASS)
                .getMethod("getBatteryCapacity")
                .invoke(mPowerProfile);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return batteryCapacity;

}
</code>```

Note: it will not give exact result, but will provide appropriate result for your need.

Body:
I have solution for your problem, use this code:

   BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
    int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

    double capacity = getBatteryCapacity(this);

    double remaining = (capacity*batLevel)/100;

    Log.d("Capapcity Remaining",remaining+" ");

and getBatteryCapacity() implementation is here.

  public double getBatteryCapacity(Context context) {
    Object mPowerProfile;
    double batteryCapacity = 0;
    final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

    try {
        mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
                .getConstructor(Context.class)
                .newInstance(context);

        batteryCapacity = (double) Class
                .forName(POWER_PROFILE_CLASS)
                .getMethod("getBatteryCapacity")
                .invoke(mPowerProfile);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return batteryCapacity;

}

Note: it will not give exact result, but will provide appropriate result for your need.


问:
I need to create a random number generator in php using mt_rand which should only generate random numbers
I need to create a random number generator in php using mt_rand which should only generate random numbers. I know I need to use an infinite loop. How can I achieve this?

This is what I've already tried:

```<code>$query = "SELECT * FROM random";
$result = mysqli_query($link,$query);
$rows = mysqli_num_rows($result);
for($j = 0; $j < $rows; ++$j) {
    $row=mysqli_fetch_assoc($result);
    if($row["randomcol"]==$a) {
    do {
        echo "\n fetched";
        echo $row["randomcol"];
        echo "\n generated";
        echo $a;
        echo "\n repetition";
        $a=mt_rand(1,10);
        echo "\n Just after regeneration";
        echo $a;
    } while ($row["randomcol"]==$a);
 }
}
</code>```

答:
I have created sample random generator function in php. You can change length and characters according to your need.</p>

```<code>function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
</code>```

Body:
I need to create a random number generator in php using mt_rand which should only generate random numbers. I know I need to use an infinite loop. How can I achieve this?

This is what I've already tried:

$query = "SELECT * FROM random";
$result = mysqli_query($link,$query);
$rows = mysqli_num_rows($result);
for($j = 0; $j < $rows; ++$j) {
    $row=mysqli_fetch_assoc($result);
    if($row["randomcol"]==$a) {
    do {
        echo "\n fetched";
        echo $row["randomcol"];
        echo "\n generated";
        echo $a;
        echo "\n repetition";
        $a=mt_rand(1,10);
        echo "\n Just after regeneration";
        echo $a;
    } while ($row["randomcol"]==$a);
 }
}

Body:
I have created sample random generator function in php. You can change length and characters according to your need.

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}


问:
Django | Displaying events grouped by month in custom format?
I have the following models:

```<code>class Event(Page)
    # my fields
    start_date = models.DateField()
    end_date = models.DateField()

class EventsIndex(Page):
    # my fields

    def get_events(self):
        events = Event.objects.all().sort_by("start_date")
        return events
</code>```

In my EventsIndex template I have 4 tabs which show the current month, the next month, the month after next and then a final tab called "Later" which should display the individual Events grouped by month:

I'm trying to figure out the logic for which to get these events to display. The individual month tabs should only display the events, whereas the "Later" tab should display a heading of the month of the events and then the events themselves. Initially I thought about creating a function for each tab, so something like:

```<code>def current_month_events(self):
    current_month, current_year = datetime.now().month, datetime.now().year
    events = Event.objects.filter(start_date__year=current_year,
                  start_date__month=current_month).order_by("start_date")
    return events

# Repeat for all required tabs
</code>```

However this seems to go against the DRY principle. Is there a more pythonic way to handle this logic?

答:
I've always been quite annoyed about the lack of support for this type of thing in Django.

Unless you're doing aggregation then it's not terribly well supported.

The most pythonic / Djangorrific way I can find to do it is in the template, using groupby there.  (This seems to me to go against the concept of not putting business logic in templates, but there you are.)

In your case, you'd do something like this in the views.py file:

```<code>from datetime import date, timedelta
today = date.today()
four_months_time  = today + timedelta(months=4)
events = Event.objects.filter(start_date__gte=today, start_date__lte=
                  four_months_time).order_by("start_date")`
</code>```

and in the templates (assuming you pass back events as the variable):

```<code>{% regroup events by start_date.month as events_list %}
<ul>
{% for event in events_list %}
    <li>{{ event.grouper }}
    <ul>
        {% for event in event.list %}
          <li>{{event}}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
</code>```

This is untested, but should send you on the right direction!

Body:
I have the following models:

class Event(Page)
    # my fields
    start_date = models.DateField()
    end_date = models.DateField()

class EventsIndex(Page):
    # my fields

    def get_events(self):
        events = Event.objects.all().sort_by("start_date")
        return events

In my EventsIndex template I have 4 tabs which show the current month, the next month, the month after next and then a final tab called "Later" which should display the individual Events grouped by month:

I'm trying to figure out the logic for which to get these events to display. The individual month tabs should only display the events, whereas the "Later" tab should display a heading of the month of the events and then the events themselves. Initially I thought about creating a function for each tab, so something like:

def current_month_events(self):
    current_month, current_year = datetime.now().month, datetime.now().year
    events = Event.objects.filter(start_date__year=current_year,
                  start_date__month=current_month).order_by("start_date")
    return events

# Repeat for all required tabs

However this seems to go against the DRY principle. Is there a more pythonic way to handle this logic?

Body:
I've always been quite annoyed about the lack of support for this type of thing in Django.

Unless you're doing aggregation then it's not terribly well supported.

The most pythonic / Djangorrific way I can find to do it is in the template, using groupby there.  (This seems to me to go against the concept of not putting business logic in templates, but there you are.)

In your case, you'd do something like this in the views.py file:

from datetime import date, timedelta
today = date.today()
four_months_time  = today + timedelta(months=4)
events = Event.objects.filter(start_date__gte=today, start_date__lte=
                  four_months_time).order_by("start_date")`

and in the templates (assuming you pass back events as the variable):

{% regroup events by start_date.month as events_list %}
<ul>
{% for event in events_list %}
    <li>{{ event.grouper }}
    <ul>
        {% for event in event.list %}
          <li>{{event}}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

This is untested, but should send you on the right direction!


问:
Training trained seq2seq model on additional training data
I have trained a seq2seq model with 1M samples and saved the latest checkpoint. Now, I have some additional training data of 50K sentence pairs which has not been seen in previous training data. How can I adapt the current model to this new data without starting the training from scratch?</p>

答:
You do not have to re-run the whole network initialization. You may run an incremental training.

Training from pre-trained parameters

Another use case it to use a base model and train it further with new training options (in particular the optimization method and the learning rate). Using -train_from without -continue will start a new training with parameters initialized from a pre-trained model.

Remember to tokenize your 50K corpus the same way you tokenized the previous one.

Also, you do not have to use the same vocabulary beginning with OpenNMT 0.9. See the Updating the vocabularies section and use the appropriate value with -update_vocab option.


问:
Why does Matplotlib's PdfPages print tabs as boxes (font encoding)?
when I run a modified version of Matplotlib's multi page example with a tab added to the title, I get the following output:

This is my working example. The comments above the code are suggestions I found here and in Non-ASCII characters in Matplotlib, but no success so far.

```<code># -*- coding: utf-8 -*-
import matplotlib
from matplotlib.backends.backend_pdf import PdfPages
from pylab import *

#matplotlib.rc('font', family='DejaVu Sans')

#matplotlib.rc('font', **{'sans-serif' : 'Arial',
#                           'family' : 'sans-serif'})

#matplotlib.rcParams['pdf.fonttype'] = 42
#matplotlib.rcParams['ps.fonttype'] = 42

pdf = PdfPages('multipage_pdf.pdf')

figure(figsize=(3,3))
plot(range(7), [3,1,4,1,5,9,2], 'r-o')
title('Page\tOne')
savefig(pdf, format='pdf') # note the format='pdf' argument!
close()

pdf.close()
</code>```

Any ideas how this could be solved?

答:
The solution is to add

```<code>matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
</code>```

as mentioned here and here.

I couldn't find out which line does the magic, not all seemed to be needed in my case, but I just added all. If there is a problem with tex complaining about not being able to encode something, you might be able to comment the ['text.usetex'] with it still working.

From the matplotlib doc:

Add "pdf.use14corefonts: True" in your configuration file to use only
  the 14 PDF core fonts. These fonts do not need to be embedded; every
  PDF viewing application is required to have them. This results in very
  light PDF files you can use directly in LaTeX or ConTeXt documents
  generated with pdfTeX, without any conversion.

These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
  Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
  Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
  Times-BoldItalic, Symbol, ZapfDingbats.

Body:
when I run a modified version of Matplotlib's multi page example with a tab added to the title, I get the following output:

This is my working example. The comments above the code are suggestions I found here and in Non-ASCII characters in Matplotlib, but no success so far.

# -*- coding: utf-8 -*-
import matplotlib
from matplotlib.backends.backend_pdf import PdfPages
from pylab import *

#matplotlib.rc('font', family='DejaVu Sans')

#matplotlib.rc('font', **{'sans-serif' : 'Arial',
#                           'family' : 'sans-serif'})

#matplotlib.rcParams['pdf.fonttype'] = 42
#matplotlib.rcParams['ps.fonttype'] = 42

pdf = PdfPages('multipage_pdf.pdf')

figure(figsize=(3,3))
plot(range(7), [3,1,4,1,5,9,2], 'r-o')
title('Page\tOne')
savefig(pdf, format='pdf') # note the format='pdf' argument!
close()

pdf.close()

Any ideas how this could be solved?

Body:
The solution is to add

matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True

as mentioned here and here.

I couldn't find out which line does the magic, not all seemed to be needed in my case, but I just added all. If there is a problem with tex complaining about not being able to encode something, you might be able to comment the ['text.usetex'] with it still working.

From the matplotlib doc:

Add "pdf.use14corefonts: True" in your configuration file to use only
  the 14 PDF core fonts. These fonts do not need to be embedded; every
  PDF viewing application is required to have them. This results in very
  light PDF files you can use directly in LaTeX or ConTeXt documents
  generated with pdfTeX, without any conversion.

These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
  Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
  Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
  Times-BoldItalic, Symbol, ZapfDingbats.


问:
What is your method of "folksonomy" tagging for files on your local machine?
Way back in the days when "delicious" was just "del.icio.us", I had assumed that everyone had finally caught on that Ontology is overrated.

So why am I still having to roll my own tagging system using sqlite and a bunch of ruby scripts in order to address this obvious deficiency on my own local machine? I can tag on-line web links, blog posts, questions on stackoverflow.com, and all kinds of web-centric miscellany, but this very basic concept still seems to be missing (or hideously crippled) in the few operating systems I get to use. Perhaps I am just using the wrong OSs?

From what I've seen out there, the pickins' seem pretty slim.

What do you use?

答: I find that if I have to enter the data, to find the files then I won't do it.  It takes too much time to think of good tags and apply them.  I find it much easier to just drop my stuff into a hierarchy I can remember and be done with it.  The hierarchy might not be perfect, and it may take slightly longer to find stuff, but it's better than spending tons of time entering tags for every file I create.</p>

OwnerDisplayName: dreftymac

OwnerDisplayName: Kibbee


问:
How to set callback function on submit button in bootstrap?
I use bootstrap modal dialog as the user register form as below:

```<code><form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form>
</code>```

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

```<code>$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}
</code>```

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

答:
You can do it like this:

```<code>$("#signup-submit-button").click(function() {
  signup(function() {
    alert("callback is called")
  })
});

function signup(callback) {
  alert("function before callback")
  callback();
}
</code>```

This will run the code inside function signup first and then fire the callback after

demo

$("#signup-submit-button").click(function() {
  signup(function() {
    alert("callback is called")
  })
});

function signup(callback) {
  alert("function before callback")
  callback();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label for="user-name-input">User Name</label>
          <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
        </div>
        <div class="form-group">
          <label for="user-email-input">Email address</label>
          <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
        </div>
        <div class="form-group">
          <label for="userPasswordInput">Password</label>
          <input type="password" class="form-control" id="user-password-input" placeholder="Password">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
      </div>
    </div>
  </div>
</form></code>```

Body:
I use bootstrap modal dialog as the user register form as below:

<form>

Sign Up

                            User Name
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>

                            Email address
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>

                            Password
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>

        </form>

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

Body:
You can do it like this:

$("#signup-submit-button").click(function() {
  signup(function() {
    alert("callback is called")
  })
});

function signup(callback) {
  alert("function before callback")
  callback();
}

This will run the code inside function signup first and then fire the callback after

demo

$("#signup-submit-button").click(function() {
  signup(function() {
    alert("callback is called")
  })
});

function signup(callback) {
  alert("function before callback")
  callback();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label for="user-name-input">User Name</label>
          <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
        </div>
        <div class="form-group">
          <label for="user-email-input">Email address</label>
          <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
        </div>
        <div class="form-group">
          <label for="userPasswordInput">Password</label>
          <input type="password" class="form-control" id="user-password-input" placeholder="Password">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
      </div>
    </div>
  </div>
</form>


问:
getting empty body while sending post request using volley Android
When I am making POST request call using JsonObjectRequest in volley then on certain wifi it is sending empty body. But it works fine with StringRequest POST request. It is working fine on all mobile networks.

I am using node.js server and expressjs/body-parser. When I am making POST request using Postman, everything works fine.

What is the error? If anyone wants to see code I can provide.

POST request using StringRequest

```<code>  private void LoginUser(final String email,final String pass) {

        try {

            /*Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);*/

            final StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();

                            try
                            {
                                Log.i("Inside try", "yes");
                                JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
                                Log.i("User name",jsonResponse.getString("name"));
                                Constants.setClinicName(jsonResponse.getString("name"));

                                String TokenDB=new JSONObject(response).getString("token");

                                //Toast.makeText(getApplicationContext(),TokenDB,Toast.LENGTH_LONG).show();

                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }

                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);

                            }catch (JSONException ks)
                            {
                                ks.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                            }

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

                        }
                    }){
                @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("username", email);
                    params.put("password", pass);
                    return params;
                }

            };

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(stringRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

POST call using JsonobjectRequest

```<code>private void LoginUser(String email,String pass) {

        try {

            Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);
            JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, jsonParams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // Parsing json object response
                                // response will be a json object
                                String TokenDB = response.getString("token");
                                JSONObject user=response.getJSONObject("user");
                                Constants.setClinicName(user.getString("name"));

                                //Constants.setTokenDB(TokenDB);
                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }

                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);
                                }
                            catch (JSONException e)
                            {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                              }

                    }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
            };

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            postRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(postRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

答:
```<code>package com.example.mwakidoshi;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by Sly on 2017-11-17.
 */

public class CustomRequest extends Request<JSONObject> {
    private Response.Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = responseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

            return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }
}
</code>```

Body:
When I am making POST request call using JsonObjectRequest in volley then on certain wifi it is sending empty body. But it works fine with StringRequest POST request. It is working fine on all mobile networks.

I am using node.js server and expressjs/body-parser. When I am making POST request using Postman, everything works fine.

What is the error? If anyone wants to see code I can provide.

POST request using StringRequest

  private void LoginUser(final String email,final String pass) {

        try {

            /*Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);*/

            final StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();

                            try
                            {
                                Log.i("Inside try", "yes");
                                JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
                                Log.i("User name",jsonResponse.getString("name"));
                                Constants.setClinicName(jsonResponse.getString("name"));

                                String TokenDB=new JSONObject(response).getString("token");

                                //Toast.makeText(getApplicationContext(),TokenDB,Toast.LENGTH_LONG).show();

                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }

                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);

                            }catch (JSONException ks)
                            {
                                ks.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                            }

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

                        }
                    }){
                @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("username", email);
                    params.put("password", pass);
                    return params;
                }

            };

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(stringRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

POST call using JsonobjectRequest

private void LoginUser(String email,String pass) {

        try {

            Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);
            JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, jsonParams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // Parsing json object response
                                // response will be a json object
                                String TokenDB = response.getString("token");
                                JSONObject user=response.getJSONObject("user");
                                Constants.setClinicName(user.getString("name"));

                                //Constants.setTokenDB(TokenDB);
                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }

                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);
                                }
                            catch (JSONException e)
                            {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                              }

                    }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
            };

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            postRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(postRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


问:
How to set an element style :focus without style :hover
Please tell me whether it is possible to use style :focus without style :hover, i.e. when the element is not selected and the mouse cursor is moved to it, then the style :hover is applied, and when the element is selected and the mouse cursor is hovered, the style :hover is not applied?

For example:

```<code>input:focus {
    border: 1px solid red;
}

input:hover {
    border: 1px solid orange;
}
</code>```

New maybe:

```<code>input:focus:not[':hover'] {
    border: 1px solid red;
}

input:hover {
    border: 1px solid orange;
}
</code>```

答:
try the below example

NB:It's just a sample you can change as per your needs.

a:hover:not(:focus) {
  color: default;
}

a:focus {
  color: green;
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Test!</code>```

Body:
Please tell me whether it is possible to use style :focus without style :hover, i.e. when the element is not selected and the mouse cursor is moved to it, then the style :hover is applied, and when the element is selected and the mouse cursor is hovered, the style :hover is not applied?

For example:

input:focus {
    border: 1px solid red;
}

input:hover {
    border: 1px solid orange;
}

New maybe:

input:focus:not[':hover'] {
    border: 1px solid red;
}

input:hover {
    border: 1px solid orange;
}

Body:
try the below example

NB:It's just a sample you can change as per your needs.

a:hover:not(:focus) {
  color: default;
}

a:focus {
  color: green;
}

<a href="https://www.google.com">Test!</a>


答: Boxing and Unboxing specifically refer to casting value types to reference types and back again. Check out this link for more Boxing and Unboxing (C# Programming Guide).</p>

Title: Casting, unboxing, conversion..?


问:
function not working properly, codeigniter
The function is fetching data from the database, but the issue is, it is not fetching the next row after printing the first row.

Kindly check and tell me what I'm doing wrong?

```<code>Public function Return_Config($P_name, $WW, $KPI) {
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name .= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
    //echo $select_query;

    $query = $this->db->query($select_query);
    if ($query->row() > '0') {
        return $query->row()->config;
    } else {
        return 'Not Measured';
    }
}
</code>```

It is going directly to the else part. please help

答:
This is because you are using ->row() instead use ->result(), like:

```<code>Public function Return_Config($P_name, $WW, $KPI)
{
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name.= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";

    // echo $select_query;

    $query = $this->db->query($select_query);
    if (!empty($query->result()))
    {
        return $query->result();
    }
    else
    {
        return 'Not Measured';
    }
}
</code>```

More details at https://www.codeigniter.com/userguide3/database/results.html

Body:
The function is fetching data from the database, but the issue is, it is not fetching the next row after printing the first row.

Kindly check and tell me what I'm doing wrong?

Public function Return_Config($P_name, $WW, $KPI) {
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name .= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
    //echo $select_query;

    $query = $this->db->query($select_query);
    if ($query->row() > '0') {
        return $query->row()->config;
    } else {
        return 'Not Measured';
    }
}

It is going directly to the else part. please help

Body:
This is because you are using ->row() instead use ->result(), like:

Public function Return_Config($P_name, $WW, $KPI)
{
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name.= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";

    // echo $select_query;

    $query = $this->db->query($select_query);
    if (!empty($query->result()))
    {
        return $query->result();
    }
    else
    {
        return 'Not Measured';
    }
}

More details at https://www.codeigniter.com/userguide3/database/results.html


问:
Route in codeigniter3
I am learning codeigniter 3

In my config.php:

```<code>$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/ci3x/admin/';
</code>```

In my routes.php:

```<code>$route['customer'] = 'customer/index';
</code>```

In controllers/customer.php:

```<code>class Customer extends MY_Controller{
    function index(){
    // some code here
    }
}
</code>```

When I type: http://localhost/ci3x/admin/customer on brower, it back error 404.
I have no clue to fix, please help me to solve it.
Many thanks

答:
As you are extending a Class and that class does have a constructor, your class needs a constructor that also calls the constructor of the extended class.

Else things won't get up and running correctly.

```<code>class Customer extends MY_Controller{

    public function __construct() {
        parent::__construct(); // Call the MY_Controller constructor
    }

    function index(){
    // some code here
    }
}
</code>```

The same goes for your MY_Controller constructor as it will need to call CI_Controller constructor... It ripples down and everything gets initialised correctly (in simplistic terms) .

Note:
Be careful with your controller and method files names. If you read the user guide it will say that the file names for controllers and methods should start with a capital letter.

So your controllers/customer.php should be controllers/Customer.php. If you are running on Windows it won't care. If you are running on Linux it will definitely matter.

Title: Route in codeigniter3

Body:
I am learning codeigniter 3

In my config.php:

$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/ci3x/admin/';

In my routes.php:

$route['customer'] = 'customer/index';

In controllers/customer.php:

class Customer extends MY_Controller{
    function index(){
    // some code here
    }
}

When I type: http://localhost/ci3x/admin/customer on brower, it back error 404.
I have no clue to fix, please help me to solve it.
Many thanks

Body:
As you are extending a Class and that class does have a constructor, your class needs a constructor that also calls the constructor of the extended class.

Else things won't get up and running correctly.

class Customer extends MY_Controller{

    public function __construct() {
        parent::__construct(); // Call the MY_Controller constructor
    }

    function index(){
    // some code here
    }
}

The same goes for your MY_Controller constructor as it will need to call CI_Controller constructor... It ripples down and everything gets initialised correctly (in simplistic terms) .

Note:
Be careful with your controller and method files names. If you read the user guide it will say that the file names for controllers and methods should start with a capital letter.

So your controllers/customer.php should be controllers/Customer.php. If you are running on Windows it won't care. If you are running on Linux it will definitely matter.


问:
Navigate to parent path from router outlet (NG5)
Problem

Trying to navigate from http://localhost:4200/#/place/(popup:tabs-modal)
(an outlet) to http://localhost:4200/#/place/someId

Notice that the outlet is basically a child route to "place".

What I can do

I can close the outlet, and just end up on: http://localhost:4200/#/place: this.router.navigate(['place', { outlets: { popup: null } }]);

Oh then its easy right?

this.router.navigate(['place', 'someId', { outlets: { popup: null } }]);should then navigate me to http://localhost:4200/#/place/someId right?

Wrong. The router generates a non-sensical route for me: "/place/(someId//popup:tabs-modal)"

Am I doing something wrong? Or is it just buggy?

答: I gave up trying to make .navigate() work, and ended up using router.navigateByUrl('/place/someId') instead. A simple solution that eluded me.


问:
How to pass data from MVC controller to Telerik UI for MVC Notification widget
I am using TelerikUI for MVC library in my ASP.Net MVC application. In one of my pages I need to use Notification widget. Is there a way I can pass data (to show) from MVC controller to Notification widget instantiated in my Razor view?

Thanks for your help!

Sam

答:
My workaround. It works.

First create a BaseController, extend desired controllers from it, and add the following class properties and methods:

```<code>public class MyBaseController : Controller
{

    // set js kendo notifications thru controllers
    public class notification {
        public string Title { get; set; }
        public string Message { get; set; }
        public string Type { get; set; }
    }

    public IList<notification> kendoNotifications;

    public void NewNotification(string title, string message, string type)
    {
        if (kendoNotifications == null)
        {
            this.kendoNotifications = new List<notification>();
        }
        this.kendoNotifications.Add(new notification { Title = title, Message = message, Type = type });
    }
    public IList<notification> GetKendoNotifications()
    {
        return this.kendoNotifications;
    }

    // GET: MyBase
    public MyBaseController()
    {
        // my stuff
        // ViewBag.KendoNotifications = this.kendoNotifications;
    }
</code>```

Next include kendo notification and following code in your layout:

```<code><script>
        var notification;// global, do not name anything else like this
    </script>
    @Html.Partial("_KendoNotification")
    @if (ViewBag.KendoNotifications != null)
    {
        if (ViewBag.KendoNotifications.Count > 0)
        {
            <script>
                $(document).ready(function () {
                    @*Ver MyBaseController *@
                    @foreach (var notification in ViewBag.KendoNotifications)
                    {
                        <text>
                            notification.show({
                                title: "@notification.Title",
                                message: "@notification.Message",
                            }, "@notification.Type");
                        </text>

                    }
                });// fin ready
            </script>
            ViewBag.KendoNotifications.Clear();
        }
    }
</code>```

Code for partial _KendoNotification (prety much js widget config)

```<code><div id="kendo-notification-wrap">

<span id="notification" style="display:none;"></span>

<script id="emailTemplate" type="text/x-kendo-template">
    <div class="new-mail">
        <span class="k-icon k-i-email k-icon-32"></span>
        <h3>#= title #</h3>
        <p>#= message #</p>
    </div>
</script>

<script id="errorTemplate" type="text/x-kendo-template">
    <div class="wrong-pass">
        <span class="k-icon k-i-error k-icon-32"></span>
        <h3>#= title #</h3>
        <p>#= message #</p>
    </div>
</script>

<script id="successTemplate" type="text/x-kendo-template">
    <div class="success">
        <span class="k-icon k-i-check-outline k-icon-32"></span>
        <h3>#= message #</h3>
    </div>
</script>

<script>
      $(document).ready(function() {

                notification = $("#notification").kendoNotification({
                    position: {
                        pinned: true,
                        top: 30,
                        right: 15
                    },
                    autoHideAfter: 5000,
                    allowHideAfter: 1000,
                    stacking: "down",
                    templates: [{
                        type: "info",
                        template: $("#emailTemplate").html()
                    }, {
                        type: "error",
                        template: $("#errorTemplate").html()
                    }, {
                        type: "success",
                        template: $("#successTemplate").html()
                    }]

                }).data("kendoNotification");

                $("#hideAllNotifications").click(function(){
                    notification.hide();
                });

                $(document).one("kendo:pageUnload", function(){ if (notification) { notification.hide(); } });

            });
</script>

<style>

    /* Info template */
            .k-notification-info.k-group {
                background: rgba(0%,0%,0%,.7);
                color: #fff;
            }
            .new-mail {
                width: auto;
                height: auto;
            }
            .new-mail h3 {
                font-size: 1em;
                padding: 32px 10px 5px;
            }
            .new-mail img {
                float: left;
                margin: 30px 15px 30px 30px;
            }

            /* Error template */
            .k-notification-error.k-group {
                background: rgba(100%,0%,0%,.7);
                color: #ffffff;
            }
            .wrong-pass {
                width: auto;
                height: auto;
            }
            .wrong-pass h3 {
                font-size: 1em;
                padding: 32px 10px 5px;
            }
            .wrong-pass img {
                float: left;
                margin: 30px 15px 30px 30px;
            }

            /* Success template */
            .k-notification-success.k-group {
                background: rgba(0%,60%,0%,.7);
                color: #fff;
            }
            .success {
                width: auto;
                height: auto;
                padding: 0 30px;
                line-height: 75px;
            }
            .success h3 {
                font-size: 1.7em;
                font-weight: normal;
                margin-bottom: 20px;
                display: inline-block;
                vertical-align: middle;
            }
            .success img {
                display: inline-block;
                vertical-align: middle;
                margin-right: 10px;
            }

</style>
</code>```

After having this done, just do the following in any controller/action where you want to pass the notification to the view:

```<code>public class MyTestController : MyBaseController
{
    // GET: Test
    public ActionResult Index()
    {

        this.NewNotification("hola", "prueba", "success");
        ViewBag.KendoNotifications = this.GetKendoNotifications();

        return View("~/Views/Test/Index.cshtml");
    }
}
</code>```

Notificaction image test

Regards!

Body:
My workaround. It works.

First create a BaseController, extend desired controllers from it, and add the following class properties and methods:

public class MyBaseController : Controller
{

    // set js kendo notifications thru controllers
    public class notification {
        public string Title { get; set; }
        public string Message { get; set; }
        public string Type { get; set; }
    }

    public IList<notification> kendoNotifications;

    public void NewNotification(string title, string message, string type)
    {
        if (kendoNotifications == null)
        {
            this.kendoNotifications = new List<notification>();
        }
        this.kendoNotifications.Add(new notification { Title = title, Message = message, Type = type });
    }
    public IList<notification> GetKendoNotifications()
    {
        return this.kendoNotifications;
    }

    // GET: MyBase
    public MyBaseController()
    {
        // my stuff
        // ViewBag.KendoNotifications = this.kendoNotifications;
    }

Next include kendo notification and following code in your layout:

<script>
        var notification;// global, do not name anything else like this
    </script>
    @Html.Partial("_KendoNotification")
    @if (ViewBag.KendoNotifications != null)
    {
        if (ViewBag.KendoNotifications.Count > 0)
        {
            <script>
                $(document).ready(function () {
                    @*Ver MyBaseController *@
                    @foreach (var notification in ViewBag.KendoNotifications)
                    {
                        <text>
                            notification.show({
                                title: "@notification.Title",
                                message: "@notification.Message",
                            }, "@notification.Type");
                        </text>

                    }
                });// fin ready
            </script>
            ViewBag.KendoNotifications.Clear();
        }
    }

Code for partial _KendoNotification (prety much js widget config)

<div id="kendo-notification-wrap">

<span id="notification" style="display:none;"></span>

<script id="emailTemplate" type="text/x-kendo-template">
    <div class="new-mail">
        <span class="k-icon k-i-email k-icon-32"></span>
        <h3>#= title #</h3>
        <p>#= message #</p>
    </div>
</script>

<script id="errorTemplate" type="text/x-kendo-template">
    <div class="wrong-pass">
        <span class="k-icon k-i-error k-icon-32"></span>
        <h3>#= title #</h3>
        <p>#= message #</p>
    </div>
</script>

<script id="successTemplate" type="text/x-kendo-template">
    <div class="success">
        <span class="k-icon k-i-check-outline k-icon-32"></span>
        <h3>#= message #</h3>
    </div>
</script>

<script>
      $(document).ready(function() {

                notification = $("#notification").kendoNotification({
                    position: {
                        pinned: true,
                        top: 30,
                        right: 15
                    },
                    autoHideAfter: 5000,
                    allowHideAfter: 1000,
                    stacking: "down",
                    templates: [{
                        type: "info",
                        template: $("#emailTemplate").html()
                    }, {
                        type: "error",
                        template: $("#errorTemplate").html()
                    }, {
                        type: "success",
                        template: $("#successTemplate").html()
                    }]

                }).data("kendoNotification");

                $("#hideAllNotifications").click(function(){
                    notification.hide();
                });

                $(document).one("kendo:pageUnload", function(){ if (notification) { notification.hide(); } });

            });
</script>

<style>

    /* Info template */
            .k-notification-info.k-group {
                background: rgba(0%,0%,0%,.7);
                color: #fff;
            }
            .new-mail {
                width: auto;
                height: auto;
            }
            .new-mail h3 {
                font-size: 1em;
                padding: 32px 10px 5px;
            }
            .new-mail img {
                float: left;
                margin: 30px 15px 30px 30px;
            }

            /* Error template */
            .k-notification-error.k-group {
                background: rgba(100%,0%,0%,.7);
                color: #ffffff;
            }
            .wrong-pass {
                width: auto;
                height: auto;
            }
            .wrong-pass h3 {
                font-size: 1em;
                padding: 32px 10px 5px;
            }
            .wrong-pass img {
                float: left;
                margin: 30px 15px 30px 30px;
            }

            /* Success template */
            .k-notification-success.k-group {
                background: rgba(0%,60%,0%,.7);
                color: #fff;
            }
            .success {
                width: auto;
                height: auto;
                padding: 0 30px;
                line-height: 75px;
            }
            .success h3 {
                font-size: 1.7em;
                font-weight: normal;
                margin-bottom: 20px;
                display: inline-block;
                vertical-align: middle;
            }
            .success img {
                display: inline-block;
                vertical-align: middle;
                margin-right: 10px;
            }

</style>

After having this done, just do the following in any controller/action where you want to pass the notification to the view:

public class MyTestController : MyBaseController
{
    // GET: Test
    public ActionResult Index()
    {

        this.NewNotification("hola", "prueba", "success");
        ViewBag.KendoNotifications = this.GetKendoNotifications();

        return View("~/Views/Test/Index.cshtml");
    }
}

Notificaction image test

Regards!


问:
Splayed table upsert leading to error: `cast
I built a data loader prototype that saves CSV into splayed tables. The workflow is as follows:

Create schema the first time e.g. volatilitysurface table:

```<code>volatilitysurface::([date:`datetime$(); ccypair:`symbol$()] atm_convention:`symbol$(); premium_included:`boolean$(); smile_type:`symbol$(); vs_type:`symbol$(); delta_ratio:`float$(); delta_setting:`float$(); wing_extrapolation:`float$(); spread_type:`symbol$());
</code>```

For every file in the rawdata folder import it:

```<code>myfiles:@[system;"dir /b /o:gn ",string `$getenv[`KDBRAWDATA],"*.volatilitysurface.csv 2> nul";()];
if[myfiles~();.lg.o[`load;"no volatilitysurface files found!"];:0N];
.lg.o[`load;"loading data files ..."];
/ load each file
{
  mypath:"" sv (string `$getenv[`KDBRAWDATA];x);
  .lg.o[`load;"loading file name '",mypath,"' ..."];
  myfile:hsym`$mypath;
  tmp1:select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from ("ZSSSSSFFFS";enlist ",")0:myfile;
  `volatilitysurface upsert tmp1;
} @/: myfiles;
delete tmp1 from `.;
.Q.gc[];
.lg.o[`done;"loading volatilitysurface data done"];

.lg.o[`save;"saving volatilitysurface schema to ",string afolder];
volatilitysurface::0!volatilitysurface;
.Q.dpft[afolder;`;`ccypair;`volatilitysurface];
.lg.o[`cleanup;"removing volatilitysurface from memory"];
delete volatilitysurface from `.;
.Q.gc[];
.lg.o[`done;"saving volatilitysurface schema done"];
</code>```

This works perfectly. I use .Q.gc[]; frequently to avoid hitting the wsfull. When new CSV files are available I open the existing schema, upsert into it and save it again effectively overwriting the existing HDB file system.

Open schema:

```<code>.lg.o[`open;"tables already exists, opening the schema ..."];
@[system;"l ",(string afolder) _ 0;{.lg.e[`open;"failed to load hdb directory: ", x]; 'x}];
/ Re-create table index
volatilitysurface::`date`ccypair xkey select from volatilitysurface;
</code>```

Re-run step #2 to append new CSV files into the existing volatilitysurfacetable, it upserts the first CSV perfectly but the second CSV fails with:

```<code>error: `cast
</code>```

I debug to the point of the error and to double-check I see that the metadata of tmp1 and volatilitysurface are perfectly the same. Any ideas why this is happening? I get the same issue with any other table. I have tried cleaning the keys from the table after every upsert but doesn't help i.e.

```<code>volatilitysurface::0!volatilitysurface;
volatilitysurface::`date`ccypair xkey volatilitysurface;
</code>```

And the metadata comparison at the point of the cast error:

```<code>meta tmp1
c                 | t f a
------------------| -----
date              | z
ccypair           | s
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

meta volatilitysurface
c                 | t f a
------------------| -----
date              | z
ccypair           | s   p
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s
</code>```

UPDATE Using the input of the answer below I tried using Torq's .loader.loadallfiles function like this (it doesn't fail but nothing happens either, the table is not created in memory and the data is not written to the database):

```<code>.loader.loadallfiles[`headers`types`separator`tablename`dbdir`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;`:hdb; {[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); `:rawdata]
</code>```

UDPATE2 This is the output I get from TorQ:

```<code>2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|**** LOADING :rawdata/20171102_113420.disccurve.csv ****
2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|reading in data chunk
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Read 10000 rows
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|processing data
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Enumerating
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4525 rows to :hdb/2017.09.12/volatilitysurface/
2017.11.20D08:46:12.581819000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4744 rows to :hdb/2017.09.13/volatilitysurface/
2017.11.20D08:46:12.659823000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 731 rows to :hdb/2017.09.14/volatilitysurface/
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|init|retrieving sort settings from :C:/Dev/torq//config/sort.csv
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sort|sorting the volatilitysurface table
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sortfunction|sorting :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time
2017.11.20D08:46:12.753428000|wsp18497wn|dataloader|dataloader1|ERR|sortfunction|failed to sort :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time.  The error was: hdb/2017.09.
</code>```

I get the following error sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters where is this sorttab documented? does it use the table PK by default?

UPDATE3 Ok fixed UPDATE2 out by providing a non-default sort.csv under my config folder:

```<code>tabname,att,column,sort
default,p,sym,1
default,,time,1
volatilitysurface,,date,1
volatilitysurface,,ccypair,1
</code>```

But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it.

UPDATE4 Still not there yet ... assuming I can check to make sure that no duplicate file is used. When I load and then start the database I get some structure back that ressembles some sort of dictionary and not a table.

```<code>2017.10.31| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.01| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.02| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.03| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
sym       | `AUDNOK`AUDCNH`AUDJPY`AUDHKD`AUDCHF`AUDSGD`AUDCAD`AUDDKK`CADSGD`C..
</code>```

Note that date is actually datetime Z and not just date. My full and latest version of the function invocation is:

```<code>target:hsym `$("" sv ("./";getenv[`KDBHDB];"/volatilitysurface"));
rawdatadir:hsym `$getenv[`KDBRAWDATA];
.loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;target;`date;{[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); rawdatadir];
</code>```

答:
`cast error refers to a value not being enumerated

I can't see any enumeration going on here, splayed tables on disk need to have symbol columns enumerated. For example, this can be done with the following line, before calling .Q.dpft

```<code>volatilitysurface:.Q.en[afolder;volatilitysurface];
</code>```

You may like to consider using an example CSV loader for loading your data. One such example is included in TorQ, the KDB framework developed by AquaQ Analytics (as a disclaimer, I work for AquaQ)

The framework is available (free of charge) here: https://github.com/AquaQAnalytics/TorQ

The specific component you will likely be interested in is dataloader.q and is documented here: http://aquaqanalytics.github.io/TorQ/utilities/#dataloaderq

This script will handle everything necessary, loading all files, enumerating, sorting on disk, applying attributes etc. as well as using .Q.fsn to prevent running out of memory

Body:
I built a data loader prototype that saves CSV into splayed tables. The workflow is as follows:

Create schema the first time e.g. volatilitysurface table:

volatilitysurface::([date:`datetime$(); ccypair:`symbol$()] atm_convention:`symbol$(); premium_included:`boolean$(); smile_type:`symbol$(); vs_type:`symbol$(); delta_ratio:`float$(); delta_setting:`float$(); wing_extrapolation:`float$(); spread_type:`symbol$());

For every file in the rawdata folder import it:

myfiles:@[system;"dir /b /o:gn ",string `$getenv[`KDBRAWDATA],"*.volatilitysurface.csv 2> nul";()];
if[myfiles~();.lg.o[`load;"no volatilitysurface files found!"];:0N];
.lg.o[`load;"loading data files ..."];
/ load each file
{
  mypath:"" sv (string `$getenv[`KDBRAWDATA];x);
  .lg.o[`load;"loading file name '",mypath,"' ..."];
  myfile:hsym`$mypath;
  tmp1:select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from ("ZSSSSSFFFS";enlist ",")0:myfile;
  `volatilitysurface upsert tmp1;
} @/: myfiles;
delete tmp1 from `.;
.Q.gc[];
.lg.o[`done;"loading volatilitysurface data done"];

.lg.o[`save;"saving volatilitysurface schema to ",string afolder];
volatilitysurface::0!volatilitysurface;
.Q.dpft[afolder;`;`ccypair;`volatilitysurface];
.lg.o[`cleanup;"removing volatilitysurface from memory"];
delete volatilitysurface from `.;
.Q.gc[];
.lg.o[`done;"saving volatilitysurface schema done"];

This works perfectly. I use .Q.gc[]; frequently to avoid hitting the wsfull. When new CSV files are available I open the existing schema, upsert into it and save it again effectively overwriting the existing HDB file system.

Open schema:

.lg.o[`open;"tables already exists, opening the schema ..."];
@[system;"l ",(string afolder) _ 0;{.lg.e[`open;"failed to load hdb directory: ", x]; 'x}];
/ Re-create table index
volatilitysurface::`date`ccypair xkey select from volatilitysurface;

Re-run step #2 to append new CSV files into the existing volatilitysurfacetable, it upserts the first CSV perfectly but the second CSV fails with:

error: `cast

I debug to the point of the error and to double-check I see that the metadata of tmp1 and volatilitysurface are perfectly the same. Any ideas why this is happening? I get the same issue with any other table. I have tried cleaning the keys from the table after every upsert but doesn't help i.e.

volatilitysurface::0!volatilitysurface;
volatilitysurface::`date`ccypair xkey volatilitysurface;

And the metadata comparison at the point of the cast error:

meta tmp1
c                 | t f a
------------------| -----
date              | z
ccypair           | s
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

meta volatilitysurface
c                 | t f a
------------------| -----
date              | z
ccypair           | s   p
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

UPDATE Using the input of the answer below I tried using Torq's .loader.loadallfiles function like this (it doesn't fail but nothing happens either, the table is not created in memory and the data is not written to the database):

.loader.loadallfiles[`headers`types`separator`tablename`dbdir`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;`:hdb; {[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); `:rawdata]

UDPATE2 This is the output I get from TorQ:

2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|**** LOADING :rawdata/20171102_113420.disccurve.csv ****
2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|reading in data chunk
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Read 10000 rows
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|processing data
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Enumerating
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4525 rows to :hdb/2017.09.12/volatilitysurface/
2017.11.20D08:46:12.581819000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4744 rows to :hdb/2017.09.13/volatilitysurface/
2017.11.20D08:46:12.659823000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 731 rows to :hdb/2017.09.14/volatilitysurface/
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|init|retrieving sort settings from :C:/Dev/torq//config/sort.csv
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sort|sorting the volatilitysurface table
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sortfunction|sorting :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time
2017.11.20D08:46:12.753428000|wsp18497wn|dataloader|dataloader1|ERR|sortfunction|failed to sort :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time.  The error was: hdb/2017.09.

I get the following error sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters where is this sorttab documented? does it use the table PK by default?

UPDATE3 Ok fixed UPDATE2 out by providing a non-default sort.csv under my config folder:

tabname,att,column,sort
default,p,sym,1
default,,time,1
volatilitysurface,,date,1
volatilitysurface,,ccypair,1

But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it.

UPDATE4 Still not there yet ... assuming I can check to make sure that no duplicate file is used. When I load and then start the database I get some structure back that ressembles some sort of dictionary and not a table.

2017.10.31| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.01| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.02| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.03| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
sym       | `AUDNOK`AUDCNH`AUDJPY`AUDHKD`AUDCHF`AUDSGD`AUDCAD`AUDDKK`CADSGD`C..

Note that date is actually datetime Z and not just date. My full and latest version of the function invocation is:

target:hsym `$("" sv ("./";getenv[`KDBHDB];"/volatilitysurface"));
rawdatadir:hsym `$getenv[`KDBRAWDATA];
.loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;target;`date;{[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); rawdatadir];

Body:
`cast error refers to a value not being enumerated

I can't see any enumeration going on here, splayed tables on disk need to have symbol columns enumerated. For example, this can be done with the following line, before calling .Q.dpft

volatilitysurface:.Q.en[afolder;volatilitysurface];

You may like to consider using an example CSV loader for loading your data. One such example is included in TorQ, the KDB framework developed by AquaQ Analytics (as a disclaimer, I work for AquaQ)

The framework is available (free of charge) here: https://github.com/AquaQAnalytics/TorQ

The specific component you will likely be interested in is dataloader.q and is documented here: http://aquaqanalytics.github.io/TorQ/utilities/#dataloaderq

This script will handle everything necessary, loading all files, enumerating, sorting on disk, applying attributes etc. as well as using .Q.fsn to prevent running out of memory


问:
Angular2 and InstaFeed query
im making a site for a client, which requires their Instagram photos to be shown on one of the tabs. Im using Angular4, and Instafeed to accomplish this. I installed Instafeed using NPM, linked the script in .angular-cli, the css in the .angular-cli as well, followed by the instaFeed script on the Tab's HTML and finally ending with a Div of class InstaFeed. However, on running the site, I do not see any errors, but no pictures are being displayed either. Any help please?? </p>

答:
This maybe late for the op but right on time for someone else struggling with this. If you have the scripts declared in angular cli, what worked for me is to declare the instafeed variable inside the component you aim to use instafeed like so...

```<code>declare var Instafeed:any;
</code>```

Then inside this same component add the code for instafeed

```<code>var feed = new Instafeed({
    get: 'user',
    userId: 'xxxxxx',
    clientId: 'xxxxxxxxx',
    accessToken: 'xxxxxxxxxxx',
    template: '<a href="{{link}}"><img src="{{image}}" /><p>Likes {{likes}}</p><p>Comments {{comments}}</p></a>',
    limit: 1
});
feed.run();
</code>```

Title: Angular2 and InstaFeed query

Body:
This maybe late for the op but right on time for someone else struggling with this. If you have the scripts declared in angular cli, what worked for me is to declare the instafeed variable inside the component you aim to use instafeed like so...

declare var Instafeed:any;

Then inside this same component add the code for instafeed

var feed = new Instafeed({
    get: 'user',
    userId: 'xxxxxx',
    clientId: 'xxxxxxxxx',
    accessToken: 'xxxxxxxxxxx',
    template: '<a href="{{link}}"><img src="{{image}}" /><p>Likes {{likes}}</p><p>Comments {{comments}}</p></a>',
    limit: 1
});
feed.run();


问:
Check if key exists in an array and replace its value
CLIENT CODE

I am sending an id of a client from the client side using

```<code>var socket = io.connect('http://localhost:8080?token='+userID);
</code>```

and getting it on the server in my io.on('connection')
function using

SERVER CODE

```<code>let token = socket.handshake.query.token;
</code>```

so now I have the userID stored in the variable token.

Also I am getting the connected socket id and storing it like

```<code>var id = socket.id;
</code>```

Then I am storing the userID and the socketID in an array as key value pair.

```<code>var item = {};
item[token] = id;
</code>```

This is an array I am pushing it into(the array is declared outside the on connection function)

```<code>keyPairArray.push(item);
</code>```

So I am getting an array like this when two people are connected.

```<code>[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' } ]
</code>```

But when any user reloads the page the array gets like

```<code>[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' },
  { '1456': 'tIhvkxFbSSAQEckWAAAC' } ]
</code>```

Same user Id but different socket id's.

The socket id changes every time the user reloads the page or opens the page in another tab and the same UserID is appended into the array with a different socket id.

I don't want to insert the same user again. If the user reloads the page, I want it to check the userId which is the key in the array and replace the old socket id with the newly generated one.

This is the code that I tried with no luck

```<code>var checkKeyPair = keyPairArray.some(function(item){
    return item[token] === id;
});

if(checkKeyPair){
    console.log("Hello");
}else{
    keyPairArray.push(item);
    console.log(keyPairArray);
}
</code>```

答:
var users = [{
    '10': 'HvlunYNFCcF5vK0-AAAA'
  },
  {
    '1456': '17XF7mbh4vYr2WUSAAAB'
  }
];

function saveUser(newUserId) {

  users.forEach(function(key) {

    if (Object.keys(key)[0] == newUserId)
      console.log('user exists');
    else {
      var item = {};
      item[newUserId] = 'fsdfsdgdfsgdfhgf55665hftgh56';
      users.push(item);
    }
  });
}

saveUser('1456');```

Body:
CLIENT CODE

I am sending an id of a client from the client side using

var socket = io.connect('http://localhost:8080?token='+userID);

and getting it on the server in my io.on('connection')
function using

SERVER CODE

let token = socket.handshake.query.token;

so now I have the userID stored in the variable token.

Also I am getting the connected socket id and storing it like

var id = socket.id;

Then I am storing the userID and the socketID in an array as key value pair.

var item = {};
item[token] = id;

This is an array I am pushing it into(the array is declared outside the on connection function)

keyPairArray.push(item);

So I am getting an array like this when two people are connected.

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' } ]

But when any user reloads the page the array gets like

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' },
  { '1456': 'tIhvkxFbSSAQEckWAAAC' } ]

Same user Id but different socket id's.

The socket id changes every time the user reloads the page or opens the page in another tab and the same UserID is appended into the array with a different socket id.

I don't want to insert the same user again. If the user reloads the page, I want it to check the userId which is the key in the array and replace the old socket id with the newly generated one.

This is the code that I tried with no luck

var checkKeyPair = keyPairArray.some(function(item){
    return item[token] === id;
});

if(checkKeyPair){
    console.log("Hello");
}else{
    keyPairArray.push(item);
    console.log(keyPairArray);
}