text:
Q: Depreciation Problem I am hoping that you can all assist, for which I would be grateful
so we have a bolt & it's worth $100
This bolt has a 40 year in service life based on its required usage (we will only need it for forty years - not a single one but access to this particular type of bolt
It is used by 5 platforms which came into life in different years, and go out of life in different years
eg
1 - 2000 - 2020 (20 year life)
2 - 2001 - 2025 (24 year life)
3 - 2004 - 2030 (26 year life)
4 - 2004 - 2035 (31 year life)
5 - 2006 - 2040 (34 year life)
Each of the 5 platforms has a start date (in service date) and an end date ( out of service date)
They all use this specific bolt
It's life based on those 5 platforms that use it is the year range 2000 - 2040 (so 40 years)
So as a single unit it has a 40 year depreciation cost ( we use the straight line method)
The bolt in this example is $100 per bolt ($100 depreciating in value each year to $0 - no scrap value)
The problem
I am trying to figure out based on the stock held against each platform how to work out total stock depreciation opposed to that of 1 bolt. If held on the shelf.
So random numbers here but lets say each of the platforms use each year
1 - 1 Bolts
2 - 2 Bolts
3 - 3 Bolts
4 - 4 Bolts
5 - 5 Bolts
1 - 1 Bolts x 20 = 20 Bolts
2 - 2 Bolts x 24 = 48 Bolts
3 - 3 Bolts x 26 = 78 Bolts
4 - 4 Bolts x 31 = 124 Bolts
5 - 5 Bolts x 34 = 170 Bolts
In the current window we have 440 bolts used over 40 years.
For 1 bolt the deprecation is $100 over 40 years
for 440 it is (440*100)/40 years
I think?????
But I am trying to work out the value of each platform as a percentage of the whole
Soooo the percentage of the deprecation of the whole
I think
1 - ( 20 Bolts * $100) / 20 Years
2 - (24 = 48 Bolts * $100) / 24 years
3 - (78 Bolts * $100) / 26 years
4 - (124 Bolts * $100) / 31 years
5 - (170 Bolts * $100) / 34 years
Because surely although they all use the bolt they contribute differently to its overall deprecation. Based on the quantity of that bolt which they uniquely consume
SO
If Platform 4 Extended its life and usage by a further 3 years.. It would use a further 93 bolts. Making its depreciation
4- (217 Bolts * $100) / 34 Years
Completely changing its percentage of the usage of the bolt and its subsequent depreciation?
The end goal is to work out how much Each platform shares the depreciation.
Then with each platform coming to its end of life what the new depreciation figure would look like.
Is this something that is possible to determine in excel?
Using
Platform
In Service day/month/year (to get days)
Out of service day/month/year
Initial purchase value of product
end value of product
Taking the earliest date of the platforms in the list as the beginning
and the end service date from the longest in service platform
In order to argue accurately costing out the monies saved by purchasing the correct amount of bolts to cover the life of each individual platform and not hold surplus at any point in the chain
The proof I am looking for is to demonstrate don't buy more milk than you can drink before it expires.
As once its expired it was a waste a money
In this case.
If we buy too many bolts, all those that we don't use which we will have paid full price for, and they will depreciate to the final day of the final platform without every being consumed. Costing money unnecessarily. But if we buy the exact amount required for each platform to cover it's life (each year the price of the bolt may change - up or down) then we won't be wasting money buying an asset that we will never use.


text:
Q: I hope you enjoyed. vs I hope you enjoyed it. Is 'I hope you enjoyed.' grammatically correct?
I have heard it used many times by non native speakers. However it sounds odd to me if there is nothing after 'enjoyed'. Such as I hope you enjoyed it/the party.

A: Apart from the rather trite imperative "Enjoy!" spoken by a waiter/serving person as they deliver your meal, enjoy is normally a transitive verb (many waiters say "Enjoy your meal").
Native speakers today never use it intransitively in contexts like "That was fun! I really enjoyed!", which needs to be reflexive (re-using the subject as object) to be valid: "I really enjoyed myself!".

A: This is a sentence fragment in that it does not express a complete thought. The verb enjoyed needs a noun that serves as its direct object to complete the thought, eg "the party."
Ironically, elimination of "you enjoyed" would make a complete sentence, expressing the thought "I hope."

redpajama_set_name: RedPajamaStackExchange


text:
Q: br tag is not working while replace the content from textarea to DIV using JQUERY text function The br tag is not working on DIV.
I am getting the message from Update Content: textareafield.
The message have the 2 lines like "Rama" next line "Lingam".
But the result is "RamaLingam" by  $("#editQuotesRowLabel_Q_013").text(replaceContent);
How to make a new line in DIV?
Here is my code:
function updateQuotes(){
    var weg_quotes = $("#weg_quotes_Q_013").val();
    replaceContent = weg_quotes.replace("\n", "
", "g");
    $("#editQuotesRowLabel_Q_013").text(replaceContent);
}

Update Content: <textarea placeholder="Update your content..." id="weg_quotes_Q_013" name="weg_quotes" cols="80" rows="3" class="appQuotesTextarea" maxlength="200" required=""></textarea>
<button onclick="updateQuotes()" id="Q_013" name="update-btn" class="appQuotesBtn">Update</button>

    This is content div.

A: To insert HTML content using jquery you need to use  .html() instead of .text().
So in your case you end up with :
 $("#editQuotesRowLabel_Q_013").html(replaceContent);
 //                              |_ use html() instead of text()

Source :

*

*.html()

*.text()

A: Just use .html() instead of .text() because textarea content will also contain  tags and .html() can show html also, .text() will only consider text -  it will not set html tags ( tag here) in div, so use .html() instead of .text()

function updateQuotes(obj){
    var weg_quotes = $("#weg_quotes_Q_013").val();
    replaceContent = weg_quotes.replace("\n", "
", "g");
    $("#editQuotesRowLabel_Q_013").html(replaceContent);
}

Update Content: <textarea placeholder="Update your content..." id="weg_quotes_Q_013" name="weg_quotes" cols="80" rows="3" class="appQuotesTextarea" maxlength="200" required=""></textarea>
<button onclick="updateQuotes(this)" id="Q_013" name="update-btn" class="appQuotesBtn">Update</button>

    This is content div.

A: Try with this:
$("#editQuotesRowLabel_Q_013").html(replaceContent);

// Try to use html() instead of text()
This will allow you to use html tags :)

A: I am not sure what that replace() method is, but it replace is
str.replace(pattern/string, function/replacement)

So your code should be
replaceContent = weg_quotes.replace(/\n/g, "
");

and you should be using .html() when you are inserting html into a div.
$("#editQuotesRowLabel_Q_013").html(replaceContent);

A: Try this one .html() instead of .text()
$("#editQuotesRowLabel_Q_013").html(replaceContent);


text:
Q: office pro plus 2016 privacy concern by organization i am using office pro plus 2016 under a organization(my university), is that mean all the organization can access all my data while i am using office? thx
i had read below link and manage the privacy as stated, but i cant confirm if it is what as above stated.
https://docs.microsoft.com/en-us/deployoffice/compat/manage-the-privacy-of-data-monitored-by-telemetry-in-office#disable-data-collection-for-the-agent

A: It depends on your user role assignment(s) within the organization.  If you check your O365 for Business Plus' Admin portal (refer to here and login, or access through the app), there should be a setting that shows which users have what access rights, with Global Administrators holding the highest visibility privileges.  You can also see what devices currently have your assigned license(s) deployed onto them, and even reset / force log-out (do this before securing your account with new password).
Note that while admins may not necessarily have direct access to your data, certain configurations may allow admins to reset your password, disable 2FA, etc., and gain access that way.


text:
Q: Erros de conflito de versões ao Rodar projeto em Angular 4.2 Peguei um projeto em Angular para dar manutenção, porém está na versão do Angular CLI 4.2
Meu sistema esta com as versões de Node, Typescript e Angular cli nas seguintes versões:
Angular CLI: 10.0.6
Node: 12.18.3
Typescript: Version 3.9.7
OS: win32 x64
Meu projeto esta com as versões:
D:\VSTS\ASMS\ASMS.Angular4.2>ng --version
Your global Angular CLI version (10.0.6) is greater than your local
version (1.3.0). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@angular/cli: 1.3.0
node: 12.18.3
os: win32 x64
@angular/animations: 4.4.7
@angular/cdk: 2.0.0-beta.12
@angular/common: 4.4.7
@angular/compiler: 4.4.7
@angular/core: 4.4.7
@angular/forms: 4.4.7
@angular/http: 4.4.7
@angular/material: 2.0.0-beta.12
@angular/platform-browser: 4.4.7
@angular/platform-browser-dynamic: 4.4.7
@angular/router: 4.4.7
@angular/cli: 1.3.0
@angular/compiler-cli: 4.4.7
@angular/language-service: 4.4.7

Ao tentar rodar o projeto está me retornando os seguintes erros:
D:\VSTS\ASMS\ASMS.Angular4.2>ng serve
Your global Angular CLI version (10.0.6) is greater than your local
version (1.3.0). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
ENOENT: no such file or directory, stat 'D:\VSTS\ASMS\ASMS.Angular4.2\src\tsconfig.app.json'
Error: ENOENT: no such file or directory, stat 'D:\VSTS\ASMS\ASMS.Angular4.2\src\tsconfig.app.json'
at Object.statSync (fs.js:1016:3)
at AotPlugin._setupOptions (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@ngtools\webpack\src\plugin.js:62:16)
at new AotPlugin (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@ngtools\webpack\src\plugin.js:27:14)
at _createAotPlugin (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@angular\cli\models\webpack-configs\typescript.js:55:12)
at Object.exports.getNonAotConfig (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@angular\cli\models\webpack-configs\typescript.js:71:19)
at NgCliWebpackConfig.buildConfig (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@angular\cli\models\webpack-config.js:29:37)
at Class.run (D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@angular\cli\tasks\serve.js:43:98)
at D:\VSTS\ASMS\ASMS.Angular4.2\node_modules\@angular\cli\commands\serve.js:114:26

Não tenho experiência em Angular, por isso não tenho idéia de como resolver estes erros.
Alguuém tem idéia do que eu devo fazer?

A: Tenta apagar a pasta node_modules.
Depois apagar o arquivo package-lock.json
após isso verifique a versão do typescript na sua máquina, não no projeto, e deixe com a mesma versão sugerida no arquivo package.json.
Após isso rode npm install


text:
Q: New digitizer stopped working after 30 seconds I plugged a brand new digitizer into my 2g iPod touch and I wanted to test it before I clip it in. It worked great at first and I managed to click with it for about 30 seconds, while not moving the digitizer or the iPod.
Suddenly, it stopped working and I have been unable to get the digitizer to work again, despite reseating it numerous times. The iPod works otherwise normally.
What happened?

A: Make sure that both sides of the connect cable a plugged in, then make sure that the center button works.  The center button has broke for many of my friends and myself.

A: I've had a digitizer die on me after a few weeks of use. I replaced the digitizer in my iPhone 3GS and it worked like a charm until one side of it just stop responding one day. (Being an iOS dev, I whipped together an app that had number buttons on only half the screen, so I was able to still use it.)
I'd suggest checking the cables. Be sure that you didn't loosen anything while "testing before refastening".
Also, considering the fragile nature of both the device and the non-apple digitizer, it could be broken. If the cables are all connected, you might need to send it back to where you bought it.


text:
Q: Why attr_accessor won't work in setting methods I am implementing BST in ruby and writing insert method using recursion.
I am trying to use attr_accessor for setting and getting root but it doesn't work. Can anyone help out?
class Node
  attr_accessor :value, :left_child, :right_child

  def initialize (value)
    @value = value
    @left_child = nil
    @right_child = nil
  end
end

class BST
  attr_accessor :root

  def initialize
    @root = nil
  end

  def insert(value, node)

    if node == nil
      node = Node.new(value)
      return node
    end

    return node if node.value == value

    if node.value > value
      if node.left_child == nil
        node.left_child = Node.new(value)
        return
      else
        insert(value, node.left_child)
      end

    else

      if node.right_child == nil
        node.right_child = Node.new(value)
        return
      else
        insert(value, node.right_child)
      end
    end
  end
end

mybst = BST.new
p mybst.root
mybst.insert(1, mybst.root)
mybst.insert(2, mybst.root)
mybst.insert(10, mybst.root)
mybst.insert(12, mybst.root)

p mybst

The code above shows a simple implementation of Node class and a BST class with insert method. Gives me #<BST:0x00557398d02378 @root=nil>
If I use a self.root it works.
One can use @root to access the root but a class should not interact with its instance variables directly. That's why we need a getter and setter method provided by attr_accessor. But it's not working. What I am missing ?
Below are the screenshots of the book POODR. It says never to use instance variables directly even in class.

A: It's actually totally OK to use instance variables within instance methods. In fact, that's what they're for! Setters and getters allow things outside the instance to access variables inside the instance. They (basically) define instance methods for the class like this:
class Foo
  # getter -- Same as attr_reader :root
  def root
    @root
  end

  # setter -- Same as attr_writer :root
  def root=(root)
    @root = root
  end

  # attr_accessor defines a setter *and* a getter.
end

So, you could simplify your code by defining #insert so that it only takes one argument (value) and replace every place where you reference node with a reference to @root.
The way that I think you're looking for (but is not the "right" way, and I wouldn't recommend) is to call the root and root= methods defined by the accessor.
If you took this route, you'd also have to define #insert to only take value as an argument and replace every place that you reference node with root. This will work, but it's not the right way to solve the problem. If you solve it this way, please ask a question on CodeReview.se so I can clarify how you can make the code better.
Why it's not working
In the #insert method, you're manipulating the node parameter that was passed to the method, not root. Ruby is pass by value not pass by reference (sorta), so when you pass mybst.root to #insert, you're effectively passing nil because mybst.root == nil. Then the mybst.insert call returns a new Node, but you don't do anything with that return value. If you wanted to set root to that return value, you could do:
mybst = BST.new
p mybst.root
mybst.root = mybst.insert(1, mybst.root)
mybst.root = mybst.insert(2, mybst.root)
mybst.root = mybst.insert(10, mybst.root)
mybst.root = mybst.insert(12, mybst.root)

p mybst

Explanation of what that textbook is trying to say
I think that the confusing part here is where the textbook says:

Hide the variables, even from the class that defines them

This is correct, but I think you're misinterpreting it. This section is saying that you should hide instance variables from anything outside of that instance. Within that instance, it's totally OK to use them, and that's actually the reason why instance variables exist -- to store state within the instance. It's just considered better to define methods for behaviors rather than directly exposing the instance variables. Of course, this is just one rule to keep in mind -- I'm sure you'll come across a situation where this advice does not apply, but generally you want to keep instance variables internal.


text:
Q: Data snooping in selecting between ML models If you train a lot of machine learning algorithms on a problem, svm, nn, rf,...via i.e. caret, and I mean a lot of it,like hundreds or thousands (not that hard,considering all parameter tuning in validation), eventually you will find one that will work.
But that is data snooping. As you have trained so much models, I think that you have to test the hypothesis that you had been lucky, maybe with White Reallity Check test or Hansen Superior Predictive Ability test.
Around 99.9% of the papers, articles, posts,.... didn't use White's or Hansen's tests (0.1% are papers regarding stock trading via ML). I suppose this is because, on a normal basis, we use to train a few models(really?).
The question is:
Do you have any idea about the number of models required to consider data snooping terrible effects?
This is, if i'm choosing between 3 models, I think that the possiblity of getting good results by chance is low. But in choosing between 30? 300? 3000?

A: A lot of effort is underway to address this issue of data dredging with the techniques from differential privacy. The algorithm allows repeated reuse of the test set in evaluating different models, and in the process keeps enough details about the test set hidden that the final model does not overfit.
See the tutorial "Rigorous Data Dredging: Theory and Tools for Adaptive Data Analysis" in this yr's ICML
http://icml.cc/2016/?page_id=97
Dwork, C., Feldman, V., Hardt, M., Pitassi, T., Reingold, O., & Roth, A. L. (2015, June). Preserving statistical validity in adaptive data analysis. In Proceedings of the Forty-Seventh Annual ACM on Symposium on Theory of Computing (pp. 117-126). ACM.


text:
Q: Python: How create a opencv Template Image Mapping? (reading playing hand cards) I am looking for an easy and smart way to read and interpret current playing hand cards on my screen (flash application).

*

*I make a screenshot in python and know the coordinates to "scan" my cards in my browser.

*Now I have an image like this:

*How can I read this playing hand cards well? OCR (Tesseract) seems to be complicated.

*Rather I am looking for an Image-Mapping. To save all possible cards as image and then to match my current screen like:

*

*Here is my current screenshot-part

*Look in my "image"-mapping which card that is

*Then to get a string like: "Ah-9d"


text:
Q: Why spring can't find my bean? I created an interface and a class:
public interface UserService {
    List<User> listAll();
}

@Transactional
public class DefaultUserService implements UserService {
    private String tableName;
    public List<User> listAll() { someDao.listAllFromTable(tableName); }
    public void setTableName(String tableName) { this.tableName = tableName; }
}

Also in my application context xml file context.xml, I defined:
<bean id="userService" class="mypackage.DefaultUserService">
    <property name="tableName" value="myusers" />
</bean>

Then I want to test the DefaultUserService:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context-test.xml"})
@TransactionConfiguration(transactionManager = "testTransactionManager")
@Transactional
public class UserServiceTest {

    @Autowired
    private DefaultUserService userService;

    @Before
    public void setup() {
        userService.setTableName("mytesttable");
    }
    @Test
    public void test() {
        // test with userService;
        userService.listAll();
    }
}

Notice it uses context-test.xml, which imported the original context.xml:
<import resource="classpath:context.xml"/>

Unfortunately, when the test starts, spring throws exception:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mypackage.UserServiceTest':
Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private mypackage.DefaultUserService mypackage.userService

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [mypackage.DefaultUserService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I'm not sure where is wrong, why spring can't find the bean DefaultUserService I defined?

A: Try to replace the class DefaultUserService to the interface UserService
public class UserServiceTest {

    @Autowired
    private UserService userService;
    ....

}

A: It's because @Transactional places the bean is behind a jdk proxy implementing UserService interface, after that the bean is only available as UserService and not DefaultUserService.
See https://stackoverflow.com/a/18875681/241986.
You can try setting the table name with a property placeholder @Value("${someprop}") and define that property in test context, or create another interface that will expose setTableName(), and autowire that helper interface into the test case.
I'm not sure there are any easy solutions of the problem, I think this task can be subsumed under the problem of bean redefinition in Spring test-context framework
Spring beans redefinition in unit test environment

A: You have not defined the getter for your property tableName in your implementing class.Spring IOC container works on the POJO model


text:
Q: How do use OpenOffice components without installing OpenOffice.org? I'm working on solution for printing office documents based on OpenOffice.org UNO. My project is writing on C# .net. So my question is - it possible to use only required OpenOffice components without installing complete OpenOffice.org. My problem - deploying solution for end users. Thanks for advance.

A: You might want to also check out the ODF Toolkit


text:
Q: Scroll view and keyboard issue Swift I have a view controller with scrollview inside and I set it in this way (with autolayout) in storyboard:
Example
As you can see I add all objects in the last view (called 'viewsotto') inside in the scrollview.
My problem is that:
Some of these objects are textfield and I want that when I tap on it and keyboard shows it can be down the textfield so that I can see what I write in it.
For this reason I do it in this way:
NotificationCenter.default.addObserver(self, selector: #selector(userProfiloGiusto.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(userProfiloGiusto.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
            }
        }

    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0{
                self.view.frame.origin.y += keyboardSize.height
            }
        }
    }

