问:
Print related object of related object python
I am creating a guide app where each guide is made of 3 classes as bellow.

How do I for example print subtask 3 of step 2 in guide 1

This is what I can do in the shell so far.

```<code>class Guide(models.Model):
    user = models.ForeignKey(User, default=1)
    guide_category = models.CharField(max_length=250)
    guide_title = models.CharField(max_length=500)
    guide_how = models.CharField(max_length=100)
    guide_why = models.CharField(max_length=100)
    guide_logo = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.guide_title + ' - ' + self.guide_category + ' - ' + self.guide_how + ' - ' + self.guide_why

class Step(models.Model):
    guide = models.ForeignKey(Guide, on_delete=models.CASCADE)
    step_title = models.CharField(max_length=250)
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.step_title

class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.subtask_title
</code>```

This is what I can do in the shell so far.

```<code>from appname.models import Guide, Step, Subtask
guide1 = Guide(pk=1)
guide2 = Guide(pk=2)
>>> Guide.objects.all()
[<Guide: Test1 - CR - how1 - why2>, <Guide: test2 - VR - how2 - why2>]
>>> Step.objects.all()
[<Step: 1>, <Step: 2>, <Step: 1>, <Step: 2>]
>>> Subtask.objects.all()
[<Subtask: 1.1.1>, <Subtask: 1.1.2>, <Subtask: 1.2.1>, <Subtask: 1.2.2>, <Subtask: 2.1.1>]
</code>```

Thanks! :)

答:
If you have guide1, then,

```<code>subtasks = Subtask.objects.filter(step__guide=guide1)
</code>```

subtasks would be a queryset of Subtask objects related to guide1.
You could then get the subtask with any additional conditions.

Body:
I am creating a guide app where each guide is made of 3 classes as bellow.

How do I for example print subtask 3 of step 2 in guide 1

This is what I can do in the shell so far.

class Guide(models.Model):
    user = models.ForeignKey(User, default=1)
    guide_category = models.CharField(max_length=250)
    guide_title = models.CharField(max_length=500)
    guide_how = models.CharField(max_length=100)
    guide_why = models.CharField(max_length=100)
    guide_logo = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.guide_title + ' - ' + self.guide_category + ' - ' + self.guide_how + ' - ' + self.guide_why

class Step(models.Model):
    guide = models.ForeignKey(Guide, on_delete=models.CASCADE)
    step_title = models.CharField(max_length=250)
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.step_title

class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.subtask_title

This is what I can do in the shell so far.

from appname.models import Guide, Step, Subtask
guide1 = Guide(pk=1)
guide2 = Guide(pk=2)
>>> Guide.objects.all()
[<Guide: Test1 - CR - how1 - why2>, <Guide: test2 - VR - how2 - why2>]
>>> Step.objects.all()
[<Step: 1>, <Step: 2>, <Step: 1>, <Step: 2>]
>>> Subtask.objects.all()
[<Subtask: 1.1.1>, <Subtask: 1.1.2>, <Subtask: 1.2.1>, <Subtask: 1.2.2>, <Subtask: 2.1.1>]

Thanks! :)

Body:
If you have guide1, then,

subtasks = Subtask.objects.filter(step__guide=guide1)

subtasks would be a queryset of Subtask objects related to guide1.
You could then get the subtask with any additional conditions.


来源: stackexchange

问:
One mysql database per user with thousands of users
I have an Android app and i want to allow my users to sync their local sqlite db with server.Since i have thousands of user's how should i set up my MySql database on server?As i see it there are two approaches,

1) One database per user plus one database to store user's credentials.Is this even possible since there will be thousands of different databases on server?

2) One database that holds all user's data.I was thinking i could add a field (user_id) on each table that identifies a user.I don't like though the idea that all user's data will be on the same table!!!

What's the best approach for my case?Is there something different i could try?

答: One database that holds all user's data.I was thinking i could add a field (user_id) on each table that identifies a user.I don't like though the idea that all user's data will be on the same table!!!</p>

ContentLicense: CC BY-SA 3.0


