text:
Q: how to use model in different controller in RoR I have a profile controller. But I want to use the User model to save some fields in the users table. So how can I load the User model in the profile controller?

A: You can load any model in any controller - just call it as you would normally.
If you need to load a User from your Profiles controller, you can just use User.find_by_whatever(), User.new, current_profile.user - not sure how your associations are set up, but there shouldn't be any access restrictions.

A: model are independent entity and you can call it from any controller.
There can be a model without a controller and vice-versa.

For you question take a example below
class ProfileController < ApplicationController

  def some_method
    @user = User.find(params[:user_id])
    if @user.update_attributes(params[:user])
       // some action
    else

       // some action
    end
  end

end


text:
Q: Mean value inequality in calculus of several variables We know that if $\Omega$ is an open subset of $\mathbb R^n$, $f:\Omega\to \mathbb R$ is a differentiable function, $\mathbf a,\mathbf b\in \Omega$ such that $S=\{(1-t)\mathbf a+t\mathbf b:t\in [0,1]\}\subset \Omega$, then there exists $\mathbf c\in S$ such that $f(\mathbf b)-f(\mathbf a)=f^{\prime}(\mathbf c)(\mathbf b-\mathbf a)$. But this not in general true if $f$ is a function from $\Omega$ to $\mathbb R^m$.
I want to prove that if $\Omega$ is an open subset of $\mathbb R^n$, $f:\Omega\to \mathbb R^m$ is a differentiable function, $\mathbf a,\mathbf b\in \Omega$ such that $S=\{(1-t)\mathbf a+t\mathbf b:t\in [0,1]\}\subset \Omega$, then there exists $\mathbf c\in S$ such that $\|f(\mathbf b)-f(\mathbf a)\|\leq\|f^{\prime}(\mathbf c)(\mathbf b-\mathbf a)\|$. Any help is appreciated.

A: I have got an answer to this question.
We know that for any $u\in \mathbb R^m$, we have $\mathbf u.(f(\mathbf b)-f(\mathbf a))=\mathbf u.(f^{\prime}(\mathbf c)(\mathbf {b-a}))$. Putting $\mathbf u=\frac{f(\mathbf b)-f(\mathbf a)}{\|f(\mathbf b)-f(\mathbf a)\|}$ we get $\|f(\mathbf b)-f(\mathbf a)\|\leq \|f^{\prime}(\mathbf c)(\mathbf {b-a})\|$ by Cauchy-Scwarz inequality.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Index is incorrectly listed in the table of contents I have a large document with an index compiled through makeindex, and is included in my source .tex as follows:
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Index}
\printindex

However, the \addcontentsline does not correctly add the Index to either the Table of Contents, or the list of bookmarks in the resulting PDF.

Bibliography  . . . . . . . . . . . . . . . . . . . . . . . . . 330

One solution is to write a new command, \immediateaddcontentsline, and this adds the Index to both the TOC and the list of Bookmarks. The Bookmark link works correctly. But in the TOC, the page number is now listed with roman numerals as "xvi" rather than "349".

Bibliography  . . . . . . . . . . . . . . . . . . . . . . . . . 330
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi

"xvi" is the current page, so it looks like something is mighty confused. It is probably related to the immediate-ness of the new TOC command.
Is it even possible to have an Index listed the Table of Contents? Or must I use a different index maker?

A: assuming that \printindex triggers \chapter* and chapters always start on right-hand pages, try inserting \cleardoublepage and then the \addcontentsline.  if a chapter can start on either a right-hand or a left-hand page, \clearpage should suffice.

A: As alternative there is also the tocbibind package to include the table of contents, bibliography and index in the table of contents. If you only want to include the index, use
\usepackage[nottoc,notbib]{tocbibind}

and place a \phantomsection before the index, so that the hyperlink does not aim at some content before the index.

A: Instead of tinkering with \addcontentsline, simply load my idxlayout package with the totoc option. (idxlayout is compatible with the standard classes, the KOMA-Script classes, and memoir.)
\documentclass{report}

\usepackage{makeidx}
\makeindex

\usepackage[totoc]{idxlayout}

\usepackage{hyperref}

\begin{document}

\tableofcontents

\chapter{foo}

Some text.\index{Text}

\printindex

\end{document}

A: Reversing the order of the lines might do the trick, e.g.,
\printindex
\addcontentsline{toc}{chapter}{Index}

At least, it did when I had the analogous problem with a bibtex bibliography,
\bibliography{references}
\addcontentsline{toc}{section}{References}


text:
Q: x position of bullet in pygame code:
import pygame
import sys
from pygame.locals import *

count = 0
moving = False

def blast1():
    blast.y -= bl

def player_animation():
    global player_speed
    player.x = player_speed

pygame.init()
running = True

clock = pygame.time.Clock()

bl = 1
player_speed = 1

player = pygame.Rect(250, 450, 50, 50)
blast = pygame.Rect(player.x, player.y , 10, 10)

screen = pygame.display.set_mode((500, 500))
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    player_animation()
    blast1()

    screen.fill((255, 255, 255)) #color
    pygame.draw.ellipse(screen, [0, 0, 255], player)
    pygame.draw.ellipse(screen, [0, 255, 0], blast)

    keys=pygame.key.get_pressed()
    if keys[K_LEFT] and player.x !=  -4 :
        player_speed -= 5

    if keys[K_RIGHT] and player.x !=  451:
        player_speed += 5
    pygame.display.flip()

    clock.tick(30)
blast.x = player.x
pygame.quit()

My objective is pretty simple. I want to create a ball that you can move to the right and left. Then I want to create a bullet that is fired from the position of the "player". I'm having some trouble with this, I don't know why but when I declare the position of the bullet  blast = pygame.Rect(player.x, player.y , 10, 10) only the y position works. The x position is somehow in the middle of the screen instead of on the player. How can I fix this?

A: The line
blast = pygame.Rect(player.x, player.y , 10, 10)

assigns a Rect to blast, with the position of the player at this moment. This blast will stay still until you edit its position. You only change the y position here:
blast.y -= bl

But you don't update the x position when you launch the bullet. You could do this like that:
def launch_blast(): # call this function when you create the bullet.
                    # At this point in the program, just call it at the beginning.
    blast.x = player.x + player.width / 2 - blast.width / 2

def blast1():
    blast.y -= bl

To launch several bullets, you can use this code:
import pygame
from pygame.locals import *
pygame.init()

class Bullet:
    def __init__(self):
        self.rect = Rect(player.rect.x - 5 + player.rect.width / 2, player.rect.y , 10, 10)

    def move(self):
        self.rect.y -= 10 # move up
        pygame.draw.ellipse(screen, [0, 255, 0], self.rect) # draw on screen

class Player:
    def __init__(self):
        self.rect = pygame.Rect(250, 450, 50, 50)

    def move(self):
        # move
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]:
            self.rect.x -= 5
        if keys[K_RIGHT]:
            self.rect.x += 5

        # don't go out of the screen
        self.rect.x = min(max(self.rect.x, 0), 500 - self.rect.width)

        # draw on screen
        pygame.draw.ellipse(screen, [0, 0, 255], self.rect)

player = Player()
bullets = []

clock = pygame.time.Clock()
screen = pygame.display.set_mode((500, 500))
running = True

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == KEYDOWN and event.key == K_SPACE:
            bullets.append(Bullet()) # generate a new bullet when space pressed

    screen.fill((255, 255, 255)) # white

    for bullet in bullets: # draw each bullet generated
        bullet.move()
        if bullet.rect.x < bullet.rect.height: # if out of the screen,
            bullets.remove(bullet) # then remove it
    player.move() # draw the player

    pygame.display.flip()
    clock.tick(30)


text:
Q: Adobe Javascript - Validate items on dropdown I have a fillable PDF with a drop-down list of 200 items (strings all in CAPS, i.e. DG114). I would like to have the user (in a tablet) type the item and the item must match one in the drop-down list. I am trying the following:
var ans = event.value.toUpperCase();
var res =  this.getField("combo1").value;
if(ans == res) {
event.value = ans;
}
else {
event.value = "NOT FOUND";
}

When typed in a tablet, by default, the first letter is CAPS followed by small letters. I am trying go convert to upper case first and make the typed text match either in lower case or upper case. It doesn't seem to work if the user types dg114, but it works if they type DG114.
What am I doing incorrect?