but it doesn't work. What am I doing wrong?

A: Try below code.
Firstly add var activeField: UITextField? to check is textfield availability.
Then in view did load call this function:
override func viewDidLoad() {
    super.viewDidLoad()self.registerForKeyboardNotifications()

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(tap)
    tap.cancelsTouchesInView = false}

func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileReviewViewController.keyboardWasShown(_:)), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileReviewViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    let info : NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if activeField != nil
    {
        if (CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }
}

func keyboardWillBeHidden(notification: NSNotification)
{
    self.scrollView.contentInset = UIEdgeInsetsZero
}
//MARK : Textfield delegate methods
func textFieldDidBeginEditing(textField: UITextField) {
    activeField = textField
}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    self.view.endEditing(true)
    activeField = nil
    return false
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {  //delegate method

    activeField = nil
    return true
}
func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.

    activeField = nil
    view.endEditing(true)
}

A: Most probably the readings you are using to understand if there is overlapping are not correct.
It's a common issue, you are confronting them with your main view, instead you should get the frame of the textfield, make the right conversion to see if the keyboard is overlapping it and adjust the content inset of the scrollview accordingly.z

This is well explained in the Managing the keyboard documentation.
When the keyboard is shown:
func keyboardWasShown(notification: NSNotification)
{
    let info : NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size!
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize.height
    if let actField = activeField
    {
        if (CGRectContainsPoint(aRect, actField.frame.origin))
        {
            scrollView.scrollRectToVisible(actField.frame, animated: true)
        }
    }
}