问:
Perform actions within the with helper
New to Ember here. I am trying to figure out how to execute an action and the product of that action be used by the #with helper. Below is an example of my code:

  {{#navigation-container as |navigationContainer|}}
    {{#with (action navigationContainer.previousPage model) as |prev|}}
      {{link-to (t 'navigation.previous') (concat 'course-run.' prev.modelName) prev activeClass="o25" title=prev.title}}
    {{/with}}
  {{/navigation-container}}

navigation-container is a component that exposes a few actions, one of which is previousPage. previousPage simply returns a model that I then use to create some links and use with ember-keyboard.

I'm receiving an error that the link-to can't build a route due to prev being undefined. The action is executing and returning correctly just above this with block, so I'm assuming the with block is the problem.

Thanks for any help!

答:
I think you understood this wrong. The with helper does not allow you to you execute an action. The result of (action navigationContainer.previousPage model) is basically a new closure function that will execute navigationContainer.previousPage with the first parameter model and the next parameters are the parameters you give to your new function.

So if you do something like <button onclick={{action prv "bar"}}></button> this will result in the function navigationContainer.previousPage to be executed with the first parameter model and the next "bar".

If you want the result of a function in your template you have to use a computed property.

Title: Perform actions within the with helper


问:
Count and remove similar elements in a list while iterating through it
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

```<code>List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);
</code>```

Thanks.

答:
From your questions, you basically want to:

1. Eliminate duplicates from given String List

You can simply convert your List to HashSet (it doesn't allow duplicates) and then convert it back to list (if you want the end result to be a List so you can do something else with it...)

2. Count all occurences of unique words in your list
The fastest coding is to use Java 8 Streams (code borrowed frome here: How to count the number of occurrences of an element in a List)

Complete code

```<code>public static void main(String[] args) {
    String fullname = "a b c d a b c"; //something
    List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(" ")));

    // Convert input to Set, and then back to List (your program output)
    Set<String> uniqueNames = new HashSet<>(fname);
    List<String> uniqueNamesInList = new ArrayList<>(uniqueNames);
    System.out.println(uniqueNamesInList);

    // Collects (reduces) your list
    Map<String, Long> counts = fname.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    System.out.println(counts);
}
</code>```

Body:
I used many references in the site to build up my program but I'm kind of stuck right now. I think using iterator will do the job. Sadly even though I went through questions which had iterator, I couldn't get the way of using it properly to implement it on my code.

I want to,
      1. remove the similar elements found in the list fname
      2. count & add the that count of each element found in fname to
          counter.

Please help me do the above using iterator or with any other method. Following is my code,

List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(""))); //Assigning the string to a list//

    int count = 1;
    ArrayList<Integer> counter = new ArrayList<>();
    List<String> holder = new ArrayList<>();

    for(int element=0; element<=fname.size; element++)
    {
        for(int run=(element+1); run<=fname.size; run++)
        {
            if((fname.get(element)).equals(fname.get(run)))
            {
                count++;
                holder.add(fname.get(run));
            }

            counter.add(count);
        }

        holder.add(fname.get(element));
        fname.removeAll(holder);
    }

    System.out.println(fname);
    System.out.println(counter);

Thanks.

Body:
From your questions, you basically want to:

1. Eliminate duplicates from given String List

You can simply convert your List to HashSet (it doesn't allow duplicates) and then convert it back to list (if you want the end result to be a List so you can do something else with it...)

2. Count all occurences of unique words in your list
The fastest coding is to use Java 8 Streams (code borrowed frome here: How to count the number of occurrences of an element in a List)

Complete code

public static void main(String[] args) {
    String fullname = "a b c d a b c"; //something
    List<String> fname = new ArrayList<>(Arrays.asList(fullname.split(" ")));

    // Convert input to Set, and then back to List (your program output)
    Set<String> uniqueNames = new HashSet<>(fname);
    List<String> uniqueNamesInList = new ArrayList<>(uniqueNames);
    System.out.println(uniqueNamesInList);

    // Collects (reduces) your list
    Map<String, Long> counts = fname.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    System.out.println(counts);
}


问:
Python Interactive Brokers ibapi
I am having trouble using and incrementing the "orderId" for each stock order using modified IB example code. I have a method that produces nextValidId within the class and prints it to stdout but I am not sure how to access the defined property (self.nextValidOrderId) that is created in my main() program body.  I am able to instantiate the EWrapper and EClient Class and place orders (If I manually input the orderId). In example code I hard code it to 126.  I thought I would be able to use the following in my main() program body.
"orderId = app.nextValidOrderId"  but it does not work. </p>

```<code>`__author__ = 'noone'

from Testbed.OrderSamples import OrderSamples
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *

class OrderApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self,self)

    def error(self,reqId:TickerId, errorCode:int, errorString:str):
        print("Error:",reqId," ", errorCode, " ", errorString)

    # This is the initial response after connection to TS from the API providing next available OrderID
    @iswrapper
    def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d", orderId)
    self.nextValidOrderId = orderId

    def contractDetails(self, reqId:int, contractDetails:ContractDetails):
        print("contractDetails: ", reqId, " ", contractDetails)

def main():
    app=OrderApp()
    app.connect("127.0.0.1",7497,0)

    ## Build the contract object to be passed to the order Method

    stock_contract = Contract()
    stock_contract.symbol = 'AAPL'
    stock_contract.secType = 'STK'
    stock_contract.exchange = 'SMART'
    stock_contract.currency = 'USD'
    stock_contract.primaryExchange = 'NASDAQ'

    # reqID must be provided to the Order. This method gets the reqID from IB DB's
    app.reqContractDetails(10, stock_contract)

    try:
        # Now place the order in Paper Money Account
        app.placeOrder(126, stock_contract, OrderSamples.LimitOrder("BUY", 50, 12))

    except:
        raise

    app.run()

if __name__ == "__main__":
    main()`
</code>```

答:
Your method is not syntactically correct. It should have indentation as below

```<code>@iswrapper
def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d" % orderId)
    self.nextValidOrderId = orderId
</code>```

Also you are not importing the function decorator iswrapper

```<code>from ibapi.utils import iswrapper
</code>```

Hope this helps

Title: Python Interactive Brokers ibapi

Body:
I am having trouble using and incrementing the "orderId" for each stock order using modified IB example code. I have a method that produces nextValidId within the class and prints it to stdout but I am not sure how to access the defined property (self.nextValidOrderId) that is created in my main() program body.  I am able to instantiate the EWrapper and EClient Class and place orders (If I manually input the orderId). In example code I hard code it to 126.  I thought I would be able to use the following in my main() program body.
"orderId = app.nextValidOrderId"  but it does not work.

`__author__ = 'noone'

from Testbed.OrderSamples import OrderSamples
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *

class OrderApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self,self)

    def error(self,reqId:TickerId, errorCode:int, errorString:str):
        print("Error:",reqId," ", errorCode, " ", errorString)

    # This is the initial response after connection to TS from the API providing next available OrderID
    @iswrapper
    def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d", orderId)
    self.nextValidOrderId = orderId

    def contractDetails(self, reqId:int, contractDetails:ContractDetails):
        print("contractDetails: ", reqId, " ", contractDetails)

def main():
    app=OrderApp()
    app.connect("127.0.0.1",7497,0)

    ## Build the contract object to be passed to the order Method

    stock_contract = Contract()
    stock_contract.symbol = 'AAPL'
    stock_contract.secType = 'STK'
    stock_contract.exchange = 'SMART'
    stock_contract.currency = 'USD'
    stock_contract.primaryExchange = 'NASDAQ'

    # reqID must be provided to the Order. This method gets the reqID from IB DB's
    app.reqContractDetails(10, stock_contract)

    try:
        # Now place the order in Paper Money Account
        app.placeOrder(126, stock_contract, OrderSamples.LimitOrder("BUY", 50, 12))

    except:
        raise

    app.run()

if __name__ == "__main__":
    main()`

Body:
Your method is not syntactically correct. It should have indentation as below

@iswrapper
def nextValidId(self, orderId: int):
    super().nextValidId(orderId)

    print("setting nextValidOrderId: %d" % orderId)
    self.nextValidOrderId = orderId

Also you are not importing the function decorator iswrapper

from ibapi.utils import iswrapper

Hope this helps

ContentLicense: CC BY-SA 4.0


问:
Pass data to User Control ASP.NET MVC
I have a user control which shows list of latest announcements. This user control would be used in almost 90% of my pages. Now my concern is how to pass data to this user control for latest announcements.

My first approach is to make a base controller and in Initialise method I pass data to user control via ViewBag/ViewData. All my other controllers derive from this base controller. This looks nice but my concern is that it may become an overkill for some simple solution existing already out there. Also I would need to make sure that no controller ever fiddles with my Viewdata/Viewbag data meant for my usercontrol.

Please let me know if this is correct way of proceeding ahead or there exists some better solution.

Thanks

答: I think the best way would be to use @Html.Action. This would allow me to call my actions dedicated to my usercontrols data and I can call it from anywhere.</p>

ContentLicense: CC BY-SA 2.5

Title: Pass data to User Control ASP.NET MVC


问:
Javascript using mouse hover class to effect child ids
I am trying to make the class navButtons effect all of the ids inside it using the mouse over  effect. I read on here that you can do this with a for loop but that would require changing the names of the ids. is there a way to do this without changing the names?

document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("navButtons").addEventListener("mouseout", mouseOut);

function mouseOver() {
    document.getElementsByClassName("navButtons").style.color = "red";
}

function mouseOut() {
    document.getElementsByClassName("navButtons").style.color = "black";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>

 </code>```

答:
If I'm understanding you correctly, you want to apply styles to all the elements inside navButtons when hovering navButtons. This can be done with CSS only.

.navButtons:hover > div {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav></code>```

If you however, for some reason, want to use Javascript instead (not recommended for this purpose) you can do the following:

var navButtons = document.getElementsByClassName('navButtons')[0];
var children = navButtons.getElementsByTagName('div');

navButtons.addEventListener('mouseenter', function() {
  for (var i = 0; i < children.length; i++) {
    children[i].style.color = 'red';
  }
});

navButtons.addEventListener('mouseleave', function() {
  for (var i = 0; i < children.length; i++) {
    children[i].style.color = 'black';
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav></code>```

Body:
I am trying to make the class navButtons effect all of the ids inside it using the mouse over  effect. I read on here that you can do this with a for loop but that would require changing the names of the ids. is there a way to do this without changing the names?

document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("navButtons").addEventListener("mouseout", mouseOut);

function mouseOver() {
    document.getElementsByClassName("navButtons").style.color = "red";
}

function mouseOut() {
    document.getElementsByClassName("navButtons").style.color = "black";
}

about

portfolio

contact

Body:
If I'm understanding you correctly, you want to apply styles to all the elements inside navButtons when hovering navButtons. This can be done with CSS only.

.navButtons:hover > div {
  color: red;
}

<nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>

If you however, for some reason, want to use Javascript instead (not recommended for this purpose) you can do the following:

var navButtons = document.getElementsByClassName('navButtons')[0];
var children = navButtons.getElementsByTagName('div');

navButtons.addEventListener('mouseenter', function() {
  for (var i = 0; i < children.length; i++) {
    children[i].style.color = 'red';
  }
});

navButtons.addEventListener('mouseleave', function() {
  for (var i = 0; i < children.length; i++) {
    children[i].style.color = 'black';
  }
});

<nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>


问:
JavaScript Clicker With LocalStorage System
I´m new in JavaScript and I have write a little Counter. Now  I will save the clicks with LocalStorage and open the data when I start the Site.
It also works but when I reload the page the number of the variable is not counted to it when I trigger the onClick function rather the number is always attached to the variable.</p>

```<code><script type="text/javascript">

    var clicks = 0;

    function datenAbrufen() {
      clicks = localStorage.getItem("aktuelleKlicks");
      document.getElementById("clicks").innerHTML = clicks;
    }

    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
        datenSpeichern();
    };

    function datenSpeichern() {
        localStorage.setItem("aktuelleKlicks", clicks);
    };

    function trash() {
      clicks = -1;
      document.getElementById("clicks").innerHTML = clicks;
    }

</script>
</code>```

答:
localStorage stores data as strings and if you try to add something to a string you do "string addition" which is actually concatenation.

What you want to do is convert the data you read from localStorage back to a number.

```<code>clicks = parseInt(localStorage.getItem("aktuelleKlicks"), 10);
</code>```

Body:
localStorage stores data as strings and if you try to add something to a string you do "string addition" which is actually concatenation.

What you want to do is convert the data you read from localStorage back to a number.

clicks = parseInt(localStorage.getItem("aktuelleKlicks"), 10);


答:
I'm going to assume that you call datenAbrufen on page load and onClick, er, on a click.

If so, the problem is in datenAbrufen: localStorage stores strings. So clicks = localStorage.getItem("aktuelleKlicks"); sets clicks to a string. clicks += 1 will then append the digit 1 to the end of the string. (On the first page load, clicks will get set to null. It works in that case because clicks += 1 when clicks is null ends up being 1, because += will coerce null to 0. + [and thus +=] wants either a number or a string; when clicks is a string, it does string concatenation; if clicks is a number, it does addition; otherwise, it does coercion, which depends on what it's coercing from. null coerces to 0 in that case.)

You need to parse the string into a number:

```<code>function datenAbrufen() {
  clicks = parseInt(localStorage.getItem("aktuelleKlicks"), 10) || 0; // ***
  document.getElementById("clicks").innerHTML = clicks;
}
</code>```

parseInt will parse the string using the given number base (10 = decimal). If it can't, it will return NaN, so || 0 after it will take 0 if the number in local storage is invalid.

Live Example: https://jsfiddle.net/dfonxrtq/ (sadly, Stack Snippets don't allow local storage)

Title: JavaScript Clicker With LocalStorage System

Body:
I´m new in JavaScript and I have write a little Counter. Now  I will save the clicks with LocalStorage and open the data when I start the Site.
It also works but when I reload the page the number of the variable is not counted to it when I trigger the onClick function rather the number is always attached to the variable.

Body:
I'm going to assume that you call datenAbrufen on page load and onClick, er, on a click.

If so, the problem is in datenAbrufen: localStorage stores strings. So clicks = localStorage.getItem("aktuelleKlicks"); sets clicks to a string. clicks += 1 will then append the digit 1 to the end of the string. (On the first page load, clicks will get set to null. It works in that case because clicks += 1 when clicks is null ends up being 1, because += will coerce null to 0. + [and thus +=] wants either a number or a string; when clicks is a string, it does string concatenation; if clicks is a number, it does addition; otherwise, it does coercion, which depends on what it's coercing from. null coerces to 0 in that case.)

You need to parse the string into a number:

function datenAbrufen() {
  clicks = parseInt(localStorage.getItem("aktuelleKlicks"), 10) || 0; // ***
  document.getElementById("clicks").innerHTML = clicks;
}

parseInt will parse the string using the given number base (10 = decimal). If it can't, it will return NaN, so || 0 after it will take 0 if the number in local storage is invalid.

Live Example: https://jsfiddle.net/dfonxrtq/ (sadly, Stack Snippets don't allow local storage)


答:
document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
you are trying to add event listener to a node list, you will have to attach it each node inside the list using a loop. then you can access the current element inside the mouseOver() function using event.target.

var navButtons = document.getElementsByClassName("navButtons");
for (var i=0; i<navButtons.length; i++){
  navButtons[i].addEventListener("mouseover", mouseOver);
  navButtons[i].addEventListener("mouseout", mouseOut);
}
function mouseOver(event) {
    event.target.parentNode.style.color = "red";
}

function mouseOut(event) {
    event.target.parentNode.style.color = "black";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>

 </code>```

Title: Javascript using mouse hover class to effect child ids

Body:
document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
you are trying to add event listener to a node list, you will have to attach it each node inside the list using a loop. then you can access the current element inside the mouseOver() function using event.target.

var navButtons = document.getElementsByClassName("navButtons");
for (var i=0; i<navButtons.length; i++){
  navButtons[i].addEventListener("mouseover", mouseOver);
  navButtons[i].addEventListener("mouseout", mouseOut);
}
function mouseOver(event) {
    event.target.parentNode.style.color = "red";
}

function mouseOut(event) {
    event.target.parentNode.style.color = "black";
}

<nav>
  <div class="navButtons">
      <div id="about">about</div>
      <div id="portfolio">portfolio</div>
      <div id="contact">contact</div>
  </div>
</nav>


问:
Big differences between MS Translator API results and Bing Translator Results. Why?
Bing Translator claims to use MS Translator. However, there can be serious differences between the translations provided by MS Transalator and the translations provided by Bing. Most of the time, Bing translations look much better.

Can someone tell me if there are some specific parameter values or options that should be set in MS-Translator such that the translations are equal (or closer) to those of Bing?
Is there any special subscription (paid if required) to get better quality translations in MS-Translator?  (I mean: closer to the Bing ones)

We currently have a paid subscription to MS-Translator and we are using the "Translate" function of the MSTranslator API.
... https://api.microsofttranslator.com/v2/http.svc/Translate?appid=Bearer%20"${bearer}"\&from="${lang_from}"\&to=en\&contentType=text%2Fplain\&category=general

A couple of examples with Simplified Chinese:
Original Taiwanese wording:
"不專業，經追問不願多講。"

English translation that we received from MS Translator:
"Not professional, asking reluctant to speak."

Bing translation:
"Unprofessional, after questioning unwilling to speak more."

Example II:

Original Taiwanese wording:
"廠地設備老舊，而且進廠車輛多顯得很混亂很壅擠。"

English translation that we received from MS Translator:
"Old factory to equipment and incoming vehicles appear very confusion was obstructing squeeze."

Bing translation:
"Factory equipment is old, and the number of vehicles in the factory seems very confusing and congested."

答:
Using the parameter &category=generalnn in the API call will produce the same results as you see in the Bing UI.
Be careful with tagged content. Tags are handled better with the default category value, blank or "general".</p>


问:
Cannot access https on codeigniter
The following is my base_url of config.php in my project.

```<code>$config['base_url'] = 'https://www.mywebsite.com/';
</code>```

But my website always go to http://www.mywebsite.com unless the user implicitly write https in browser url.

What is the problem?

Why codeigniter goes to url that define in config.php ?

答:
If you have a .htaccess file in the root directory that is used to allow "pretty URLs", you can add some commands that will force a redirect the "https" protocol.

After the line

```<code>RewriteEngine on
</code>```

at these lines

```<code>RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</code>```

The rest of the commands remain the same.

Leave your setting of $config['base_url'] as you show in the question. No other code changes are required.

Title: Cannot access https on codeigniter

Body:
The following is my base_url of config.php in my project.

$config['base_url'] = 'https://www.mywebsite.com/';

But my website always go to http://www.mywebsite.com unless the user implicitly write https in browser url.

What is the problem?

Why codeigniter goes to url that define in config.php ?

Body:
If you have a .htaccess file in the root directory that is used to allow "pretty URLs", you can add some commands that will force a redirect the "https" protocol.

After the line

RewriteEngine on

at these lines

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

The rest of the commands remain the same.

Leave your setting of $config['base_url'] as you show in the question. No other code changes are required.


问:
Babel throws a syntax error on arrow function
I'm trying to adapt this code for a small project with React, but I'm having trouble, and I don't know how to fix this, because I don't know if this is the original code or my Babel that's buggy (like, missing a library or something), or if I can't because React.

So the thing is I had to adapt some functions because otherwise Babel would throw an unexpected token on them, i.e,

```<code>static propTypes = { // unexpected '='
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.string.isRequired,
  orderBy: PropTypes.string.isRequired,
};
</code>```

became

```<code>static get propTypes() {
    return {
        onRequestSort: PropTypes.func.isRequired,
        onSelectAllClick: PropTypes.func.isRequired,
        order: PropTypes.string.isRequired,
        orderBy: PropTypes.string.isRequired,
    }
}
</code>```

and this:

```<code>handleRequestSort = (event, property) => { ... } // unexpected '='
</code>```

became this:

```<code>handleRequestSort(event, property) { ... }
</code>```

For my main issue, I replaced this:

```<code>createSortHandler = property => event => { // unexpected '='
    this.props.onRequestSort(event, property);
};
</code>```

by this

```<code>createSortHandler(property) {
    return function (event) {
        this.props.onRequestSort(event, property);
    };
};
</code>```

However, if I click on the arrow on the table that triggers the order's change, I get  cannot read props of undefined. Otherwise, I get `unexpected token '=', as written in my code.

So my question is the following: is the original code buggy, is it my babel or is it something else? I'm currently on a Rails base with webpacker, but i don't believe this is the reason why I have these issues.

答:
You're missing the babel-plugin-transform-class-properties plugin to transform the class properties which is experimental syntax (hence the unexpected token =). Include that in Babel configuration if you would like to use class properties for propTypes and class property arrow functions. The second error, that this.props is undefined is because you're using a regular function which this doesn't refer to the component. Return an arrow function instead:

```<code>createSortHandler(property) {
  return (event) => {
    this.props.onRequestSort(event, property);
  };
};
</code>```

Body:
I'm trying to adapt this code for a small project with React, but I'm having trouble, and I don't know how to fix this, because I don't know if this is the original code or my Babel that's buggy (like, missing a library or something), or if I can't because React.

So the thing is I had to adapt some functions because otherwise Babel would throw an unexpected token on them, i.e,

static propTypes = { // unexpected '='
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.string.isRequired,
  orderBy: PropTypes.string.isRequired,
};

became

static get propTypes() {
    return {
        onRequestSort: PropTypes.func.isRequired,
        onSelectAllClick: PropTypes.func.isRequired,
        order: PropTypes.string.isRequired,
        orderBy: PropTypes.string.isRequired,
    }
}

and this:

handleRequestSort = (event, property) => { ... } // unexpected '='

became this:

handleRequestSort(event, property) { ... }

For my main issue, I replaced this:

createSortHandler = property => event => { // unexpected '='
    this.props.onRequestSort(event, property);
};

by this

createSortHandler(property) {
    return function (event) {
        this.props.onRequestSort(event, property);
    };
};

However, if I click on the arrow on the table that triggers the order's change, I get  cannot read props of undefined. Otherwise, I get `unexpected token '=', as written in my code.

So my question is the following: is the original code buggy, is it my babel or is it something else? I'm currently on a Rails base with webpacker, but i don't believe this is the reason why I have these issues.

Body:
You're missing the babel-plugin-transform-class-properties plugin to transform the class properties which is experimental syntax (hence the unexpected token =). Include that in Babel configuration if you would like to use class properties for propTypes and class property arrow functions. The second error, that this.props is undefined is because you're using a regular function which this doesn't refer to the component. Return an arrow function instead:

createSortHandler(property) {
  return (event) => {
    this.props.onRequestSort(event, property);
  };
};


问:
How can I include a model association in a JSON response in Rails?
I've looked at similar posts but can't seem to quite figure it out.

I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response.

How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?

```<code>def update
    @listing = Listing.find(params[:listing][:id])

    #if params were passed in for updating
    if @listing.update_attributes(params[:listing])
    #should we return the whole thing or just what's needed?
        json_response = {
             "success" => @listing.save, #save to DB and assign true/false based on success...
             "message" => @listing.attributes #USE attributes to show output the content of the @message obj, and not another object called "message"
        }

        respond_to do |format|
            #json response
            format.html { render:json => json_response }
            format.xml { render :xml => @listing }

            #normal response. Consider leaving this for now?
            #format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
            #format.xml  { head :ok }
        end
    end #end if

end
</code>```

答:
add a method in your Listing model with the price_range and call it in serializable_hash

```<code>class Listing

  def price_range
    price.price_range
  end
end
</code>```

Like explain on comment you can use delegate instead this method :

```<code>class Listing
  delegate :prince_range, :to => price
end
</code>```

In you controller you can now do :

```<code>   json_response = {
         "success" => @listing.save, #save to DB and assign true/false based on success...
         "message" => @listing.serializable_hash(:methods => [:price_range])
    }
</code>```

Body:
I've looked at similar posts but can't seem to quite figure it out.

I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response.

How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?

def update
    @listing = Listing.find(params[:listing][:id])

    #if params were passed in for updating
    if @listing.update_attributes(params[:listing])
    #should we return the whole thing or just what's needed?
        json_response = {
             "success" => @listing.save, #save to DB and assign true/false based on success...
             "message" => @listing.attributes #USE attributes to show output the content of the @message obj, and not another object called "message"
        }

        respond_to do |format|
            #json response
            format.html { render:json => json_response }
            format.xml { render :xml => @listing }

            #normal response. Consider leaving this for now?
            #format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
            #format.xml  { head :ok }
        end
    end #end if

end

Body:
add a method in your Listing model with the price_range and call it in serializable_hash

class Listing

  def price_range
    price.price_range
  end
end

Like explain on comment you can use delegate instead this method :

class Listing
  delegate :prince_range, :to => price
end

In you controller you can now do :

   json_response = {
         "success" => @listing.save, #save to DB and assign true/false based on success...
         "message" => @listing.serializable_hash(:methods => [:price_range])
    }


问:
PostgreSQL does not post a field
I'm currently running through using Node-Express and Sequelize as the ORM for PostgreSQL. I am trying to test my API route when I noticed that my todoId is not being returned. When I check my table I see a null value even though I have allowNull:false set.

```<code>module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.createTable('TodoItems', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      content: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      complete: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      todoId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        allowNull: false,
        references: {
          model: 'Todos',
          key: 'id',
          as: 'todoId',
        },
      },
    }),
  down:(queryInterface/*, Sequelize*/) => queryInterface.dropTable('TodoItems'),
};
</code>```

I have tried everything from dropping my database and creating a new one and migrations for the schema all over again. What I'm trying to achieve is to ensure that the value of the todoId column references and maps my the id of a separate table called todo.

答: Solved it. The error was using a deprecated class methods</p>

Title: PostgreSQL does not post a field

Body:
I'm currently running through using Node-Express and Sequelize as the ORM for PostgreSQL. I am trying to test my API route when I noticed that my todoId is not being returned. When I check my table I see a null value even though I have allowNull:false set.

module.exports = {
  up: (queryInterface, Sequelize) =>
    queryInterface.createTable('TodoItems', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      content: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      complete: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      todoId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        allowNull: false,
        references: {
          model: 'Todos',
          key: 'id',
          as: 'todoId',
        },
      },
    }),
  down:(queryInterface/*, Sequelize*/) => queryInterface.dropTable('TodoItems'),
};

I have tried everything from dropping my database and creating a new one and migrations for the schema all over again. What I'm trying to achieve is to ensure that the value of the todoId column references and maps my the id of a separate table called todo.


问:
Formtastic/ActiveAdmin set a default value for a select input
I am working on a custom form in ActiveAdmin which I decided to use it for adding/editing to follow the DRY principle so I need to populate it if the user uses it for editing a record ( which isn't a DB record ).

So the problem is I have those inputs :

```<code>f.input :model_id, as: :select, collection: Model.all.map { |m| [m.id.to_s + ' - ' + m.name, m.id] }, input_html: { required: true }
f.input :enabled, as: :select, collection: {'Yes': true, 'No': false}, input_html: { required: true }
</code>```

And I'd like to set a default value for them if I'm using the form for editing but I failed to know how because everybody is talking about using belongs_to or a DB relation and ActiveAdmin will take care of the default value for you which isn't applicable for my case because it's not a DB record and I don't have an ActiveRecord Model for it.

Even the official docs of Formtastic didn't help.

答:
I figured out how to do it and here is the answer for anyone facing the same problem :</p>

```<code>f.input :model_id, collection: Model.all.map { |m| [m.id.to_s + ' - ' + m.name, m.id] }, selected: object.model_id
f.input :enabled, collection: { 'Yes': true, 'No': false }, selected: object.enabled
</code>```

Body:
I am working on a custom form in ActiveAdmin which I decided to use it for adding/editing to follow the DRY principle so I need to populate it if the user uses it for editing a record ( which isn't a DB record ).

So the problem is I have those inputs :

f.input :model_id, as: :select, collection: Model.all.map { |m| [m.id.to_s + ' - ' + m.name, m.id] }, input_html: { required: true }
f.input :enabled, as: :select, collection: {'Yes': true, 'No': false}, input_html: { required: true }

And I'd like to set a default value for them if I'm using the form for editing but I failed to know how because everybody is talking about using belongs_to or a DB relation and ActiveAdmin will take care of the default value for you which isn't applicable for my case because it's not a DB record and I don't have an ActiveRecord Model for it.

Even the official docs of Formtastic didn't help.

Body:
I figured out how to do it and here is the answer for anyone facing the same problem :

f.input :model_id, collection: Model.all.map { |m| [m.id.to_s + ' - ' + m.name, m.id] }, selected: object.model_id
f.input :enabled, collection: { 'Yes': true, 'No': false }, selected: object.enabled


问:
php ajax file upload issue
I have a form with various inputs and a file input for uploading 1 image. I am using ajax to post the data. When I submit, I get a console error that says

Undefined index: file

Before making it more secure, I am just trying to get it to actually upload the file.

```<code>$target_dir = "../img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
    $status = 1;
}
</code>```

jQuery

```<code>$('form').submit(function(e){
    e.preventDefault();
    var form = $( "#form1" ).serialize();
    $(".alert").hide();
    $.ajax({
        url: 'functions/add-news-ajax.php',
        type: 'POST',
        dataType: 'json',
        data: form,

        beforeSend: function() {
            $( "#btn-add" ).hide();
            $( "#loader" ).show();
        },
    })

    .done(function (data) {
        if(!data.success) {
        // validation messages etc..
</code>```

答:
I'm afraid you won't be able to send your image through serialize

```<code>var form = $( "#form1" ).serialize();
</code>```

Try this :

```<code> $('form').submit(function(e){
    e.preventDefault();
    //var form = $( "#form1" ).serialize();
    var form = new FormData($(this));
    (...)
</code>```

where $this is your form element.

Title: php ajax file upload issue

Body:
I have a form with various inputs and a file input for uploading 1 image. I am using ajax to post the data. When I submit, I get a console error that says

Undefined index: file

Before making it more secure, I am just trying to get it to actually upload the file.

$target_dir = "../img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
    $status = 1;
}

jQuery

$('form').submit(function(e){
    e.preventDefault();
    var form = $( "#form1" ).serialize();
    $(".alert").hide();
    $.ajax({
        url: 'functions/add-news-ajax.php',
        type: 'POST',
        dataType: 'json',
        data: form,

        beforeSend: function() {
            $( "#btn-add" ).hide();
            $( "#loader" ).show();
        },
    })

    .done(function (data) {
        if(!data.success) {
        // validation messages etc..

Body:
I'm afraid you won't be able to send your image through serialize

var form = $( "#form1" ).serialize();

Try this :

 $('form').submit(function(e){
    e.preventDefault();
    //var form = $( "#form1" ).serialize();
    var form = new FormData($(this));
    (...)

where $this is your form element.


问:
Layout missed up on 3.5" Screen iPhone 4
I have developed my App on XCODE 8  which by default removes iPhone 4 emulator and I didn't notice that until I finished my app, and I used Auto layout to make the UI fits all iPhone screens and that what happened (the layout was good on iPhone 7,6,5) the problem is when I additionally installed iPhone 4 emulator I found that the layout is totally missed up and unreadable/usable.

So what options do I have to solve this and make it fit the iPhone 4 screen too with Auto-Layout with missing up the other sizes ?

Here is screen shot of my Login screen on iPhone 6 (4.7") vs iPhone 4 (3.5")

答: It seems like your constraint is set to have a fixed distance related to the top of your screen. So when the screen height get smaller, your views are pushed out of the screen. So to better adjust views position, you can have your views to be related to vertical center. Say your login box is in both horizontal and vertical center, not metter you are using iphone 6 or 4, you should always see your login box.


问:
What does the column and rows for images in TensorBoard mean?
I was trying to use the tensorflow tf. image_summary but it wasn't clear to me how to use it. In the tensorboard readme file they have the following sentence that confuses me:

The dashboard is set up so that each row corresponds to a different
  tag, and each column corresponds to a run.

I don't understand the sentence and thus, I am having a hard time figuring out what the columns and rows mean for TensorBoard image visualization. What exactly is a "tag" and what exactly is a "run"? How do I get multiple "tags" and multiple "runs" to display? Why would I want multiple "tags" and "runs" to display?

Does someone have a very simple but non-trivial example of how to use this?

Ideally, what I want to use is compare how my model performs with respect to PCA so in my head it would be nice to compare how the reconstructions compare to PCA reconstruction at each step. Not sure if this is a good idea but I also want to see what the activation images look like and how the templates look like.

Curenttly I have a very simple script with the following lines:

```<code>with tf.name_scope('input_reshape'):
    x_image = tf.to_float(x, name='ToFloat')
    image_shaped_input = tf.reshape(x_image, [-1, 28, 28, 1])
    tf.image_summary('input', image_shaped_input, 10)
</code>```

currently I have managed to discover that the rows are of length 10 so i assume its showing me 10 images that have something to do with the current run/batch.

however, if possible I'd like to see reconstruction, filters (currently I am doing fully connected to keep things simple but eventually it would be nice to see a conv net examples), activation units (with any number of units that I choose), etc.

答:
TensorFlow was officially released (r1.0) after this question was posed, and the functions and documentation accompanying Tensorboard have been simplified.

tf.summary.image is now the Op for writing images represented by a 4D Tensor to the summary file; here is the documentation.

To answer your questions about rows and columns, each call to tf.summary.image generates a new tag or row of image summaries with the total number dictated by the value passed as max_outputs (10 in your given example).

As to why one might want to view more than one column of data, If the first dimension of the 4D Tensor is greater than 1 (i.e. batch size > 1), it will be helpful to see more than one column in Tensorboard to get a better sense of the entire batch of images.

Finally, having multiple tags is helpful when wanting to view two different collections of images, such as input images and reconstructed images if you were building an autoencoder architecture.

Body:
I was trying to use the tensorflow tf. image_summary but it wasn't clear to me how to use it. In the tensorboard readme file they have the following sentence that confuses me:

The dashboard is set up so that each row corresponds to a different
  tag, and each column corresponds to a run.

I don't understand the sentence and thus, I am having a hard time figuring out what the columns and rows mean for TensorBoard image visualization. What exactly is a "tag" and what exactly is a "run"? How do I get multiple "tags" and multiple "runs" to display? Why would I want multiple "tags" and "runs" to display?

Does someone have a very simple but non-trivial example of how to use this?

Ideally, what I want to use is compare how my model performs with respect to PCA so in my head it would be nice to compare how the reconstructions compare to PCA reconstruction at each step. Not sure if this is a good idea but I also want to see what the activation images look like and how the templates look like.

Curenttly I have a very simple script with the following lines:

with tf.name_scope('input_reshape'):
    x_image = tf.to_float(x, name='ToFloat')
    image_shaped_input = tf.reshape(x_image, [-1, 28, 28, 1])
    tf.image_summary('input', image_shaped_input, 10)

currently I have managed to discover that the rows are of length 10 so i assume its showing me 10 images that have something to do with the current run/batch.

however, if possible I'd like to see reconstruction, filters (currently I am doing fully connected to keep things simple but eventually it would be nice to see a conv net examples), activation units (with any number of units that I choose), etc.


答:
You can get all the children of the class by this method

```<code>var c = document.getElementById("navButtons").children;
</code>```

c is now an Array. So you can iterate over this array, thereby having contact with each child
i.e c[0] is the first element

Body:
I am trying to make the class navButtons effect all of the ids inside it using the mouse over  effect. I read on here that you can do this with a for loop but that would require changing the names of the ids. is there a way to do this without changing the names?

document.getElementsByClassName("navButtons").addEventListener("mouseover", mouseOver);
document.getElementsByClassName("navButtons").addEventListener("mouseout", mouseOut);

function mouseOver() {
    document.getElementsByClassName("navButtons").style.color = "red";
}

function mouseOut() {
    document.getElementsByClassName("navButtons").style.color = "black";
}

about

portfolio

contact

Body:
You can get all the children of the class by this method

var c = document.getElementById("navButtons").children;

c is now an Array. So you can iterate over this array, thereby having contact with each child
i.e c[0] is the first element


问:
Dictionary without generics
I'm learning C# and I have an exercise with these three classes:

```<code>public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>
</code>```

On the exercise there is this:

```<code>var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };
</code>```

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

```<code>public class Dictionary : Dictionary<object, object>
</code>```

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

答:
In .NET Dictionary class is generic, and there is no other class named Dictionary in BCL.
You can get a similar functionality form the predescessor - HashTable that also implements IDictionary interface

Note, that there is no need to inherit from Dictionary - just use the instance of generic class with the types you need, or use a Hashtable.

If you are in doubt if a specific class is in the BCL or not - check it's namespace.

If you are curious about it's implementation check reference source

Specifically for your exersise, it looks like you have to inherit from Dictionary and use a collection initializer:

Note: Don't inherit from Dictionary in production code, most of the times it is unnecessary.

```<code>namespace ClassLibrary2
{
    public class TestClass
    {
        public abstract class BaseClass<T> where T : BaseClass<T> {}

        public class Class1 { }

        public class Class2 : BaseClass<Class2> { }

        private class Dictionary : Dictionary<Class1, Class2> { }

        public void Test()
        {
            var dictionary = new Dictionary { { new Class1(), new Class2() } };
        }
    }
}
</code>```

By the way, having this public abstract class BaseClass<T> where T : BaseClass<T> {} is an example of curiously recurring template pattern, @Eric Lippert wrote a nice article on that - see Curiouser and curiouser

Title: Dictionary without generics

Body:
I'm learning C# and I have an exercise with these three classes:

public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>

On the exercise there is this:

var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

public class Dictionary : Dictionary<object, object>

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

Body:
In .NET Dictionary class is generic, and there is no other class named Dictionary in BCL.
You can get a similar functionality form the predescessor - HashTable that also implements IDictionary interface

Note, that there is no need to inherit from Dictionary - just use the instance of generic class with the types you need, or use a Hashtable.

If you are in doubt if a specific class is in the BCL or not - check it's namespace.

If you are curious about it's implementation check reference source

Specifically for your exersise, it looks like you have to inherit from Dictionary and use a collection initializer:

Note: Don't inherit from Dictionary in production code, most of the times it is unnecessary.

namespace ClassLibrary2
{
    public class TestClass
    {
        public abstract class BaseClass<T> where T : BaseClass<T> {}

        public class Class1 { }

        public class Class2 : BaseClass<Class2> { }

        private class Dictionary : Dictionary<Class1, Class2> { }

        public void Test()
        {
            var dictionary = new Dictionary { { new Class1(), new Class2() } };
        }
    }
}

By the way, having this public abstract class BaseClass<T> where T : BaseClass<T> {} is an example of curiously recurring template pattern, @Eric Lippert wrote a nice article on that - see Curiouser and curiouser


问:
Join two tables, where one is not uniqe
Hey everyone. I need to join two tables according to those parameters:

1) I need only data that are both in the first and in the second table

2) Data in the second table can have more rows attached to one row of the first table, but I need those rows displayed only once.

I tried this

```<code>SELECT * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id
</code>```

but I am getting duplicates, as mentioned.

Thanks

答:
To collapse a group of rows into a single row in the result set, use a GROUP BY clause. The GROUP BY clause should specify all columns which have identical values in each set to collapse into a single row. Your query should not SELECT any columns that are not part of the GROUP BY clause unless they are aggregate columns, allowing the RDBMS to know which of the values you want.

If you only wanted the columns from one table which have a corresponding row in the other, then you don't need the join or group at all.

```<code>SELECT * FROM table1 WHERE some_column IN (SELECT related_column FROM table2)
</code>```

or use a WHERE EXISTS clause.

Title: Join two tables, where one is not uniqe

Body:
Hey everyone. I need to join two tables according to those parameters:

1) I need only data that are both in the first and in the second table

2) Data in the second table can have more rows attached to one row of the first table, but I need those rows displayed only once.

I tried this

SELECT * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id

but I am getting duplicates, as mentioned.

Thanks

Body:
To collapse a group of rows into a single row in the result set, use a GROUP BY clause. The GROUP BY clause should specify all columns which have identical values in each set to collapse into a single row. Your query should not SELECT any columns that are not part of the GROUP BY clause unless they are aggregate columns, allowing the RDBMS to know which of the values you want.

If you only wanted the columns from one table which have a corresponding row in the other, then you don't need the join or group at all.

SELECT * FROM table1 WHERE some_column IN (SELECT related_column FROM table2)

or use a WHERE EXISTS clause.


问:
Print related object of related object python
I am creating a guide app where each guide is made of 3 classes as bellow.

How do I for example print subtask 3 of step 2 in guide 1

This is what I can do in the shell so far.

```<code>class Guide(models.Model):
    user = models.ForeignKey(User, default=1)
    guide_category = models.CharField(max_length=250)
    guide_title = models.CharField(max_length=500)
    guide_how = models.CharField(max_length=100)
    guide_why = models.CharField(max_length=100)
    guide_logo = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.guide_title + ' - ' + self.guide_category + ' - ' + self.guide_how + ' - ' + self.guide_why

class Step(models.Model):
    guide = models.ForeignKey(Guide, on_delete=models.CASCADE)
    step_title = models.CharField(max_length=250)
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.step_title

class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.subtask_title
</code>```

This is what I can do in the shell so far.

```<code>from appname.models import Guide, Step, Subtask
guide1 = Guide(pk=1)
guide2 = Guide(pk=2)
>>> Guide.objects.all()
[<Guide: Test1 - CR - how1 - why2>, <Guide: test2 - VR - how2 - why2>]
>>> Step.objects.all()
[<Step: 1>, <Step: 2>, <Step: 1>, <Step: 2>]
>>> Subtask.objects.all()
[<Subtask: 1.1.1>, <Subtask: 1.1.2>, <Subtask: 1.2.1>, <Subtask: 1.2.2>, <Subtask: 2.1.1>]
</code>```

Thanks! :)

答:
```<code>class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return ' '.join([self.subtask_title, '.'.join([str(self.step.guide.id), str(self.step.id), str(self.id)])])
</code>```

and test it:

```<code>Subtask.objects.all()
</code>```

Body:
I am creating a guide app where each guide is made of 3 classes as bellow.

How do I for example print subtask 3 of step 2 in guide 1

This is what I can do in the shell so far.

class Guide(models.Model):
    user = models.ForeignKey(User, default=1)
    guide_category = models.CharField(max_length=250)
    guide_title = models.CharField(max_length=500)
    guide_how = models.CharField(max_length=100)
    guide_why = models.CharField(max_length=100)
    guide_logo = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.guide_title + ' - ' + self.guide_category + ' - ' + self.guide_how + ' - ' + self.guide_why

class Step(models.Model):
    guide = models.ForeignKey(Guide, on_delete=models.CASCADE)
    step_title = models.CharField(max_length=250)
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.step_title

class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return self.subtask_title

This is what I can do in the shell so far.

from appname.models import Guide, Step, Subtask
guide1 = Guide(pk=1)
guide2 = Guide(pk=2)
>>> Guide.objects.all()
[<Guide: Test1 - CR - how1 - why2>, <Guide: test2 - VR - how2 - why2>]
>>> Step.objects.all()
[<Step: 1>, <Step: 2>, <Step: 1>, <Step: 2>]
>>> Subtask.objects.all()
[<Subtask: 1.1.1>, <Subtask: 1.1.2>, <Subtask: 1.2.1>, <Subtask: 1.2.2>, <Subtask: 2.1.1>]

Thanks! :)

Body:
class Subtask(models.Model):
    step = models.ForeignKey(Step, on_delete=models.CASCADE)
    subtask_title = models.CharField(max_length=250)
    subtask_description = models.CharField(max_length=250)
    subtask_image = models.FileField()
    is_complete = models.BooleanField(default=False)

    def __str__(self):
        return ' '.join([self.subtask_title, '.'.join([str(self.step.guide.id), str(self.step.id), str(self.id)])])

and test it:

Subtask.objects.all()


问:
Cannot setup floating action buttons as class cannot be found (Android Studio)
So I am pretty new to android and I am trying to setup a floating action button with the Android Design Support Library using this guide in Android Studio.

My Project: Noted build.gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

My Module: app build.gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.noted"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
}
</code>```

In myactivity_main.xml I try to implement

```<code><android.support.design.widget.FloatingActionButton
    ... />
</code>```

but I get one of those Rendering Problems pop ups after building saying:

The following classes could not be found:
  -android.support.design.widget.FloatingActionButton

My guess is that I'm doing something wrong with my dependencies but I really have no idea. I have been trying to get this to work for hours with no luck and would really appreciate any help.

Thanks!

答:
I had the same problem with Android Studio complaining that it couldn't instantiate FloatingActionButton.  The "Exception Details" showed this:

```<code>java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
    at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:159)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:153)
</code>```

Basically, I was using Material.Light as my theme, but I needed to use an AppCompat theme.  I switched to AppCompat.Light and the problem was solved!

Body:
So I am pretty new to android and I am trying to setup a floating action button with the Android Design Support Library using this guide in Android Studio.

My Project: Noted build.gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

My Module: app build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.noted"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

In myactivity_main.xml I try to implement

<android.support.design.widget.FloatingActionButton
    ... />

but I get one of those Rendering Problems pop ups after building saying:

The following classes could not be found:
  -android.support.design.widget.FloatingActionButton

My guess is that I'm doing something wrong with my dependencies but I really have no idea. I have been trying to get this to work for hours with no luck and would really appreciate any help.

Thanks!

Body:
I had the same problem with Android Studio complaining that it couldn't instantiate FloatingActionButton.  The "Exception Details" showed this:

java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
    at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:159)
    at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:153)

Basically, I was using Material.Light as my theme, but I needed to use an AppCompat theme.  I switched to AppCompat.Light and the problem was solved!


问:
javascript match hebrew word inside double curly brackets
i have a js function that working in english but i get error in hebrew

the function match all the words in string that inside  {{ }} and return the word inside the double curly bracket in a array without the curly bracket
the string can Contains both english and non english words like this:    {{test}} {{בדיקה}} hi this is my test {{test2}}

```<code>var str_eng =  "{{test}} {{test1}}";
var str_non_eng = "{{בדיקה}} {{עעע}}";

str_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) //array[ "test","test1" ] //ok

str_non_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) // error not working
</code>```

Thanks!

答:
\w does not match Hebrew characters - to do that you need to match on the Unicode range for Hebrew with [\u0590-\u05FF] - see here.

You can blend \w and [\u0590-\u05FF] to match both ASCII and Hebrew:

// var str_non_eng = "{{בדיקה}} {{עעע}}";
var str_non_eng = "{{test}} {{בדיקה}} hi this is my test {{test2}}";

var r1 = /{{\s*[\w\u0590-\u05FF\.]+\s*}}/g
var r2 = /[\w\u0590-\u05FF\.]+/;

var foo = str_non_eng.match(r1).map(function(x) {
  return x.match(r2)[0];
});
console.log(foo);```

Body:
i have a js function that working in english but i get error in hebrew

the function match all the words in string that inside  {{ }} and return the word inside the double curly bracket in a array without the curly bracket
the string can Contains both english and non english words like this:    {{test}} {{בדיקה}} hi this is my test {{test2}}

var str_eng =  "{{test}} {{test1}}";
var str_non_eng = "{{בדיקה}} {{עעע}}";

str_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) //array[ "test","test1" ] //ok

