问:
SQL Order By Specific String in a Column
I was recently tasked to put a column in order base on a specific string. Bellow is the screenshot of my table:

How can I sort the picture column in the following order:

```<code>2017/June/06/169799_1_kYFJf.jpg
2017/February/18/169799_2_rkJ2d.jpg
2017/January/12/169799_3_23wKj.jpg
2017/March/18/169799_4_iMbw7.jpg
2017/May/18/169799_5_HwDBf.jpg
</code>```

I tried ORDER BY picture DESC but it didn't work.

Unfortunately I am not allowed to add a new column, like maybe column "sort", which will define the sort number of the image.

答:
try this one:

```<code>SELECT *
FROM test
ORDER BY SUBSTRING(picture, LOCATE(pid, picture) + LENGTH(pid) + 1, 1) DESC
</code>```

Fiddle: http://sqlfiddle.com/#!9/7a334c/3

It's a combination of various string functions readily available for MySQL

For the SUBSTRING function, it takes the string you want to get a substring of, the starting position, and the length of substring you wish to extract..

So lets break down the three parameters we used for the SUBSTRING function

1.) picture - the column that we need to extract the numbers from

2.) LOCATE(pid, picture) + LENGTH(pid) + 1 - we are locating the string containing the pid substring from the picture column, then adding the length of the pid itself so we get the "underscore" character, then adding 1 again to get the "number" for sorting.. this will return the position of the number after the pid and "underscore" character

3.) 1 - This represents the length that you need to "cut" or "extract" from the string, this will pose a problem if you have 2 digits to extract... but for now, we can work with this..

http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php

Body:
I was recently tasked to put a column in order base on a specific string. Bellow is the screenshot of my table:

How can I sort the picture column in the following order:

2017/June/06/169799_1_kYFJf.jpg
2017/February/18/169799_2_rkJ2d.jpg
2017/January/12/169799_3_23wKj.jpg
2017/March/18/169799_4_iMbw7.jpg
2017/May/18/169799_5_HwDBf.jpg

I tried ORDER BY picture DESC but it didn't work.

Unfortunately I am not allowed to add a new column, like maybe column "sort", which will define the sort number of the image.

Body:
try this one:

SELECT *
FROM test
ORDER BY SUBSTRING(picture, LOCATE(pid, picture) + LENGTH(pid) + 1, 1) DESC

Fiddle: http://sqlfiddle.com/#!9/7a334c/3

It's a combination of various string functions readily available for MySQL

For the SUBSTRING function, it takes the string you want to get a substring of, the starting position, and the length of substring you wish to extract..

So lets break down the three parameters we used for the SUBSTRING function

1.) picture - the column that we need to extract the numbers from

2.) LOCATE(pid, picture) + LENGTH(pid) + 1 - we are locating the string containing the pid substring from the picture column, then adding the length of the pid itself so we get the "underscore" character, then adding 1 again to get the "number" for sorting.. this will return the position of the number after the pid and "underscore" character

3.) 1 - This represents the length that you need to "cut" or "extract" from the string, this will pose a problem if you have 2 digits to extract... but for now, we can work with this..

http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php


来源: stackexchange

问:
how to check constructor of instance
i created new instance('instance1' and 'instance2') using 'new' keyword. just like this.

1.with 'Child.prototype.constructor = Child'

```<code>function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var instance1 = new Child();
</code>```

2.without 'Child.prototype.constructor = Child'

```<code>function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();
</code>```

And i can check the constructor of instance using 'instanceof' keyword.

```<code>instance1 instanceof Child  // true
instance1 instanceof Parent // true
</code>```

this result is make sense, because i clearly wrote 'Child.prototype.constructor = Child;'. so instanceof keyword can find both constructor. BUT

```<code>instance2 instanceof Child  // true
instance2 instanceof Parent // true
</code>```

.
but this result is not make sense for me. i expected

```<code>instance2 instanceof Child  // false
</code>```

because i did not write 'Child.prototype.constructor = Child;'.

Why???

答:
instanceof operator looks up if the Constructor.prototype object is present in the Prototype chain (__proto__) of the object being tested.

So in your example:

```<code>function Parent() {}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();
</code>```

Since instance2 is constructed from Child() constructor, the __proto__ of instance2 points to the prototype object of Child() constructor i.e. Child.prototype.

When you test for:

```<code>instance2 instanceof Child
</code>```

instanceof operator will look if Child.prototype object is present in the prototype chain of instance2, which results in true since instance2 was constructed from Child() constructor.

In other words:

```<code>instance2.__proto__ === Child.prototype
</code>```

Taking your example of second case:

```<code>instance2 instanceof Parent
</code>```

Here also instance2's prototype chain i.e. (__proto__) has Parent.prototype object it will evaluate to true. i.e.

```<code>instance2.__proto__.__proto__ === Parent.prototype
</code>```

Final Note:

instanceof operator works very much like the above conditional checks to test whether an object is an instance of a constructor. The constructor property present on Constructor function's prototype object is never used by instanceof operator while testing.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: how to check constructor of instance

Body:
i created new instance('instance1' and 'instance2') using 'new' keyword. just like this.

1.with 'Child.prototype.constructor = Child'

function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var instance1 = new Child();

2.without 'Child.prototype.constructor = Child'

function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();

And i can check the constructor of instance using 'instanceof' keyword.

instance1 instanceof Child  // true
instance1 instanceof Parent // true

this result is make sense, because i clearly wrote 'Child.prototype.constructor = Child;'. so instanceof keyword can find both constructor. BUT

instance2 instanceof Child  // true
instance2 instanceof Parent // true

.
but this result is not make sense for me. i expected

instance2 instanceof Child  // false

because i did not write 'Child.prototype.constructor = Child;'.

Why???

Body:
instanceof operator looks up if the Constructor.prototype object is present in the Prototype chain (__proto__) of the object being tested.

So in your example:

function Parent() {}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();

Since instance2 is constructed from Child() constructor, the __proto__ of instance2 points to the prototype object of Child() constructor i.e. Child.prototype.

When you test for:

instance2 instanceof Child

instanceof operator will look if Child.prototype object is present in the prototype chain of instance2, which results in true since instance2 was constructed from Child() constructor.

In other words:

instance2.__proto__ === Child.prototype

Taking your example of second case:

instance2 instanceof Parent

Here also instance2's prototype chain i.e. (__proto__) has Parent.prototype object it will evaluate to true. i.e.

instance2.__proto__.__proto__ === Parent.prototype

Final Note:

instanceof operator works very much like the above conditional checks to test whether an object is an instance of a constructor. The constructor property present on Constructor function's prototype object is never used by instanceof operator while testing.

Hope this helps.


问:
Print out same format with escape characters in HTML from JSON?
I'm having a problem with printing out JSON data in HTML

```<code>var a = "We are the world.\n \tWelcome to our place.";
</code>```

let's assume that I have this json data from the backend and I wanna print out something like this.

```<code><div>
We are the world.
  Welcome to our place.
</div>
</code>```

I've tried with ng-bind-html but it shows all string inline.

Thanks.

答:
You can let tell browser to keep your white spaces by using style="white-space: pre"

If you still need the auto wrapping, you can use white-space: pre-wrap

Body:
I'm having a problem with printing out JSON data in HTML

var a = "We are the world.\n \tWelcome to our place.";

let's assume that I have this json data from the backend and I wanna print out something like this.

We are the world.
  Welcome to our place.

I've tried with ng-bind-html but it shows all string inline.

Thanks.