The important point is when they ask the view height, they subtract the keyboard height and they check of the text view is inside that area.
This calculation may change in relation with your view hierarchy, this is becaus e a frame is the the position of a view respect its superview, thus if your rect is inside another view, you need to convert its frame to obtain which is its frame related to the main view.


text:
Q: Django: Add another field to django-registration I am pretty new to django and I am very lost with django-registration. At the moment I have the django-registration set up an going but I need to add another field to it for a phone number. I need the phone number field in the registration field instead so I can use the api from twilio to send a verification link through text instead of email. How would I go about adding this one field to django-registration?

A: Not django-registration, but I customized django-userena once to add a custom field to the signup form.
You can view the code here.
I am sure the process works more or less the same in django-registration too: overriding the signup form and adding custom fields.
However, django-registration is no longer maintained, I believe. It is a classic and works so well, but there are other options too.

A: I work with django at work and for that kind of issue we used to attach a model to the user, example:

*

*You create a new model, for example profile with a OneToOneField to user

*Add your desired fields to that profile model, such as (tlf, country, language,log...)

*Create admin.py to manage this model (profile) at the same time you manage users in django admin

Profile Model Example
class Profile(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=255, blank=True, null=True, verbose_name='phone')
    description = models.TextField(blank=True, verbose_name='descripction')
    ...
    ...
    class Meta:
        ordering = ['user']
        verbose_name = 'user'
        verbose_name_plural = 'users'

admin.py example
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    filter_horizontal = ['filter fields']  # example: ['tlf', 'country',...]
    verbose_name_plural = 'profiles'
    fk_name = 'user'

class UserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active')

admin.site.unregister(User)  # Unregister user to add new inline ProfileInline
admin.site.register(User, UserAdmin)  # Register User with this inline profile

Create an user and attach a profile to him
# Create user
username = 'TestUser'
email = 'test@example.com'
passw = '1234'
new_user = User.objects.create_user(username, email, passw)

# Create profile
phone = '654654654'
desc = 'Test user profile'
new_profile = Profile(user=new_user, phone = phone, description=desc)
new_profile.profile_role = new_u_prole
new_profile.user = new_user

# Save profile and user
new_profile.save()
new_user.save()

Now you'll have this Profile model attached to each user, and you could add the fields you wish to Profile Model, and for example if you make:
user = User.objects.get(id=1)
you can access to his profile doing:
user.profile
and to access phone
user.profile.phone


text:
Q: How do you store uploaded files in a filesystem? I'm trying to figure out the best way to store user uploaded files in a file system.  The files range from personal files to wiki files.  Of course, the DB will point to those files by someway which I have yet to figure out.
Basic Requirements:

*

*Fairy Decent Security so People Can't Guess Filenames
(Picture001.jpg, Picture002.jpg,
Music001.mp3 is a big no no)

*Easily Backed Up & Mirrorable (I prefer a way so I don't have to copy the entire HDD every single time I want to backup.  I like the idea of backing up just the newest items but I'm flexible with the options here.)

*Scalable to millions of files on multiple servers if needed.

A: One technique is to store the data in files named after the hash (SHA1) of their contents. This is not easily guessable, any backup program should be able to handle it, and it easily sharded (by storing hashes starting with 0 on one machine, hashes starting with 1 on the next, etc).
The database would contain a mapping between the user's assigned name and the SHA1 hash of the contents.

A: Guids for filenames, automatically expanding folder hierarchy with no more than a couple of thousand files/folders in each folder. Backing up new files is done by backing up new folders.
You haven't indicated what environment and/or programming language you are using, but here's a C# / .net / Windows example:
using System;
using System.IO;
using System.Xml.Serialization;

/// <summary>
/// Class for generating storage structure and file names for document storage.
/// Copyright (c) 2008, Huagati Systems Co.,Ltd.
/// </summary>

public class DocumentStorage
{
    private static StorageDirectory _StorageDirectory = null;

    public static string GetNewUNCPath()
    {
        string storageDirectory = GetStorageDirectory();
        if (!storageDirectory.EndsWith("\\"))
        {
            storageDirectory += "\\";
        }
        return storageDirectory + GuidEx.NewSeqGuid().ToString() + ".data";
    }

    public static void SaveDocumentInfo(string documentPath, Document documentInfo)
    {
        //the filestream object don't like NTFS streams so this is disabled for now...
        return;

        //stores a document object in a separate "docinfo" stream attached to the file it belongs to
        //XmlSerializer ser = new XmlSerializer(typeof(Document));
        //string infoStream = documentPath + ":docinfo";
        //FileStream fs = new FileStream(infoStream, FileMode.Create);
        //ser.Serialize(fs, documentInfo);
        //fs.Flush();
        //fs.Close();
    }

    private static string GetStorageDirectory()
    {
        string storageRoot = ConfigSettings.DocumentStorageRoot;
        if (!storageRoot.EndsWith("\\"))
        {
            storageRoot += "\\";
        }

        //get storage directory if not set
        if (_StorageDirectory == null)
        {
            _StorageDirectory = new StorageDirectory();
            lock (_StorageDirectory)
            {
                string path = ConfigSettings.ReadSettingString("CurrentDocumentStoragePath");
                if (path == null)
                {
                    //no storage tree created yet, create first set of subfolders
                    path = CreateStorageDirectory(storageRoot, 1);
                    _StorageDirectory.FullPath = path.Substring(storageRoot.Length);
                    ConfigSettings.WriteSettingString("CurrentDocumentStoragePath", _StorageDirectory.FullPath);
                }
                else
                {
                    _StorageDirectory.FullPath = path;
                }
            }
        }

        int fileCount = (new DirectoryInfo(storageRoot + _StorageDirectory.FullPath)).GetFiles().Length;
        if (fileCount > ConfigSettings.FolderContentLimitFiles)
        {
            //if the directory has exceeded number of files per directory, create a new one...
            lock (_StorageDirectory)
            {
                string path = GetNewStorageFolder(storageRoot + _StorageDirectory.FullPath, ConfigSettings.DocumentStorageDepth);
                _StorageDirectory.FullPath = path.Substring(storageRoot.Length);
                ConfigSettings.WriteSettingString("CurrentDocumentStoragePath", _StorageDirectory.FullPath);
            }
        }

        return storageRoot + _StorageDirectory.FullPath;
    }

    private static string GetNewStorageFolder(string currentPath, int currentDepth)
    {
        string parentFolder = currentPath.Substring(0, currentPath.LastIndexOf("\\"));
        int parentFolderFolderCount = (new DirectoryInfo(parentFolder)).GetDirectories().Length;
        if (parentFolderFolderCount < ConfigSettings.FolderContentLimitFolders)
        {
            return CreateStorageDirectory(parentFolder, currentDepth);
        }
        else
        {
            return GetNewStorageFolder(parentFolder, currentDepth - 1);
        }
    }

    private static string CreateStorageDirectory(string currentDir, int currentDepth)
    {
        string storageDirectory = null;
        string directoryName = GuidEx.NewSeqGuid().ToString();
        if (!currentDir.EndsWith("\\"))
        {
            currentDir += "\\";
        }
        Directory.CreateDirectory(currentDir + directoryName);

        if (currentDepth < ConfigSettings.DocumentStorageDepth)
        {
            storageDirectory = CreateStorageDirectory(currentDir + directoryName, currentDepth + 1);
        }
        else
        {
            storageDirectory = currentDir + directoryName;
        }
        return storageDirectory;
    }

    private class StorageDirectory
    {
        public string DirectoryName { get; set; }
        public StorageDirectory ParentDirectory { get; set; }
        public string FullPath
        {
            get
            {
                if (ParentDirectory != null)
                {
                    return ParentDirectory.FullPath + "\\" + DirectoryName;
                }
                else
                {
                    return DirectoryName;
                }
            }
            set
            {
                if (value.Contains("\\"))
                {
                    DirectoryName = value.Substring(value.LastIndexOf("\\") + 1);
                    ParentDirectory = new StorageDirectory { FullPath = value.Substring(0, value.LastIndexOf("\\")) };
                }
                else
                {
                    DirectoryName = value;
                }
            }
        }
    }
}

A: SHA1 hash of the filename + a salt (or, if you want, of the file contents. That makes detecting duplicate files easier, but also puts a LOT more stress on the server). This may need some tweaking to be unique (i.e. add Uploaded UserID or a Timestamp), and the salt is to make it not guessable.
Folder structure is then by parts of the hash.
For example, if the hash is "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12" then the folders could be:
/2
/2/2f/
/2/2f/2fd/
/2/2f/2fd/2fd4e1c67a2d28fced849ee1bb76e7391b93eb12