text:
Q: How can I parse nested source files with ANTLR4? I've asked this question before (slightly differently) but didn't understand the answers enough at the time to give intelligent feedback (sigh).
I need to be able to include files inside other files at arbitrary points so I need to be able to have a stack of files with a single parse tree.
If I was writing this myself (and I have done this in the past), my parser would recognize the "Include xyz" or "Import abc", and would cause the lexer to suspend reading from the current file, push that file on a stack, and continue reading characters from the new file until exhausted.
However, when using ANTLR4 (where so far I've avoided inserting any code into the grammar file itself) and using the visitor pattern, all I see is the created tree which of course is too late.
I've found references to PUSHSTREAM as something that can be done in the lexer but I cannot find an actual example and would really appreciate some help (either a pointer to an actual example that I perhaps missed when searching or a short code sample if someone has one).
Note that I'm writing code in C++, not Java.
Thanks in advance

A: Years ago I developed a solution for ANTLR 2.7, to parse Windows resource files (*.rc). Such files are structured very much like C/C++ header files and support preprocessor directives like #if/#end/#pragma/#include.
For that I created a special character input stream (with a nested char input stream) which implements a stack based approach for include files. Whenever a new include directive is found in the char input a new stack entry is created with the current actual input stream, its position and line/column information (to provide local source locations, in case a parsing problem was found). That entry is pushed onto a stack and a new input stream is created. Once this is exhausted the TOS is popped off the stack and serving chars continued from the last position (after the #include statement). The lexer only sees a continuous stream of characters.


text:
Q: Asymptotic expression for the $n$th prime number Quoting from the Wikipedia article:

As a consequence of the prime number theorem, one gets an asymptotic expression for the $ n $th prime number, denoted by $ p_n $:
$$ p_n \sim n \log n.$$

Can you explain how we get this approximate expression? I understand the number of prime numbers less than or equal to an integer $ N $, denoted as $ \pi(N) $ is approximately:
$$
\pi(N) \sim \frac{N}{\log N}.
$$
If the $ n $th prime number is approximately $ n \log n $, it implies that there are approximately $ n $ prime numbers less than or equal to $ n \log n $, i.e.,
$$
\pi(n \log n) \sim n.
$$
But substituting $ N $ with $ n \log n $ in the formula of $\pi(N)$ we get
$$
\pi(N) \sim \frac{N}{\log N} = \frac{n \log n}{\log (n \log n)} \not\sim n.
$$
What am I doing wrong? How can I show that the statement quoted from Wikipedia is correct?

A: $$\log(n\log n)=\log n+\log\log n=(1+o(1))\log n$$
therefore
$$\frac{n\log n}{\log(n\log n)}=\frac{n\log n}{(1+o(1))\log n}
=\frac{n}{(1+o(1))}\sim n.$$

A: It seems you are very new to prime number theory hence I am not sure if you understand the little $o$ notations. Hence I present @Lord Shark's answer in layman's terms.
$$
\log (n\log n) = \log n + \log\log n
$$
But $\log\log n$ is exponentially smaller compared to $\log n$ i.e. it can be ignore compared to $\log n$. Hence as an approximation, we have
$$
\log (n\log n) \sim \log n
$$
With this approximation
$$
\pi (n\log n) \sim \frac{n\log n}{\log (n\log n)} \sim \frac{n\log n}{\log n} \sim n
$$
The smallest values of $x$ for which $\pi(x) = n$ is $x = p_n$ hence we have
$$
\pi (p_n) = n \sim \pi(n\log n)
$$
or $p_n \sim n\log n$.


text:
Q: Prove that for every set of functions $f_i$ from N to N there is $g>^*f_i$ Prove that for every set $\lbrace f_i : i \in \Bbb N\rbrace \subseteq {\Bbb N}^{\Bbb N}$. there is $g\in{\Bbb N}^{\Bbb N}$ such that $f_i<^*g$
Definition of $<^*$ :
$f<^*g\iff \exists _n \forall_{m>n} \ f(m)<g(m)$
Can someone Help with guidance ?

A: You can use Cantor's diagonalization method. To define $f(n)$, instead of just ensuring that it is different from $f_n(n)$, try to think of a way that instead gives you a value which is larger than $f_i(n)$, for $i\leq n$.


text:
Q: SQL COALESCE return more that 1 value or alternate solution Post has been revised!!!....
I need help on the WHERE condition as the following:
ID# 1 belongs to Engineering Department.
ID# 2 belongs to Sales Department
ID# 3 belongs to Other Department.
ID# 4 belongs to Eng-Level2 department
ID# 5 belongs to Eng-Level3 department
ID# 6 belongs to Eng-Level4 department
What I try to accomplish is, if ID# 1 log run this report, it will show the activities belong to him (ID# 1), AND Eng-Levelx (ID#4, ID#5, and ID#6).  However, if ID belongs to another Departments (ID# 2 & 3), will ONLY show the activities below to his/her.
Here is my non working query:
SELECT * FROM dbo.CRM_Activity
WHERE
(ActivityOwnerID = 1579
AND [Status] = 'Open'
AND Status <> 'Deleted')
OR
    ActivityOwnerID IN (
        SELECT COALESCE(
            (SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering')
            ,  (SELECT Tech_ID FROM dbo.employee WHERE LEFT(first_name, 4) = 'Eng-')  --- THIS ONE FAILED BECAUSE IT RETURNS MULTIPLE RECORDS
        )
    )
    AND [Status] = 'Open'

ORDER BY CreatedDate DESC

A: You could just use UNION instead, so this will get a list of unique Tech_ID's from both queries.
SELECT * FROM dbo.CRM_Activity
WHERE
    ActivityOwnerID IN (

            SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering'
            UNION
            SELECT Tech_ID FROM dbo.employee WHERE LEFT(first_name, 4) = 'Eng-'
        )

A: In your case SELECT COALESCE(.... can return more than one value because IN allows multiple values, but result of SELECT Tech_ID FROM dbo.employee WHERE tech_ID = 1579 and POSITION = 'Engineering' or so must be one because COALESCE expects expression (not result set).


text:
Q: Why is cron job failing to send email when php mail()'s fifth parameter is included? I have a cron cron job setup to send emails. It is executed using the following command:
/usr/bin/php -q /var/www/vhosts/domain.com/cron/job.php

When I execute the php script from a browser, the script sends emails as expected. It fails when run by the cron job.
I don't see any errors in the maillog. Only difference is in the "from" line. When the script is executed from a browser, the log reads:
Jan 25 12:24:39 VMW01 qmail-remote-handlers[1001]: from=sender@domain.com

But when the cron job executes the script the "from" line becomes:
Jan 25 12:15:01 VMW01 qmail-queue-handlers[1000]: from=anonymous@VMW01.server.net

Oddly, the cron job will send emails when I remove the fifth parameter of the mail() line.
mail($email, $subject, $body, $headers, '-fsender@domain.com');

I would simply live with this, but if I remove the parameter, emails are often rejected by  servers - which I presume is because the parameter is not set.
Any idea why this is happening and how I can fix it? I'd be happy to add more detail to this question in order to get to a solution.

A: As @Michael said, most likely your cron job is using a different php.ini file. You can use the php_ini_loaded_file() function to see what file is loaded in your script - then run it from the command line, or your cron to see the difference with the web execution.
My guess is that the problem arises because the php.ini for the cron job (same as command line) has safe_mode set, and when that is the case, you shouldn't use the last parameter to the mail() function as it can fail. As evidence, if you look at the PHPMailer class there is a mail_passthru() method that simply calls the PHP mail() function under the covers. Notice that it leaves out the extra parameter when not in safe_mode:
private function mail_passthru($to, $subject, $body, $header, $params) {
    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
    } else {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
    }
    return $rt;
}

You can load a specific php.ini file when calling php from the command line (or your cron job) like this:
/usr/bin/php -q /var/www/vhosts/domain.com/cron/job.php -c /path/to/php.ini

A: I had the same problem, I found changing my cron command to wget -O/dev/null http://myurl.com/ executed it just like in the browser would and email was sent.


text:
Q: Random popup out of nowhere: "Verifying file.." As the title says, a popup appeared while I was on the internet, I was not on any sketchy website btw. I was not downloading anything either.
All I saw was "Verifying file", I don't think it mentioned a specific file, I just closed the popup as fast as I could.
Is this an issue? I just wanted to make sure my device isn't infected.


text:
Q: How to add stylish break lines for text like '___ 'and '-' with CSS and HTML? I'm attaching a few example images to show what I mean.
For now what I was doing is adding extra div inside HTML and styling it in CSS with border-bottom, width and color codes, after that centering it within text with margin and padding. Is here are more effective way of doing it?
How you approach designs like this?

A: You can use pseudo selectors like this:

h1 {
  display: inline-block;
  position: relative;
}

h1:after {
  position: absolute;
  content: "";
  display: block;
  width: 10rem;
  height: 2px;
  background: blue;
  left: 10%;
  bottom : -10%;
}

something here

h1:before{
content:"- ";
color: red;
}

something else

or if you have a list, you can take advantage of list-style-type: '-':

ul {
  list-style-type: '- ';
}

first

second

third


text:
Q: Template not loading for ion-nav-view I've double-checked and triple-checked typos, but my ionic app still fails to load the template for the tabs I have.
app.js
angular.module('testing', ['ionic', 'ngIOS9UIWebViewPatch', 'ngMaterial', 'ngMessages', 'ngCordova'])
    .run(function($ionicPlatform, $cordovaSQLite, $rootScope, $ionicHistory, $state, $mdDialog, $mdBottomSheet) {
        /**
         * Ionic on-ready function
         */
        $ionicPlatform.ready(function() {
            ionic.Platform.isFullScreen = true;
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                cordova.plugins.Keyboard.disableScroll(true);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });
    })
    .config(function($ionicConfigProvider, $stateProvider, $urlRouterProvider, $mdThemingProvider, $mdIconProvider, $mdColorPalette, $mdIconProvider) {
        /*
         * States
         */
        $stateProvider
            .state('app', {
                url: "/app",
                abstract: true,
                templateUrl: "elements/menu/menu.html"
            })
            .state('app.feed', {
                url: "/feed",
                views: {
                    'tab-feed': {
                        templateURL: "elements/feed/feed.html",
                        controller: 'feedCtrl'
                    }
                }
            })
            .state('app.patients', {
                url: "/patients",
                views: {
                    'tab-patients': {
                        templateURL: "elements/patient/patient.html",
                        controller: 'patientCtrl'
                    }
                }
            })
            .state('app.settings', {
                url: "/settings",
                views: {
                    'tab-settings': {
                        templateURL: "elements/settings/settings.html",
                        controller: 'settingsCtrl'
                    }
                }
            });

        /**
         * Takes care of otherwise URL redirect to the start page
         */
        $urlRouterProvider.otherwise('/app/patients');
    });

The menu html:
<ion-tabs class="tabs-striped tabs-icon-top">

   <ion-tab title="Feed" icon-on="ion-ios-paper" icon-off="ion-ios-paper-outline" href="#/app/feed">
      <ion-nav-view name="tab-feed"></ion-nav-view>
    </ion-tab>

    <ion-tab title="Patients" icon-on="ion-ios-people" icon-off="ion-ios-people-outline" href="#/app/patients">
      <ion-nav-view name="tab-patients"></ion-nav-view>
    </ion-tab>

    <ion-tab title="Settings" icon-on="ion-ios-gear" icon-off="ion-ios-gear-outline" href="#/app/settings">
      <ion-nav-view name="tab-settings"></ion-nav-view>
    </ion-tab>

</ion-tabs>

And finally the partial template html:
<ion-view>
  Patient List
  <ion-content class="padding">

something or the other

  </ion-content>
</ion-view>

Nothing in the above html shows.   I inspected the section, and everything is there until the ion-nav-view, further nested sections are not in the generated code at all.
Anything I missed?  My controller for all of these tabs just placeholders.  No errors in the console.

A: Did you link your controllers file?
You have to declare your file on app.js, like that:
angular.module('testing', [
  'ionic',
  'ngIOS9UIWebViewPatch',
  'ngMaterial',
  'ngMessages',
  'ngCordova',
  'testing.controllers'
])

If you miss that, you'll get all html as you described.


text:
Q: How to learn multi-class multi-output CNN with TensorFlow I want to train a convolutional neural network with TensorFlow to do multi-output multi-class classification.
For example: If we take the MNIST sample set and always combine two random images two a single one and then want to classify the resulting image. The result of the classification should be the two digits shown in the image.
So the output of the network could have the shape [-1, 2, 10] where the first dimension is the batch, the second represents the output (is it the first or the second digit) and the third is the "usual" classification of the shown digit.
I tried googling for this for a while now, but wasn't able find something useful. Also, I don't know if multi-output multi-class classification is the correct naming for this task. If not, what is the correct naming? Do you have any links/tutorials/documentations/papers explaining what I'd need to do to build the loss function/training operations?
What I tried was to split up the output of the network into the single outputs with tf.split and then use softmax_cross_entropy_with_logits on every single output. The result I averaged over all outputs but it doesn't seem to work. Is this even a reasonable way?

A: For nomenclature of classification problems, you can have a look at this link:
http://scikit-learn.org/stable/modules/multiclass.html
So your problem is called "Multilabel Classification". In normal TensorFlow multiclass classification (classic MNIST) you will have 10 output units and you will use softmax at the end for computing losses i.e. "tf.nn.softmax_cross_entropy_with_logits".
Ex: If your image has "2", then groundtruth will be [0,0,1,0,0,0,0,0,0,0]
But here, your network output will have 20 units and you will use sigmoid  i.e. "tf.nn.sigmoid_cross_entropy_with_logits"
Ex: If your image has "2" & "4", then groundtruth will be [0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], i.e. first ten bits to represent first digit class and second to represent second digit class.

A: First you have to provide two labels to an image comprised of two different images. Then change your objective loss function so it maximizes the outputs of the two given labels and train your model. I don't think you need to split the outputs.


text:
Q: Error in simple Network What is wrong with this tensorflow code? I seem to be tardy to see the mistake. It doesn't converge. It stopps by 2.30.
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x = tf.placeholder(tf.float32, [None, 784])
W1 = tf.Variable(tf.zeros([784, 100]))
b1 = tf.Variable(tf.zeros([100]))

W2 = tf.Variable(tf.zeros([100, 20]))
b2 = tf.Variable(tf.zeros([20]))

W3 = tf.Variable(tf.zeros([20, 10]))
b3 = tf.Variable(tf.zeros([10]))

y1 = tf.nn.relu(tf.add(tf.matmul(x, W1), b1))
y2 = tf.nn.relu(tf.add(tf.matmul(y1, W2), b2))
y3 = tf.nn.softmax(tf.add(tf.matmul(y2, W3), b3))
sess = tf.InteractiveSession()

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y3), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run()
init = tf.global_variables_initializer()
sess.run(init)

for _ in range(10000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys}))
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

Thank you!

A: I can see a couple of things that should be addressed:

*