str_non_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) // error not working

Thanks!


问:
How to prevent users from editing the same record in WPF
I'm developing a WPF application for multiple user work on the same local network using MS SQL Server. I want to prevent users from editing the same record at the same time.

Example: Let us say the User1 modifying record number 5, If User2 Try to view or modify record 5 the application will return warning message to the User 2.

Any Idea?

Thanks in advance

答:
You can create another table called ModifyCheck, just containing the record_id and user_id.
When a user is modifying a record, it should insert an entry into ModifyCheck.
When the user finish modifying that record, you can either delete that entry or update it to reflect completed. Can store timestamp too.

So when another user tries to view / modify, you need to do a check with ModifyCheck table to see if that specific record is being modified right now.


问:
IDE for C application development that you admire most
I am looking for a good Integrated development environment for developing applictaions in C language for both windows and linux.

IDE should have:

good interface,

easy file management,

auto filling and

any advanced options.

Tell me which IDE you most admire for these tasks

For general PC application development

For embedded application development in C

If you think it is more specific question then you may also take it as a general case.
Thanks in advance.

答:
For general PC development - Microsoft Visual Studio + VisualAssist

For large-scale development you can hardly find anything better than Source Insight

If you need a cross-platform IDE have a look at Eclipse CDT

OwnerDisplayName: Manoj Doubts