问:
Get month number from name from other language
If I have a month name in a certain language(let's say Albanian), how do I get the number corresponding to it (in PHP)? Besides the obvious method of making an array with the month names of that language (I'm afraid that's quite vulnerable to spelling mistakes) I presume that you can use setlocale but I can't figure out what to do next. </p>

答:
I may be wrong but, as far as I know, you can use locales to generate month names but there aren't builtin date functions that are able to parse non-English names.

It should be fairly easy to generate a list of names to compare against:

```<code><?php

$langs = array(
    // Windows only locale names
    'Albanian',
    'French',
    'German',
    'Spanish',
);
$months = array();

foreach($langs as $lang){
    setlocale(LC_TIME, $lang);
    foreach(range(1, 12) as $i){
        $months[$lang][$i] = strftime('%B', mktime(0, 0, 0, $i));
    }
}
</code>```

However, it's possible that there're alternative spellings in some languages so the reliability of this method actually depends on your exact needs.

PHP has some Internationalization Functions that might be a better bet. The IntlDateFormatter::parse() method appears to do exactly what you are asking. However, its requirements include PHP 5 >= 5.3.0, PECL intl >= 1.0.0.

ContentLicense: CC BY-SA 2.5

Body:
I may be wrong but, as far as I know, you can use locales to generate month names but there aren't builtin date functions that are able to parse non-English names.

It should be fairly easy to generate a list of names to compare against:

<?php

$langs = array(
    // Windows only locale names
    'Albanian',
    'French',
    'German',
    'Spanish',
);
$months = array();

foreach($langs as $lang){
    setlocale(LC_TIME, $lang);
    foreach(range(1, 12) as $i){
        $months[$lang][$i] = strftime('%B', mktime(0, 0, 0, $i));
    }
}

However, it's possible that there're alternative spellings in some languages so the reliability of this method actually depends on your exact needs.

PHP has some Internationalization Functions that might be a better bet. The IntlDateFormatter::parse() method appears to do exactly what you are asking. However, its requirements include PHP 5 >= 5.3.0, PECL intl >= 1.0.0.


问:
Spliting directory path in UNIX bash script
I am learning UNIX bash shell scripting and struggling with splitting a directory path.

e.g. /home/sample/test

I want to get permissions for all the directories in the path. Following is the sample output.
e.g.

```<code>r w x   r - x   r - x   /
r w x   r - x   r - x   home
r w x   - - x   - - x   sample
r w x   r - x   r - x   test
</code>```

Thanking you in advance.

答:
That's a job for namei (comes with util-linux):

```<code>namei -m /home/sample/test
</code>```

-m would get the permission modes

Also check man namei.

Example:

```<code>% namei -m /etc/passwd
f: /etc/passwd
 drwxr-xr-x /
 drwxr-xr-x etc
 -rw-r--r-- passwd
</code>```

Body:
I am learning UNIX bash shell scripting and struggling with splitting a directory path.

e.g. /home/sample/test

I want to get permissions for all the directories in the path. Following is the sample output.
e.g.

r w x   r - x   r - x   /
r w x   r - x   r - x   home
r w x   - - x   - - x   sample
r w x   r - x   r - x   test

Thanking you in advance.

Body:
That's a job for namei (comes with util-linux):

namei -m /home/sample/test

-m would get the permission modes

Also check man namei.

Example:

% namei -m /etc/passwd
f: /etc/passwd
 drwxr-xr-x /
 drwxr-xr-x etc
 -rw-r--r-- passwd


问:
StaleElementException when Clicking on a TableRow in an Angular WebPage
```<code><div id="crm" class="row gridrow clickable ng-scope" ng-repeat="customer in customerList" ng-click="gotoRecord(customer.id)">
     <i class="col m1 s1 tiny fa fa-male"></i>
     <div class="col m3 s11 ng-binding"> Allard</div>
     <div class="col m2 s12 ng-binding"></div>
</div>
</code>```

I have this snippet of HTML, it's one row displaying as a result of a search action for a Customer with nameCustomer 'Allard'. I want to click on this customer to continue to the next page but most of the time this results in a StaleElementException.

I tried it two different ways, using Protractor and without Protractor.

First way:

```<code>IWebElement elem = driver.FindElement(By.XPath("//*[contains(text(),'" + nameCustomer + "')]//parent::div[contains(@id,'crm')]"));
        ExplicitWait.WaitAndClick(driver, elem);
</code>```

Second way:

```<code>var customers = driver.FindElements(NgBy.Repeater("customer in customerList"));
        foreach (var customer in customers)
        {
            if (elem.Text.Equals(nameCustomer))
            {
                elem.Click();
            }
        }
</code>```

答:
The problem (I think)

With StaleReferenceExceptions, an IWebElement that was previously created is no longer attached to the DOM (you probably already know this). What's most likely happening is this:

1: You click search.

2: Selenium executes driver.FindElement(...) and finds a matching element.

3: Then the search function finishes and the DOM updates. The old IWebElement found previously is gone.

4: Then Selenium tries to click on the element (which no longer exists, causing the StaleElementException. There is an element that matches the one that was there before, but it's not the same element in Selenium's eyes.)

Your statement that this happens "most of the time" makes me suspect this is the case even more, because the exception would depend on the order of events, which would vary depending on the relative speeds of Selenium vs. the web-page.

How to resolve (if this is your problem)

You need to find something on the page that will indicate to Selenium that the search action is done. This is where the creativity of writing GUI automation scripts comes in. If there is something on the page that you know will change as a result of the load, craft an explicit wait to ensure that is complete. Maybe there is a loading bar that shows up, or a message that appears when the search is done. You could grab an element that doesn't match your search before clicking search, then do an explicit wait to make sure it disappears before going on to look for the result you do expect to be there.

It would look something like this below.

# Search action performed before this.
WebDriverWait wait= new WebDriverWait(driver, TimeSpan.FromSeconds(secondsToWait));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath( expressionForElementThatWillDissapear )));

IWebElement elem = driver.FindElement(By.XPath("//*[contains(text(),'" + nameCustomer + "')]//parent::div[contains(@id,'crm')]"));
            ExplicitWait.WaitAndClick(driver, elem);
```

I'd recommend making the method to implement the explicit wait above. These situations will come up often.

Body:
 Allard

I have this snippet of HTML, it's one row displaying as a result of a search action for a Customer with nameCustomer 'Allard'. I want to click on this customer to continue to the next page but most of the time this results in a StaleElementException.

I tried it two different ways, using Protractor and without Protractor.

First way:

IWebElement elem = driver.FindElement(By.XPath("//*[contains(text(),'" + nameCustomer + "')]//parent::div[contains(@id,'crm')]"));
        ExplicitWait.WaitAndClick(driver, elem);

Second way:

var customers = driver.FindElements(NgBy.Repeater("customer in customerList"));
        foreach (var customer in customers)
        {
            if (elem.Text.Equals(nameCustomer))
            {
                elem.Click();
            }
        }

Body:
The problem (I think)

With StaleReferenceExceptions, an IWebElement that was previously created is no longer attached to the DOM (you probably already know this). What's most likely happening is this:

1: You click search.

2: Selenium executes driver.FindElement(...) and finds a matching element.

3: Then the search function finishes and the DOM updates. The old IWebElement found previously is gone.

4: Then Selenium tries to click on the element (which no longer exists, causing the StaleElementException. There is an element that matches the one that was there before, but it's not the same element in Selenium's eyes.)

Your statement that this happens "most of the time" makes me suspect this is the case even more, because the exception would depend on the order of events, which would vary depending on the relative speeds of Selenium vs. the web-page.

How to resolve (if this is your problem)

You need to find something on the page that will indicate to Selenium that the search action is done. This is where the creativity of writing GUI automation scripts comes in. If there is something on the page that you know will change as a result of the load, craft an explicit wait to ensure that is complete. Maybe there is a loading bar that shows up, or a message that appears when the search is done. You could grab an element that doesn't match your search before clicking search, then do an explicit wait to make sure it disappears before going on to look for the result you do expect to be there.

It would look something like this below.

# Search action performed before this.
WebDriverWait wait= new WebDriverWait(driver, TimeSpan.FromSeconds(secondsToWait));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath( expressionForElementThatWillDissapear )));

IWebElement elem = driver.FindElement(By.XPath("//*[contains(text(),'" + nameCustomer + "')]//parent::div[contains(@id,'crm')]"));
            ExplicitWait.WaitAndClick(driver, elem);

I'd recommend making the method to implement the explicit wait above. These situations will come up often.


问:
Is it possible to use Facebook App Links with email and pass through App Store install?
I am planning to use app link from FBSDK to invite using my iOS app via email.

I know if my iOS app was installed on the device it will be opened when I select the link and handle invite token in URL.

But how about if my app was not installed?

After user install it from App Store can I handle invite token also?

Hope anyone used to work with this scenario can help me.

答:
There are a lot of reasons why what you're trying to do won't come out the way you want it to. Let's dive in...

App Links don't work anymore

Facebook created App Links in 2014 as an open standard to solve the limitations of URI scheme deep links. App Links have two main components:

A set of meta tags to add to the web page destination of a standard http:// link. These tags specify the custom URI scheme location of corresponding content inside the native app, and the behavior that should occur if the app is not installed.

A routing engine for use inside apps that support opening links. This engine checks the destination URL for App Links tags before opening it, and then launches the corresponding app or executes the specified fallback behavior.

App Links were supposed to be an open-source standard to change the world, making app-to-app deep linking simple and universal. Unfortunately Facebook has decided they actually don't want that world (it's much better for them to keep users inside the Facebook app — see Instant Articles if you don't believe me), meaning the App Links standard is essentially dead. It's no longer supported on the iOS Facebook app, and Applinks.org isn't even a separate website now.

App Links were not designed to work with email (or essentially any app except Facebook)

Even if it were still supported by Facebook, the App Links standard has a critical flaw: it requires work by both the origin and destination apps. While the meta tags component saw wide adoption, the only major implementations of the routing engine were in the core Facebook and Messenger apps.

To function as you want, where deep linking can occur from links in emails, the routing engine component would need to be implemented in any email app where your link could possibly be clicked. This was never going to happen for apps like the default iOS Mail app from Apple, or the Gmail app, for example.

App Links had no meaningful support for deferred deep linking

Deferred Deep Linking (Deep Linking refers to using a link to open your app  directly to a specific piece of content, and Deferred means that it works even if the app isn't installed first) requires a remote server to close the loop. You can build this yourself, but you really shouldn't for a lot of reasons, not the least of which being you have more important things to do. You'll notice that neither of the two App Links components included a remove server to retain link data through install, so deferred deep linking was never properly supported in the core App Links standard. Facebook ads make use of the partial support for deferred deep linking offered by the FBSDK in conjunction with App Links, but this only works when the link/ad is clicked within a Facebook app and the receiving app has the FBSDK integrated.

Deferred deep linking is tough anyway

Moving on from App Links, deferred deep linking is still complicated. URL schemes don't work, because they always fail with an error if the app isn't installed. Apple's newer Universal Links in iOS 9+ get closer in that they at least don't trigger an error if the app isn't installed, but you'd still have to handle redirecting the user from your website to the App Store. You can't pass context through to the app after install with Universal Links, so you wouldn't be able to send the user to the correct item, and they actually aren't supported in a lot of places.

Deep linking out of email on iOS is very hard

Almost all email links involve some sort of click tracking, which is always implemented as a link wrapping redirect. This isn't technically a problem if the user doesn't have your app installed, but if they do, Universal Links don't work with wrapped links. If you're building it yourself, you'll either need to completely disable click tracking in your emails, or accept that deep links won't work there.

Bottom Line

App Links were never the solution you needed. A free service like Branch.io (full disclosure: they're so awesome I work with them) or Firebase Dynamic Links is what you need. Both services support deferred deep linking, out of Facebook or almost any email app. Branch is more powerful and offers far more features, and works with major email senders to offer a solution for deep linked email (the only one on the market today).


问:
Excel Formula | Can't take Sheet's name with SUMIFS
=SUMIFS(A1 & !G:G, A1 & !A:A, "PERIOD " & B3, A1 & !F:F, C3)

A1 represent the Sheet's name that I type in A1 cell.
But it didn't work, Excel recognize it as a mathematical formula.

What I except is:

=SUMIFS(SHEETNAME!G:G, A1 & SHEETNAME!A:A, "PERIOD " & B3, SHEETNAME!F:F, C3)

答:
To call a sheet's name dynamically you can use INDIRECT("'"&A1&"'!G1")

```<code>=SUMIFS(INDIRECT("'"&A1&"'!G:G"), INDIRECT("'"&A1&"'!A:A"), "PERIOD " & B3, INDIRECT("'"&A1&"'!F:F"), C3)
</code>```

Body:
To call a sheet's name dynamically you can use INDIRECT("'"&A1&"'!G1")

=SUMIFS(INDIRECT("'"&A1&"'!G:G"), INDIRECT("'"&A1&"'!A:A"), "PERIOD " & B3, INDIRECT("'"&A1&"'!F:F"), C3)


问:
adjust output with input field and add/minus button AngularJS
it is my first time to use angularjs
i am trying to make a sample code wherein the user can put a number on the field or he can use the button to increase/ decrease the number but not less than 0.

```<code>  <div data-ng-app='CountApp' data-ng-controller='CountCtrl'>
  <div class="outside-border">
    <input id="output_test" type="text" ng-model="count" style="width: 150px;">
    <div class="minus">
      <button class="button" id="test_sample" data-ng-click='count = count - 1'>-</button>
    </div>
    <div class="add">
      <button class="button" data-ng-click='count = count + 1'>+</button>
    </div>
  </div>