*The learning rate of 0.5 is quite large for stochastic gradient descent. If a network isn't training, you can always try with different values, typically in the range [1e-2, 1e-5].

*Networks initialized with zeros (tf.zeros) fail to learn for two reasons:

*

*Without any difference between parameter values, gradient is shared evenly across them all, meaning that they all learn to be the same value.

*As the gradients are multiplied by weights during back-propagation, the resultant value will always equal zero - meaning no change in weight values.

I would also recommend using the built-in tf.losses.softmax_cross_entropy instead of doing it yourself. It's generally a good idea, as it minimizes the chance of making a mistake along the way. :)


text:
Q: I don't manage to install Robotframework Ride on my Debian When I type in my terminal :
sudo pip3 install robotframework-ride

I get this error :
Collecting robotframework-ride
  Using cached https://files.pythonhosted.org/packages/4e/a6/1835a17fa566b19c166735a9a75d55101e53b68566771ddb0b690dd4be83/robotframework_ride-1.7.3.1-py2.py3-none-any.whl
Collecting robotframeworklexer (from robotframework-ride)
  Downloading https://files.pythonhosted.org/packages/24/18/ad01d42227d824b890f1b4d32237e5003bf7afe8764cb13545fb63d7fcb5/robotframeworklexer-1.1-py3-none-any.whl
Collecting Pypubsub==3.3.0 (from robotframework-ride)
  Using cached https://files.pythonhosted.org/packages/95/5a/1801be1a63af9250e79b8941a37b88e3ca0d660b880b9862fe9016ae6a3a/PyPubSub-3.3.0.zip
Collecting Pygments (from robotframework-ride)
  Using cached https://files.pythonhosted.org/packages/be/39/32da3184734730c0e4d3fa3b2b5872104668ad6dc1b5a73d8e477e5fe967/Pygments-2.5.2-py2.py3-none-any.whl
Collecting robotframework (from robotframework-ride)
  Using cached https://files.pythonhosted.org/packages/22/0f/1b9ffa0c4e59789b50e6034866e823b7d4a5c7eaedad7bfd0bba42f2aa9d/robotframework-3.1.2-py2.py3-none-any.whl
Collecting Pywin32 (from robotframework-ride)
  Could not find a version that satisfies the requirement Pywin32 (from robotframework-ride) (from versions: )
No matching distribution found for Pywin32 (from robotframework-ride)

Anybody knows how to fix this ? I don't understand why it tells me that it can't find Pywin32 while I'm on Debian.

A: According to this RIDE-doc, one needs to do the following if they are not on windows.
Excerpt from release notes

NOTE: The installation process mentioned in
  the RIDE-RELEASE-NOTES is only working smoothly on Windows.

For other operating systems is better to do a two step install, with:
pip install -U -r https://raw.githubusercontent.com/robotframework/RIDE/master/requirements.txt
pip install -U robotframework-ride

NOTE: This problem is fixed in Release v1.7.4b2, read this for the recommendations to install.


text:
Q: I am unable to visualize anything on tensorboard. How to fix this? I am currently using Tensorflow on Linux, and when I launch tensorboard and go to the localhost using Firefox, I am only able to see what's enclosed in the image. I am unable to interact with anything, and the whole thing is unresponsive. How do you think I might be able to fix this?
Tensorboard Window


text:
Q: "Good day" in modern AmE The phrase "Good day" used in old-fashioned English, as a greeting or when one was going to say goodbye during the day.
Perhaps it is still in common use in Australian English though.
I am wondering what is used in greeting / saying goodbye today in American English, especially, when you have no idea about the time frame you are in. i.e. let's say you are unaware which phrase suits the time situation better between "good afternoon" or "good evening".

A: I haven't heard "good morning" or "good afternoon" used to say goodbye in American English, just to say hello. And I haven't heard "good day" used for either. To say goodbye, I'm used to hearing or saying things like:

*

*Have a nice day

*Take care

*(See/take to) you later/tomorrow/etc.

For greeting when you don't know the time,

*

*Hello/Hi

*How are you doing? / How's it going?


text:
Q: What's a gay transsexual woman? I know how it sounds but it's a serious question. I saw an article title about it on the Guardian today. If someone tells you that a person is a "gay transsexual woman", is it possible, logically, to know who exactly this person is?

*

*Is it a man who became a woman, then turned gay and started liking other women?

*Or is it a woman who likes other women (thus is gay), and then turned into a man?

*Or conversely?

This confuses me and I wonder if the English language can tell us, logically, what the answer is? Or is it completely meaningless?

A: Generally, a transsexual woman is someone who comports herself as a woman, and was considered by others to be male earlier in life.  (That is, less ambiguously, a male-to-female transsexual.)  The idea is that, to the person, she is a woman, and the transsexual part is merely a descriptor.
How you then apply "gay" to that I'm not totally sure.  I suppose if you were to consider "transsexual" to be merely a descriptor, then it could be dropped (at the expense of being less precise), and then you'd get "gay woman", which is unambiguously a woman with sexual interest in other women.

A: A bit of updating is needed here, because terminology is changing over time. At this point, transsexual is starting to lose currency in favor of transgender. I think the shift does improve clarity somewhat.
A transgender woman (now commonly called a transwoman) is a genetic male who identifies herself as and knows herself to be female. And by the way, this holds true whether she has begun any degree of physical change towards any version of typical socially recognizable female appearance or not. If she has made the physical change, it is easier for those around her to understand, of course, but it is no more or less valid either way.
If she is gay, it means she is sexually attracted to females (of any kind).
So a gay transwoman (what you were originally calling a gay transsexual woman in this question), is what you might say is a lesbian who began life as a genetic male.
A final note: In One Person, John Irving's latest novel, is an insightful and sympathetic exploration of almost every person's life that could possibly have been touched by this and any other LGBTQ issue in the last half a century. In one way or another, that amounts to just about all of us. I urge everyone to read it.

A: A transsexual woman is:

a male-to-female (MTF) transsexual or transgender person and the term trans woman is preferred by some individuals over various medical terms.

Because a transsexual woman would view herself as of the female gender (though of the male sex), the term "gay" applies as it would to any other woman. That is, a gay transsexual woman is a gay woman, who happened to be born as a man.
As for your original questions --

Is it a man who became a woman, then turned gay and started liking other women?
  Or is it a woman who likes other women (thus is gay), and then turned into a man?

You cannot, simply by the English language, tell which came first. Sexuality and gender identity are fluid and personal, and standard phrases (such as "gay transsexual woman") will not be able to tell you whether the individual first realized that they were gay, or first realized that they gender-identified as a woman. Only the individual, if they feel comfortable telling you this, will be able to explain.
What if you changed the word order, and got a "transsexual gay woman"? Then breaking it down, you have a gay woman. This woman is also a transsexual. But you don't know which part came first still--were they a transsexual woman who later realized she was gay? Maybe. Perhaps they just feel more comfortable identifying as a gay woman, who is transsexual. This is their identity, but the term does not capture which came first.

A: In my comment, I said that people don't turn gay, and upon further reflection, I can see that in this case, you could make that argument.
Gender and sexuality are separate from each other.  Gender is whether we identify ourselves as male or female.  Sexuality is whether we are sexually attracted to women or men.
A gay trans-sexual woman is a genetic male who identifies as female but is sexually attracted to women.  Before she identified as female, she (as a man) would have still been attracted to women, and therefore would have been heterosexual. Changing her gender identity "turned her gay" but it didn't actually change anything except how she identifies herself.
Had she been a gay man who changed her gender identity, she would now be considered a heterosexual trans-sexual woman.  In other words, she would be a genetic male who identifies as female and is attracted to men.
So yes, the term is unambiguous.


text:
Q: ruby > sort images inside directory with multiple conditions I need to sort the images present inside some directory with the following order:
00a.jpg
00b.jpg
00c.jpg
...
00x.jpg
00y.jpg
00z.jpg
0aa.jpg
0bb.jpg
0cc.jpg
...
0xx.jpg
0yy.jpg
0zz.jpg
001.jpg
002.jpg
003.jpg
...
097.jpg
098.jpg
099.jpg
100.jpg
101.jpg
102.jpg

But I am not getting any logic to put inside my sort_by? Can anyone has any idea what logic would be best suited for sorting all images in the above mentioned order..
I am expecting something like this :
Dir.entries('.').sort_by { |x| ?? }

Thanks,
Dean

A: Your requested sort order is not apparent, so I'm going to assume that you want all the images which contain a letter to be before those with numbers only.
For this logic, you can return an array from sort_by, which be evaluated in order - firs item first, second one if the first is tied, etc.
In this example this would be something like:
jpgs.sort_by { |j| [j[/.*[a-z].*\.jpg/] ? 0 : 1, j] }

The first item in the array returned answers the question of whether the image name contains a letter before the extension, and if it does returns a smaller number than if it doesn't. This assures us that images with letters in their names will be before images with only numbers in their names.
Will result in this order:
[
    "00a.jpg",
    "00b.jpg",
    "00c.jpg",
    "00x.jpg",
    "00y.jpg",
    "00z.jpg",
    "0aa.jpg",
    "0bb.jpg",
    "0cc.jpg",
    "0xx.jpg",
    "0yy.jpg",
    "0zz.jpg",
    ...,
    "001.jpg",
    "002.jpg",
    "003.jpg",
    "097.jpg",
    "098.jpg",
    "099.jpg",
    "100.jpg",
    "101.jpg",
    "102.jpg"
]

A: I would use:
Dir.entries('.').sort { |a,b| a.split('.').first <=> b.split('.').first }
I think it may be faster than regexp option. Also, its simplier and easier to customize (due using 2 iterators and comparator).


text:
Q: Avoiding coupling in a document-based Cocoa app? I'm new to Mac programming and I'm working on a document-based application.
My NSDocument subclass creates a NSWindowController subclass. This window controller creates two NSViewController subclasses as well.
Sometimes, a change in one of the views of a NSViewController needs to notify the NSDocument and/or the main model class. Also, a change in the model needs to be notified to every/some view(s).
My question is: what is the best approach so that there is no (or minimum) coupling? I know there are several choices, but I'm not sure which one suits best for my application as I'm newbie not to programming but to Cocoa and especially NSDocument:

*

*KVO. Looks nice and easy to implement, but I don't like the idea of not explicitly notifying the observer(s) about a change (AFAIK, self.someProperty = newValue does automagically notify observers), and don't like the fact that you have to register to property names which could change in time.

*Notifications. I know what they are and I've used them for iOS. But I've read somewhere that they are not guaranteed to be sent immediately to observers. Is it true? If not, do you see them as a good approach for a document-based app?