OwnerDisplayName: aku

LastEditorDisplayName: aku


答:
```<code>SELECT distinct * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id
</code>```

That should get rid of the duplicates? Is that what you are looking for?

Title: Join two tables, where one is not uniqe

Body:
SELECT distinct * FROM table AS p
            JOIN `table2` AS ps ON (p.id = ps.`id_table2`)
            ORDER BY p.id

That should get rid of the duplicates? Is that what you are looking for?


问:
Variable being passed with single quotes using PHP and MYSQL
I have the following variable I want to pass to a prepare statement: $subject. It is done using PDO. Unfortunately it is being passed in with single quotes around it.Example is that i pass in maths and the query uses 'maths' instead. I have tried other answers such as bindParam, bindValue as well as specifying it is a string attribute, however I cannot get it to work. Thanks in advance if anyone knows what is wrong My code is below.

```<code>$query = "SELECT * FROM :subject;";
        $sql = $connection->prepare($query);
        $sql->bindParam(':subject', $subject);
        try{
            $sql->execute();
        }catch(Exception $e){
            echo $e;
        }
</code>```

And i get the following error:

```<code>exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maths'' at line 1' in D:\xampp\htdocs\acards\functions.php:18
Stack trace:
#0 D:\xampp\htdocs\acards\functions.php(18): PDOStatement->execute()
#1 D:\xampp\htdocs\acards\getMathsQuestions.php(13): Functions->getFeed('maths')
#2 {main}[]
</code>```