</div>

var app = angular.module('CountApp', []);

app.controller('CountCtrl', function($scope) {
  $scope.count = 1;
});
</code>```

Currently what is happening is that whenever there is no number on the field and user click  + button, the output is 1111111
or if the user enter a number (e.g. 35) the output becomes 3511111
can someone explain or help me with regards to this.

here is what i have done so far https://jsfiddle.net/wbuh2hrd/

答:
use ternary operation to validate the count is less than 0 or not like this

```<code> <button class="button" id="test_sample" data-ng-click='count = (count <= 0) ? 0 : count-1' >-</button>
</code>```

and add function to plus button and cast the string to int

```<code><button class="button" data-ng-click='plusCount()'>+</button>
$scope.plusCount = function(){
  $scope.count = parseInt($scope.count) + 1;
}
</code>```

Demo

Body:
it is my first time to use angularjs
i am trying to make a sample code wherein the user can put a number on the field or he can use the button to increase/ decrease the number but not less than 0.

    <input id="output_test" type="text" ng-model="count" style="width: 150px;">

      <button class="button" id="test_sample" data-ng-click='count = count - 1'>-</button>

      <button class="button" data-ng-click='count = count + 1'>+</button>

var app = angular.module('CountApp', []);

app.controller('CountCtrl', function($scope) {
  $scope.count = 1;
});

Currently what is happening is that whenever there is no number on the field and user click  + button, the output is 1111111
or if the user enter a number (e.g. 35) the output becomes 3511111
can someone explain or help me with regards to this.

here is what i have done so far https://jsfiddle.net/wbuh2hrd/

Body:
use ternary operation to validate the count is less than 0 or not like this

 <button class="button" id="test_sample" data-ng-click='count = (count <= 0) ? 0 : count-1' >-</button>

and add function to plus button and cast the string to int

<button class="button" data-ng-click='plusCount()'>+</button>
$scope.plusCount = function(){
  $scope.count = parseInt($scope.count) + 1;
}

Demo


问:
Can I Assign A value from javascript to asp.net server side
I have table with dynamic created labels in it and I want the label width equals too the td cell above it by any mean . I think of getting the td by javascript and set the variable in asp.net but it didn't work . All that in page load.</p>

```<code>window.onload = function() {
var td1= document.getElementById('td1').offsetWidth;
document.getElementById("HiddenField1").value = td1;
);

<table id="tabel1" class="style8" border="2">
    <tr>
        <td id="td1">
            0:00<br />
            0:00<br />
            0
            </td>
        <td id="td2">
           9:00<br />
            9:45<br />
            1
        </td>
</code>```

答: Ajax Solved this problem , If you want a value from client side to be submitted to server side you should use ajax to send data , send the td by ajax to server side and set the variable in asp.net then return the result to client side that will work </p>

Body:
I have table with dynamic created labels in it and I want the label width equals too the td cell above it by any mean . I think of getting the td by javascript and set the variable in asp.net but it didn't work . All that in page load.

window.onload = function() {
var td1= document.getElementById('td1').offsetWidth;
document.getElementById("HiddenField1").value = td1;
);

            0:00

            0:00

            0

           9:00

            9:45

            1


问:
Ruby on rails No method error.
I'm running into the infamous No Method Error. I've worked my way through a number of examples here on STOF but I can't see an error in my code that stands out. I've checked that rake routes matches what I think should be happening and the paths provided from using resources in the routes.db file seem to be correct. I know I'm missing some small detail but I can't for the life of me see it now. Any help would be appreciated.

My Controller code:

```<code>class GenevarecordsController < ApplicationController

  def index
    @genevarecords = GenevaRecord.all.page(params[:page]).per(5)
  end

  def new
    @genevarecord = GenevaRecord.new
  end

end
</code>```

My routes:

```<code>Rails.application.routes.draw do

  root 'genevarecords#index'

  resources :genevarecords

end
</code>```

答:
You have a naming discrepency between your model and your controller / routes.
your model is GenevaRecord, underscored makes it geneva_record. However your controller only has a single capital letter at the beginning: Geneverecords which underscored would be genevarecords. Therefore when you pass your model to the form it tries to use a controller / routes helpers with the same naming format as the model, which would be geneva_records_controller ie. GenevaRecordsController.

What you need to do is match your controller and routes to the same naming format as your model:

```<code>class GenevaRecordsController < ApplicationController
  #...
end

Rails.application.routes.draw do
  #...
  resources :geneva_records