*Delegates. Yes, under normal conditions (or what I've usually seen), a class has one delegate. But creating an array of delegates works as well (just tested it). The problem I see here is that every time I need to notify the delegates I have to loop through them, make sure they respond to a method, and call that method.
Are there any other alternatives I'm missing?

A: KVO by a controller class is the most common way to do coupling between a model and its view(s). In fact, Cocoa Bindings, which are intended to mostly eliminate code in the controller layer, are based on KVO. It is true that KVO/KVC relies on property names, and that if those change, you'll have to change the bindings or KVO setup connecting your view. However, it's not usually feasible to make your views completely unaware of the underlying model specifics, so I don't see this as a problem.
My recommendation would be to use Cocoa Binding where you can, as they eliminate a lot of glue code. In places where they can't be used, your controllers (the middle layer in MVC) should use KVO to observe model changes and update the appropriate views. Changes in the views can be passed back to the model via property accessors and/or KVC by the controllers.

A:
Yes, under normal conditions (or what I've usually seen), a class has
  one delegate. But creating an array of delegates works as well (just
  tested it).

Delegates are often used to modify the behavior of the delegating object. An application delegate is a good example: NSApplication by itself isn't very interesting; it relies on its delegate to define the interesting behavior of the application. Having multiple delegates all trying to modify the behavior of a single object could be a problem if the various delegates conflict with each other. What do you do if the delegates disagree?
There are some cases in Cocoa where a class uses more than one delegate, but each one has a separate role. For example, NSTableView has both a delegate and a data source, but both are really delegates of a sort.

The problem I see here is that every time I need to notify the
  delegates I have to loop through them, make sure they respond to a
  method, and call that method.

That's not hard to solve. For example, you could create an NSInvocation to encapsulate the call, and then send the invocation to each "delegate." However, if you do that you'll have nearly reinvented the notification system. If you need the one-to-many communication that you'd get with your multiple delegates proposal, you'll probably be better off using notifications or KVO.


text:
Q: Make an element unclickable while animated I am trying to make an element not clickable when it is animated. When the animation is done I want it to be clickable again. I have searched a long time for some help on how to achieve this, but I can't get it to work and I don't know why.
The HTML:

   Allright B C D

When letter A is clicked, it moves to the left and then some text fades in next to it.
The jQuery:
(function() {

var letterA = $('#a'),
    llright = $('#llright');

$('#a:not(.open)').live('click', function() {
    letterA.animate({
    marginRight: "5.7in",
    }, 1300, function() {
        letterA.addClass('open');
        llright.fadeIn(1300); // Animation complete.
    });

});

$('#a.open').live('click', function() {
    llright.fadeOut(700);
    letterA.delay(700).animate({
    marginRight: "0.0in",
    }, 700, function() {
        letterA.removeClass('open');
    });

});

})();

The animation works great, but this doesn't:
if(letterA.is(':animated')) {
    letterA.unbind('click');
};

The last part doesn't work at all, even when I insert a simple alert() instead of unbind() it doesn't seem to figure out when A is moving and not.
I could really use some help here, I have tried everything I can think of.
Thx
/Oscar

A: Your check is only running on page load. Do the check inside of the click function:
$('#a:not(.open)').live('click', function() {
    if(!letterA.is(':animated')) {
        letterA.animate({
        marginRight: "5.7in",
        }, 1300, function() {
            letterA.addClass('open');
            llright.fadeIn(1300); // Animation complete.
        });
    }
});

Also, live() is deprecated; consider moving to on().

A: It's more economical to attach just one click handler with internal branching to cater for the different circumstances; forward animation, reverse animation and to reject while animation is in progress.
You can also get away without addClass/removeClass('open') by testing the state of llright instead.
Something like this should do it:
$('#a').on('click', function() {
    var $this = $(this),
        llright = $this.next("span");
    if($this.is(":animated") || llright.is(":animated")) {
        return;//reject (no action)
    }
    if(llright.is(":visible")) { //reverse animation sequence
        llright.fadeOut(700, function(){
            $this.animate({
                marginRight: 0,
            }, 700);
        });
    }
    else {
        $this.animate({ //forward animation sequence
            marginRight: "5.7in",
        }, 1300, function() {
            llright.fadeIn(1300);
        });
    }
});

Note also that with this code it is not necessary to use .live().


text:
Q: Mysql-specific query in SubSonic I'd like to add a query to my SubSonic DAL that uses the MySQL fulltext search construct "WHERE MATCH (columnlist) AGAINST (searchterm)", but can't find an equivalent in SubSonic.
Is there a way of using Subsonic to execute a "literal" query - i.e. it just queries with the exact MySQl code I feed it?
Alternatively, could I implement a subclass of SubSonic.Where to run the fulltext search? If so, how would I go about this?
I'm using SubSonic 2.x. Any ideas welcome. Thanks.
ddoctor

A: You can use CodingHorror to run any SQL you like.


text:
Q: How to delete values of a string between a char and expression - SQL Server I would like to delete all values in a column 'F250N' of type string between a known char ']' and an expression '[G56]' in Table 'T250'
This would also need to cover cases where a preceding char of ] cannot be found eg. at the start of the string.
Eg:
 SYSADMIN[G63]Z-GHQ[G62]Z-WE[G56]Z-MEX[G56]Z-NAZ[G56]Z-LAS[G56]Z-LAN[G56]Z-CEE[G56]Z-APAC[G56]Z-CAD[G56]

Would become:
 SYSADMIN[G63]Z-GHQ[G62]

and:
LVN-CHNG[G62]LVN-READ[G56]LVN-FULL[G63]

Would become:
LVN-CHNG[G62]LVN-FULL[G63]

So far I have tried something like:
update T250
set F250N = replace(F250N, '[G56]', '')
from T250

however this does not take into account the portion of the string preceding [G56] to the last ]

A: Could not think of a way to solve this inline, in an UPDATE clause. So there would be this procedural approach:
set nocount on

declare
  @T250 table(pk int primary key, F250N nvarchar(max))
declare
  @s nvarchar(max),
  @pk int,
  @i int,
  @left nvarchar(max),
  @right nvarchar(max),
  @lenbefore int

insert @T250 values
  (1, N'SYSADMIN[G63]Z-GHQ[G62]Z-WE[G56]Z-MEX[G56]Z-NAZ[G56]Z-LAS[G56]Z-LAN[G56]Z-CEE[G56]Z-APAC[G56]Z-CAD[G56]'),
  (2,N'LVN-CHNG[G62]LVN-READ[G56]LVN-FULL[G63]')

--before
select F250N from @T250

declare c cursor for select pk, F250N from @T250
where F250N like N'%[[]G56]%' --skip rows that do not even contain the marker
open c
fetch next from c into @pk,@s
while @@FETCH_STATUS=0 begin
  --handle single value
  set @lenbefore=len(@s)
  while @s like N'%[[]G56]%' begin
    set @i=CHARINDEX(N'[G56]', @s)
    if @i>0 begin
      set @right=SUBSTRING(@s, @i+len(N'[G56]'),len(@s))
      set @left = REVERSE(substring(@s, 1, @i - 1))
      if @i>0 begin
        set @left=reverse(SUBSTRING(@left,@i,len(@left)))
        set @s=@left+@right
      end else begin
        set @s=@right
      end
    end else begin
      break
    end
    --fuse
    if len(@s)=@lenbefore break
  end
  --persist
  update t set t.F250N=@s from @T250 t where t.pk=@pk
  --advance
  fetch next from c into @pk, @s
end
close c
deallocate c

--after
select F250N from @T250

I did not test for the border cases, but at least it will not go into an endless loop.

A: I still can't decide if I love or hate T-SQL for not supporting regex without all the tom-foolery like Oracle does...

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. - Programming Aphorism

Honestly though, this looks like a regular expression problem (database design questions aside). While T-SQL is regex averse, it can be supported via CLR.
Read more here. Godspeed!

A: Here is my crack at it. First, go find a split function. Here is the one I used:
http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/
This works for both of your samples. Provide more and we will see.
IF OBJECT_ID('tempdb..#holdingtable') IS NOT NULL
    DROP TABLE #holdingtable

--DECLARE @ VARCHAR(1000) = REPLACE('SYSADMIN[G63]Z-GHQ[G62]Z-WE[G56]Z-MEX[G56]Z-NAZ[G56]Z-LAS[G56]Z-LAN[G56]Z-CEE[G56]Z-APAC[G56]Z-CAD[G56]', '[G56]', ',')

declare @ varchar(1000) = REPLACE('LVN-READ[G56]LVN-CHNG[G62]LVN-READ[G56]LVN-FULL[G63]LVN-READ[G56]', '[G56]', ',')
SELECT *
INTO #holdingtable
FROM [fnSplitString](@, ',')

IF (
        SELECT COUNT(*)
        FROM #holdingtable
        WHERE splitdata LIKE '%[[]%'
        ) > 1
BEGIN
        ;

    WITH cte
    AS (
        SELECT LEFT(splitdata, LEN(splitdata) - CHARINDEX(']', REVERSE(splitdata)) + 1)  AS col_
        FROM #holdingtable
        WHERE LEFT(splitdata, LEN(splitdata) - CHARINDEX(']', REVERSE(splitdata)) + 1) LIKE '%[[]%'
        )
    SELECT col_ AS [text()]
    FROM cte
    ORDER BY col_
    FOR XML PATH('')
END
ELSE IF (
        SELECT COUNT(*)
        FROM #holdingtable
        WHERE splitdata LIKE '%[[]%'
        ) = 1
BEGIN
    SELECT LEFT(splitdata, LEN(splitdata) - CHARINDEX(']', REVERSE(splitdata)) + 1)
    FROM #holdingtable
    WHERE LEFT(splitdata, LEN(splitdata) - CHARINDEX(']', REVERSE(splitdata)) + 1) LIKE '%[[]%'
END


text:
Q: run ng-click function from console with JavaScript I'm building an interaction over a page with a following code (not mine):

I need to activate somehow this refresh() function form the ng-click either by clicking the button, or addressing the function directly.
The standard approcach .getElementById("x").click does not work.
I found some solutions that play around $scope like here, but they look more for usage inside the page-code itself, while I rather need a one-line approach to run it straight from the console (or, actually, addressing from VBA with ".execScript("x", "JavaScript")).

A: ng-click does not trigger when you run vanilla click callback, because it's an Angular action attribute. Besides your HTML being malformed(I don't know if its on purpose), you can try this:

Then:
getElementById("_some_id").click();

A: On VBA we need to put the index number, you can try.
Set elem = ie.Document.getElementById("_some_id")(0)

elem.Click

or
Set elems = ie.Document.getElementById("_some_id")

For Each e In elems
    If (e.innerText = " The One") Then
        e.Click
        Exit For
    End If
Next e


text:
Q: Kinect One calibration using OpenCV I'm working on a project with stereo calibration for Kinect one using OpenCV. The CoordinateMapper in the Kinect SDK does not provide sufficent results (speed & quality). The color camera has a full HD resolution (1920x1080 pixel) and the depth/infrared image is 512x424 pixel. My checkerboard is 10x7 with 36mm on an A3-sheet.
I perform the intrinsic calibration with cv::calibrateCamera for both cameras separately. The resulting camera and distortion matrix is pretty similar to GML camera calibration. cv::undistort returns good visual results applying these parameters. The error is 0.941842 (infrared) and 0.583004 (color)
Next is stereo Calibration using previous intrinsics:
cv::Mat rotation, translation, fundamental, essential;
std::cout << "Stereo Error: " << cv::stereoCalibrate(pointsBoard, points1, points2, cameraMatrix1, distortion1, cameraMatrix2, distortion2, imageSize,
        rotation, translation, essential, fundamental, cv::TermCriteria(CV_TERMCRIT_ITER+ CV_TERMCRIT_EPS, 100, 1e-5), CV_CALIB_FIX_INTRINSIC|CV_CALIB_ZERO_TANGENT_DIST) << std::endl;

cv::Mat R1, R2, P1, P2, Q;
cv::Rect validRoi[2];
cv::stereoRectify(cameraMatrix1, distortion1,
    cameraMatrix2, distortion2,
    imageSize, rotation, translation, R1, R2, P1, P2, Q,
    cv::CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]);

cv::initUndistortRectifyMap(cameraMatrix1, distortion1, R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][7]);
cv::initUndistortRectifyMap(cameraMatrix2, distortion2, R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][8]);

I create the map for undistortion and rectifing only one time during calibration. The translation in pixel is calculated by cv::remap one calibration image, again searching for checkerboard and calculating the average translation in X since both images should match on height and width?! The stereo is 0.412727 and reprojection error is 0.715183 using only images with checkerboard parallel to camera (growing on different positions/angles). Calibration image remapping and translation looks ok.
In live mode both images are remaped and translated so that they should match:
//overlay images
// recitfy
cv::remap(depth1, depth2, rmap[0][0], rmap[0][13], cv::INTER_LINEAR);
cv::remap(color1, color2, rmap[1][0], rmap[1][14], cv::INTER_LINEAR);