答:
The issue is here:

```<code>"SELECT * FROM :subject;";
</code>```

bindParam is used with the parameters which are used in where clause, not in the table name.

The correct syntax is like:

```<code>$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
</code>```

Reference

Body:
I have the following variable I want to pass to a prepare statement: $subject. It is done using PDO. Unfortunately it is being passed in with single quotes around it.Example is that i pass in maths and the query uses 'maths' instead. I have tried other answers such as bindParam, bindValue as well as specifying it is a string attribute, however I cannot get it to work. Thanks in advance if anyone knows what is wrong My code is below.

$query = "SELECT * FROM :subject;";
        $sql = $connection->prepare($query);
        $sql->bindParam(':subject', $subject);
        try{
            $sql->execute();
        }catch(Exception $e){
            echo $e;
        }

And i get the following error:

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maths'' at line 1' in D:\xampp\htdocs\acards\functions.php:18
Stack trace:
#0 D:\xampp\htdocs\acards\functions.php(18): PDOStatement->execute()
#1 D:\xampp\htdocs\acards\getMathsQuestions.php(13): Functions->getFeed('maths')
#2 {main}[]

Body:
The issue is here:

"SELECT * FROM :subject;";

bindParam is used with the parameters which are used in where clause, not in the table name.

The correct syntax is like:

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