end
</code>```

Title: Ruby on rails No method error.

Body:
I'm running into the infamous No Method Error. I've worked my way through a number of examples here on STOF but I can't see an error in my code that stands out. I've checked that rake routes matches what I think should be happening and the paths provided from using resources in the routes.db file seem to be correct. I know I'm missing some small detail but I can't for the life of me see it now. Any help would be appreciated.

My Controller code:

class GenevarecordsController < ApplicationController

  def index
    @genevarecords = GenevaRecord.all.page(params[:page]).per(5)
  end

  def new
    @genevarecord = GenevaRecord.new
  end

end

My routes:

Rails.application.routes.draw do

  root 'genevarecords#index'

  resources :genevarecords

end

Body:
You have a naming discrepency between your model and your controller / routes.
your model is GenevaRecord, underscored makes it geneva_record. However your controller only has a single capital letter at the beginning: Geneverecords which underscored would be genevarecords. Therefore when you pass your model to the form it tries to use a controller / routes helpers with the same naming format as the model, which would be geneva_records_controller ie. GenevaRecordsController.

What you need to do is match your controller and routes to the same naming format as your model:

class GenevaRecordsController < ApplicationController
  #...
end

Rails.application.routes.draw do
  #...
  resources :geneva_records
end


问:
Responsive Image Resize Issue
I have looked everywhere on the site and tried every method I have come across, but still am not having any luck with getting this image to be responsive and scale properly. It stays at its default size no matter what code I enter. I resize the browser and use a mobile phone emulator and it stays the same size.

HTML

```<code><section class="image">
<div>
<img class="info" src="jewelry-large-info.png">
</div>
</section>
</code>```

CSS

```<code>.image {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
.info {
height: auto;
width: auto;
max-width: 1500px;
max-height: 666px;
}
</code>```

If anyone can help it would be very greatly appreciated, and chances are I probably have just overlooked something.

答:
In CSS, the value 'auto' is default. This doesn't modify your image's proportions in any way. In your example, you used auto for your width and height. This has the image keep its original dimensions. You can read more about this on W3Schools.

Try adding values to the width and height to how you want the image to look. Here's an example of your requested responsive image.

.image {
  height: 100%;
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="image" src="http://www.bultannews.com/files/fa/news/1395/11/16/671335_664.jpg" /></code>```

Title: Responsive Image Resize Issue

Body:
I have looked everywhere on the site and tried every method I have come across, but still am not having any luck with getting this image to be responsive and scale properly. It stays at its default size no matter what code I enter. I resize the browser and use a mobile phone emulator and it stays the same size.

HTML

CSS

.image {
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
.info {
height: auto;
width: auto;
max-width: 1500px;
max-height: 666px;
}

If anyone can help it would be very greatly appreciated, and chances are I probably have just overlooked something.

Body:
In CSS, the value 'auto' is default. This doesn't modify your image's proportions in any way. In your example, you used auto for your width and height. This has the image keep its original dimensions. You can read more about this on W3Schools.

Try adding values to the width and height to how you want the image to look. Here's an example of your requested responsive image.

.image {
  height: 100%;
  width: auto;
}

<img class="image" src="http://www.bultannews.com/files/fa/news/1395/11/16/671335_664.jpg" />


问:
Angular 2 : Google Docs Viewer
I want view my documents inside a browser. I was refering one github article for which i found once url to be formed

https://docs.google.com/a/[DOMINIO]/viewer?url=[FILE_URL]

not able to understand what does DOMINIO means?

https://gist.github.com/izazueta/4961650

答:
The owner of the GitHub link you provided is probably using his native language here (which I presume is Spanish), so DOMINIO is DOMAIN in English. And from the same link:

kingsleyudenewu:

Hi please the google doc FIle viewer https://docs.google.com/a/[DOMINIO]/viewer?url=[FILE_URL] what do i replace the DOMINIO with.

SeasDev:

Kingsley you replace the [DOMINIO] with the site's domain name like this
  [FILE_URL] = http://www.nasonline.org/publications/biographical-memoirs/memoir-pdfs/einstein-albert.pdf
  [DOMINIO] = nasonline

https://docs.google.com/a/nasonline/viewer?url=http://www.nasonline.org/publications/biographical-memoirs/memoir-pdfs/einstein-albert.pdf

Title: Angular 2 : Google Docs Viewer


问:
Tracking Salesforce Pardot Form Submits / Completions in DTM
I have never had this issue before with normal forms however with trying to track form submits and even form completions from Salesforce Pardot forms Adobe analytics is always counting less form submits/completions then the Pardot platform. It is always very random sometimes 4% lower form submits then Pardot but can be as high as 50-60% at times on forms. The higher the total the bigger the discrepancy between the 2 platforms however Pardot always has more submits (and they are valid because they also contain the information from the user who filled out the form). So Adobe is somehow missing out on form submissions which I assume it may be because Pardot fires really fast at the top of the page and Adobe is slow and probably misses out on a number of form submits.

any help would be greatly appreciated

Setup:
My Adobe DTM / Adobe Analytics tool fires at page bottom and I am using a direct call rule to fire _satellite.track('form submit'); on the form button as form submission and also using an event based rule that looks for a datalayer object called with the string value "thank you page" that triggers a form complete.

答:
Is there a reason you aren't using "Event Type --> submit" here?

Another suggestion that would probably help with the parody between Pardot and Adobe Analytics would be to fire the event on the "thank you" page (or completion) of the form instead of the click of submit.

There are many reasons you might see different numbers between 2 different systems on submit (Form errors on submit,etc.) so it's better to set the analytics event when you know the action is considered complete by Pardot.

Hope this helps.


问:
Is there a way to change all keys in a flat indexed array to the same string ("Name")?
Is there a way to change all the numeric keys to "Name" without looping through the array (a native PHP function)?</p>
```<code>[
    0 => 'blabla',
    1 => 'blabla',
    2 => 'blblll',
    // etc ...
]
</code>```

答:
To have the same key I think they must be in separate nested arrays.

```<code>for ($i = 0; $i < count($array); $i++) {
    $newArray[] = ['name' => $array[$i]];
};
</code>```

Output:

```<code>0 => array:1 ["name" => "blabla"]
1 => array:1 ["name" => "blabla"]
2 => array:1 ["name" => "blblll"]
</code>```

OwnerDisplayName: Ice

LastEditorDisplayName: Kent Fredric

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to change all the numeric keys to "Name" without looping through the array (a native PHP function)?

[
    0 => 'blabla',
    1 => 'blabla',
    2 => 'blblll',
    // etc ...
]

Body:
To have the same key I think they must be in separate nested arrays.

for ($i = 0; $i < count($array); $i++) {
    $newArray[] = ['name' => $array[$i]];
};

Output:

0 => array:1 ["name" => "blabla"]
1 => array:1 ["name" => "blabla"]
2 => array:1 ["name" => "blblll"]


问:
AWS IAM Lambda "is not authorized to perform: lambda:GetFunction"
When I have my IAM Policy for my lambda execution role set to:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:GetFunction"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}
</code>```

I get this error:

```<code>[AccessDeniedException: User:
arn:aws:sts::xxx:assumed-role/supercoolsoftware-dev-us-west-2-lambdaRole/supercoolsoftware-dev-addEmail
is not authorized to perform:
lambda:GetFunction on resource:
arn:aws:lambda:us-west-2:xxx:function:supercoolsoftware-dev-dailyEmail]
</code>```

However, when I set the policy to:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:*"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}
</code>```

The error is gone...  What else do I need to add?

答:
Figured it out.  Apparently the SDK uses "lambda:GetFunctionConfiguration" as well.  Once I included that it all worked.</p>

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:GetFunction",
                "lambda:GetFunctionConfiguration"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}
</code>```

Body:
When I have my IAM Policy for my lambda execution role set to:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:GetFunction"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}

I get this error:

[AccessDeniedException: User:
arn:aws:sts::xxx:assumed-role/supercoolsoftware-dev-us-west-2-lambdaRole/supercoolsoftware-dev-addEmail
is not authorized to perform:
lambda:GetFunction on resource:
arn:aws:lambda:us-west-2:xxx:function:supercoolsoftware-dev-dailyEmail]

However, when I set the policy to:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:*"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}

The error is gone...  What else do I need to add?

Body:
Figured it out.  Apparently the SDK uses "lambda:GetFunctionConfiguration" as well.  Once I included that it all worked.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "lambda:GetFunction",
                "lambda:GetFunctionConfiguration"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}


答:
Hi so you can do a case statement but I couldn't figure out the logic you wanted it to order by ? Is it the 1, 2, 3, 4, 5 in the middle in the filename ? You can also use a regular expression to just look at those numbers and order by that. I don't know regular expressions off the top of my head though. What I gave you will work but its not the best answer as it's a lot of overhead in the query with poor performance.

```<code>order by
(Case when picture like '%_1_%' then '1'
when picture like '%_2_%' then '2'
when picture like '%_3_%' then '3'
when picture like '%_4_%' then '4'
when picture like '%_5_%' then '5' else '0' end)
</code>```

Just keep adding the order you want it to sort by depending on how many numbers that go but again this might be a lot of overhead in a query and take a bit of time. Not sure how faster a regular expression can be to parse out just the number after the underscores to sort by. So performance might be an issue with my answer.

Title: SQL Order By Specific String in a Column

Body:
I was recently tasked to put a column in order base on a specific string. Bellow is the screenshot of my table:

How can I sort the picture column in the following order:

2017/June/06/169799_1_kYFJf.jpg
2017/February/18/169799_2_rkJ2d.jpg
2017/January/12/169799_3_23wKj.jpg
2017/March/18/169799_4_iMbw7.jpg
2017/May/18/169799_5_HwDBf.jpg

I tried ORDER BY picture DESC but it didn't work.

Unfortunately I am not allowed to add a new column, like maybe column "sort", which will define the sort number of the image.

Body:
Hi so you can do a case statement but I couldn't figure out the logic you wanted it to order by ? Is it the 1, 2, 3, 4, 5 in the middle in the filename ? You can also use a regular expression to just look at those numbers and order by that. I don't know regular expressions off the top of my head though. What I gave you will work but its not the best answer as it's a lot of overhead in the query with poor performance.

order by
(Case when picture like '%_1_%' then '1'
when picture like '%_2_%' then '2'
when picture like '%_3_%' then '3'
when picture like '%_4_%' then '4'
when picture like '%_5_%' then '5' else '0' end)

Just keep adding the order you want it to sort by depending on how many numbers that go but again this might be a lot of overhead in a query and take a bit of time. Not sure how faster a regular expression can be to parse out just the number after the underscores to sort by. So performance might be an issue with my answer.


问:
How to process new files in HDFS directory once their writing has eventually finished?
In my scenario I have CSV files continuously uploaded to HDFS.

As soon as a new file gets uploaded I'd like to process the new file with Spark SQL (e.g., compute the maximum of a field in the file,  transform the file into parquet). i.e. I have a one-to-one mapping between each input file and a transformed/processed output file.

I was evaluating Spark Streaming to listen to the HDFS directory, then to process the "streamed file" with Spark.

However, in order to process the whole file I would need to know when the "file stream" completes. I'd like to apply the transformation to the whole file in order to preserve the end-to-end one-to-one mapping between files.

How can I transform the whole file and not its micro-batches?

As far as I know, Spark Streaming can only apply transformation to batches (DStreams mapped to RDDs) and not to the whole file at once (when its finite stream has completed).

Is that correct? If so, what alternative should I consider for my scenario?

答:
You can use DFSInotifyEventInputStream  to watch Hadoop dir and then execute Spark job programmatically when file is created.

See this post:
HDFS file watcher


问:
Set a datestyle in Swift
I want to set a datestyle in Swift.
I've already done this in Objective-c, this is the objective-c code.

```<code>NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

[dateFormatter setDateStyle:(NSDateFormatterMediumStyle)];

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init];

[timeFormatter setDateFormat:@"h:mm a"];

NSString *fireDate = [dateFormatter stringFromDate:notification.fireDate];
NSString *fireTime = [timeFormatter stringFromDate:notification.fireDate];
NSString *dateTime = [NSString stringWithFormat:@"%@ - %@", fireDate, fireTime];
</code>```

Now I want this in swift. I already come up with this:

```<code>var dateFormatter = NSDateFormatter()
var timeFormatter = NSDateFormatter()

timeFormatter.dateFormat = "h:mm a"
//code to set date style.....
var fireDate: NSString = dateFormatter.stringFromDate(notification.fireDate)
var fireTime: NSString = timeFormatter.stringFromDate(notification.fireDate)
var dateTime: NSString = "\(fireDate) - \(fireTime)"
</code>```

But I can't figure out how to set the date style in Swift. With NSDateFormatterMediumStyle

答:
Swift 3:</p>

```<code>dateFormatter.dateStyle = .medium
</code>```

Title: Set a datestyle in Swift

Body:
I want to set a datestyle in Swift.
I've already done this in Objective-c, this is the objective-c code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

[dateFormatter setDateStyle:(NSDateFormatterMediumStyle)];

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init];

[timeFormatter setDateFormat:@"h:mm a"];

NSString *fireDate = [dateFormatter stringFromDate:notification.fireDate];
NSString *fireTime = [timeFormatter stringFromDate:notification.fireDate];
NSString *dateTime = [NSString stringWithFormat:@"%@ - %@", fireDate, fireTime];

Now I want this in swift. I already come up with this:

var dateFormatter = NSDateFormatter()
var timeFormatter = NSDateFormatter()

timeFormatter.dateFormat = "h:mm a"
//code to set date style.....
var fireDate: NSString = dateFormatter.stringFromDate(notification.fireDate)
var fireTime: NSString = timeFormatter.stringFromDate(notification.fireDate)
var dateTime: NSString = "\(fireDate) - \(fireTime)"

But I can't figure out how to set the date style in Swift. With NSDateFormatterMediumStyle

Body:
Swift 3:

dateFormatter.dateStyle = .medium


问:
Determine two ComException types with the same HResult
When Interop with Outlook, I need to handle several exceptions, they are all COMException with the same HResult, the only difference is in their Message property.

I have to tell them from each other by examining the Message property, but such code is asking for trouble.

```<code>if (ex.Message.Contains("is bigger than the server allows")) //???
</code>```

So what is the proper way to handle exception when examining the type of exception and the HResult property won't work?

答:
checking the message was what we did in similar project. It is ugly but works. To get more comfort, you can look for some outlook specification to get full list of error messages.
What do you mean exactly by 'asking for trouble'? the code not robust?</p>

Body:
When Interop with Outlook, I need to handle several exceptions, they are all COMException with the same HResult, the only difference is in their Message property.

I have to tell them from each other by examining the Message property, but such code is asking for trouble.

if (ex.Message.Contains("is bigger than the server allows")) //???

So what is the proper way to handle exception when examining the type of exception and the HResult property won't work?


答:
You need to take Did you mean? section seriously,

Anyway, if you closely look at ruby syntax following is the representation for the class name,

AbcDef and equivalent snake case is abc_def

In your case,

Your model is named as GenevaRecord but your controller is GenevarecordsController

change it to GenevaRecordsController, also you need to match it's equivalent snake case in routes...

```<code>Rails.application.routes.draw do

  root 'geneva_records#index'

  resources :geneva_records