// translation and crop
depth1 = depth2(cv::Rect(750, 380, imagesOutputSize.width, imagesOutputSize.height)).clone();
color1 = color2(cv::Rect(750+translationX, 380, imagesOutputSize.width, imagesOutputSize.height)).clone();

The result is pretty bad :(

*

*remaped depth

*remaped color


text:
Q: Ember routing out from modal doesn't render correct content into the outlet I have problem with Ember.js and Bootstrap 3.0 modal.
Here is the sample jsfiddle: http://jsfiddle.net/9Bs32/9/
My modal is implemented as subroute for the dynamic segment.
If you enter the test route and then open the modal, everything works OK.
But if you follow the route directly to the test.contact (clicking second link from test.index path), and then follow the link to other route from modal, the content of test is not removed and other route is inserted before the content of test route.
Can anyone give me a hint if the problem here is Bootstrap's modal or Ember itself?
Should I file a bug report for Ember or Bootstrap, or I did something wrong?
Thanks
Damian

A: I should implement modals based on routes see this article...
http://nerdyworm.com/blog/2013/04/20/ember-modal-example/
The code is outdated but easy to adapt to newest ember versions.
Good luck


text:
Q: Closed continuous surjective function that Is not open I want to show that $f:[0,2\pi]\longrightarrow\mathbf{S}^1$ defined as $f(x)=(\cos x,\sin x)$ is closed, surjective, and continuous but not open. I already prooved that it is surjective but I still can't show that it is closed and not open.

A: The topology on $[0, 2\pi]$ is very nearly the same as the one on $\mathbf{S}^1$; only the endpoints $0, 2\pi$ are cause problems.
In particular, sets of the form $[0, x)$ or $(x, 2\pi]$ are open in $[0, 2\pi]$, but their image is not open in $\mathbf{S}^1$.
On the other hand, closed sets in the two spaces are exactly the same, which causes $f$ to be a closed map.
To show this formally, you can show that for any closed set $C \subseteq [0, 2\pi]$, $f(C)$ is closed by taking a sequence $\{y_n\} \in f(C)$ converging to a $y_0 \in \mathbf{S}^1$ and arguing from the fact that $C$ is closed and $f$ is continuous that there is a sequence $x_n \rightarrow x_0\in C$ such that $f(x_n) = y_n$ and  $f(x_0) = y_0$ so that $y_0 \in F(C)$.
If $y_0 \in \mathbf{S}^2 \setminus\{(1, 0)\}$, there is a unique $x_0 \in C$ such that $f(x_0) = y_0$, so this should not give you trouble.
If $y_0 = (0, 1)$, then $f(0) = f(2\pi) = y_0$, and you will need to chose which of these shoud be your $x_0$ for the argument to continue.

A: The set $[0,\pi)$ is open in $[0,2\pi]$ since it can be written as $(-\pi,\pi)\cap[0,2\pi)$
On the other hand, $f([0,pi))$ is the upper half of the circle including $p=(1,0)$ included which is not open since you cannot have an open set $U$ on $S^1$ such that
$$p\in U \subseteq f([0,\pi))$$
You can also show that $f([0,\pi))$ is not open by showing its complement is not closed. $p$ is a limit point of $S^1\setminus f([0,\pi))$ and not contained in it.


text:
Q: Unexpected 'else' on $_GET request I've been working on this code awhile, the error thrown just doesn't make any sense, I've googled around but I just can't find a working solution, or anyone to explain why so I can prevent it in the future.
This error is thrown:

Parse error: syntax error, unexpected 'else' (T_ELSE) in /home/cabox/workspace/up/frontend/pages/settings.php on line 139

Line 139 is the first else statement:
if (isset($_GET['act'])) {
        $act = $_GET['act'];
        $arr = array('delete');
        $arr2 = array('blacklist');
        $arr3 = array('unblacklist');
        if (in_array($act, $arr)) {
                $de = $odb->prepare("DELETE FROM login_attempts WHERE id = :i");
                $de->execute(array(":i" => $tid));
                echo '
log deleted.
<meta http-equiv="refresh" content="2;url=settings.php">';
                break;
            }else{
                echo '
Something went wrong, please try again
';
            }
        }else{
        }
        if (in_array($act, $arr2)) {
            echo 'div class="alert alert-danger">blacklist
';
        }else{
            $getblack = $_GET['ip'];
            $de2 = $odb->prepare("INSERT INTO blacklist VALUES(null, :ip)");
            $de2 = $odb->execute(array(":ip" => $getblack));
        }else{
            echo '
Something went wrong, please try again
';
        }
}


text:
Q: Print data of a file Print data of a file
This it the file content
{
 "nodes": {
    "server.xyz": {
      ":ip": "192.168.56.5",
      "ports": [],
      ":memory": 1024,
      ":bootstrap": "bootstrap-master.sh"
    },
    "client1.abc": {
      ":ip": "192.168.56.10",
      "ports": [],
      ":memory": 1024,
      ":bootstrap": "bootstrap-node.sh"
    },
    "client1.def": {
      ":ip": "192.168.56.15",
      "ports": [],
      ":memory": 1024,
      ":bootstrap": "bootstrap-node.sh"
    }
  }
}

I only want to print
server.xyz
client1.abc
client2.def
and this IP
192.168.56.5
192.168.56.10
192.168.56.15

A: You can use jq,
Example
{
 "nodes": {
  "server.local": {
  ":ip": "192.168.56.5",
  "ports": [],
  ":memory": 1024,
  ":bootstrap": "bootstrap-master.sh"
},
"client1.local": {
  ":ip": "192.168.56.10",
  "ports": [],
  ":memory": 1024,
  ":bootstrap": "bootstrap-node.sh"
},
"client1.local": {
  ":ip": "192.168.56.15",
  "ports": [],
  ":memory": 1024,
  ":bootstrap": "bootstrap-node.sh"
}
}}

And run,
cat file | jq -r '.nodes | keys[]'

Output
client1.abc
client1.def
server.xyz

Edit:
If you want ip as well,
cat file | jq -r '.nodes | to_entries[] | [.key, .value.":ip"] | @tsv'