This is to prevent large folders (some Operating Systems have trouble enumarating folders with a million of files, hence making a few subfolders for parts of the hash. How many levels? That depends on how many files you expect, but 2 or 3 is usually reasonable.

A: Just in terms of one aspect of your question (security): the best way to safely store uploaded files in a filesystem is to ensure the uploaded files are out of the webroot (i.e., you can't access them directly via a URL - you have to go through a script).
This gives you complete control over what people can download (security) and allows for things such as logging. Of course, you have to ensure the script itself is secure, but it means only the people you allow will be able to download certain files.

A: Expanding on Phill Sacre's answer, another aspect of security is to use a separate domain name for uploaded files (for instante, Wikipedia uses upload.wikimedia.org), and make sure that domain cannot read any of your site's cookies. This prevents people from uploading a HTML file with a script to steal your users' session cookies (simply setting the Content-Type header isn't enough, because some browsers are known to ignore it and guess based on the file's contents; it can also be embedded in other kinds of files, so it's not trivial to check for HTML and disallow it).


text:
Q: How to get ID of clicked element with jQuery I have the following html:
link
link
link
/*etc.... */

and the following jQuery script:
$(document).ready(function() {

    var $container = $('.gallery_r').cycle({
        fx:     'scrollHorz',
        speed:   500,
        timeout: 0
    });

    $('a.pagerlink').click(function() {
        var id = $(this).attr('id');
        $container.cycle(id);
        return false;
    });

});

the 'pagerlink' links control are to jQuery Cycle slideshow. If I swap this line:
$container.cycle(id);

for this
$container.cycle(7);

It works. (obviously only navigating to slide number 7). So, my question is how can I pick up the ID of the link being clicked and pass it into that line?

A: Your IDs are #1, and cycle just wants a number passed to it.  You need to remove the # before calling cycle.
$('a.pagerlink').click(function() {
    var id = $(this).attr('id');
    $container.cycle(id.replace('#', ''));
    return false;
});

Also, IDs shouldn't contain the # character, it's invalid (numeric IDs are also invalid).  I suggest changing the ID to something like pager_1.
link

$('a.pagerlink').click(function() {
    var id = $(this).attr('id');
    $container.cycle(id.replace('pager_', ''));
    return false;
});

A: You just need to remove the hash from the beginning:
$('a.pagerlink').click(function() {
    var id = $(this).attr('id').substring(1);
    $container.cycle(id);
    return false;
});

A: @Adam Just add a function using onClick="getId()"
function getId(){console.log(this.event.target.id)}

A: Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

A: First off you can't have just a number for your id unless you are using the HTML5 DOCTYPE. Secondly, you need to either remove the # in each id or replace it with this:
$container.cycle(id.replace('#',''));


text:
Q: Parâmetro pelo Ajax Estou precisando passar alguns argumentos pelo Ajax, a princípio o código apresenta erro de sintaxe.
            var comeco = $("data_filtroe").val();
            var fim = $("data_filtrod").val();
            jQuery.ajax({
                type: "get",
                url: "status_relatorio.php",
                data: "comeco="+comeco+" && fim="+fim,
                success: function(data){
                    document.querySelector('#status_dia').innerHTML = data;
                }
            });

Código PHP("status_relatorio.php"):
<?php
session_start();
$con = mysql_pconnect("localhost","root","eeep_#2017");
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
mysql_select_db("alunos",$con);
setlocale( LC_ALL, 'pt_BR', 'pt_BR.iso-8859-1', 'pt_BR.utf-8', 'portuguese' );
date_default_timezone_set( 'America/Fortaleza' );
$data_inicio = $_GET['comeco'];
$data_fim = $_GET['fim'];
$data="";
for ($i=$data_inicio; $i <= $data_fim; $i++) {
    if($data==""){
        $data = "data = ".$i;
    }else{
        $data = "and data = ".$i;
    }
}
if($data_inicio==$data_fim){
$data = "data=".$data_inicio;
}
$sql = "select * from ocorrencias where '$data' order by curso, nome_aluno asc";
$resultado = mysql_query($sql,$con);
$cont = 0;
$falta = 0;
$falta_justificada = 0;
$fardamento_incompleto = 0;
$es_autorizada = 0;
$indis = 0;
while($linha1 = mysql_fetch_array($resultado)){
    $cont++;
    if($linha1['tipo']=="Falta"){
        $falta++;
    }
    if($linha1['tipo']=="Falta Justificada"){
        $falta_justificada++;
    }
    if($linha1['tipo']=="Fardamento Incompleto"){
        $fardamento_incompleto++;
    }
    if($linha1['tipo']=="Entrada/Saída Autorizada"){
        $es_autorizada++;
    }
    if($linha1['tipo']=="Indisciplína"){
        $indis++;
    }
}
        echo "

                Faltas: ".$data_inicio."
                Faltas Justificadas: ".$falta_justificada."
                Fardamentos Incompletos: ".$fardamento_incompleto."
                Entradas/Saídas Autorizadas: ".$es_autorizada."
                Indisciplína: ".$indis."
                Total: ".$cont."

";?>

A: De acordo com a documentação do jQuery você precisa enviar dados no formato PlainObject, String ou Array.

data Type: PlainObject or String or Array Data to be sent to the
  server. It is converted to a query string, if not already a string.
  It's appended to the url for GET-requests. See processData option to
  prevent this automatic processing. Object must be Key/Value pairs. If
  value is an Array, jQuery serializes multiple values with same key
  based on the value of the traditional setting (described below).

Escreva o código abaixo:
        // Supondo que "data_filtroe" é uma classe.
        // Se for um ID, utilize $("#data_filtroe").val();
        var comeco = $(".data_filtroe").val();
        // Supondo que "data_filtrod" é uma classe.
        // Se for um ID, utilize $("#data_filtrod").val();
        var fim = $(".data_filtrod").val();
        jQuery.ajax({
            method: "POST",
            dataType: "json",
            url: "status_relatorio.php",
            data: { "comeco": comeco, "fim": fim },
            success: function(data){
                document.querySelector('#status_dia').innerHTML = data;
            }
        });

Lembrando que:

*

*GET - Busca, requer, solicita dados de algum lugar especificado.

*POST - Envia os dados para serem processados em algum lugar especificado.


text:
Q: Is there a way to make this grammar LALR(1)? I have a grammar with rules like this
A -> pq
B -> pr

Block -> { Astar Bstar }

Astar -> Astar A
       | epsilon

Bstar -> Bstar B
       | epsilon

Is there any way to turn this grammar into LALR(1)? From what I can make out, if the parser sees p inside a block, there's a shift/educe conflict.

A: Your language is regular, and is equivalent to the regular expression \{(pq)*(pr)*\}.  The problem is that any simple conversion to a grammar is going to require two-character lookahead to see whether there's a q or r after the p
Now you have this tagged both yacc and parsing so its not clear whether your looking for a practical answer of "how do you deal with this with yacc" or a theoretical answer "is there an LALR(1) grammar for this language."
For the practical answer, the solution is that you punt -- you move the recognition for A and B into the lexer where you recognize the character sequences pq  and pr as the tokens A and B.  Since lex/flex uses a DFA and backtracks to the longest matched token, they have no problem with arbitrary lookahead here.
For the theoretical answer, you need to transform the grammar to remove the need for lookahead.  The problematic construct is (pq)*(pr)* (the braces are irrelevant) which is equivalent to p(qp)*(rp)*r | p(qp)*q | epsilon which suggests a grammar like:
Block -> { p Astar Bstar r }
       | { p Astar q }
       | { }
A -> q p
B -> r p
Astar -> Astar A | epsilon
Bstar -> Bstar B | epsilon

An alternate approach is unfactoring the star rules to make them not match empty strings:
Block -> { Aplus Bplus }
       | { Aplus }
       | { Bplus }
       | { }
A -> p q
B -> p r
Aplus -> Aplus A | A
Bplus -> Bplus B | B

giving you two very different LALR(1) grammars for the same language.

A: Let's start off by seeing exactly why you're getting a LALR(1) conflict, then see if we can rework the grammar to make it LALR(1).
To see why the grammar isn't LALR(1), let's begin by computing the LR(1) configurating sets for the grammar:
(1)
S'     -> .Block [$]
Block  -> .{ Astar Bstar } [$]

(2)
S'     -> Block. [$]

(3)
Block -> { . Astar Bstar } [$]
Astar -> .Astar A [ }p ]
Astar -> .epsilon [ }p ]

(4)
Block -> { Astar . Bstar } [$]
Astar -> Astar .A [ }p]
A     -> .pq [}p]
Bstar -> .epsilon [ }p ]
Bstar -> . Bstar B [ }p ]

At this point, we can stop because we have a shift/reduce confict in state (4) on the symbol p: do you shift the p for A -> .pq [ {p ], or do you reduce BStar -> .epsilon [ }p ]?  Since there's a shift/reduce conflict in the LR(1) grammar, the grammar is not LR(1) at all, meaning that it can't possibly be LALR(1) (because every LALR(1) grammar is also an LR(1) grammar).
Fundamentally, the issue is that when the parser sees a p, it can't tell whether it's looking at the start of an A (meaning that it needs to shift it) or if there are no more A's left and it's looking at the start of a B (meaning that it needs to reduce Bstar -> epsilon).
To fix this, let's see what happens if we make a small tweak.  The issue we encountered is that the parser needs to immediately determine upon seeing a p whether to shift or reduce.  What if we give it time to delay the decision by looking at the p and then the follow-up character?  To do this, let's change your grammar slightly by rewriting
Bstar -> epsilon
Bstar -> Bstar B

as
Bstar -> epsilon
Bstar -> B Bstar

Now, the parser gets to look at more tokens before deciding what to do.  If it's looking at pq, it knows that it isn't looking at anything B-related.  If it sees pr, it knows it's looking at a B, and can therefore start doing productions of the second sort.  Let's see what happens to our LR(1) states if we do this:
(1)
S'     -> .Block [$]
Block  -> .{ Astar Bstar } [$]

(2)
S'     -> Block. [$]

(3)
Block -> { . Astar Bstar } [$]
Astar -> .Astar A [ }p ]
Astar -> .epsilon [ }p ]

(4)
Block -> { Astar . Bstar } [$]
Astar -> Astar .A [ }p]
A     -> .pq [}p]
Bstar -> .epsilon [ } ]
Bstar -> . B Bstar [ } ]
B     -> .pr [}]

(5)
Block -> { Astar Bstar . } [$]

(6)
Block -> { Astar Bstar } . [$]

(7)
A     -> p.q [}p]
B     -> p.r [}]

(8)
A     -> .pq [}p]

(9)
B     -> pr. [}]

(10)
Bstar -> B . Bstar [ } ]
Bstar -> . B Bstar [ } ]
B     -> .pr [}]

(11)
B     -> p.r [}]

Notice that our original shift/reduce conflict has disappeared, and this new grammar no longer has any shift/reduce conflicts at all.  Moreover, since there aren't any pairs of states with the same core, the above set of states is also the set of states we would have in our LALR(1) table.  Therefore, the above grammar is indeed LALR(1), and we haven't changed the meaning of the grammar at all.
Hope this helps!