end
</code>```

So, when you pass @genevarecord to the form it is initialized as GenevaRecord.new and searches for geneva_records_path which is undefined because you have defined it as genevarecords_path which doesn't match you model (resources)..

Hope it helps in understanding..

Title: Ruby on rails No method error.

Body:
You need to take Did you mean? section seriously,

Anyway, if you closely look at ruby syntax following is the representation for the class name,

AbcDef and equivalent snake case is abc_def

In your case,

Your model is named as GenevaRecord but your controller is GenevarecordsController

change it to GenevaRecordsController, also you need to match it's equivalent snake case in routes...

Rails.application.routes.draw do

  root 'geneva_records#index'

  resources :geneva_records

end

So, when you pass @genevarecord to the form it is initialized as GenevaRecord.new and searches for geneva_records_path which is undefined because you have defined it as genevarecords_path which doesn't match you model (resources)..

Hope it helps in understanding..


问:
`http` polyfill for React Native
Trying to port an app over which is based on a bunch of node modules using http.

Is there a solution to this, other than rewriting libraries for fetch?

答:
http is only an issue on iOS 9+. You can just allow the http like this - React Native fetch() Network Request Failed

Here is where it is mentioned in the docs - http://facebook.github.io/react-native/releases/0.44/docs/running-on-device.html#app-transport-security

Go to your info.plist file here: /Users/Noitidart/Documents/YOUR_PROJECT_NAME/ios/YOUR_PROJ_NAME/Info.plist

then find NSExceptionDomains. You will see localhost is already there. You can add other domains here. This is what it looks like to allow bing as http:

```<code><key>NSAppTransportSecurity</key>
<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>bing.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
</code>```

You can allow all http by setting:

```<code><key>NSAllowsArbitraryLoads</key>
<true/>
</code>```

Per - https://stackoverflow.com/a/38427829/1828637

On Android, http is not a problem.

Title: `http` polyfill for React Native

Body:
http is only an issue on iOS 9+. You can just allow the http like this - React Native fetch() Network Request Failed

Here is where it is mentioned in the docs - http://facebook.github.io/react-native/releases/0.44/docs/running-on-device.html#app-transport-security

Go to your info.plist file here: /Users/Noitidart/Documents/YOUR_PROJECT_NAME/ios/YOUR_PROJ_NAME/Info.plist

then find NSExceptionDomains. You will see localhost is already there. You can add other domains here. This is what it looks like to allow bing as http:

<key>NSAppTransportSecurity</key>
<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>bing.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

You can allow all http by setting:

<key>NSAllowsArbitraryLoads</key>
<true/>

Per - https://stackoverflow.com/a/38427829/1828637

On Android, http is not a problem.


问:
How to setup Fake Reponsitory using Moq With dependency Injection (Error Casting Queryable)
How can I setup Data Queryable Data Using Moq

I have The Reponsitory (IMediaCoverageReponsitory).

```<code>public interface IMediaCoverageRepository : RepositoryAsync<MediaCoverage>
</code>```

I create Moq IMediaCoverageRepository using Moq

```<code>var mockFactory = new MockRepository(MockBehavior.Strict) {
    DefaultValue = DefaultValue.Mock
};
var mockMediaRepository = mockFactory.Create<IMediaCoverageRepository>();
</code>```

I have a list example:

```<code>var listOfMediaCoverages = new List<MediaCoverage>()
{
    new MediaCoverage { MediaCoverageId = 1, Name = "Media 10", IsActive = true },
    new MediaCoverage {MediaCoverageId = 2, Name = "Media 100", IsActive = true },
    new MediaCoverage {MediaCoverageId = 3, Name = "Media 1000", IsActive = false }
};
</code>```

After that, I setup data using listOfMediaCoverage Fake Into Mock MediaCoverageRepository like this

```<code>var queryableListMediaCoverage = listOfMediaCoverages.ToArray().AsQueryable();
</code>```

```<code>mockMediaRepository.Setup(r => r.Queryable(null).GetEnumerator()).Returns(queryableListMediaCoverage.GetEnumerator());
mockMediaRepository.Setup(r => r.Queryable(null).Provider).Returns(queryableListMediaCoverage.Provider);
mockMediaRepository.Setup(r => r.Queryable(null).ElementType).Returns(queryableListMediaCoverage.ElementType);
mockMediaRepository.Setup(r => r.Queryable(null).Expression).Returns(queryableListMediaCoverage.Expression);
</code>```

==> I get the error:
  **Unable to cast object of type

```<code>'System.Linq.EnumerableQuery`1[Pacman2.Core.Entities.MediaCoverage]' to type 'Moq.IMocked'.**
</code>```

Please Help me solve this problem. I already search on google And  try the solution on this link but won't solve the problem

```<code><links>
     http://davidcondemarin.blogspot.com/2012/07/testing-sarp-lite-repositories-with-moq.html
</links>
</code>```

Notes:

r => r.Queryable(null) Is the method return IQueryable

答:
I solve it with this code

mockMediaRepository.Setup(r => r.Queryable(It.IsAny())).Returns(queryableListMediaCoverage)

==> The pronlem is I want to populate the method Queryable with is return IQueryable. And Moq have populate it for me.

Body:
How can I setup Data Queryable Data Using Moq

I have The Reponsitory (IMediaCoverageReponsitory).

public interface IMediaCoverageRepository : RepositoryAsync<MediaCoverage>

I create Moq IMediaCoverageRepository using Moq

var mockFactory = new MockRepository(MockBehavior.Strict) {
    DefaultValue = DefaultValue.Mock
};
var mockMediaRepository = mockFactory.Create<IMediaCoverageRepository>();

I have a list example:

var listOfMediaCoverages = new List<MediaCoverage>()
{
    new MediaCoverage { MediaCoverageId = 1, Name = "Media 10", IsActive = true },
    new MediaCoverage {MediaCoverageId = 2, Name = "Media 100", IsActive = true },
    new MediaCoverage {MediaCoverageId = 3, Name = "Media 1000", IsActive = false }
};

After that, I setup data using listOfMediaCoverage Fake Into Mock MediaCoverageRepository like this

var queryableListMediaCoverage = listOfMediaCoverages.ToArray().AsQueryable();

mockMediaRepository.Setup(r => r.Queryable(null).GetEnumerator()).Returns(queryableListMediaCoverage.GetEnumerator());
mockMediaRepository.Setup(r => r.Queryable(null).Provider).Returns(queryableListMediaCoverage.Provider);
mockMediaRepository.Setup(r => r.Queryable(null).ElementType).Returns(queryableListMediaCoverage.ElementType);
mockMediaRepository.Setup(r => r.Queryable(null).Expression).Returns(queryableListMediaCoverage.Expression);

==> I get the error:
  **Unable to cast object of type

'System.Linq.EnumerableQuery`1[Pacman2.Core.Entities.MediaCoverage]' to type 'Moq.IMocked'.**

Please Help me solve this problem. I already search on google And  try the solution on this link but won't solve the problem

<links>
     http://davidcondemarin.blogspot.com/2012/07/testing-sarp-lite-repositories-with-moq.html
</links>

Notes:

r => r.Queryable(null) Is the method return IQueryable


问:
Web.config customisations lost using a Wix installer to perform an upgrade
I've created a WiX installer to deploy a set of websites on at a customer site and use xmlfile to plug correct values for hostnames and connectionStrings into our web.config files.  Since these values come from the installer UI I've run into a problem when doing an Upgrade install using:

```<code>msiexec /i Websites.msi  /l*vx Website.log REINSTALL=ALL REINSTALLMODE=vomus
</code>```

While the update performs correctly the xmlfile actions plug empty values in since the UI isn't run.

Is there a way of getting these values into the installer without parsing the XML or prompting the installation engineer for the values again?

Cheers,
Damien

答: If you'd like your web.config to be modified during install only, you can condition your components containing XmlFile elements with Not Installed condition. In this case the action to modify the XML file won't run for those components during upgrade.

Body:
I've created a WiX installer to deploy a set of websites on at a customer site and use xmlfile to plug correct values for hostnames and connectionStrings into our web.config files.  Since these values come from the installer UI I've run into a problem when doing an Upgrade install using:

msiexec /i Websites.msi  /l*vx Website.log REINSTALL=ALL REINSTALLMODE=vomus

While the update performs correctly the xmlfile actions plug empty values in since the UI isn't run.

Is there a way of getting these values into the installer without parsing the XML or prompting the installation engineer for the values again?

Cheers,
Damien