Reference


问:
Hide/Blur Activity on opening another Activity over as pop-up Window(Not a Dialog Box) In Android
I am finding the solution from last few days, a solution will appreciate.
The scenario is:
There are two activities in my application 1. mainActivity 2.newActivity. On button click on mainActivity newActivity will be open as a pop-up window(not a dialog box). I want to hide/blur mainActivity when pop-up window(newActivity) is active and display mainActivity when pop-up(newActivity) activity close. how can I achieve this?

答:
You can set background color code "#CC000000" of "newActivity" in xml layout.

Just use android:background="#CC000000" for your main Layout.


问:
Flex/Bison PHP AST generation
This is basically second part of my first Question which is about making source code browser. After reading tutorials I found that I need to parse PHP file and Build AST and from there I will have symbols I need. However, searching for days have brought nothing useful on how I can do that. Is there any tutorial or question already answered about building PHP AST?
Sorry if it is answered somewhere, my searches found nothing useful! </p>

答:
In 2017 there is stable and powerful tool for that - PHP-Parser.

It allows TOKEN parsing and AST parsing of the PHP source code.

Here is AST code generation example.

If you look for C extension that would allow it, check nikic/ast.

Title: Flex/Bison PHP AST generation


问:
Variable '' is used before it has been assigned a value.
I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.</p>