text:
Q: Tag synonyms: warnings and compiler-warnings Tags warnings (2,206 questions tagged) and compiler-warnings (858 questions tagged) seem like they should be synonyms/merged.
I'm not sure of the technical details of concepts of "tag synonyms" and "merging tags" here, and I'm not sure which would be the better tag name, so not suggesting what exactly should be done, yet (and forgive me if this meta question is tagged badly, feel free to fix).
The wiki text could definitely use some improvement after possible merging.


text:
Q: limit spatial extent of arcpy cursor How do I limit spatial extent of features that is returned by arcpy.da.SearchCursor?  Can I use arcpy.env.extent?  Or somehow come up with sql statement to specify spatial relationship?   Or do I have to arcpy.SelectLayerByLocation_management to do intersection of my area of interest.
EDIT:
Here is what I want to accomplish.  Want to visit features from a feature class within a set extent.  I was hoping that second use of arcpy.da.SearchCursor respects arcpy.env.extent, but apparently it ignores it.
How can I do this (visit spatial subset of features)?  I want to have method with decent efficiency (e.g. avoid copying of features).
import arcpy
def proc():

    # I/O files
    fo = open('c:/users/yosuke/documents/log.txt','w')
    fc = arcpy.CopyFeatures_management('c:/Users/Yosuke/documents/ArcGIS/polytical_boundaries.mdb/tl_2010_us_state10', r'in_memory\fc')

    # grab everything, works fine
    arcpy.env.extent = 'MAXOF'
    n = int(arcpy.GetCount_management(fc).getOutput(0))
    m = len(list(arcpy.da.SearchCursor(fc, ('SHAPE@',))))
    extent = arcpy.Describe(fc).extent
    # got 52 from both, as expected
    fo.write('n: %s\n' % n)
    fo.write('m: %s\n' % m)
    fo.write('extent: %s\n' % extent)
    fo.write('\n')

    # want to grab only western USA
    arcpy.env.extent = arcpy.Extent(-120, 0, -90, 80)
    # this counts 27 western states, I suppose.
    n = int(arcpy.GetCount_management(fc).getOutput(0))
    # this still marches through all states, I want this to be spatial subset of USA
    m = len(list(arcpy.da.SearchCursor(fc, ('SHAPE@',))))
    extent = arcpy.Describe(fc).extent
    fo.write('n: %s\n' % n)
    fo.write('m: %s\n' % m)
    fo.write('extent: %s\n' % extent)
    fo.write('\n')

    # For now I am making copy of feature class
    # turned out that this is not very bad for my application, other processing
    # tasks I am applying on cursor rows are more computationally expensive.
    # I still want to know if this is standard way to accomplish this kind of
    # tasks (subset cursor by extent)
    fc2 = arcpy.CopyFeatures_management(r'in_memory\fc', r'in_memory\fc2')
    n = int(arcpy.GetCount_management(fc2).getOutput(0))
    m = len(list(arcpy.da.SearchCursor(fc2, ('SHAPE@',))))
    extent = arcpy.Describe(fc2).extent
    fo.write('n: %s\n' % n)
    fo.write('m: %s\n' % m)
    fo.write('extent: %s\n' % extent)
    fo.write('\n')

A: From what I have tested the extent does not limit the search cursors spatially..When using tools like "GetCount_Management" etc. it is limited but it appears that Cursors do not follow the extent

A: I haven't tried this out so I may be incorrect but I think the search cursor will honor the env.extent based on these notes in ArcGIS help.
Output Extent

extent (Read and Write)
Tools that honor the Output Extent environment will only process
  features or rasters that fall within the extent specified in this
  setting.

Cursors

Note:   Cursors honor layer/table view definition queries and
  selections. The cursor object only contains the rows that would be
  used by any geoprocessing tool during an operation.

I'm taking that last sentence to mean if a geoprocessing tool will only process features that fall into the defined extent than cursors will have the same behavior.


text:
Q: How to Set `route` parameter and Load New Page I am trying to pass in a paper-button value to the default router using the Polymer Shop App framework.  The app-location and app-route components are in both the App Shell and the Home Page.  I am not sure how to pass the data into the route object and refresh the view.
App Shell
<app-location route="{{route}}"></app-location>
<app-route
  route="{{route}}"
  pattern="/:page"
  data="{{routeData}}"
  tail="{{subroute}}"></app-route>

<iron-pages role="main" selected="[[page]]" attr-for-selected="name" selected-attribute="visible">
  <shop-home name="home"></shop-home>
  <shop-detail name="detail"></shop-detail>
</iron-pages>

Home Page
<paper-button id="item" value="[[item.name]]" on-tap="viewItem">[[item.name]]</paper-button>

...

viewItem() {
  this.route.path = '/detail';
  this.routeData = '/inventory/' + this.$.item.value;
}

P.S.
 successfully redirects to the `detail` page and loads the data.

A: In order to pass the data to the route object, wrap a tag the item instead of a button element, At below example I didn't try to convert your all code to this. just I tried to explain what I meant: (Note: I was working on this subject for 2-3 weeks for an app, it works nicely now.) I will try to add a demo while.

[[item.name]]

instead of:
 <paper-button id="item" value="[[item.name]]" on-tap="viewItem">[[item.name]]</paper-button>


text:
Q: Properties of the Complement of a Sumset Let $(G, +)$ be a finite abelian group.
Let $A, B$ be subsets of $G$.
Then we define the sumset (or Minkowski sum) as:
$$A + B = \{a + b\mid a\in A, b\in B\}$$
Fix a subset $C\subseteq G$.
For any $A\subseteq C$, we can (attempt to) define the complement of $A$ (denoted $\overline{A}$) within $C$ as follows:
$$\overline{A} := \arg\max_{A'\subseteq C}(A + A' \subseteq C)$$
This name is meant to contrast with the traditional set complement $A^c$, which can be written (where $\sqcup$ is the disjoint union):
$$A^c := \arg\max_{A'\subseteq C}(A \sqcup A' \subseteq C)$$
Has this notion been introduced before?
If so, have properties of $\overline{A}$ been worked out?
I've tried leafing through some textbooks on Additive combinatorics, but haven't seen anything similar (despite it being a rather naïve notion to introduce).


text:
Q: ng-repeat doesnt work when include using ng-include I am learning to code in Angular. I am trying to perform a ng-repeat from within a file myTable.htm that is included in the main html file 1.html this however doesnt work.
1.html
<!DOCTYPE html>

The HTML, and AngularJS code, for this table are located in the file "myTable.htm".

myTable.htm

<select ng-model="selectedName" ng-options="x for x in names">
</select>

If I add  to myTable.htm and execute myTable.htm then I get the values in the select box. But it doesn't fill when I execute 1.html.
Can anyone tell me what I have done wrong or whether what I am attempting to do is possible?

A: You need to have the ng-app defined only in the first.html

Remove it from the myTable.htm

DEMO


text:
Q: animated positioned toke too much space - flutter animated positioned took too much space while changing the position. the question is there is any way to minimize this space ?
it ascends to safeare

the source code is below so you can try it:
class Test extends StatefulWidget {
  const Test({Key? key}) : super(key: key);

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> with TickerProviderStateMixin {
  bool selected = false;

  late AnimationController colorController;
  late Animation animation;

  @override
  initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      setState(() {
        selected = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    changeStatusColor(colorPrimary);
    return Scaffold(
      backgroundColor: colorPrimary,
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          AnimatedPositioned(
            curve: Curves.elasticOut,
            duration: Duration(milliseconds: 10000),
            width: MediaQuery.of(context).size.width,
            height: selected
                ? MediaQuery.of(context).size.height
                : MediaQuery.of(context).size.height * .7,
            top: selected
                ? 50.0
                : MediaQuery.of(context).size.height -
                    MediaQuery.of(context).size.height * .7,
            child: Container(
                padding: EdgeInsets.fromLTRB(26, 0, 26, 25.51),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(top: Radius.circular(40)),
                ),
                child: Column(children: [])),
          ),
        ],
      ),
    );
  }
}

A: The animation curve: Curves.elasticOut is responsible for this. You can switch to difference one or reduce the top animation point.

You can check this elasticOut behavior
Check Curves class and choose the one you need


text:
Q: Convert PPT into Images in Rails I am using docsplit gem to convert PPT into images
Docsplit.extract_images(uploaded.path.to_s, :size => '550x', :format => [:jpg],:output=>"#{Rails.root}/public/images")

it convert successfully but i will take more time . Can i Convert any other way Please anyone help me.