问:
How do I call an API from HTML?
I am trying to call my API for which is for database checking by the way from HTML such that when I click the button, it will call the API which then checks with the database for the correct results and output accordingly. So far, I am not entirely sure of the way to do this and have tried this

```<code><div id="login">
      <h1>Welcome Back!</h1>

      <form action="http://localhost:3000/api/login" method="post">

        <div class="field-wrap">
        <label>
         Username<span class="req">*</span>
        </label>
        <input type="userID"required autocomplete="off"/>
      </div>

      <div class="field-wrap">
        <label>
          Password<span class="req">*</span>
        </label>
        <input type="Password"required autocomplete="off"/>
      </div>

      <p><button class="button button-block">Log In</button></p>

      </form>

 </div>
</code>```

Do note that this is only for login in checking database as to whether that user and password exists. It is just a testing for my project. In my js file,

```<code>$(document).ready(function(){
$("p").click(function(){
    var settings = {
        "async": true,
        "url": "http://localhost:3000/api/login",
        "method": "POST",
        "headers": {
            "content-type": "application/json",
            "cache-control": "no-cache",
        },
        "processData": false,
        "data": "{\n\t\"userID\" : \"John\",\n\t\"Password\":
  \"Password\"\n}"
    }
    $.ajax(settings).done(function (response) {
    console.log(response);
    });
 });
});
</code>```

I have tried using AJAX but it kept redirecting back to home page so I decided to try putting the <form action="http://localhost:3000/api/login" method="post"> to see if it would check against the database but it keeps giving a wrong output although it should be correct because its inside the database. Do tell me if you need more details in any way. Any help is appreciated! Do note that this is not for authenticating just for experimenting.

答:
First, you should add an event listener to listen when it has been submitted.

```<code>document.getElementById("loginForm").addEventListener('submit', login);

function login() {
$.ajax(settings).done(function (response) {
console.log(response);
}
}
</code>```

However. Make sure the data your are passing to the api is beeing processed the right way so it can be validated.
Guess your api expects some data, passed to the function as a parameter, inout fields must have name attribute value as the corresponding params in your code.
If yor behind code is like:

```<code> function login(string user, string userpswd) {
    // Code here...
}
</code>```

Then your HTML should be something like:

```<code><form id="myForm">
    <input type="text" name="user" placeholder="Username" />
    <input type="password" name="userpswd" requiered="required" />
 </form>
</code>```

As an example.

Title: How do I call an API from HTML?

Body:
I am trying to call my API for which is for database checking by the way from HTML such that when I click the button, it will call the API which then checks with the database for the correct results and output accordingly. So far, I am not entirely sure of the way to do this and have tried this

Welcome Back!

      <form action="http://localhost:3000/api/login" method="post">

         Username*

        <input type="userID"required autocomplete="off"/>

          Password*

        <input type="Password"required autocomplete="off"/>

<button class="button button-block">Log In</button>

      </form>

Do note that this is only for login in checking database as to whether that user and password exists. It is just a testing for my project. In my js file,

$(document).ready(function(){
$("p").click(function(){
    var settings = {
        "async": true,
        "url": "http://localhost:3000/api/login",
        "method": "POST",
        "headers": {
            "content-type": "application/json",
            "cache-control": "no-cache",
        },
        "processData": false,
        "data": "{\n\t\"userID\" : \"John\",\n\t\"Password\":
  \"Password\"\n}"
    }
    $.ajax(settings).done(function (response) {
    console.log(response);
    });
 });
});

I have tried using AJAX but it kept redirecting back to home page so I decided to try putting the <form action="http://localhost:3000/api/login" method="post"> to see if it would check against the database but it keeps giving a wrong output although it should be correct because its inside the database. Do tell me if you need more details in any way. Any help is appreciated! Do note that this is not for authenticating just for experimenting.

Body:
First, you should add an event listener to listen when it has been submitted.

document.getElementById("loginForm").addEventListener('submit', login);

function login() {
$.ajax(settings).done(function (response) {
console.log(response);
}
}

However. Make sure the data your are passing to the api is beeing processed the right way so it can be validated.
Guess your api expects some data, passed to the function as a parameter, inout fields must have name attribute value as the corresponding params in your code.
If yor behind code is like:

 function login(string user, string userpswd) {
    // Code here...
}

Then your HTML should be something like:

<form id="myForm">
    <input type="text" name="user" placeholder="Username" />
    <input type="password" name="userpswd" requiered="required" />
 </form>

As an example.


问:
integrating 2 lists and a data farme in RR
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

```<code>n1
n2
n3
n4
</code>```

and a list M:

```<code>m1
m2
m3
m4
m5
</code>```

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

```<code>n1; m1; 100
n1; m2; 300
</code>```

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

```<code>     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -
</code>```

答:
We could use a indexing method

```<code>m1 <- matrix(0, length(listM), length(listN), dimnames = list(unlist(listM), unlist(listN)))
m1[cbind(match(as.character(C$m), rownames(m1)),
                  match(as.character(C$n), colnames(m1)))] <- C$I
m1
#    n1  n2  n3 n4 n5
#m1 100   0   0  0  0
#m2   0 300   0  0  0
#m3   0   0 400  0  0
#m4   0   0   0  0  0
#m5   0   0   0  0  0
</code>```

data

```<code>listN <- list("n1","n2","n3","n4","n5")
listM <- list("m1","m2","m3","m4","m5")
C <- data.frame(n=c("n1","n2","n3"),m=c("m1","m2","m3"),I=c(100,300,400))
</code>```

Body:
Please could you advise on the R code I could use in order to do the    following operation :

I have 2 lists of "genome coordinates" : a list is composed by numbers that represent genome coordinates;

let's say list N:

n1
n2
n3
n4

and a list M:

m1
m2
m3
m4
m5

and a dataframe C, where for some pairs of coordinates (n,m)    from the lists above, we have a numerical intensity;

for example:

n1; m1; 100
n1; m2; 300

The question would be : what is the most efficient R code I could use in order to integrate the list N, the list M, and the   dataframe C, in order to obtain a dataframe with:

list N as the columns names

list M as the rows names

the values in the cells of N * M, corresponding to the numerical values in the data frame C.

A little example would be :

     n1  n2  n3 n4
m1  100  -   -   -
m2  300  -   -   -
m3   -   -   -   -
m4   -   -   -   -
m5   -   -   -   -

Body:
We could use a indexing method

m1 <- matrix(0, length(listM), length(listN), dimnames = list(unlist(listM), unlist(listN)))
m1[cbind(match(as.character(C$m), rownames(m1)),
                  match(as.character(C$n), colnames(m1)))] <- C$I
m1
#    n1  n2  n3 n4 n5
#m1 100   0   0  0  0
#m2   0 300   0  0  0
#m3   0   0 400  0  0
#m4   0   0   0  0  0
#m5   0   0   0  0  0

data

listN <- list("n1","n2","n3","n4","n5")
listM <- list("m1","m2","m3","m4","m5")
C <- data.frame(n=c("n1","n2","n3"),m=c("m1","m2","m3"),I=c(100,300,400))


问:
unity webgl and browser javascript communication
So i have this problem with communicating between browser and unity webgl,
basically what i want to do is generate objects in unity's scene with javascript code from the view the webgl is being played. In other words, view will have javascript code to create game objects after the scene loaded, not sure if this is possible yet.

i've read the unity documentation but i haven't found an example of how to implement the code shown there or if it's what i'm looking for.

https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html this is what i have been reading, specially the code visibility part, but since i've never worked with frontend that much i'm a bit clueless.

答:
What you can do is to send messages to Unity inside your Javascript code but you'll let Unity do the dirty work about instantiating objects.

This is an example that I just made:

First you create a C# script that spawns your object/prefab, like this:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MyObjectSpawner : MonoBehaviour {
    public Transform Prefab;

    public void Spawn(string data) {
        var instance = Instantiate(Prefab);

        // do what you like with your instantiated object and the data from the javascript here
    }
}
```

<p>Now you create an object inside the scene and attach this script to it. Keep attention about the name you give to the Game Object you just created, this will be important in the next step. For now, let's say we named it "MyGameObject".</p>

<p>The last step is your javascript inside the game page container. For this example, I've created a button and when it's clicked, the <code>spawnUnityObject()</code> method is called. Like this:</p>

<p>HTML:
</p>

```<button type="button" onclick="spawnUnityObject()">Press me</button>
```

<p>Javascript:
</p>

```function spawnUnityObject() {
    // game object in the scene, method name, method parameter
    SendMessage('MyGameObject', 'Spawn', 'Super string');
}
```

The result will be: when you click the "Press me" button inside the html, the game will spawn an object and you can use the "Super string" as a data inside the Spawn() method.

I hope this helps you. Let me know if you need more details.

Body:
What you can do is to send messages to Unity inside your Javascript code but you'll let Unity do the dirty work about instantiating objects.

This is an example that I just made:

First you create a C# script that spawns your object/prefab, like this:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MyObjectSpawner : MonoBehaviour {
    public Transform Prefab;

    public void Spawn(string data) {
        var instance = Instantiate(Prefab);

        // do what you like with your instantiated object and the data from the javascript here
    }
}

Now you create an object inside the scene and attach this script to it. Keep attention about the name you give to the Game Object you just created, this will be important in the next step. For now, let's say we named it "MyGameObject".

The last step is your javascript inside the game page container. For this example, I've created a button and when it's clicked, the spawnUnityObject() method is called. Like this:

HTML:

<button type="button" onclick="spawnUnityObject()">Press me</button>

Javascript:

function spawnUnityObject() {
    // game object in the scene, method name, method parameter
    SendMessage('MyGameObject', 'Spawn', 'Super string');
}

The result will be: when you click the "Press me" button inside the html, the game will spawn an object and you can use the "Super string" as a data inside the Spawn() method.

I hope this helps you. Let me know if you need more details.


问:
Button seems to be covered by video
I am trying to write a program that captures photos with webcam. I want to add a JButton to the JFrame of a live video. Yet, the button doesnt show up. My belief is that it is covered by the video. I attached my code below.

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame extends JFrame {
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    MyFrame frame = new MyFrame();
    frame.contentPane.add(new JButton("Camera"));
    frame.setVisible(true);
}
 // Create the frame.
public MyFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 650, 490);
    contentPane = new JPanel();
    setContentPane(contentPane);
    contentPane.setLayout(null);
    new MyThread().start();
}
VideoCap videoCap = new VideoCap();
public void paintComponent(Graphics g){
    g = contentPane.getGraphics();
    g.drawImage(videoCap.getOneFrame(), 0, 0, this);
}
class MyThread extends Thread{
    @Override
    public void run() {
        for (;;){
            repaint();
            try { Thread.sleep(30);
            } catch (InterruptedException e) {    }
        }
    }
}
}
</code>```