```<code>Sub Main()
    Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
    Console.WriteLine("Downloading . . . ")
    Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
    If System.IO.File.Exists(FileDelete) = True Then
        System.IO.File.Delete(FileDelete)
    End If
    download()
    Threading.Thread.Sleep(1000)
    Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
    Dim tempRead As String ' = s.ReadLine
    Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
    Dim i As Integer = 0
    Dim tempStore As String()
    s.ReadLine()
    s.ReadLine()
    Do Until s.EndOfStream = True
        tempRead = s.ReadLine
        tempSplit = tempRead.Split(New Char() {" "})
        Console.WriteLine(tempSplit(0))
        tempStore(i) = tempSplit(0)'The part that gives me the error
        i = i + 1
    Loop
    Console.ReadKey()
End Sub

Sub download()
    Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
    '"Enter file URL"
    Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
    '"Enter directory"
    Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
    My.Computer.Network.DownloadFile(url, dirr)
    'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub
</code>```

答:
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.

```<code>    Function countlines()
    Dim count As Integer
    Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
    s.ReadLine()
    s.ReadLine()
    count = 0
    Do Until s.EndOfStream = True
        s.ReadLine()
        count = count + 1
    Loop
    Console.WriteLine(count)
    Return count
    Console.ReadKey()
End Function
</code>```

Then what you do is:

```<code>    Dim count As Integer
    count = countlines()

    Dim tempStore(count) As String
</code>```

Body:
I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.

Sub Main()
    Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
    Console.WriteLine("Downloading . . . ")
    Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
    If System.IO.File.Exists(FileDelete) = True Then
        System.IO.File.Delete(FileDelete)
    End If
    download()
    Threading.Thread.Sleep(1000)
    Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
    Dim tempRead As String ' = s.ReadLine
    Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
    Dim i As Integer = 0
    Dim tempStore As String()
    s.ReadLine()
    s.ReadLine()
    Do Until s.EndOfStream = True
        tempRead = s.ReadLine
        tempSplit = tempRead.Split(New Char() {" "})
        Console.WriteLine(tempSplit(0))
        tempStore(i) = tempSplit(0)'The part that gives me the error
        i = i + 1
    Loop
    Console.ReadKey()
End Sub

Sub download()
    Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
    '"Enter file URL"
    Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
    '"Enter directory"
    Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
    My.Computer.Network.DownloadFile(url, dirr)
    'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub

Body:
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.

    Function countlines()
    Dim count As Integer
    Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
    s.ReadLine()
    s.ReadLine()
    count = 0
    Do Until s.EndOfStream = True
        s.ReadLine()
        count = count + 1
    Loop
    Console.WriteLine(count)
    Return count
    Console.ReadKey()