A: Im using Docsplit as well,
and if you meant that your application is idling/loading while docsplit is converting you ppt files you should keep in mind that:
Every process that takes time, will get you application "stuck" until its job is done.
therefore,
You should run heavy job/tasks that takes a long time - in the background / in delayed job
If you do so: users won't get stuck!
(dont forget that you should let them know that the job is "in process", so they won't think there was an error)


text:
Q: How can I create an algorithm that optimizes/combines tiles in a tileset My problem is that I can't entirely figure out how to make an algorithm that combines tiles to create one tile. Maybe these pictures that I made in ms paint will help you to get an idea for what I mean.
The idea that I have is that there is a loop that goes over every single tile and creates a correlation when there is another tile like it. Illustrated below.
https://i.imgur.com/ifMUgdL.png
And the expected result from this unknown algorithm should be:
https://i.imgur.com/xtRJbEN.png
For clarification, every tile has an x, y, w, h, and sprite which is currently a string directory which is bound to change.
Though I would like to hear the theory behind this. The code is not important for me. Thanks in advance.
class Tile {

  float x, y, w, h;
  String sprite;

  Tile(float x, float y, float w, float h, String sprite) {
    // here be the initiating.
  }

}

The result should combine tiles which are the same to increase performance loading the tiles. It is also fun to think of this and try to solve this problem. Thank you for this in advance.
Good luck and have a nice day!
Added information:
Lets say there is a 3 x 3 grid. How could you couple as many colors  of the same type together so that there are the least amount of couples in  there.
https://i.imgur.com/B1K9R3q.png
That would be:
https://i.imgur.com/QfMGFYz.png
Now what if it were a 13 x 5 grid?
https://i.imgur.com/p6arXvK.png
I would like an algorithm to solve this for me, though I can not figure one out.
Summary:
Create the least amount of couples in a grid with different tiles. And have the most amount of tiles residing in the objects.

A: I am pretty new here as well, so please do not judge my answer too harshly…
Here is my solution in a descriptive manner:

Step 1:
We detect each individual blob (where blob is a connected mass of tiles that share the same color). This can be done efficiently with a dictionary/hashtable.
Step 2 (greedy algorithm):
We then run the following process over each blob. We split it into lines once horizontally and once vertically.
If two consecutive lines are "aligned" and have the same length, they are joined to make a bigger tile and the process then repeats.
If the next line does not match this criteria, then then we return the lines gathered so far as a tile.
At the end we will have two possible results for the tile distribution.
Step 3:
We compare the output of the horizontal scan with the output of the vertical scan. Whichever one yielded the least amount of tiles is treated as the final result.

I believe obtaining the best result with dynamic programming is also an option, however it would take too long and defeat the whole purpose (unless I am missing something).


text:
Q: Is there a way of calculating the gradient descent of a Neural Nework output w.r.t the input with tensorflow 2.0? I have trained a Recurrent Neural Network for time-series prediction and I'm now trying to find the optimal input for the network (i.e. the input that minimizes the output). At this purpose, I was thinking of applying a gradient descent method (for example, the classic SGD method) using the input-output function that is represented by the trained network itself. I managed to build a tf function that computes the gradient of the network output w.r.t. the input but I don't really know how to use it to implement the descent algorithm.
I attach the code I've written for my network's structure and gradient function. Any suggestion will be very much appreciated.
import tensorflow as tf
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, Concatenate, Dropout
from keras import regularizers
from keras import optimizers
from keras.callbacks import EarlyStopping
from keras import backend as K

#Define the first RNN
first_model = Sequential()
first_model.add(LSTM(64, input_shape=(lb, nbr_features), return_sequences=False))

#Define the second RNN
second_model = Sequential()
second_model.add(LSTM(64, input_shape=(ph2, nbr_features-1), return_sequences=False))

#Concatenate the two models' outputs and pass it to the overall output layer
MergedOutput = Concatenate()([first_model.output, second_model.output])
MergedOutput = Dense(ph1, activation='relu')(MergedOutput)

#Generate the overall model
final_model = Model([first_model.input, second_model.input], MergedOutput)

#Model summary
final_model.summary()

#Compile the model
opt=optimizers.Adam(learning_rate=0.001)
final_model.compile(optimizer=opt, loss='mean_squared_error')

#Train the model
stopping = EarlyStopping(monitor='val_loss', patience=4)
history = final_model.fit([x_train1, x_train2], y_train, batch_size=40, epochs=300, validation_data=([x_valid1, x_valid2], y_valid), callbacks=[stopping], verbose=2, shuffle=True)

#Define the gradient of the output w.r.t the input
grads = K.gradients(final_model.output, final_model.input)

#Define a TensorFlow function that computes this gradient
gradient_func = K.function([final_model.input], grads)


text:
Q: gcc compilation flags when targeting linux from Visual Studio I'm developing c++ code on Visual Studio 2019 (Version 16.5.4), and for the build i'm targeting Linux Ubuntu 18.04 with gcc 7.5 - both on a remote machine via ssh, and on my local machine via WSL2.
In both cases i have the same problem:
when using std::async, i have to add the compilation flag -lpthread to gcc's input, in order for the program to compile, otherwise i get

undefined reference to pthread_create

Moreover, the flag has to come after the cpp file name, i.e. g++ -lpthread xxx.cpp will fail with gcc 7.5, while g++ xxx.cpp -lpthread works fine.
so far so good, but here's the problem: i can't do a successful build through Visual Studio: when i add the -lpthread flag under Additional Options in the project's C/C++ properties, there doesn't seem to be any effect - the compilation still fails. moreover, since i don't see the flag being added to the full build command line (which is presented read-only), i have no way to see if the flag is actually being sent, and in the right order (namely after the cpp file name). since i don't see any way to manually edit the build command line, I'm out of ideas...
anyone?
Thanks.


text:
Q: bash script and awk to sort a file so I have a project for uni, and I can't get through the first exercise. Here is my problem:
I have a file, and I want to select some data inside of it and 'display' it in another file. But the data I'm looking for is a little bit scattered in the file, so I need several awk commands in my script to get them.
Query= fig|1240086.14.peg.1

Length=76
                                                                  Score     E
Sequences producing significant alignments:                          (Bits)  Value

 fig|198628.19.peg.2053                                              140     3e-42

> fig|198628.19.peg.2053
Length=553

Here on the picture, you can see that there are 2 types of 'Length=', and I only want to 'catch' the "Length=" that are just after a "Query=".
I have to use awk so I tried this :
 awk '{if(/^$/ && $(NR+1)/^Length=/) {split($(NR+1), b, "="); print b[2]}}'

but it doesn't work... does anyone have an idea?

A: awk solution:
awk '/^Length=/ && r~/^Query/{ sub(/^[^=]+=/,""); printf "%s ",$0 }
     NF{ r=$0 }END{ print "" }' file

*

*NF{ r=$0 } - capture the whole non-empty line

*/^Length=/ && r~/^Query/ - on encountering Length line having previous line started with Query(ensured by r~/^Query/)

A: You need to understand how Awk works.  It reads a line, evaluates the script, then starts over, reading one line at a time.  So there is no way to say "the next line contains this".  What you can do is "if this line contains, then remember this until ..."
awk '/Query=/ { q=1; next } /Length/ && q { print } /./ { q=0 }' file

This sets the flag q to 1 (true) when we see Query= and then skips to the next line.  If we see Length and we recently saw Query= then q will be 1, and so we print.  In other cases, set q back to "not recently seen" on any non-empty line. (I put in the non-empty condition to allow for empty lines anywhere without affecting the overall logic.)

A: It sounds like this is what you want for the first part of your question:
$ awk -F'=' '!NF{next} f && ($1=="Length"){print $2} {f=($1=="Query")}' file
76

but idk what the second part is about since there's no "data" lines in your input and only 1 valid output from your sample input best I can tell.


text:
Q: Ionic: how can I access constructor objects from nested methods? I am using leaflet to render a map, and leaflet draw to draw shapes. I am able to draw & save shapes as well as retrieve them. I am struggling how to interact with the retrieved shapes.
In my specific case, I want to init a popover.
myfile.ts
constructor(public popoverCtrl: PopoverController) {...}

drawShape(data) {
    let shape = {...} // has geometry etc.

    L.geoJSON(shape, {
        onEachFeature: this.onEachFeature
      }).addTo(this.myMap);
}

onEachFeature(feature, layer) {
    layer.on('click', function (e) {
    let popover = this.popoverCtrl.create('MyComponent', { layer: event });

    popover.present();
});

I can't get to this.popoverCtrl since it's in a different scope than the constructor. How can I get access to the popover component?
Thank you for any suggestions!

A: So you need to deal with 'this' in your case. For that you can use fat arrow functions to do that as they do not create their own "this" unlike anonymous and other functions: see in the layer.on part where i did the change going from anonymous to fat arrow function:
onEachFeature(feature, layer) {
    layer.on('click', event => {
    let popover = this.popoverCtrl.create('MyComponent', { layer: event });

    popover.present();
});

Sometimes you will still have issues "getting to" the "this" you need from your component method if you sort of traverse through various execution contexts. In such cases you can also do this trick in your component methods: assign method through variable
onEachFeature = (feature, layer) => {
    layer.on('click', event => {
    let popover = this.popoverCtrl.create('MyComponent', { layer: event });

    popover.present();
});

This basically prevents your methods from creating their own "this" context.
PS: please note that your code defines event differently in argument of function and then in the code (e vs event) i hope you can fix that


text:
Q: How to restore an earlier version of a table from recyclebin? I'm practicing on restoring tables from recyclebin in Oralce 19.
I've already known about the FLASHBACK TABLE statement. However, it does restore the last version of a table only.
What if I want to restore an earlier state of my table?
Here's what I've already found and tried:
By this query I get names of the deleted instances of my table and when these were deleted.
select object_name, droptime from recyclebin where original_name = 'TEST';

Then I copy an object_name of the instance I need to my flashback statement:
flashback table BIN$USnbm7YhQBu9TbSyOdqyKA==$0 TO BEFORE DROP;

this sentence gave me ORA-00905: missing keyword.
Is there a way to correct the last statement or the whole method isn't working?

A: Recycle bin objects have strange names and must be surrounded with quotation marks like this:
flashback table "BIN$USnbm7YhQBu9TbSyOdqyKA==$0" TO BEFORE DROP;


text:
Q: Evaluate $\int{ \boldsymbol{x}^T \boldsymbol{x} \exp^{-\boldsymbol{x}^T \boldsymbol{x}} \, d\boldsymbol{x}}$ How can one proceed to evaluate the integral
$\int_{-\infty}^{\infty}{ \boldsymbol{x}^T \boldsymbol{x} \exp^{-\boldsymbol{x}^T \boldsymbol{x}} \, d\boldsymbol{x}}$
This case of $\boldsymbol{x}$ being vector valued is throwing me off. Any tips would be appreciated.


text:
Q: python - class - AttributeErr - but method defined class Card(object):
    suitList = ("Clubs", "Diamonds", "Hearts", "Spades")
    rankList = ("narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King")

    def __init__(self, suit = 0, rank = 2):
        self.suit = suit
        self.rank = rank
    def __str__ (self):
        return "%s of %s" % (self.rankList[self.rank], self.suitList[self.suit])
    # override built-in compare function:
    def __cmp__(self, other):
        # use if instead of if...elif..else
        if self.suit > other.suit: return 1
        if self.suit < other.suit: return -1

        if self.rank == 1 and other.rank != 1: return 1
        if self.rank != 1 and other.rank == 1: return -1
        if self.rank > other.rank: return 1
        if self.rank < otehr.rank: return -1

        return 0

# test code
card1 = Card(0, 12)
card2 = Card(1, 2)
print card1.cmp(card2)

below is the err msg:
Traceback (most recent call last):
  File "C:\Python27\OOP_thecardclass.py", line 29, in
    print card1.cmp(card2)
AttributeError: 'Card' object has no attribute 'cmp'
Why?

A: That must be __cmp__, not cmp:
print card1.__cmp__(card2)

A: __cmp__ != cmp. Try using == or != instead, as the reason for implementing __cmp__ is for these operators. You don't use __cmp__ directly, you use it to "overload" operators. See: http://en.wikipedia.org/wiki/Ad-hoc_polymorphism


text:
Q: How to clone typing to every input from the first box with jquery on checkbox checked (dynamically)? Referring to the solution of https://stackoverflow.com/a/46159513/1620626 with a big help from @osdavison.
Now I want the script to find it's child class or id without predefined it. All I thinking now is making a function. So I'd hope to do this.
JS
function cloneAllz(chkBoxID, clsName) {
  alert(chkBoxID + '/' + clsName);//test value
  var $input1 = $(document).find('#' + clsName).filter(':visible:first'); //find the first input begins with *box or other same id???
  $input1.keypress(function() { //duplicate the first box typing
    var $this = $(this);
    window.setTimeout(function() { //delay a bit
      if ($('#' + chkBoxID).is(':checked')) { //if checkbox empty
        $('*[id^="' + clsName + '"]').val($this.val()).attr('readonly', true); //clone all inputs and set them readonly
        $input1.attr('readonly', false);
      }
    }, 0);
  });
}

HTML
 1.
<input type="text" value="" id="box1" />

  <input type="checkbox" id="cloneAll" onChange="cloneAllz('cloneAll','box')" />clone all

 2.
<input type="text" value="" id="box2" />

 3.
<input type="text" value="" id="box3" />

 4.
<input type="text" value="" id="box4" />

 5.
<input type="text" value="" id="box5" />

 .

 .

 .

 100.
<input type="text" value="" id="box100" />

All I got from the console is Uncaught ReferenceError: cloneAllz is not defined
Fiddle here

A: Firstly your fiddle is using jQuery 1.5.2 which is very outdated. You should update that ASAP.
Secondly you should use unobtrusive event handlers instead of event attributes in the HTML.
To fix your actual problem you can hook to the input event of the first input. Within that event handler you can inspect to see if the checkbox is checked, and if so se the val() of all other inputs to match that of the current one. Using this method will massively simplify your code which currently seems a little over-complicated. Try this:

$('.container .master').on('input', function() {
  var $container = $(this).closest('.container');
  if ($container.find('.cloneAll').is(':checked'))
    $container.find('input:not(.master)').val(this.value);
});

  1. <input type="text" value="" class="master" />

    <input type="checkbox" class="cloneAll" />
    clone all

  2. <input type="text" value="" id="box2" />

  3. <input type="text" value="" id="box3" />

  4. <input type="text" value="" id="box4" />

  5. <input type="text" value="" id="box5" />

  .
 .
 .

  100. <input type="text" value="" id="box100" />

  1. <input type="text" value="" class="master" />

    <input type="checkbox" class="cloneAll" />
    clone all

  2. <input type="text" value="" id="box2" />

  3. <input type="text" value="" id="box3" />

  4. <input type="text" value="" id="box4" />

  5. <input type="text" value="" id="box5" />

  .
 .
 .

  100. <input type="text" value="" id="box100" />

A: After a night I head ached. This noon I come up with the working code. Thanks to those efforts and google. Fiddle

$(document).on('change', $('.clone'), function(el) {
  var $this = $(el.target);
  var $clss = $(el.target).attr('value'); //target class name
  var $master = $('.prdEdt').find('td.' + $clss + ' input[type="text"]').filter(':visible:first');
  var $tdVal = $('td.' + $clss + '>input[type="text"]');

  if ($this.is(':checked')) {
    $($tdVal).attr('readonly', 'true'); //set child readonly
    $master.attr('readonly', false); //exclude 1st input

    $master.on('input', function() {
      $($tdVal).val($(this).val());
      $tdVal.each(function() {
        console.log($(this).attr('id') + '/' + $(this).val());
        //call ajax
      });
    })
  } else {
    console.log('unchecked');
    $($tdVal).removeAttr('readonly');
  }
});
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

    ID
    Code

        <input type="checkbox" class="clone" value='cde' />

    Title

        <input type="checkbox" class="clone" value="tt_en"  />

    Cost

    00067

      <input type="text" name="prd_cde" id="prd_cde|67" class="form-control" value="3000009" />

      <input type="text" name="prd_title_en" id="prd_title_en|67" class="form-control" value="TRANSFER" />

      <input type="number" name="prd_cost" id="prd_cost|67" class="form-control" value="800" />

    00068

      <input type="text" name="prd_cde" id="prd_cde|68" class="form-control " value="3000009" />

      <input type="text" name="prd_title_en" id="prd_title_en|68" class="form-control " value="TRANSFER" />

      <input type="number" name="prd_cost" id="prd_cost|68" class="form-control" value="600" />


text:
Q: I can't get my additive weighting algorithm to work properly I have a data structure that look like this
$data = [
    [
        "name" => "user_a",
        "code" => "c1",
        "description" => "criteria 1",
        "type" => "benefit",
        "weight" => 25,
        "value" => 75
    ],
    [
        "name" => "user_a",
        "code" => "c2",
        "description" => "criteria 2",
        "type" => "benefit",
        "weight" => 20,
        "value" => 67
    ],
    [
        "name" => "user_a",
        "code" => "c3",
        "description" => "criteria 3",
        "type" => "benefit",
        "weight" => 15,
        "value" => 80
    ],
    [
        "name" => "user_a",
        "code" => "c4",
        "description" => "criteria 4",
        "type" => "benefit",
        "weight" => 22,
        "value" => 90
    ],
    [
        "name" => "user_a",
        "code" => "c5",
        "description" => "criteria 5",
        "type" => "benefit",
        "weight" => 8,
        "value" => 20
    ],
    [
        "name" => "user_a",
        "code" => "c6",
        "description" => "criteria 6",
        "type" => "benefit",
        "weight" => 10,
        "value" => 80
    ],
    [
        "name" => "user_b",
        "code" => "c1",
        "description" => "criteria 1",
        "type" => "benefit",
        "weight" => 25,
        "value" => 65
    ],
    [
        "name" => "user_b",
        "code" => "c2",
        "description" => "criteria 2",
        "type" => "benefit",
        "weight" => 20,
        "value" => 70
    ],
    [
        "name" => "user_b",
        "code" => "c3",
        "description" => "criteria 3",
        "type" => "benefit",
        "weight" => 15,
        "value" => 80
    ],
    [
        "name" => "user_b",
        "code" => "c4",
        "description" => "criteria 4",
        "type" => "benefit",
        "weight" => 22,
        "value" => 90
    ],
    [
        "name" => "user_b",
        "code" => "c5",
        "description" => "criteria 5",
        "type" => "benefit",
        "weight" => 8,
        "value" => 20
    ],
    [
        "name" => "user_b",
        "code" => "c6",
        "description" => "criteria 6",
        "type" => "benefit",
        "weight" => 10,
        "value" => 80
    ],
];

I'm trying to get the normalized values but it wasn't giving me the expected result with my current algorithm.
// This one is fine
$matrix_x = get_matrix_x($data);

// result: [
//   "user_a": [75, 67, 80, 90, 20, 80],
//   "user_b": [65, 70, 80, 90, 20, 80],
//   "user_c": [56, 70, 75, 80, 50, 70],
// ];

// This one is producing the wrong result (I rounded it just to make it readable, decimals are OK to be shown as is)
$matrix_r = get_matrix_r($data, $matrix_x);

// current result: [
//   "user_a": [0.8, 0.7, 0.8, 1.0, 0.2, 0.8],
//   "user_b": [0.7, 0.7, 0.8, 1.0, 0.2, 0.8],
//   "user_c": [0.7, 0.8, 0.9, 1.0, 0.6, 0.8],
// ];

// expected result: [
//   "user_a": [1.0, 0.9, 1.0, 1.0, 0.4, 1.0],
//   "user_b": [0.8, 1.0, 1.0, 1.0, 0.4, 1.0],
//   "user_c": [0.7, 1.0, 0.9, 0.8, 1.0, 0.8],
// ];

I have been stuck with this problem for about 4 days, the problem is in the min(...) and max(...) function inside the get_matrix_r method. It was supposed to take the number from top to bottom for each column instead of taking the highest/lowest number directly from the key given by $matrix_x but I don't know how to do that.
I also asked a question related to this issue, but when I loop inside the $reducer using the given solutions, it produce extra items in the result. Please help!
functions.php
/**
 * Generate matrix_x from the given data.
 *
 * @param  array $data
 * @param  string $key
 * @param  string $valkey
 * @return array
 */
function get_matrix_x(array $data, string $key = 'name', string $valkey = 'value')
{
    $reducer = function ($acc, $item) use ($key, $valkey) {
        $index = $item[$key];

        if (!isset($acc[$index])) {
            $acc[$index] = [];
        }

        $acc[$index][] = (int) $item[$valkey];

        return $acc;
    };

    return array_reduce($data, $reducer, []);
}

/**
 * Generate matrix_r from data and matrix_x as origin.
 *
 * @param  array $data
 * @param  array $origin
 * @param  string $key
 * @param  string $valkey
 * @param  string $compkey
 * @return array
 */
function get_matrix_r(array $data, array $origin, string $key = 'name', string $valkey = 'value', string $compkey = 'type')
{
    $reducer = function ($acc, $item) use ($key, $valkey, $origin, $compkey) {
        $index = $item[$key];

        if (!isset($acc[$index])) {
            $acc[$index] = [];
        }

        $item[$compkey] === 'cost'
            ? $acc[$index][] = (int) $item[$valkey] / min($origin[$index])
            : $acc[$index][] = (int) $item[$valkey] / max($origin[$index]);

        return $acc;
    };

    return array_reduce($data, $reducer, []);
}

A: Well, the first problem, is that in the dataset you are providing there is not user_c, but in the output matrix there are references to that, so that's weird.
The second problem, is that in the reducer, you are considering the ROWs, and not the COLUMNs... to consider those, you should do something like this:
/**
 * Generate matrix_r from data and matrix_x as origin.
 *
 * @param  array $data
 * @param  array $origin
 * @param  string $key
 * @param  string $valkey
 * @param  string $compkey
 * @return array
 */
function get_matrix_r(array $data, array $origin, string $key = 'name', string $valkey = 'value', string $compkey = 'type')
{
     $reducer = function ($acc, $item) use ($key, $valkey, $origin, $compkey) {
          $index = $item[$key];
          print_r($item);
          if (!isset($acc[$index])) {
               $acc[$index] = [];
          }
          // consider the nth COLUMN, with $origin[$index] you was considering the ROW
          $col = array_column($origin, count($acc[$index]));
          $item[$compkey] === 'cost'
               ? $acc[$index][] = (int) $item[$valkey] / min($col)
               : $acc[$index][] = (int) $item[$valkey] / max($col);

          return $acc;
     };

     return array_reduce($data, $reducer, []);
}


text:
Q: MongoDB - Get the sum of an object in an array Hi I'm very new to MongoDB, I'm trying to get the total price and promo of the below MongoDB data with document.collection.find and $add functionality:
Data:
[
  {
    "catalog":"A",
    "book":[
    {
      "title":"Mermaid yang terdampar",
      "price":90000,
      "promo":15000
    },
    {
      "title":"Srigala berbulu domba",
      "price":30000,
      "promo":15000
    }
  }
]

And my expected result would be sth like this:
[
  {
    "catalog": "A",
    "totalPrice": 140000,
    "totalPromo": 32000
  },
]

Does anybody ever encounter a similar issue? I'm confused with the query :)

A: For .find() query, you can direct use the $sum operator.
db.collection.find({},
{
  catalog: 1,
  totalSum: {
    $sum: "$book.price"
  },
  totalPromo: {
    $sum: "$book.promo"
  }
})

Sample Mongo Playground

A: use aggregate
db.getCollection('myCollection').aggregate([
    { "$group": {
        "_id": "$tempId",
        "totalPrice": {
            "$sum": { "$sum": "$book.price" }
        },
        "totalPromo": {
            "$sum": { "$sum": "$book.promo" }
        }
    } }
])

A: Using $group (aggregation)
db.getCollection('catlog').aggregate([{
    $group: {
        _id: "$_id",
        catalog: { $first: "$catalog" },
        totalPrice: { "$sum": { $sum: "$book.price" } },
        totalPromo: { "$sum": { $sum: "$book.promo" } }
    }
}])

Output will be:
{
    "_id" : ObjectId("6247b33cffc5b6f714769fbb"),
    "catalog" : "A",
    "totalPrice" : 120000,
    "totalPromo" : 30000
}


text:
Q: Domain mapping of appengine

Please** help me ** the domain is not mapping still ..is that the cname setting in this dns is correct ...

A: it seems incorrect to me... why do you have 4 repeated entries of www on both left and right side?
It should be something like:
www on the left side,  type cname, then content should be ghs.googlehosted.com


text:
Q: How to get Excel to use digit grouping separator (thousand separator) universally? Digit grouping separator is already set in my regional settings

But excel doesn't show numbers like that. How can I get excel to do that everywhere including the average number in status bar.

I don't wanna have to select and format each sheet to show numbers like that.

A: Numbers entered or pasted into an Excel cell use the General format by default. This doesn't use thousand separators because that wouldn't always be appropriate. The numbers you've entered or pasted might be identifiers, or some multi digit number for which it wouldn't be appropriate to separate the digits. The General format is the safe option as it tries to make as few assumptions as possible.
For example, I frequently have columns that have a four-digit year in them. If these were automatically formatted to 2,020 (for this year), it would be very annoying!
You can use the keyboard shortcut Ctrl+Shift+! to format selected cells to the "Comma Style" format, which will usually use thousands separator and two decimal places. In Excel 365, Alt+H+K will achieve the same thing.
EDIT:
A workaround is to create a macro in your Personal macro workbook and assign a keyboard shortcut to it.
If you haven't used the personal macro workbook before, the easiest way to get at it is to record a new macro and select it from the drop-down.
Click "Record Macro" from the "Code" group on the "Developer" tab of the ribbon, then use the drop-down in the dialog box. You can give it a shortcut at the same time:

Record the step you usually take to format in the way you want.
I clicked "Comma style" then removed the decimals then I made the column a bit wider to make sure it worked on a large number I had in my test data. Press Alt+F11 to open the code editor, and saw this:
Sub MyFormat()
'
' MyFormat Macro
'
' Keyboard Shortcut: Ctrl+g
'
    Selection.Style = "Comma"
    Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
    Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
    Columns("A:A").ColumnWidth = 24.71
End Sub

I don't need all of that. Just the third line, so I edited it so I had this:
Sub MyFormat()

' Keyboard Shortcut: Ctrl+g
Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"

End Sub

Now I have that macro in the Personal macro workbook, Ctrl+G will apply that format to whatever I have selected.


text:
Q: Appending data to User Model in Django Here is how my model looks like:
    class Maintab(models.Model):
        email = models.CharField(max_length=255)
        username = models.CharField(max_length=255)
        password = models.CharField(max_length=255)
        lab_name = models.CharField(max_length=255)
        type = models.CharField(max_length=255)
        def __str__(self):
             return self.username

I want to append the User table that looks after the login, with the username and password of my Maintab model. If only the username and password of the user table could get updated.
Or if I could use Maintab as my Custom UserModel (but it would not have attributes like is_active, is_staff, etc)

A: Seems like creating your own user models by subclassing the existing user model is the right solution as it enables you to use the existing django code while also adding your own user attributes.
Here is a link to the Django documentation where they describe how to do this:
https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project


text: Q: Email macro on Mail for MacOS I get receipts to my email which need to go to my book keeping. I would love to semi-automate this process, by adding a button for me somewhere where I can go "THAT's a receipt, email to the right place as the right alias". I have trouble combining the interactivity (me selecting an email) and the automation (forwarding etc). Is there a magic bullet here? I've looked at Mail rules, AppleScript and Shortcuts. Nothing seems quite right. Bonus points if I can bind the selection to a keyboard shortcut.


text:
Q: How to call stored procedure in pentaho reporting designer? I am new to learn pentaho reporting tool,
Can anyone tell me how to call stored procedure in pentaho report designer.
In Report designer we have not seen the directly stored procedure .
How will i find out and call stored procedure in report designer ?

A: If your database is MS SQL server, convert your Store Procedure to Function with table as its  result.

A: if your db is postgres then you can simply write following query:
Select * from  As ( ,....);
Here  is the columns that you need in report.

A: CALL SCHEMA.STORED_PROCEDURE (Parameters you wish to pass in)
CALL SCHEMA.STORED_PROCEDURE (Param1, Param2, Param3)

*

*This is with a db2 database but syntax similar for others.


text:
Q: mongodb won't start from nodejs The problem: web page works only if i manually start the mongodb. Otherwise i get error "Error failed to connect 127.0.0.1:27017". However, I believe i do create server, maybe i am missing some step.
Also, feel free to point out better ways of doing things, or if something is outdated...
The code:
var express = require('express'),
    app = express(),
    cons = require('consolidate'),
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

var mongoclient = new MongoClient(new Server("127.0.0.1", 27017));
var db = mongoclient.db('course');

app.get('/', function(req, res){

    // Find one document in our collection
    db.collection('hello_combined').findOne({}, function(err, doc) {

        if(err) throw err;

        res.render('hello', doc);
    });
});

app.get('*', function(req, res){
    res.send('Page Not Found', 404);
});

mongoclient.open(function(err, mongoclient) {

    if(err) throw err;

    app.listen(8080);
    console.log('Express server started on port 8080');
});

A: If you really need to start it "from nodejs", you can start mongodb when you start your node.js server using the child_process module.
Add the code below in your app code :
var child_process = require('child_process')
child_process.exec('start mongod', function (err, stdout, stderr) {
        if (err) {
            console.log(err);
            return;
        }
    });


text:
Q: Scanf does not store the expected value I am setting up a chess board in c. The idea is the user to type the source square and destiny square (Ex: b2 b4), the first(source) scanf works perfectly, the second (destination) does not.
int main(void)
{
    int line_source, line_dest;
    char col_source, col_dest;

    while (1)
    {
        print_screen();
        printf("Type a source column and line: ");
        scanf("%c%d", &col_source, &line_source);
        printf("Type a destination column and line: ");
        scanf("%c%d", &col_dest, &line_dest);
        printf("%c%d\n", col_dest, line_dest);
        printf("%c%d\n",col_source, line_source);
        //move_piece(line_source, col_source, line_dest, col_dest);
    }

    return (0);
}

With the example of "b2 b4" line_dest is returning "32766" and col_dest is just a line break.
Someone can help me?
Ps. Sorry for my English, I'm a newbie!


text:
Q: Exceptions throwing exceptions When playing around with exceptions in C++, I noticed a curious behaviour that I was hoping someone here could explain. Look at the code below:
class Foo
{
public:

    Foo()
    {
        throw 0;
    }
};

class RandomException
{
public:

    Foo f;
};

void bar()
{
    throw RandomException();
}

// Case #1
int main()
{
    bar();
    return 0;
}

In the case above, I have an unhandled exception. Now if I change the body of the main function to:
// Case #2
int main()
{
    try
    {
        bar();
    }
    catch (int)
    {
    }

    return 0;
}

I'm swallowing the exception. There are no unhandled exceptions, and the code runs fine. And if I change the code to:
// Case #3
int main()
{
    try
    {
        bar();
    }
    catch (RandomException&)
    {
    }

    return 0;
}

Now I have an unhandled exception again.
I want to know why in case Case #2 I have no unhandled exceptions, and in Case #3 I do, even though in both cases I'm throwing 2 exceptions, one int and one of type RandomException.
How does C++ handle things when an exception is thrown while throwing an exception?

A: Here, the construction of the RandomException object fails with an exception, so throw RandomException() is never completed and an int (0) is thrown (in the process of constructing RandomException).
If you have a handler for that (as in case #2), control will be transferred to that handler. If not (as in case #3), std::terminate() will be invoked.


text:
Q: What is the difference between category, group, and item type in HCL OneTest Data? While creating schema in HCL OneTest Data, I came across the terms as Category, Group, and Item Type. Can anyone help me with understanding these terms in HCL OneTest Data?

A: Category: A category type is used for inheritance and for organizing other types in a schema. For example, you might have a category named "OrderField" to organize the different kinds of order fields in your schema.
Group: A group type represents a complex data object that consists of other objects. For example, "FullName" is a group type that contains the components: FirstName, MiddleInitial, and LastName.
Item: An item type represents a simple data object that does not consist of other objects. It is a default class of schema.