Any suggestions would be awesome.

I looked through many questions regarding Jbuttons not showing up, but I am not sure which one is similar to mine. Please point me in the right direction if there is.

Thank you in advance.

答:
You are adding button to content pane and then drawing the video on it. Of course video will overlay your button.

Some suggestions:

Don't set custom content pane.

Create two separate panels and add them to content pane.

Add button to one panel.

Draw your video onto another.

Refactor your code to properly override paintComponent and redraw it from another thread.

Title: Button seems to be covered by video

Body:
I am trying to write a program that captures photos with webcam. I want to add a JButton to the JFrame of a live video. Yet, the button doesnt show up. My belief is that it is covered by the video. I attached my code below.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyFrame extends JFrame {
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    MyFrame frame = new MyFrame();
    frame.contentPane.add(new JButton("Camera"));
    frame.setVisible(true);
}
 // Create the frame.
public MyFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 650, 490);
    contentPane = new JPanel();
    setContentPane(contentPane);
    contentPane.setLayout(null);
    new MyThread().start();
}
VideoCap videoCap = new VideoCap();
public void paintComponent(Graphics g){
    g = contentPane.getGraphics();
    g.drawImage(videoCap.getOneFrame(), 0, 0, this);
}
class MyThread extends Thread{
    @Override
    public void run() {
        for (;;){
            repaint();
            try { Thread.sleep(30);
            } catch (InterruptedException e) {    }
        }
    }
}
}

Any suggestions would be awesome.

I looked through many questions regarding Jbuttons not showing up, but I am not sure which one is similar to mine. Please point me in the right direction if there is.

Thank you in advance.


问:
how to get the header files for graphicsmagick
i am developing an image processing tool using QT. Am new to both QT & graphicsmagick(magick++) c++ library. i have planned to use c++ as my development language. can anyone suggest me how to get the  graphicsmagick header files?</p>

答: Going to their sourceforge website maybe... http://sourceforge.net/projects/graphicsmagick/files/graphicsmagick/</p>


问:
Sequential filtering using data.table in R
I have data as follows:

```<code>PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    10 1986     NA
    10 1986     NA
    10 1987    240
    10 1987     NA
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
    12 1984    240
</code>```

I need to filter rows based on following criteria:

For each PERMNO, sort data by date

Parse through the sorted data and delete rows after a company gets delisted (ie. DLSTCD != NA)

If the first row corresponds to company getting delisted, do not include any rows for that company

Based on these criteria, following is my expected output:

```<code>PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
</code>```

I am using data.table in R to work with this data. The example above is an oversimplified version of my actual data, which contains around 3M rows corresponding to 30k PERMNOs.

I implemented three different methods for doing this, as can be seen here:

 r-fiddle: http://www.r-fiddle.org/#/fiddle?id=4GapqSbX&version=3

Below I compare my implementations using a small dataset of 50k rows. Here are my results:

Time Comparison

```<code>system.time(dt <- filterbydelistingcode(dt))   # 39.962 seconds
system.time(dt <- filterbydelistcoderowindices(dt))   # 39.014 seconds
system.time(dt <- filterbydelistcodeinline(dt))   # 114.3 seconds
</code>```

As you can see all my implementations are extremely inefficient. Can someone please help me implement a much faster version for this? Thank you.

Edit: Here is a link to a sample dataset of 50k rows that I used for time comparison: https://ufile.io/q9d8u

Also, here is a customized read function for this data:

```<code>readdata = function(filename){
    data = read.csv(filename,header=TRUE, colClasses = c(date = "Date"))
    PRCABS = abs(data$PRC)
    mcap = PRCABS * data$SHROUT
    hpr = data$RET
    HPR = as.numeric(levels(hpr))[hpr]
    HPR[HPR==""] = NA
    data = cbind(data,PRCABS,mcap, HPR)
    return(data)
}

data <- readdata('fewdata.csv')
dt <- as.data.table(data)
</code>```

答:
Here's an attempt in data.table:

```<code>dat[
  dat[order(date),
  {
    pos <- match(TRUE, !is.na(DLSTCD));
    (.I <= .I[pos] & pos != 1) | (is.na(pos))
  },
  by=PERMNO]
$V1]

#   PERMNO date DLSTCD
#1:     10 1983     NA
#2:     10 1985    250
#3:     11 1984     NA
#4:     11 1984     NA
#5:     11 1985     NA
#6:     11 1987     NA
</code>```

Testing it on 2.5million rows, 400000 with a delisting date:

```<code>set.seed(1)
dat <- data.frame(PERMNO=sample(1:22000,2.5e6,replace=TRUE), date=1:2.5e6)
dat$DLSTCD <- NA
dat$DLSTCD[sample(1:2.5e6, 400000)] <- 1
setDT(dat)

system.time({
dat[
  dat[order(date),
  {
    pos <- match(TRUE, !is.na(DLSTCD));
    (.I <= .I[pos] & pos != 1) | (is.na(pos))
  },
  by=PERMNO]
$V1]
})
#   user  system elapsed
#   0.74    0.00    0.76
</code>```

Less than a second - not bad.

Body:
I have data as follows:

PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    10 1986     NA
    10 1986     NA
    10 1987    240
    10 1987     NA
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
    12 1984    240

I need to filter rows based on following criteria:

For each PERMNO, sort data by date

Parse through the sorted data and delete rows after a company gets delisted (ie. DLSTCD != NA)

If the first row corresponds to company getting delisted, do not include any rows for that company

Based on these criteria, following is my expected output:

PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA

I am using data.table in R to work with this data. The example above is an oversimplified version of my actual data, which contains around 3M rows corresponding to 30k PERMNOs.

I implemented three different methods for doing this, as can be seen here:

 r-fiddle: http://www.r-fiddle.org/#/fiddle?id=4GapqSbX&version=3

Below I compare my implementations using a small dataset of 50k rows. Here are my results:

Time Comparison

system.time(dt <- filterbydelistingcode(dt))   # 39.962 seconds
system.time(dt <- filterbydelistcoderowindices(dt))   # 39.014 seconds
system.time(dt <- filterbydelistcodeinline(dt))   # 114.3 seconds

As you can see all my implementations are extremely inefficient. Can someone please help me implement a much faster version for this? Thank you.

Edit: Here is a link to a sample dataset of 50k rows that I used for time comparison: https://ufile.io/q9d8u

Also, here is a customized read function for this data:

readdata = function(filename){
    data = read.csv(filename,header=TRUE, colClasses = c(date = "Date"))
    PRCABS = abs(data$PRC)
    mcap = PRCABS * data$SHROUT
    hpr = data$RET
    HPR = as.numeric(levels(hpr))[hpr]
    HPR[HPR==""] = NA
    data = cbind(data,PRCABS,mcap, HPR)
    return(data)
}

data <- readdata('fewdata.csv')
dt <- as.data.table(data)

Body:
Here's an attempt in data.table:

dat[
  dat[order(date),
  {
    pos <- match(TRUE, !is.na(DLSTCD));
    (.I <= .I[pos] & pos != 1) | (is.na(pos))
  },
  by=PERMNO]
$V1]

#   PERMNO date DLSTCD
#1:     10 1983     NA
#2:     10 1985    250
#3:     11 1984     NA
#4:     11 1984     NA
#5:     11 1985     NA
#6:     11 1987     NA

Testing it on 2.5million rows, 400000 with a delisting date:

set.seed(1)
dat <- data.frame(PERMNO=sample(1:22000,2.5e6,replace=TRUE), date=1:2.5e6)
dat$DLSTCD <- NA
dat$DLSTCD[sample(1:2.5e6, 400000)] <- 1
setDT(dat)

system.time({
dat[
  dat[order(date),
  {
    pos <- match(TRUE, !is.na(DLSTCD));
    (.I <= .I[pos] & pos != 1) | (is.na(pos))
  },
  by=PERMNO]
$V1]
})
#   user  system elapsed
#   0.74    0.00    0.76

Less than a second - not bad.


问:
Trouble displaying code on screen
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help. </p>

```<code>function convertToRoman(num) {
var romans = {
    M:  1000,
    CM: 900,
    D:  500,
    CD: 400,
    C:  100,
    XC: 90,
    L:  50,
    XL: 40,
    X:  10,
    IX: 9,
    V:  5,
    IV: 4,
    I:  1,
};

var result = '';

for (var key in romans) {
    if (num >= romans[key]) {
        result += key.repeat(Math.trunc(num / romans[key]));
        num -= romans[key] * Math.trunc(num / romans[key]);
    }
}

return result;

}
</code>```

Title: Trouble displaying code on screen

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

function convertToRoman(num) {
var romans = {
    M:  1000,
    CM: 900,
    D:  500,
    CD: 400,
    C:  100,
    XC: 90,
    L:  50,
    XL: 40,
    X:  10,
    IX: 9,
    V:  5,
    IV: 4,
    I:  1,
};

var result = '';

for (var key in romans) {
    if (num >= romans[key]) {
        result += key.repeat(Math.trunc(num / romans[key]));
        num -= romans[key] * Math.trunc(num / romans[key]);
    }
}

return result;

}