End Function

Then what you do is:

    Dim count As Integer
    count = countlines()

    Dim tempStore(count) As String


问:
Do I need to bundle AWS SDK dependancies when creating Java Lambda Functions
When creating Java based Lambda Functions using the AWS Eclipse Plugin I see that the uploaded zip files include all the AWS dependencies as defined in the POM file.

Is this by design? Are the required dependencies not available from the "class path" of the executing Lambda Function at runtime?

答:
Yes, it is by design, though I have been able to trim down the dependencies considerably over what the plugin adds just by adding only the dependencies I need in the POM file. You can create a POM file that packages dependencies by using either the apache shade plugin or the maven assembly plugin. From the AWS docs:

The build creates this resulting .jar, using information in the pom.xml to do the necessary transforms. This is a standalone .jar (.zip file) that includes all the dependencies. This is your deployment package that you can upload to AWS Lambda to create a Lambda function.

References:

Maven Deployment package and upload to AWS-Lambda

Creating a .jar Deployment Package Using Maven without any IDE (Java)


问:
template does not exist error in django?
it renders the form correctly

```<code><div >
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form }}
    <input type="submit">
</form>
</div>
</code>```

but while rendering

```<code><div >
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form.form_element }}
    <input type="submit">
</form>
</div>
</code>```

but while rendering the single form field on submitting it shows template does not exist. I am using UpdateView to render the form

```<code>class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
</code>```

in part_view_detail I am passing the form that is to be rendered in the  part_detail_view

```<code>class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        context['form'] = part_stock_form()
        return context
</code>```

答:
I think you wanna hide some form fields in template. This may be useful for you.

You can check the documentation for more information;

https://docs.djangoproject.com/en/1.11/topics/forms/#looping-over-the-form-s-fields

```<code>{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}
</code>```

Body:
it renders the form correctly

<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form }}
    <input type="submit">
</form>

but while rendering

<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
          {{ form.form_element }}
    <input type="submit">
</form>

but while rendering the single form field on submitting it shows template does not exist. I am using UpdateView to render the form

class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

in part_view_detail I am passing the form that is to be rendered in the  part_detail_view

class part_detail_view(DetailView):
    model = part_list
    context_object_name = 'part_detail'
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(part_detail_view, self).get_context_data(**kwargs)
        context['my_list'] = populate_nav_bar()
        context['form'] = part_stock_form()
        return context

Body:
I think you wanna hide some form fields in template. This may be useful for you.

You can check the documentation for more information;

https://docs.djangoproject.com/en/1.11/topics/forms/#looping-over-the-form-s-fields

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}


问:
Programmatically pushing data to Quickbooks Online?
Our company uses Quickbooks Online to track our books. When our application bills a customer, it would be nice to have that information recorded automatically in QB rather than logging in to QB Online to fill in the info.

Is there a way to accomplish this using Quickbook's APIs? The Intuit developer information is very confusing; it is mainly oriented towards extending the desktop version of Quickbooks or  developing apps to publish in Intuit's app store.

Have you successfully created a web or other service-side app that was able to pull data to or from QB Online?

答:
If you're building a one-off application, the QuickBooks Online qbXML gateway is the way to go. It's a pretty simple POST-your-XML-requests-over-HTTP sort of interface that gives you access to a large chunk (but not all) of the functionality within QuickBooks Online.

If you're building a SaaS application, then you should be looking at the Intuit Partner Platform instead. It sounds like you're building a one-off app for your company, so we'll focus on that:

If you look on my QuickBooks integration wiki there are some example qbXML requests to show you how to sign on, and how to POST qbXML requests to the QuickBooks servers.

You don't specify a language, but if you're using PHP, then try out my open-source QuickBooks PHP DevKit (look at docs/example_online_edition.php and docs/example_raw_online_edition.php in the .zip nightly builds).

You'll want to use the QuickBooks OSR for qbXML reference. The QuickBooks SDK also has 40+ pages specifically about QuickBooks Online Edition that you should probably review.

The Intuit Developer Forums are another good resource.


问:
get all the latest entries from table linq
I have two tables like below: (date format : mm/dd/yyyy)

Parameter master table:

```<code>   Id  Parameter
    1      ST
    2      GP
    3     Interest
    4      CC
</code>```

And Second TaxValue table :

```<code>Date     ParameterId   Value
1/1/2017    1          4
2/1/2017    1          4.5
1/15/2017   2          15
3/20/2017   2          20
3/21/2017   3          18
4/28/2017   3          20
1/1/2017    4          10
</code>```

I want to write a linq query to get all the latest parameters values from the date specified.

Desired Result: (if I want to get latest entries for today)

```<code>Date     Parameter   Value
2/1/2017    ST          4.5
3/20/2017   GP          20
4/28/2017   Interest    20
1/1/2017    CC          10
</code>```

Please help!!

答:
You can use this query: (I tested it and it worked properly)

```<code>using (testEntities db = new testEntities())
            {
                var res = from element in
                              (from p in db.Parameters
                               join t in db.TaxValues on p.Id equals t.ParameterId
                               select new { Date = t.Date, Parameter = p.Parameter1, Value = t.Value, ParameterId = t.ParameterId }).ToList()
                          group element by element.ParameterId
                              into groups
                              select groups.OrderBy(p => p.Value).Last();
            }
</code>```

Result

Body:
I have two tables like below: (date format : mm/dd/yyyy)

Parameter master table:

   Id  Parameter
    1      ST
    2      GP
    3     Interest
    4      CC

And Second TaxValue table :

Date     ParameterId   Value
1/1/2017    1          4
2/1/2017    1          4.5
1/15/2017   2          15
3/20/2017   2          20
3/21/2017   3          18
4/28/2017   3          20
1/1/2017    4          10

I want to write a linq query to get all the latest parameters values from the date specified.

Desired Result: (if I want to get latest entries for today)

Date     Parameter   Value
2/1/2017    ST          4.5
3/20/2017   GP          20
4/28/2017   Interest    20
1/1/2017    CC          10

Please help!!

Body:
You can use this query: (I tested it and it worked properly)

using (testEntities db = new testEntities())
            {
                var res = from element in
                              (from p in db.Parameters
                               join t in db.TaxValues on p.Id equals t.ParameterId
                               select new { Date = t.Date, Parameter = p.Parameter1, Value = t.Value, ParameterId = t.ParameterId }).ToList()
                          group element by element.ParameterId
                              into groups
                              select groups.OrderBy(p => p.Value).Last();
            }

Result


问:
Handling nvarchar parameter vs decimal
This works:

```<code>declare @sql nvarchar(4000)
declare @minAmount decimal

set @sql = N'select PRODUCTGROUP
             from dbo.ICMaster
             where ONHAND > @minAmount'

set @minAmount = 400

print @sql

exec sp_executesql @sql, N'@minAmount decimal', @minAmount
</code>```

But as soon as I change the @minAmount to nvarchar, it does not (no errors but the output is null). What am I missing ?

```<code>declare @sql nvarchar(4000)

declare @minAmount nvarchar(100)

set @sql = N'select PRODUCTGROUP
             from dbo.ICMaster
             where PRODUCTGROUP = @minAmount'

set @minAmount = '400'

print @sql

exec sp_executesql @sql, N'@minAmount nvarchar', @minAmount
</code>```

I also tried :

```<code>set @minAmount = char(39)+'400'+char(39)
</code>```

答:
The value you query PRODUCTGROUP for is 4 not 400 because you forgot a size for the nvarchar:

```<code>exec sp_executesql @sql, N'@minAmount nvarchar(4000)', @minAmount
</code>```

Title: Handling nvarchar parameter vs decimal

Body:
This works:

declare @sql nvarchar(4000)
declare @minAmount decimal

set @sql = N'select PRODUCTGROUP
             from dbo.ICMaster
             where ONHAND > @minAmount'

set @minAmount = 400

print @sql

exec sp_executesql @sql, N'@minAmount decimal', @minAmount

But as soon as I change the @minAmount to nvarchar, it does not (no errors but the output is null). What am I missing ?

declare @sql nvarchar(4000)

declare @minAmount nvarchar(100)

set @sql = N'select PRODUCTGROUP
             from dbo.ICMaster
             where PRODUCTGROUP = @minAmount'

set @minAmount = '400'

print @sql

exec sp_executesql @sql, N'@minAmount nvarchar', @minAmount

I also tried :

set @minAmount = char(39)+'400'+char(39)

Body:
The value you query PRODUCTGROUP for is 4 not 400 because you forgot a size for the nvarchar:

exec sp_executesql @sql, N'@minAmount nvarchar(4000)', @minAmount