A: you can execute the file as commands
and have echo in the file so like
 "nodes": {
    echo"server.xyz": {
     echo ":ip": "192.168.56.5",
     ```
and so on then you do
```eval $(cat file location)```
but i think the has to be in one line


text:
Q: display thumbnails and title youtube api v3 javascript I use the following code to complete a search by keyword.  How can I display just the thumbnails and titles on my web page?  I can't figure out how to extract that info from the search results and display it on my page.
<!doctype html>

<title>Search</title>

   <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button>

A: I figured out one way to do it:
<!doctype html>

   <title>Search</title>

    <input id="query" value='cats' type="text"/><button id="search-button"  onclick="keyWordsearch()">Search</button>

Search Results


text:
Q: Sum of $\sum\limits_{m = 1}^\infty {\frac{{m(m + 1)}}{2}} {p^{\frac{{m(m - 1)}}{2}}}\left( {1 - {p^m}} \right)$ I'm trying to find if the following sum is converging to some known identity:
$$\sum\limits_{m = 1}^\infty  {\frac{{m(m + 1)}}{2}} {p^{\frac{{m(m - 1)}}{2}}}\left( {1 - {p^m}} \right)$$
$$ p \in [{0,1}] $$
Thanks for any help

A: I am suggested to think that the answer is negative, because series of the form $\sum_{m=0}^\infty a_m p^{m^2}$ are not natural in the analysis, in contrast to series of the form $\sum_{m=0}^\infty a_m p^m$.


text:
Q: Prove $13^{17} \ne x^2 + y^5$ I've been going in circles trying to prove $$13^{17} \ne x^2 + y^5$$
A friend of mine hinted to use modular arithmetic, but I'm not familiar with that field of study.
Any suggestions are appreciated.
Edit: $x,y \in\mathbb {N} $

A: There is a simple solution using congruences. The set of quadratic residues modulo $11$ is $\{1,3,4,5,9\}$, the set of degree-$5$ residues is $\{1,10\}$; thus, $x^2\in\{0,1,3,4,5,9\}\pmod{11}$ and $y^5\in\{0,1,10\}\pmod{11}$ and consequently, for any integer $x$ and $y$,
  $$ x^2+y^5 \in \{0,1,3,4,5,9\} + \{0,1,10\} = \{0,1,2,3,4,5,6,8,9,10\} \pmod{11}. $$
Notice that $7$ is missing from the set in the right-hand side, meaning that an integer congruent to $7$ modulo $11$ cannot be represented in the form $x^2+y^5$ with $x$ and $y$ integer. However, using "Fermat's little theorem",
  $$ 13^{17} \equiv 2^{17} \equiv 2^7 \equiv -2^2 \equiv 7\pmod{11}. $$

A: "mod 11" means "arithmetic where you ignore multiples of 11", so that 24 is the same as 2 (mod 11), because they differ by 22, which is a multiple of 11.
A cool fact: for any integer $n$, $n^{11}$ is the same as $n$ (mod 11)
So let's look at $13^{17}$ mod 11. Since $13 = 11 + 2$, this is the same as $2^{17}$ mod 11, which is the same as $2^{11} 2^6$, which is the same as $2\cdot 2^6 = 2^7$, which is $128$, which is the same as 7 (mod 11).
So mod 11, the left side of your equation is 7.
What about the right side? Well m if you look at the square of 0, 1, 2, 3, 4, ..., mod 11, you get
$$
(0, 1, 4, 9, 16, 25, ...) \bmod 1 = (0, 1, 4, 9, 5, 3, 3, 5, 9, 4, 1, 0, ...)
$$
i.e., every square, mod 11, is $0, 1, 3, 4, 5,$  or $9$. Every 5th power, similarly, turns out to be either $0, 1,$ or $10$  (mod 11).
Now: If you take the numbers in the first list and add $0$ to them (mod 11), the results are not $7$ (mod 11). If you add $1$ to each, you get $1, 2, 4, 5, 10$, none of which is $7$ mod 11. And if you add $10$ to each, and simplify mod 11, you get $10, 0, 2, 3, 4$ and $8$, none of which is $7$ mod 11.
So since you can't make the left and right sides equal (mod 11), you can't make them equal at all.

A: Check your equation mod 11:
$$13^{17} = 7 \pmod{11}$$
$$\begin{array} {r|r} X & X^2 \pmod{11} \\ \hline
0 & 0\\
1 & 1\\
2 & 4\\
3 & 9\\
4 & 5\\
5 & 3\\
6 & 3\\
7 & 5\\
8 & 9\\
9 & 4\\
10 & 1\\
\end{array}$$
$$\begin{array} {r|r} Y & Y^5 \pmod{11} \\ \hline
0 & 0\\
1 & 1\\
2 & 10\\
3 & 1\\
4 & 1\\
5 & 1\\
6 & 10\\
7 & 10\\
8 & 10\\
9 & 1\\
10 & 10\\
\end{array}$$
The java program I used to find $11$:
public class ThirteenSeventeen {

  public static void main(String[] args) {
    // does exist X,Y : 13^17 = x^2 + y^5

    for (int ModBase = 1; ModBase < 100; ModBase++) {
      boolean ExistFound = false;
      for (int X = 0; X < ModBase; X++) {
        for (int Y = 0; Y < ModBase; Y++) {
          if (ModExpt(13, 17, ModBase) == (ModExpt(X, 2, ModBase) + ModExpt(Y, 5, ModBase)) % ModBase) {
            ExistFound = true;
            break;
          }
        }
        if (ExistFound) break;
      }

      if (!ExistFound) {
        System.out.println("No Existance found for modular base: " + ModBase);
        System.out.println("13^17 = " + ModExpt(13, 17, 11));

        System.out.println("\\begin{array} {r|r} X & X^2 \\pmod{" + ModBase + "} \\\\ \\hline");
        for (int X = 0; X < ModBase; X++) {
          System.out.println("" + X + " & " + ModExpt(X, 2, ModBase) + "\\\\");
        }
        System.out.println("\\end{array}");

        System.out.println("\\begin{array} {r|r} Y & Y^5 \\pmod{" + ModBase + "} \\\\ \\hline");
        for (int Y = 0; Y < ModBase; Y++) {
          System.out.println("" + Y + " & " + ModExpt(Y, 5, ModBase) + "\\\\");
        }
        System.out.println("\\end{array}");

        break;
      }

    }

    System.out.println("Done");
  }

  // compute X^Y % P
  public static int ModExpt(int X, int Y, int P) {
    int R = 1;
    int S = X % P;
    while (Y > 0) {
      if (Y % 2 != 0) {
        R = (R * S) % P;
      }
      S = S * S % P;
      Y = Y / 2;
    }
    return R;
  }

}


text:
Q: Should both healthd and android.hardware.health@2.0-service.imx be running? On my Android system, there are two separate healthd processes:
$ adb shell "ps -ef | grep health"
root          3535     1 3 14:33:18 ?     00:00:00 healthd
system        3548     1 5 14:33:18 ?     00:00:00 android.hardware.health@2.0-service.imx

They both use the same code from system/core/healthd and hardware/interfaces/health/2.0/default, but only android.hardware.health@2.0-service.imx uses code from vendor/nxp-opensource/imx/health.

*

*Is there any reason for both to run?

*Should NXP (or downstream vendor) have stopped the default Android healthd from building/running?

Update:
The .rc files for the two services differ:
smarc_mx8mq:/etc/init # cat healthd.rc
service healthd /system/bin/healthd
    class hal
    critical
    group root system wakelock

smarc_mx8mq:/etc/init # cat /vendor/etc/init/android.hardware.health@2.0-service.imx.rc
service vendor.health-hal-2-0 /vendor/bin/hw/android.hardware.health@2.0-service.imx
    class hal
    user system
    group system
    capabilities WAKE_ALARM
    file /dev/kmsg w

Removing /etc/init/healthd.rc from the built system causes the vanilla healthd not to start.  I have not yet noticed any ill effects.

A: healthd is version 1.0 hal, it can be  removed. ref: Removing healthd


text:
Q: Wordpress footer costumization I am learning wordpress and i want to edit my footer. I am using generatePress theme.
i go to appearence->edit theme->footer.php and i edit that file and i wrote that footer div.
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}
?>

<?php
do_action( 'generate_before_footer' );
?>

<div <?php generate_do_element_classes( 'footer' ); ?>>
    <?php

    do_action( 'generate_before_footer_content' );

    do_action( 'generate_after_footer_content' );
    ?>

anything

<?php

do_action( 'generate_after_footer' );

wp_footer();
?>

i don't know if that is 100% correct but it's works and it wrote in web page footer.But now i want to edit with css. i already went to style.css and i wrote
.footer{background-color:red;}
but this didn't work, so i was wondering if anyone here can help me.

A: Your CSS is correct. However the reason why it is not working might be due to where you added it or if the background is covered by another style or due to caching.
You can try to add it at the end of your style.css file and if that fails try adding this:
.footer {
background-color:red !important;
background:red !important;
}

You should also disable all caching plugins and check to see if the server has caching enabled. Caching will prevent you from seeing CSS changes.
Please note that the use of !important in CSS is not recommended, therefore you can try it with removing it but if it only works with !important then you can keep it or troubleshoot why it fails without it.
If that fails, send us a link to your site.


text:
Q: How do I make an http request using the data from a prior http request? I have an Issue object, one property of which is an array of Tool objects. Issues and Tools are two different tables in my database.
In my issues-log.component I am dispatching an action to search for issues that match my search query. This works just fine.
The next thing I've been trying to do, is to take the list of issues and for each issue id, pass that to my tools service so that I can get the tools related to that issue.
The way I was able to get that working is to add another effect that listens for the ISSUE.SEARCH.COMPLETE action. Then I looped through the array of issues in my tools service so that I could call the API service for each issue id and add the tools property to that issue. This seems wrong in a couple ways. One is that for large lists of issues, it takes a long time to for all the tools to load and if I try to kick off another issues search I have to wait for the tools to load from the previous one before my app responds. Two, is that it seems wrong to pass the whole issues array into the tools service when I only need one issue id at a time for my tools API to get the list of tools associated with that issue; this doesn't make my tools service easily re-usable in other places in my app.
I would prefer not to wait until my API call to get the list of issues is done before I can start getting the tools associated with each issue id. Is it possible to add code in my issuesSearch$ effect, where commented below, to start adding the tools as my list of issues is being built?
Component:
@Component({
selector: issue-log,
template: `
  <issue-search (search)="search($event)></issue-search>
  <issue-list [issues]=$issues | async></issue-list>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IssueLogComponent {
  issues$: Observable<Issue[]>;

  constructor(private store: Store<fromRoot.State>) {
    this.issues$ = store.select(fromRoot.getIssueSearchResults);
  }

  search(query) {
    this.store.dispatch(new issue.IssueSearch(query));
  }
}

Effect:
@Effect() issueSearch$: Observable<Action> = this.actions$
  .ofType(issue.ISSUE_SEARCH)
  .debounceTime(300)
  .map(toPayload)
  .switchMap(query => {
    if (query === '') {
      return empty();
    }
    const nextSearch$ = this.actions$.ofType(issue.ISSUE_SEARCH).skip(1);
    return this.issueService.getIssuesFromQuery(query) //calls API service
      .takeUntil(nextSearch$)
      .mergeMap((res: Issue[]) => {
        // How do I make another API call here, passing data from each element of res array?
        return Observable.from([
          new issue.IssueSearchComplete(res)
        ])
      })
      .catch(() => of(new issue.IssueSearchComplete([])));
});

I also tried calling my tools service from inside my issues service, but don't think this is the right approach either.

A: Since you need to access the results of your issues immediately BEFORE making other asynchronous requests using the data of those issues, you may want to use an RxJS Subject of some sort.
You can observe for issues on that subject, and also subscribe to the observable of the result of all final calls.
Conceptual breakdown:

*

*We fetch issues

*We pass the issues to another observable stream so they can be accessed immediately

*We use the issues to make other async calls

*We return the result of the final calls, which too can be subscribed to

So you will have to subscribe to two observable streams with this approach.
Here is a simple, contrived example:
@Injectable()
export class FooService {
    issuesSubject: BehaviorSubject<Issue[]> = new BehaviorSubject([]);

    get issues$(): Observable<Issue[]> {
        return this.issuesSubject.asObservable();
    }

    getIssuesAndMakeOtherAsyncCalls(): Observable<any> {
       return this.issueService
                  .getIssuesFromQuery(query)
                  .flatMap((issues: Issue[]) => {
                      // This is where you add issues to the issues stream
                      this.issuesSubject.next(issues);

                      // This is where you make other HTTP calls using the issues
                      return this.makeSomeOtherCallsUsingIssues(issues);
                  })
    }
}

In your component:
@Component({})
export class FooComponent implements OnInit {
    ngOnInit() {
        this.issueService.getIssuesAndMakeOtherAsyncCalls().subscribe(res => {
            // `res` will be the result of the `makeSomeOtherCallsUsingIssues(issues)` call in the service
        });

        this.issueService.issues$.subscribe((issues: Issue[]) => {
            // You will get issues here when the `this.issuesSubject.next(issues)` line is called in your service
        });
    }
}

Does that work for you?


text:
Q: Delete pointer after return statement I ran into the following problem: I want to return a Y-coordinate, and after I returned it, it needs to be deleted.
Is there a way to do this, because I think I'm missing some major things here.
void setY(int y)
    {
        this->y = new(int); //pointing to new address
        *this->y = y; //change value of pointer
    }

    int getY()
    {
        return *y; //give the coordinate
        delete y; //what I want
        *y = NULL; //what I want
    }

Thank you in advance. If the question is not well described, please let me know.

A: Simply change your data member type fromj int* to plain int.
Then store the value there, and return the value, no new stuff.
Additional tip: a get prefix is useful in a language with introspection such as Java or C#, but is not neccessary (just verbiage) in C++.

A: Notwithstanding the design flaws, the simplest thing to do is to take a copy:
int getY()
{
    int ret = *y;
    delete y; //what I want
    /*No assignment to deferenced y is possible - you've deleted it*/
    y = nullptr; /*a further delete on y will be benign*/
    return ret;
}

A: Since you say you really do need to muck around with pointers as part of a learning exercise, you need to read the return value before deleting:
int result = *y;
delete y;
y = nullptr;    // NOT *y - that's been deleted
return result;

(If you're stuck with a historic version of C++, then write NULL or 0 instead of nullptr. nullptr is better though - it would have prevented the mistake in your code).
You should also check y before dereferencing it, and fix the memory leak you get when calling setY more than once. Since the class is managing a separate resource, you'll also need to carefully follow the Rule of Three to avoid further memory errors.
Hopefully, the point of this exercise is to show you how difficult pointer-juggling can be, and how much easier it is to use more idiomatic techniques - in this case, simply storing an int directly.

A: Something like this
int getY()
{
   int value = -1;

   if (y_ptr) {
      value = *y_ptr;
      y_ptr = nullptr;
   }

   return value;
}

However i must add that this is just plain abuse of pointers, don't do it.


text:
Q: VS 2013 does not compile new code after saving I've been using VS 2013 at school to write simple code for c++. After I save the code using "Save As" and compiling the code, it runs fine. The problem is when I add some new code and compile it does not take the new code that's been added. It will just run the code from the point I save it no matter the changes that I make. If I exit VS and re-open the project/solution it will compile and run any changes before I "save as". I've searched(probably not in the right way), I've asked students around me, and I've even asked the instructor(stick up his bum) but no answers.
addition info: ive been saving to my thumb drive.()


text:
Q: What's the scalajs equivalent of per page javascript? Suppose I already have an play app, with three or four pages, each one of which has a seperate javascript script file imported at the bottom.
eg
   <script src="@routes.Assets.versioned("javascripts/detailsPage.js")" type="text/javascript"></script>

Each one contains some specific behaviour - jquery events, or an EventSource listener for that page, which isn't necessary on other pages. (The EventSource isn't on every page).
Going forward, I'd like to give scalajs a try. But that produces a single script file, which expects to be included in all pages. I'm not worried about the overhead - the javascript file will be cached.
But what's the equivalent way of structuring my scalajs so that I can include the appropriate behaviour in each page?

A: I don't know what the canonical answer is here, but have ended up doing the following:
Each "script" is declared in an object with a single @JSExportTopLevel (needs scalajs 0.6.15 or above) function:
@JSExportTopLevel("enhancedFrobnication")
def main(): Unit = {
}

The full scalajs file is then included in the main method, and specific bits of functionality are switched on in short <script> sections after that has been included:
    <script type="text/javascript">enhancedFrobnication();</script>


text:
Q: OpenLayers Vector polygon and jQuery Droppable How can I use jQuery Droppable to drag and drop an Icon over an openlayers polygon vector and select the polygon while over on hover? I have managed create a create a popup when over a div element, but I can't figure out how to do the same for a polygon inside the "map" div. Hope that makes sense.
Here is a link to show the concept:
Update:
Here is a bit of code to show specifically the bit of code I am struggling with. I can currently select a polygon by clicking... but want to select by dropping an icon on the polygon.
$(function() {

$( "#cow" ).draggable({ revert: true});
$( "#map" ).droppable({
  drop: function( event, ui ) {

    **\\How do I select a polygon on drop here?**
    alert( "Dropped!" );
  }
});

A: Here is the code I figured out how to use jquery drag and drop to select a polygon.
This assumes you have a select control on the map and activated:
 $( "#cow" ).draggable({ revert: true});
    $( "#map" ).droppable({
    drop: function( event, ui ) {
    var farmid = 448;
    var point = map.getLonLatFromPixel( map.events.getMousePosition(event, ui ) )
    var lon =  point.lon.toFixed(3);
    var lat =   point.lat.toFixed(3);
    var dropPosition = point.lon.toFixed(3) + ' ' + point.lat.toFixed(3);

    $.ajax({
    type: "GET",
    url: "../php/position.php",
    contentType: "application/json; charset=utf-8",
    data: "{'farmid':'"+ farmid +"', 'position':'"+ dropPosition +"'}",
    success: function(returnval){

    var pid = parseInt(returnval);
    var selectB = new OpenLayers.Control.SelectFeature([farmbounds]);
    for(var f=0;f<farmbounds.features.length;f++) {
                                    if(farmbounds.features[f].fid == 'farmpaddocks.'+pid+'') {
                                selectB.select(farmbounds.features[f]);
break;
  }}
}//success
});//ajax
}
});

And here is the php code:
<?php
$farmid= $_GET["farmid"];
$position = $_GET["position"];
$db = pg_connect("host=localhost dbname=postgis user=aaaaa password=bbbbb" );
$sql = "SELECT * FROM public.farmpaddocks WHERE farmid = '$farmid' AND st_contains(farmpaddocks.the_geom,ST_GeomFromText('POINT($position)',3111)) ='t'";
$resultD = pg_query($db,$sql);
while($rowD=pg_fetch_row($resultD))
{
$paddockid= $rowD[0];
echo $paddockid;
}

?>


text:
Q: ThreeJS + NextJS: class constructors must be invoked with 'new' I am trying to render a simple scene inside a nextJS route inside "lab2".
I keep recieving this error:
class constructors must be invoked with 'new'
Call Stack
renderWithHooks
node_modules\react-reconciler\cjs\react-reconciler.development.js (7363:0)
mountIndeterminateComponent
node_modules\react-reconciler\cjs\react-reconciler.development.js (12327:0)
beginWork
node_modules\react-reconciler\cjs\react-reconciler.development.js (13831:0)
callCallback
node_modules\react-reconciler\cjs\react-reconciler.development.js (14219:0)
invokeGuardedCallbackDev
node_modules\react-reconciler\cjs\react-reconciler.development.js (14268:0)
invokeGuardedCallback
node_modules\react-reconciler\cjs\react-reconciler.development.js (14329:0)
beginWork$1
node_modules\react-reconciler\cjs\react-reconciler.development.js (19537:0)
performUnitOfWork
node_modules\react-reconciler\cjs\react-reconciler.development.js (18686:0)
workLoopSync
node_modules\react-reconciler\cjs\react-reconciler.development.js (18597:0)
renderRootSync
node_modules\react-reconciler\cjs\react-reconciler.development.js (18565:0)
performConcurrentWorkOnRoot
node_modules\react-reconciler\cjs\react-reconciler.development.js (17836:0)
workLoop
node_modules\react-reconciler\node_modules\scheduler\cjs\scheduler.development.js (266:0)
flushWork
node_modules\react-reconciler\node_modules\scheduler\cjs\scheduler.development.js (239:0)
performWorkUntilDeadline
node_modules\react-reconciler\node_modules\scheduler\cjs\scheduler.development.js (533:0)
EventHandlerNonNull*
node_modules\react-reconciler\node_modules\scheduler\cjs\scheduler.development.js (571:0)
<unknown>
node_modules\react-reconciler\node_modules\scheduler\cjs\scheduler.development.js (633:3)
./node_modules/react-reconciler/node_modules/scheduler/cjs/scheduler.development.js
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (148:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (288:21)
<unknown>
node_modules\react-reconciler\node_modules\scheduler\index.js (6:2)
./node_modules/react-reconciler/node_modules/scheduler/index.js
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (159:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (288:21)
$$$reconciler
node_modules\react-reconciler\cjs\react-reconciler.development.js (19:24)
createRenderer
node_modules\@react-three\fiber\dist\index-4f1a8e2f.esm.js (1041:31)
<unknown>
node_modules\@react-three\fiber\dist\index-4f1a8e2f.esm.js (1628:2)
./node_modules/@react-three/fiber/dist/index-4f1a8e2f.esm.js
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (18:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (288:21)
<unknown>
webpack-internal:///./node_modules/@react-three/fiber/dist/react-three-fiber.esm.js (30:99)
./node_modules/@react-three/fiber/dist/react-three-fiber.esm.js
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (29:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (288:21)
<unknown>
webpack-internal:///./pages/lab2.js (4:95)
./pages/lab2.js
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (93:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
fn
/_next/static/chunks/webpack.js (288:21)
<unknown>
node_modules\next\dist\build\webpack\loaders\next-client-pages-loader.js?absolutePagePath=C%3A%5CUsers%5Croot%5CDocuments%5CCS%20things%5CPhys_2%5Cphys2labs%5Cpages%5Clab2.js&page=%2Flab2! (5:15)
onEntrypoint/<
node_modules\next\dist\client\route-loader.js (235:50)
promise callback*onEntrypoint
node_modules\next\dist\client\route-loader.js (235:41)
register
node_modules\next\dist\client\index.js (268:58)
<unknown>
node_modules\next\dist\build\webpack\loaders\next-client-pages-loader.js?absolutePagePath=C%3A%5CUsers%5Croot%5CDocuments%5CCS%20things%5CPhys_2%5Cphys2labs%5Cpages%5Clab2.js&page=%2Flab2! (2:0)
./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?absolutePagePath=C%3A%5CUsers%5Croot%5CDocuments%5CCS%20things%5CPhys_2%5Cphys2labs%5Cpages%5Clab2.js&page=%2Flab2!
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (71:1)
options.factory
/_next/static/chunks/webpack.js (633:31)
__webpack_require__
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/webpack.js (37:33)
__webpack_exec__
/_next/static/chunks/pages/lab2.js (220:61)
<unknown>
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (221:78)
__webpack_require__.O
/_next/static/chunks/webpack.js (86:23)
<unknown>
file:/C:/Users/root/Documents/CS%20things/Phys_2/phys2labs/.next/static/chunks/pages/lab2.js (222:56)
<unknown>
webpackJsonpCallback@http://localhost:3000/_next/static/chunks/webpack.js?ts=1656026286152 (1181:46)
<unknown>
/_next/static/chunks/pages/lab2.js (9:61)

I get three of these errors, and the console attributes these to within <BoxGeometry>, <MeshPhysicalMaterial>, and <ForwardRef(Canvas)> components.
Here is my Lab2.js route:
import { Canvas } from "@react-three/fiber";
import Floor from "../components/floor";

function Lab2() {
    return(
        <div className="w-screen h-screen">
            <Canvas
            shadows={true}
            className="bg-slate-500"
            camera={{
                position: [-6, 7, 7],
            }}>
                <Floor position={[0, -1, 0]} />
            </Canvas>
        </div>
    );
}

export default Lab2;

And my floor.js component:
import { BoxBufferGeometry, MeshPhysicalMaterial } from "three";

function Floor(props) {
    return (
        <mesh {...props} recieveShadow={true}>
            <BoxBufferGeometry args={[20,1,10]} />
            <MeshPhysicalMaterial color='white' />
        </mesh>
    );
}

export default Floor;

My dependencies and versions:
"dependencies": {
    "@react-three/fiber": "^8.0.27",
    "next": "12.1.6",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "three": "^0.141.0"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.7",
    "eslint": "8.18.0",
    "eslint-config-next": "12.1.6",
    "postcss": "^8.4.14",
    "tailwindcss": "^3.1.4"
  }

Any help would be greatly appreciated.

A: In React-Three-Fiber you don't need to import BoxBufferGeometry and MeshPhysicalMaterial from three if you want to just return them in the jsx component (just like you did not import mesh!), convert these to camel-case like so:
function Floor(props) {
    return (
        <mesh {...props} recieveShadow={true}>
            <boxBufferGeometry args={[20,1,10]} />
            <meshPhysicalMaterial color='white' />
        </mesh>
    );
}

export default Floor;


text:
Q: List Index out of range in python? I'm kind of new to python and needed help with this - it says list index out of range?
file=open("Reg_Details.csv","r")
Reg=[line.split(',') for line in file]
file=open("Speed_Exceeded.csv","r")
Speed=[line.split(',') for line in file]

for x in Reg:
    for y in Speed:
        if x[2]==y[2]:
            print("match")
            file=open("Details_user.csv","w")
            file.write("%s,%s,%s\n" % (x[0],[0],x[1]))
file.close()

(Original screencap)

A: It means that the list doesn't have an element with the index id you're asking for.
>>> variable = [1,2,3]
>>> variable[2]
3
>>> variable[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

In this example the valid ids are 0, 1 and 2, but 3 is invalid.

A: When you check
    x[2] == y[2]
you're accessing the third element of each of the two lists (0 is the first element). The error you are getting means that either x or y has less than 3 elements, so the element you are asking for is out of range. Most likely Reg_Details.csv or Speed_Exceeded.csv have only 1 or 2 columns.
Also looking at your code, you probably want to replace
file=open("Details_user.csv", "w")

by
file=open("Details_user.csv", "a")

The opening mode "w" puts the writing stream at the beginning of the file, so every time you run this line you are erasing whatever was inside before (meaning each iteration of your loop you are deleting the previous line, and at the end "Details_user.csv" will contain only one line). Using the opening mode "a" (from 'append') opens the file putting the writing stream at the end of the file, so you will append a new line to the file at every iteration.


text:
Q: moment estimation for weibull distribution I would like to fit weibull parameter using "Method of moments estimation"(MME) in R. I know we can estimate these value with fitdisr() function in MASS package, but I want to know if there is function or package to calculate the parameter with MME.
for example I want to approximate MME with Monte carlo Method. When I generate 1000 value from uniform distribution, the function that I write for this problem(for estimate of an integral), give me the 0 value. How can I fix this problem?

A: Here's one way to use MME for finding the parameters of a Weibull distribution.
# load packages
require(rootSolve)
# generate data
N <- 1000
shape <- 2
scale <- 6
X <- rweibull(n=N, shape=shape, scale=scale)
# range of plausible shapes (for solver)
min_shape <- 0.1
max_shape <- 100
# bootstraping
Nboot <- 1000
sim <- replicate(Nboot, {
  Xboot <- sample(X, replace=TRUE)
  # find shape
  rt <- 1+(sd(Xboot)/mean(Xboot))^2
  rootFct <- function(k) {
    gamma(1+2/k)/gamma(1+1/k)^2 - rt
  }
  shape_est <- uniroot.all(rootFct, c(min_shape, max_shape))
  if (length(shape_est)!=1) stop("The shape may be outside min_shape and max_shape")
  scale_est <- mean(Xboot)/gamma(1+1/shape_est)
  c(shape=shape_est, scale=scale_est)
})
apply(sim, 1, function(x)
  c(est=mean(x), se=sd(x), quantile(x, c(.025, .5, .975))))


text:
Q: Angular2 Using Router instance from tests I'm trying to develop some Jasmine tests for an Angular2 component. This component receives two parameters in the constructor, a service and a router.
import {Component , OnInit} from '@angular/core';
import {Router} from '@angular/router-deprecated';
import { HeroService } from './hero.service';

@Component({
  ...
})

export class HeroesComponent implements OnInit {
  ...
  constructor(
      private heroService: HeroService ,
      private router: Router
  ) { }
  ...
}

I want to write a test to check this component is well defined, but I have doubts about how to instanciate the component in the test passing the two parameters, the first (HeroService) is easy, just using a new , but, ¿how can I pass the second parameter (Router) ? I'm trying to use a new, but I don't know how to pass the RouterRegistry needed as first parameter of Route constructor. Is there another approach to do this?
import { Router }         from '@angular/router-deprecated';
import { HeroService } from './hero.service';
...
describe('HeroesComponent with new', function () {
  it('should instantiate component', () => {
    expect(new HeroesComponent(new HeroService() , new Router())).toBeDefined('Done!');
  });
});

This raises this error:
app/heroes.component.spec.ts(30,52): error TS2346: Supplied parameters do not match any signature of call target.

Thanks in advance


text:
Q: How to install XGBoost on OSX with multi-threading I'm trying to install xgboost on my mac (osx 10.12.1) following the guide here but I'm running into some issues.

Step1

Obtain gcc-6.x.x with openmp support by brew install gcc --without-multilib

Terminal
Ben$ brew install gcc --without-multilib
Error: gcc-5.3.0 already installed
To install this version, first `brew unlink gcc`

Ben$ brew unlink gcc
Unlinking /usr/local/Cellar/gcc/5.3.0... 1288 symlinks removed

Ben$ brew install gcc --without-multilib
[26 minutes later]
==> Summary
  /usr/local/Cellar/gcc/6.2.0: 1,358 files, 238.3M, built in 26 minutes 20 seconds

Step2

Clone the repository git clone --recursive https://github.com/dmlc/xgboost

Terminal
Ben$ git clone --recursive https://github.com/dmlc/xgboost
Cloning into 'xgboost'...
remote: Counting objects: 18754, done.
remote: Compressing objects: 100% (21/21), done.
remote: Total 18754 (delta 1), reused 0 (delta 0), pack-reused 18733
Receiving objects: 100% (18754/18754), 6.23 MiB | 3.74 MiB/s, done.
Resolving deltas: 100% (11347/11347), done.
Checking connectivity... done.
Submodule 'dmlc-core' (https://github.com/dmlc/dmlc-core) registered for path 'dmlc-core'
Submodule 'rabit' (https://github.com/dmlc/rabit) registered for path 'rabit'
Cloning into '/Users/Ben/xgboost/dmlc-core'...
Cloning into '/Users/Ben/xgboost/rabit'...
Submodule path 'dmlc-core': checked out 'f35f14f30835af238257b979cc1fac3e41ff3291'
Submodule path 'rabit': checked out 'a9a2a69dc1144180a43f7d2d1097264482be7817'

Step3

build using the following commands cd xgboost; cp make/config.mk ./config.mk; make -j4
NOTE: If you use OSX El Capitan, brew installs gcc the latest version gcc-6. So you may need to modify Makefile#L46 and change gcc-5 to gcc-6. After that change gcc-5/g++-5 to gcc-6/g++-6 in make/config.mk then build using the following commands

Hmmm. Not entirely sure what to do here. I see a file called "Makefile" inside xgboost/. Inside it I see a lot of stuff I don't understand, but these lines look relevant
Makefile (snippet)
# on Mac OS X, force brew gcc-6, since the Xcode c++ fails anyway
# it is useful for pip install compiling-on-the-fly
OS := $(shell uname)
ifeq ($(OS), Darwin)
export CC = $(if $(shell which gcc-6),gcc-6,$(if $(shell which gcc-mp-6), gcc-mp-6, clang))
export CXX = $(if $(shell which g++-6),g++-6,$(if $(shell which g++-mp-6),g++-mp-6, clang++))
endif

Going to ignore this and move on...
Terminal
Ben$ cd xgboost; cp make/config.mk ./config.mk; make -j4
[Tons of log output. Appears to finish succesfully]
...
g++-6 -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -shared -o lib/libxgboost.so build/learner.o build/logging.o build/c_api/c_api.o build/c_api/c_api_error.o build/common/common.o build/data/data.o build/data/simple_csr_source.o build/data/simple_dmatrix.o build/data/sparse_page_dmatrix.o build/data/sparse_page_raw_format.o build/data/sparse_page_source.o build/data/sparse_page_writer.o build/gbm/gblinear.o build/gbm/gbm.o build/gbm/gbtree.o build/metric/elementwise_metric.o build/metric/metric.o build/metric/multiclass_metric.o build/metric/rank_metric.o build/objective/multiclass_obj.o build/objective/objective.o build/objective/rank_obj.o build/objective/regression_obj.o build/tree/tree_model.o build/tree/tree_updater.o build/tree/updater_colmaker.o build/tree/updater_histmaker.o build/tree/updater_prune.o build/tree/updater_refresh.o build/tree/updater_skmaker.o build/tree/updater_sync.o dmlc-core/libdmlc.a rabit/lib/librabit.a -pthread -lm  -fopenmp

Step4 (instructions here?)

If you would like to use the latest xgboost version and already
  compiled xgboost, use library(devtools); install('xgboost/R-package')
  to install manually xgboost package (change the path accordingly to
  where you compiled xgboost).

New R session
library(devtools)
install("/Users/Ben/xgboost/R-package")

Installing xgboost
'/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL  \
  '/Users/Ben/xgboost/R-package' --library='/Library/Frameworks/R.framework/Versions/3.3/Resources/library' --install-tests

* installing *source* package 'xgboost' ...
** libs
g++-5 -std=c++11 -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I../..//include -I../..//dmlc-core/include -I../..//rabit/include -I../../ -DXGBOOST_STRICT_R_MODE=1 -DDMLC_LOG_BEFORE_THROW=0 -DDMLC_ENABLE_STD_THREAD=1 -DDMLC_DISABLE_STDIN=1 -DDMLC_LOG_CUSTOMIZE=1 -DXGBOOST_CUSTOMIZE_LOGGER=1 -DRABIT_CUSTOMIZE_MSG_ -DRABIT_STRICT_CXX98_ -I/usr/local/opt/llvm/include   -fopenmp  -fPIC  -Wall -mtune=core2 -g -O2 -c xgboost_R.cc -o xgboost_R.o
make: g++-5: No such file or directory
make: *** [xgboost_R.o] Error 1
ERROR: compilation failed for package 'xgboost'
* removing '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/xgboost'
* restoring previous '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/xgboost'
Error: Command failed (1)

Fail :(  Where did I go wrong?

A: Updated Solution
As of March 2019, R version 3.5.3, xgboost version 0.82.0.1, things have changed since my old answer. The following steps are based on the installation guide here, but differ slightly.

*

*brew install cmake or brew upgrade cmake (cmake --version shows 3.14.0 for me)

*brew install gcc or brew upgrade gcc (Note the version of gcc that gets installed. It should be located in /usr/local/bin. I get gcc 8.3.0 (gcc-8 --version))

*cd some/unimportant/directory

*git clone --recursive https://github.com/dmlc/xgboost

*cd xgboost/

*mkdir build

*cd build

*CC=gcc-8 CXX=g++-8 cmake .. -DR_LIB=ON

*make -j4

*sudo make install
Now restart/refresh RStudio and it should be installed
Test in R
set.seed(222)
N <- 2*10^5
p <- 350
x <- matrix(rnorm(N  * p), ncol = p)
y <- rnorm(N)

system.time(mymodel <- xgboost(
  # nthread = 4,
  data = x,
  label = y,
  nrounds = 5,
  objective = "reg:linear",
  tree_method = "exact",
  max_depth = 10,
  min_child_weight = 1,
  eta = 1,
  subsample = 0.66,
  colsample_bytree = 0.33
))

# Tested on 2018 MPB, xgboost version 0.82.0.1, multi-threaded version
# nthread = default:   7.4 seconds (elapsed)
# nthread = 1:        24.0 seconds (elapsed)
# nthread = 2:        13.7 seconds (elapsed)
# nthread = 4:         7.5 seconds (elapsed)

Old Answer
It's amazing how writing your question on StackOverflow often leads you directly to the answer. After spending hours on this, I figured out that I needed to change these three lines in ~/.R/Makevars
CC=gcc-5
CXX=g++-5
CXX1X = g++-5

to
CC=gcc-6
CXX=g++-6
CXX1X = g++-6

Also, I ended up installing xgboost from the "drat" repo
install.packages("drat", repos="https://cran.rstudio.com")
drat:::addRepo("dmlc")
install.packages("xgboost", repos="http://dmlc.ml/drat/", type = "source")

A: My approach is after your first(update gcc) and second(clone) steps, no need to build anything(they are for other languages like python)
3) update ~/.R/Makevars
https://github.com/dmlc/xgboost/issues/1136
How to make R package xgboost parallel in OS X with OpenMP compilation?
4) from the clone xgboost/R-package/configure change ac_pkg_openmp to yes
https://github.com/dmlc/xgboost/issues/2503
5) in xgboost/R-package type R CMD INSTALL .
http://xgboost.readthedocs.io/en/latest/build.html#r-package-installation


text:
Q: EF Core Code First - Clustered Index and Identity Column I am using EF Core 2.0 to create a table in which the primary key is a GUID and the clustered index is an auto-incrementing INT column.  But I'm getting this error:

Cannot create more than one clustered index on table 'Tenants'. Drop the existing clustered index 'PK_Tenants' before creating another

This is the code for creating entity and Fluent API.
Tenant.cs
public class Tenant : EntityBase
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ClusteredId { get; set; }
    public new Guid TenantId { get; set; }

    public string TenantCode { get; set; }
}

FluentAPI
protected override void OnModelCreating(ModelBuilder builder)
{
        builder.Entity<Tenant>().HasIndex(c => c.TenantId).ForSqlServerIsClustered(false);
        builder.Entity<Tenant>().HasIndex(c => c.ClusteredId).HasName("ClusteredId").ForSqlServerIsClustered(true);

        base.OnModelCreating(builder);
}

Please suggest, how to remove this error and create primary key for GUID and clustered index for auto-incrementing INT column.
Thanks.

A: The PK index is not maintained explicitly. In EF Core it can be configured via KeyBuilder fluent API (note the HasKey in place of HasIndex):
    builder.Entity<Tenant>().HasKey(c => c.TenantId).ForSqlServerIsClustered(false);
    builder.Entity<Tenant>().HasIndex(c => c.ClusteredId).HasName("ClusteredId").ForSqlServerIsClustered(true);


text:
Q: .loc only returning first value in a list instead of the full list I have a data frame and I'm trying to return all the matching values in one column based on another column using loc.  The dataframe looks like this.

Col1
Col2

Alpha
Bravo

Alpha
Charlie

Delta
Charlie

Delta
Echo

Delta
Echo

Mike
Rodeo

I'm wanting to return an additional column that has all the values in Col2 for each item in Col1.  I tried posting the second table, but StackOverflow thought it was a code command and won't let me post.
When I run this code, Col3 is value from Col2 and not the full list, but when I run only the right side of the code for a specific value, it returns the correct list
for value in col1_values:
    df.loc[df['Col1'].eq(value),'Col3'] = list(df['Col2'].loc[df['Col1'].eq(value)])


text:
Q: opened file can't be seen with lsof I wrote the following scripts(the two scripts are at the same directory),
script A,
#!/bin/bash

. B.sh

script B,
#!/bin/bash

echo "script B..."
read -rsp $'Press enter to continue...\n'

After executing script A, I found when 'Press enter to continue...' message displays on the screen, but I still can't see script B is been opening using lsof.
lsof +D "/PATH/"