Body:
You can use the trusty old alert function. Just do alert(convertToRoman(10)). Put this in a <script> tag or inside body onload attribute

For fancier more professional debugging, you can use console.log. Originating with an old Firefox addon called Firebug, it is now supported by all browsers. Simply type console.log(convertToRoman(10)); The result will be printed out to console, to see it, right click your browser, and open inspect document and move to Console tab, or alternatively, Ctrl+Shift+I in Chrome


问:
UILabel get Frame width or height
```<code>`lblAddress.frame.width`
`lblAddress.frame.size.width`
</code>```

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

答: Both frame and size have a width property. You might be getting confused because size is also a property of frame. It's like me asking you what color of shoes I have on but the next moment asking what color of shoes my feet have on, I'm asking the same thing, it just might be convenient for me to ask it one way or the other depending on my circumstances.</p>

Title: UILabel get Frame width or height

Body:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.


问:
python sql query with variable
```<code>testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, testid)
print cur.fetchone()
</code>```

I am getting an integer error when attempting this. I have tried converting testid to a string with no luck.

答:
The second paraemter of Cursor.execute should be a sequence (tuple or list) or a mapping (dict):

```<code>testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, [testid])  # <--
print cur.fetchone()
</code>```

Title: python sql query with variable

Body:
testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, testid)
print cur.fetchone()

I am getting an integer error when attempting this. I have tried converting testid to a string with no luck.

Body:
The second paraemter of Cursor.execute should be a sequence (tuple or list) or a mapping (dict):

testid = 69
query = """SELECT * FROM basic_info WHERE ownerid=%s"""
cur.execute(query, [testid])  # <--
print cur.fetchone()


问:
C++ code issue? Compiler issue? code block?
I am not sure if this is a visual studio problem or if this is a problem with code. If this is posted in the wrong area please let me know and I will change it.

Problem: Image of errorI am working on an application. I am getting an LNK2019 error code and an LNK1120 error code when testing my application. I am total stumped on this. personally, I think is a coding problem. However I could be wrong. I am using visual studio 2017 just a fyi.

Program Code:

```<code>       int main()
       {

         //User Choice for in or out patient.
         cout << "Please choose a Menu option." << endl;
         cout << "1: In-Patient" << endl;
    cout << "2: Out_Patient" << endl;
    cout << "Option:";
    cin >> User_Input;

    //Clear screen
    clearScreen();
    User_Input = validation(User_Input);
    if (User_Input = 1)
    {
        total_Charge = in_patient();
        clearScreen();
        cout << "Total amount charged:" << total_Charge;
    }
    if (User_Input = 2)
    {
        total_Charge = out_patient();
        clearScreen();
        cout << "total amoung charged:" << total_Charge;
    }

}

double validation(double User_in)
{
    bool Validated = false;
    //Validate greater than one
    while (Validated = true)
    {
        if (User_in <= 0)
        {
            cout << "Please enter a number greater than zero:";
            cin >> User_in;
            Validated = false;
        }

        if (User_in >= 1)
        {
            Validated = true;
        }

    }
    return User_in;
}

double in_patient()
{
</code>```

答:
```<code>double validation(double User_in)
{
    while (User_in <= 0)
    {
       cout << "Please enter a number greater than zero:";
       cin >> User_in;
    }
    return User_in;
}
</code>```

You don't need a Boolean also the while statement that you have will run always run but if you change it to while(Validated == true) it will never run since you you set Validated = false

Body:
I am not sure if this is a visual studio problem or if this is a problem with code. If this is posted in the wrong area please let me know and I will change it.

Problem: Image of errorI am working on an application. I am getting an LNK2019 error code and an LNK1120 error code when testing my application. I am total stumped on this. personally, I think is a coding problem. However I could be wrong. I am using visual studio 2017 just a fyi.

Program Code:

       int main()
       {

         //User Choice for in or out patient.
         cout << "Please choose a Menu option." << endl;
         cout << "1: In-Patient" << endl;
    cout << "2: Out_Patient" << endl;
    cout << "Option:";
    cin >> User_Input;

    //Clear screen
    clearScreen();
    User_Input = validation(User_Input);
    if (User_Input = 1)
    {
        total_Charge = in_patient();
        clearScreen();
        cout << "Total amount charged:" << total_Charge;
    }
    if (User_Input = 2)
    {
        total_Charge = out_patient();
        clearScreen();
        cout << "total amoung charged:" << total_Charge;
    }

}

double validation(double User_in)
{
    bool Validated = false;
    //Validate greater than one
    while (Validated = true)
    {
        if (User_in <= 0)
        {
            cout << "Please enter a number greater than zero:";
            cin >> User_in;
            Validated = false;
        }

        if (User_in >= 1)
        {
            Validated = true;
        }

    }
    return User_in;
}

double in_patient()
{

Body:
double validation(double User_in)
{
    while (User_in <= 0)
    {
       cout << "Please enter a number greater than zero:";
       cin >> User_in;
    }
    return User_in;
}

You don't need a Boolean also the while statement that you have will run always run but if you change it to while(Validated == true) it will never run since you you set Validated = false


答:
Assign an id in the form and also name and id for individual controls.

```<code><form method="POST" action="http://localhost:3000/api/login" id="loginform">
      <input type="userID" id="userID" name="userID" required autocomplete="off"/>
      .....
      <input type="submit" id="submit" value="Log In">
</form>
</code>```

Jquery code.
Replace postvaruid and postvarpwd with actual server parameters.

```<code> $(document).ready(function(){
        // Set form variable
        var form = $('#loginform');

        form.submit(function(event){
          var userid = $('#userID').val();
          var password = $('#password').val();

          if ( $.trim(username) != '' && $.trim(password) != '') {
            // Process AJAX request
            $.post('http://localhost:3000/api/login',
                   {postvaruid: userid, postvarpwd: password }, function(data){
             console.log(data);
            });
          }
          // Prevent default form action
          event.preventDefault();
        });
      });
</code>```

EDIT:

See this to understand the form submit callback function

What I wrote is similar to

```<code>$("#formid").submit(function( event ) {
  alert( "Handler for .submit() called." );
  event.preventDefault();
});
</code>```

$.post actually fires a http post request to server.

It's a shorthand ajax call equivalent to below

```<code>$.ajax({
  type: "POST",  <---Note this
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
</code>```

Title: How do I call an API from HTML?

Body:
Assign an id in the form and also name and id for individual controls.

<form method="POST" action="http://localhost:3000/api/login" id="loginform">
      <input type="userID" id="userID" name="userID" required autocomplete="off"/>
      .....
      <input type="submit" id="submit" value="Log In">
</form>

Jquery code.
Replace postvaruid and postvarpwd with actual server parameters.

 $(document).ready(function(){
        // Set form variable
        var form = $('#loginform');

        form.submit(function(event){
          var userid = $('#userID').val();
          var password = $('#password').val();

          if ( $.trim(username) != '' && $.trim(password) != '') {
            // Process AJAX request
            $.post('http://localhost:3000/api/login',
                   {postvaruid: userid, postvarpwd: password }, function(data){
             console.log(data);
            });
          }
          // Prevent default form action
          event.preventDefault();
        });
      });

EDIT:

See this to understand the form submit callback function

What I wrote is similar to

$("#formid").submit(function( event ) {
  alert( "Handler for .submit() called." );
  event.preventDefault();
});

$.post actually fires a http post request to server.

It's a shorthand ajax call equivalent to below

$.ajax({
  type: "POST",  <---Note this
  url: url,
  data: data,
  success: success,
  dataType: dataType
});


问:
Swift Array extension with struct and generic object
So I have this code:

```<code>struct Asset<T>: AssetProtocol{
    typealias AssetType = T

    var parent: T!
    var children: [T]!
    init(parent: T, children: [T] = [T](),){
        self.parent = parent
        self.children = children
    }
}

protocol AssetProtocol{
    associatedtype AssetProtocolType
    var parent: AssetProtocolType! { get }
    var children: [AssetProtocolType]! { get }
}

extension Array where Element: AssetProtocol{
    fun getExtractParents() -> [<I’m not sure what type should be here the “T” doesn’t work>] {
        // iterate here to get all the parents then return it.
    }
}
</code>```

Is there a way that I can create an Array extension and a method inside it that returns all the "parent" in that array? note that the type of the "parent" is generic as shown in the struct Asset.

答:
So I think I found the answer. I'm not sure if this is correct or efficient but it does the work for me.

```<code>extension Array where Element: AssetProtocol{
    func extractParents() -> [Element.AssetProtocolType] {
        var parents: [Element.AssetProtocolType] = []
        for element in self {
            parents.append(element.parent)
        }

        return parents
    }
}
</code>```

I'm still open for suggestion if anyone would give...

Body:
So I have this code:

struct Asset<T>: AssetProtocol{
    typealias AssetType = T

    var parent: T!
    var children: [T]!
    init(parent: T, children: [T] = [T](),){
        self.parent = parent
        self.children = children
    }
}

protocol AssetProtocol{
    associatedtype AssetProtocolType
    var parent: AssetProtocolType! { get }
    var children: [AssetProtocolType]! { get }
}

extension Array where Element: AssetProtocol{
    fun getExtractParents() -> [] {
        // iterate here to get all the parents then return it.
    }
}

Is there a way that I can create an Array extension and a method inside it that returns all the "parent" in that array? note that the type of the "parent" is generic as shown in the struct Asset.

Body:
So I think I found the answer. I'm not sure if this is correct or efficient but it does the work for me.

extension Array where Element: AssetProtocol{
    func extractParents() -> [Element.AssetProtocolType] {
        var parents: [Element.AssetProtocolType] = []
        for element in self {
            parents.append(element.parent)
        }

        return parents
    }
}

I'm still open for suggestion if anyone would give...