text:
Q: Expected to return a value in arrow function array-callback-return I am using React.js and I am fairly new to web development in general. I'm trying to have the divs rendered that are in the componentDidMount method but they aren't being rendered and I am getting the warning message "Expected to return a value in arrow function array-callback-return". Also, when I console.log(this.state) it's only showing an empty object and so this.state.renderedStreamingLinks is never being set. I even tried putting this.setState inside of setTimeout just to see if it's an asynchronous problem going on, but that didn't work either so I am not really sure how to go about solving this. Any help would be much appreciated.
componentDidMount() {
    let renderedStreamingLinks = this.props.streamingLinks.map(streamingLink => {
        fetch(streamingLink.relationships.streamer.links.related)
        .then(data => data.json())
        .then(data => {
            return(

                    {data.data.attributes.siteName}

            )
        })
    })
    this.setState({renderedStreamingLinks: renderedStreamingLinks})
}

render() {
    return (

            {this.state.renderedStreamingLinks ? this.state.renderedStreamingLinks : ""}

    )
}

A: The resulting return of .then() is a promise. Ie, its a "promise" that something will happen or fail. Theres no "real value" being returned. How to manage promise callbacks is to do the assignment when and where the value is actually obtained, inside the callback. And, your hunch is right, there is an async problem going on.
componentDidMount() {
    let renderedStreamingLinks = this.props.streamingLinks.map(streamingLink => {
        fetch(streamingLink.relationships.streamer.links.related)
        .then(data => data.json())
        .then(data => {
            const renderedStreamingLinks = (

                    {data.data.attributes.siteName}

            );
            this.setState({renderedStreamingLinks: renderedStreamingLinks})
        })
    })

}

render() {
    return (

            {this.state.renderedStreamingLinks ? this.state.renderedStreamingLinks : ""}

    )
}


text:
Q: accessing Access 2007 System Object tables and schemas I am looking for some help on retrieving Access 2007 database schema information for system object tables. I have reviewed, read and tested this successfully for the non system tables. The database tables info I am trying to retrieve are in the tables that begin with MSys{xxxxxxxxxx} and store things like relationships, creation date, dateupdate, etc. This tables are viewable by right clicking on the Navigation Options popup menu in Access and selecting Show System Objects.
For clarification, I have added the System.mdw database to the connection string, and I have attempted multiple settings in the restrictions property of the getSchema method. I am using ado.net, vb.net, and VS2008, these are access 2007 databases not mdb files.
My issue appears to continue to be no read access to the System tables. My end goal is to manage relationships initially and eventually hopefully script these databases much like can be done EASILY (Microsoft) in SQL Server Mgmt Studio.
I am hoping someone can point me to some good web link resources or even a good book that clearly discusses this functionality.
thanks,

A: As it turns out the easiest way to gain access to the system table data is to execute a permissions command on the Systems database table(s). The following query did the trick....
    Dim strDdl As String = "GRANT SELECT ON MSysObjects TO Admin;"
    Dim command12 As New OleDbCommand(strDdl, connection)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the equivalent of Java's default (package) access in C#? What is the equivalent of Java's default (package) access in C#? Is there one?  Is there anyway to restrict access to a particular namespace?
The Problem:
I'm trying to restrict access to certain methods to just my NUnit tests - in JUnit I would do this by making the methods package access and having the test in the same package but under src/test/java instead of src/main/java.  How can I achieve something similar in C#?
Note: I can't make the methods internal because my tests are in a separate assembly - as is the NUnit convention - or is it?

A: C# does not have package or namespace level access - only assembly level - which is also known as internal access.
However, you can make your methods internal and use the InternalsVisibleTo attribute to expose them to your unit test assembly.
You may find it useful to read this post and this one.

A: There's nothing that's an exact equivalent. The internal keyword is close, but it limits by assembly, not by namespace.
If something is tagged with internal, it can only be accessed by code within the same assembly (dll, exe)

A: There's another way that's vastly different. You can use partial classes like so:

*

*File #1 = code under test. Written just like normal but with the 'partial' keyword

*File #2 = unit test, contains a nested class that is the actual unit test.

Nested classes have access to everything in their parent class (including private methods). As part of your build process (perhaps MSBuild or NAnt scripts), just don't compile the tests as part of the final assembly, and the code-under-test will work just fine.

A: you could restrict the methods to be visible only in its assembly by making them internal


text:
Q: Remotely Create a Button for an HTML page in JS I am trying to create a button remotely to go to a page. I can create the button, I just don't know how to add a "onclick" inside my button.
I have tried to appendChild() of the button, and that doesn't work. I have also tried to make the button an <a>, that also didn't work.
var btn = document.createElement("button");
var txt = document.createTextNode(name);
var lnk = document.createTextNode("fooPage");
btn.appendChild(txt);
document.body.appendChild(btn);

A button should appear to take the user to a new page (marked by fooPage).

A: What you want to do is to put the button inside of an a.
You can then set the href attribute of the a tag with .setAttribute(attrName, attrValue).

var btn = document.createElement("button");
var txt = document.createTextNode("button");

// Create an 'a' element.
var lnk = document.createElement("a");

// Set the 'href' attribute of the 'a' element.
lnk.setAttribute("href", "https://example.com");

btn.appendChild(txt);

// Nest the button inside the a tag.
lnk.appendChild(btn);

// Add the a tag to the dom.
document.body.appendChild(lnk);

If instead of redirecting the user, you want to set the onclick attribute (or any other attribute) of a button (or any other element) for a different purpose, you could use .setAttribute on the btn element.
var btn = document.createElement("button");
btn.setAttribute("onclick", "alert('Hello, World!')");


text:
Q: Make the anchor address the upper left cell in active window when Excel Hyperlink to another tab is clicked I have an Excel workbook with a table of contents tab that has hyperlinks to other tabs and different locations on those tabs i.e. names and regions.
My question is, how can I get it to where no matter what hyperlink I click on, it will go to that tab and the cell will always appear in the upper left corner instead of the lower right.  Excel by default makes the target cell upper left in the active window, but this is not the case when the target cell is in the active window.
I am trying to make it easier for the end user so they will not have to keep scrolling to that section to get it in view.  Thank you in advance.

A: Slight Addition to: Excel-Hyperlink-Jump-to-cell-and-scroll-window
Place this code in your Table of Contents sheet.  Any Hyperlink on your ToC sheet will go to the tab, and scroll to the row and column of the hyperlinks destination.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    ActiveWindow.ScrollRow = ActiveCell.Row
    ActiveWindow.ScrollColumn = ActiveCell.Column
End Sub

A: When the user clicks a link and it sends them to a sheet, the cell that is linked to becomes the ActiveCell. If you include this in every cell that will be linked to, it will auto-scroll to the desired cell when the link is clicked.
Private Sub Worksheet_Activate()
    Application.Goto ActiveCell, True
End Sub

The only caveat would be that for occasions where a user might instead click on a cell manually with no intention of scrolling to that cell, it will do so next time the sheet is activated

A:
Insert -> Add HyperLink -> Same document (you can specified any cell)
If you mean Anchor in WorkSheet :-)

A: If you put this in the sheet activate event R40 will be the top left cell so perhaps you can work with that?
Private Sub Worksheet_Activate()
    Application.Goto Range("R40"), True
End Sub

To take a stage further, this would work if your hyperlinked cells all contained sheet name ! cell address , e.g. Sheet2!R40. The code goes in the sheet module.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

Dim v

v = Split(Replace(Target.SubAddress, "'", ""), "!")
Application.Goto Sheets(v(0)).Range(v(1)), True

End Sub

A: If you understand how to use VBA with events, this should do what you want.
It includes a defense against sheets with spaces in them.
Sub JumpToPostion()
Dim WS As Worksheet, CellAddress As String
    Set WS = Sheet2
    CellAddress = "z100"

    Application.Goto Range(FixSheet(WS.Name) & "!" & CellAddress), Scroll:=True

End Sub

Private Function FixSheet(txt As String) As String
    If InStr(1, txt, " ") > 0 Then
        FixSheet = "'" & txt & "'"
    Else
        FixSheet = txt
    End If

End Function


text:
Q: Javascript history.back() causes firefox warning
Possible Duplicate:
Prevent Back button from showing POST confirmation alert

I have used the history.back(1) function of javascript to redirect users to the previous page.  I have linked this function to my back button.  It works, but when I click the back button a JS alert warns:

"To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier."

I don't want to show this alert.  How can I remove this alert or use another function that will not trigger this alert?

A: Whenever you leave a page, store that link in some cookie.  On target, instead of using history.back(1), use location.href=extractLinkFromCookie();.
function extractLinkFromCookie()
{
//some mechanism to read previous link from cookie
}


text:
Q: django facebook how to redirect back to previous page I am using the django facebook app, how do I get the user redirected back to previous page after login ?
I tried to use the "next" hidden input box, but that did not work .
<input type = "hidden" name = "next" value = "{{ request.GET.next }}" />

A: from the Django-facebook docs:
In settings.py you can set
FACEBOOK_LOGIN_DEFAULT_REDIRECT = "/whatever/"
to change the default-redirect.
edit
Another way is to subclass the facebook-app's custom backend like so (excerpt from the docs):
from django_facebook.registration_backends import FacebookRegistrationBackend

class CustomBackend(FacebookRegistrationBackend):
    def post_connect(action):
        # go as crazy as you want, just be sure to return a response
        response = HttpRedirect('/something/')
        if action is CONNECT_ACTIONS.LOGIN:
            response = HttpRedirect('/')
        return response

post_connect handles the redirect after connecting.


text:
Q: swfobject : how to add html title attribute to object (flash) I use swfobject.js file to embed flash content onto my website. How does one add the html title attribute to the flash-object embed through it.
Since, some of the browsers do show the title of the object on mouseover or in status, as a tooltip or in browser status. [ Eg. IE6 and Opera ]
Please help
Anita

A: You can pass in variables to a Flash file, and enable the tooltip in a cross-platform way.
so.addVariable("var", "value");

Get the value from DOM:
document.title

So:
var mytitle;
var = document.title;
so.addVariable("mytitle", mytitle);

A: Using SWFObject 2.2
var attributes = {
   title: document.title
};
swfobject.embedSWF("mymovie.swf", //URL for SWF file
                   "mytargetdiv", //Target element
                   "550",         //SWF width
                   "400",         //SWF height
                   "9",           //Minimum required version of Flash Player
                   false,         //Path to ExpressInstall SWF (if desired)
                   false,         //Flashvars (if desired)
                   false,         //Parameters (if desired)
                   attributes);   //Attributes (if desired)

This assumes your <title> element is placed before your <script> element in your page's markup.


text:
Q: Enlive - extract original HTML Is it possible to retrieve the original HTML (with its quirks and formatting) using enlive selectors?
(def data "

some text
 some more text

")
(apply str
    (enlive/emit* (enlive/select (enlive/html-snippet data)
                                 [:.foo :> enlive/any-node])))

=> "
some text
 some more text
"

In this example, enlive has transformed the
 tag into a self-closing tag, unlike the original input snippet.
I suspect that enlive is transforming it into a hiccup-like list of tags, such that the original information is unfortunately lost.

A: Your suspicion is correct, enlive consumes this information in it's efforts to provide a consistent abstraction over the HTML. I don't think this was a feature it was designed to offer.

A: Although this is perhaps only tangentially related, if you use "append" you can preserve information (such as comments) that would otherwise be thrown out by net.cgrand.enlive-html/html-resource
https://github.com/cgrand/enlive/wiki/Table-and-Layout-Tutorial%2C-Part-3%3A-Simple-Transformations

jcrit.server=> (pprint
             (transform layout [:#wrapper]
                        (append page-content)))
({:tag :html,
     {:tag :div,
      :attrs {:id "wrapper"},
      :content
      ("\n       "
       {:type :comment, :data "body"}   ; <<== Still there.
       "\n    "
       {:tag :p, :content ("Hi, mom!")})}
     "\n")}
   "\n\n")})


text:
Q: Playing audio from data:url google chrome mobile I use this code to generate a audio element from byte , it create a simple wav sound , I am able to play that in google chrome or firefox of DESKTOP , but when I want to play that in Google Chrome Mobile , it play nothing , where is the problem , I am able to play wav file easly but I am not able to play music from binary data in google chrome mobile :
<!DOCTYPE html>

        <title>Explosion Generator</title>

A: This is most certainly a bug.  Any time that you have it working on desktop and it fails to work on Chrome for Android that it is 99.5% likely to be a bug.
I have raised the bug here: https://code.google.com/p/chromium/issues/detail?id=253466 with a demo of the error here: http://jsbin.com/ajocid/latest
There is another solution on the desktop to encode the audio into a Blob and play that, unfortunately that does not work either on Chrome for Android and needs to be fixed.
The best you can currently hope for until the two bugs are fixed is to upload this to a server and play it from there.


text:
Q: Using auto in output parameter Is there a way to use auto keyword in this scenario:
void foo(bar& output){
    output = bar();
}

int main(){
   //Imaginary code
   auto a;
   foo(a);
}

Of course, it impossible to know what type of a. So, the solution should be to merge them in one sentence in a way or another. Is this available?

A: bar foo()
{
    return bar{};
}

int main()
{
    auto a = foo();
}

All the modern compilers will do copy-elision, there will be no copies at all.

A: It looks like you are wanting to default-initialize an object of the type a given function expects as an argument.
You can't do this with auto, but you could write a trait to extract the type a function expects, then use that to declare your variable:
namespace detail {
    //expects the argument number and a function type
    template <std::size_t N, typename Func>
    struct arg_n;

    //does all the work
    template <std::size_t N, typename Ret, typename... Args>
    struct arg_n <N, Ret (Args...)> {
        using type = std::remove_reference_t<
                         std::tuple_element_t<N, std::tuple<Args...>>
                     >;
    };
}

//helper to make usage neater
template <std::size_t N, typename Func>
using arg_n = typename detail::arg_n<N, Func>::type;

Then you use it like so:
//type of the first argument expected by foo
arg_n<0,decltype(foo)> a{};
foo(a);

Of course, as soon as you overload the function this all fails horribly.


text:
Q: Assigning service principal to azure MSI cluster I'm trying to deploy an app to an Azure cluster from a .gitlab-ci.yml. My cluster is currently using managed identities so I can't do that. I tried to add a new service principal in order to use credentials from the CI using:
az aks update-credentials \
--resource-group <> \
--name <> \
--reset-service-principal \
--service-principal <> \
--client-secret <>

However, I get the following error:

(BadRequest) Updating service principal profile is not allowed on MSI cluster.
Code: BadRequest
Message: Updating service principal profile is not allowed on MSI cluster.

What should I do?

A: As you are currently using managed identities make sure to assign role and scopes to this service principal.
I agree with Thomas check whether you have Enabled RBAC deploy to your cluster.
To assign role and scopes to the service principal please try the below command mentioned in this MsDoc
az ad sp create-for-rbac [--cert]
                         [--create-cert]
                         [--display-name]
                         [--keyvault]
                         [--role]
                         [--scopes]
                         [--sdk-auth {false, true}]
                         [--skip-assignment{false,true}]
                         [--years]

You can also make use of az role assignment create to create role assignments
Make sure for --client-secret using azure bash terminal use ${SP_SECRET@Q}.
To know more in detail please refer below link:
Update service principal key authorization for Azure Kubernetes Service (opsmx.com) by Yugandhar Kumar Pidugu


text:
Q: Large Javascript Slowing Down Google Chrome Extension I'm messing around with making my first Google Chrome Extension - A very simple one that basically replaces text on a specific page.
The problem is, the number of text that it searches & replaces is very large, so it's taking around 30-40 seconds to display each page.
So everything works OK, but I have this code:

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("Christian Bethancourt", "g"), "Christian Bethancourt - Canadians");
document.body.innerHTML = document.body.innerHTML.replace(new RegExp("Kris Bryant", "g"), "Kris Bryant - Canadians");

But there are approximately 200 lines that it goes through to search. I tried minifying the script but it didn't do much.
Is there any better way to do this? Or a way to speed things up?
(For those wondering, it's for a Fantasy Baseball league that has full minors - so this would replace the prospects name with their name & team owner in yahoo's fantasy baseball pages)
Thanks!


text:
Q: Maximum number of columns / values you can INSERT INTO a table - mysql Does anybody know what's the maximum number of columns/values you can insert into a table (mysql)? I get an error for... IDK... 20 columns/values? (yes, #_of_col = #no_of_val)
INSERT INTO comenzi (a,b,c,d,e,f,...)
VALUES (1,2,3,4,5,6,...)

A: The hard limit is 4096 columns per table, with a maximum row size of 65,535 bytes (Source: MySQL Documentation).

A: You can have more than 20 columns in a table so I don't think that is your problem.
Most likely you have the wrong number of columns in your values list or one of your column names is a keyword.
You said you've already checked that number of values is correct. In my experience counting 20 things by hand is very difficult so you might want to double-check that you've counted correctly.
But assuming that isn't the problem then I'd guess that it's probably because one of your column names is a reserved keyword. Surrounding your column names with backticks prevents them being parsed incorrectly:
INSERT INTO comenzi (`a`, `b`, `c`, `d`, `e`, `f`, ...)
VALUES (1, 2, 3, 4, 5, 6, ...)

You should also make sure that if you have any strings in your value list that they are quoted and properly escaped if necessary.


text:
Q: Cor em uma consulta SQL Gostaria de colocar uma com em uma consulta SQL por exemplo:
wp_usermeta.meta_key = 'first_name' or wp_usermeta.meta_key ='last_name'

Gostaria de colocar vermelho aqui 'last_name' é possível?
Segue o código da consulta completo:
$sql = ("select DISTINCT ".TABLE_PREFIX.DB_USERTABLE.".".DB_USERTABLE_USERID." userid, (select REPLACE(Group_concat(wp_usermeta.meta_value),',',' ') as full_name from wp_users left join wp_usermeta on wp_users.ID = wp_usermeta.user_id where (wp_usermeta.meta_key = 'first_name' or wp_usermeta.meta_key ='last_name') and wp_users.ID = userid) username, ".TABLE_PREFIX.DB_USERTABLE.".user_nicename link, wp_usermeta.meta_value avatar, cometchat_status.lastactivity lastactivity, cometchat_status.status, cometchat_status.message, cometchat_status.isdevice from ".TABLE_PREFIX.DB_USERTABLE." left join wp_usermeta on ".TABLE_PREFIX.DB_USERTABLE.".".DB_USERTABLE_USERID." = wp_usermeta.user_id left join cometchat_status on ".TABLE_PREFIX.DB_USERTABLE.".".DB_USERTABLE_USERID." = cometchat_status.userid ".$offlinecondition." and (wp_usermeta.meta_key = 'user_avatar' ) order by username asc");

A: Na tag HTML que você estiver mostrando o resultado, basta colocar a propriedade color: red no style. Por exemplo, digamos que a tag que exiba o valor seja uma <td> de uma <table>:
<td style="color:red;">


text:
Q: pysnmp cmdGen - How to feed OIDs from a variable I have a list of SNMP OIDs I want to return but I cannot substitute the variable for the OIDs in the command. I have even tried wrapping the variable in an eval, and combining with ObjectType and ObjectIdentity with no success.
I have taken the base config template from here and edited for my purposes.
Here's the block of config in full:
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
    cmdgen.UsmUserData(user,
                    authKey=authKe,
                    privKey=privKe,
                    authProtocol=authProto,
                    privProtocol=privProto,
                    securityEngineId=None
            ),
    cmdgen.UdpTransportTarget((sHost, 161)),
    (_OID),

In place of (_OID), the following substitutions all work:
    cmdgen.MibVariable('1.3.6.1.2.1.1.1.0'),
    cmdgen.MibVariable('1.3.6.1.2.1.1.6.0'),
    cmdgen.MibVariable('1.3.6.1.2.1.1.5.0'),
    cmdgen.MibVariable('1.3.6.1.2.1.1.4.0'),
    cmdgen.MibVariable(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)),
    '1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.4.0', '1.3.6.1.2.1.1.5.0', '1.3.6.1.2.1.1.6.0',

All the above can be added as a complete block, individually, or any other combination. The _OID Variable takes a list of OIDs and converts it to a string to look like this: '1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.4.0', '1.3.6.1.2.1.1.5.0', '1.3.6.1.2.1.1.6.0',. I suspect there may even be a way to use the list directly.
I know I can wrap getCmd in a for to do it and, so long as I instantiate the engine beforehand, there's is little performance hit, as documented here, but I like the cmdgen method as it is clean, and I suspect wrapping this would be expensive.
How can I use the _OID variable to dynamically set the OIDs required?
pysnmp Version 4.4.4

A: If you have your positional arguments in a sequence, just use the * operator to unpack them into function's positional arguments.
_oids = ('1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.4.0',
         '1.3.6.1.2.1.1.5.0', '1.3.6.1.2.1.1.6.0')

cmdGen.getCmd(
    cmdgen.UsmUserData(
        user,
        authKey=authKe,
        privKey=privKe,
        authProtocol=authProto,
        privProtocol=privProto
    ),
    cmdgen.UdpTransportTarget((sHost, 161)),
    *[ObjectType(ObjectIdentity(oid)) for oid in _oids]
)


text:
Q: Unresolved external symbol,confused
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

I have a median function that finds a median from elements of the array as follows
median.h
template <class N>
N median (N*,size_t);

median.cpp
#include "median.h"
template <class N>
 N median (N* numbers,size_t size){
    size_t mid = size/2;
    return size % 2 == 0? (numbers[mid] + numbers[mid-1])/2 : numbers[mid];
}

main
#include <iostream>
#include "median.h"

using namespace std;

int main(){
    double Numbers [] = {1,2,3,4,5,6,7};

    size_t size = sizeof(Numbers)/sizeof(*Numbers);

    double med = median(Numbers,size);
    cout << med << endl;
    return 0;

}

But I get the following error
main.obj : error LNK2019: unresolved external symbol "double __cdecl median<double>(double *,unsigned int)" (??$median@N@@YANPANI@Z) referenced in function _main

A: Templates should instantiated by compiler before they used. In median.h you have declaration of median template, and in media.cpp you have its implementation but you don't use it in that file, so template won't instantiated in that file. On other side on main.cpp you try to instantiate template but there is no implementation, just declaration! So compiler will fail to instantiate template's implementation and that's the cause of your error. Just move implementation to median.h or instantiate the template in median.cpp by using:
template double median<double>(double*, size_t);

A: You can either put an #include "median.cpp" into your main or move the implementation of the template into the header file median.h


text:
Q: Getting metabox value within a shortcode? Is it possible to get page's metabox value within shortcode that is executed on that page?
Scenario:

*

*I have a sidebar metabox for every page.

*I have some kind of custom
gallery shortcode.

My gallery shortcode outputs 600x200 images (I'm using timthumb here).
BUT I want it to display 900x300 if there's no sidebar.
Normally I'd use:
$sidebar = get_post_meta($post->ID, 'metabox_sidebar', true);
   if($sidebar == "true") { do something }
   else { do something else }

But get_post_meta returns nothing within the shortcode body.

A: $post is outside the scope of your shortcode function, you have to globalize it first:
global $post;
$sidebar = get_post_meta($post->ID, 'metabox_sidebar', true);


text:
Q: Working of ring modulator I am having trouble understanding how this ring modulator works i.e. how it multiplies the input & carrier to give us appropriate output? Any help or guide will bedeeply appreciated.
 Reference - http://en.wikipedia.org/wiki/Ring_modulation

A: The use of "multiply" in this instance refers to that when a diode is switched OFF and is, therefore, blocking a signal, that's equivalent to multiplying the signal by zero, and when it's switched ON and the signal is allowed to pass, that's equivalent to multiplying the signal by 1.


text:
Q: How to mock angular2 platform-browser Title component for testing purpose I am writing unit tests for Angular 2 component with Jasmine. I would like to test if my document title has been set to a specific value when my component is instantiated.
Here is my component
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: `cx-account`,
  templateUrl: `app/account/account.component.html`,
})
export class AccountComponent {
  public constructor(titleService: Title) {
    titleService.setTitle(`Account`);
  }
}

Here what I have written for testing, but it is not working. titleService.getTitle() gives me Karma debug runner page title.
import { TestBed } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';
import { AccountComponent } from './account.component';

describe(`AppComponent`, () => {
  const titleService: Title = new Title();

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AccountComponent],
      providers: [{ provide: Title }],
    });
  });

  it(`Title should be "Account"`, () => {
    expect(titleService.getTitle()).toBe(`Account`);
  });
});

Karma output is :

Error: Expected 'Karma DEBUG RUNNER' to be 'Account'.

A: I finally found a solution to my problem. I used the TestBed to get the service I have injected. Then use that service to get the page Title in the current Test context.
Here is my new Code
import { TestBed } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';
import { AccountComponent } from './account.component';

describe(`AccountComponent`, () => {
  let titleService: Title;
  let fixture: any;
  let component: AccountComponent;

  beforeEach(async (() => {
    TestBed.configureTestingModule({
      declarations: [AccountComponent],
      providers: [Title],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AccountComponent);

    // Access the dependency injected component instance
    component = fixture.componentInstance;
  });

  it(`should instantiate component`, () => {
    expect(component instanceof AccountComponent).toBe(true, `should create AccountComponent`);
  });

  it(`Page title should be "Account"`, () => {
    titleService = TestBed.get(Title);

    expect(titleService.getTitle()).toBe(`Account`);
  });
});


text:
Q: Rails 3 script to create model I am trying to create a runner script to build a model. The model is this:
class Day < ActiveRecord::Base
  has_many :slots
  attr_accessible  :available, :day_date, :venue
end

class Slot < ActiveRecord::Base
  belongs_to :day
end

I would like to make 100 blank Days with 9 Slots for each Day. This is runner script load_days.rb
Day.transaction do
  (1..100).each do |i|
   days = Date.today+i
   Day.create( :available => "Available", :venue => "Pitch_1", :day_date => days )
   (1..9).each to |j|
      hours = days.hours+j
      id = Day.id
      Slot.create ( :time_slot => hours , :day_id => id )
  end
 end
end

I am getting the following error:
script/load_days.rb:8: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.'
      Slot.create ( :time_slot => hours , :day_id => id )

A: You are calling .id on the Day class instead of the Day object you created, this should work:
Day.transaction do
  (1..100).each do |i|
   days = Date.today+i
   day = Day.create( :available => "Available", :venue => "Pitch_1", :day_date => days )
   (1..9).each to |j|
      hours = days.hours+j
      id = day.id
      Slot.create ( :time_slot => hours , :day_id => id )
  end
 end
end


text:
Q: Maclaurin series for $x^6 \cdot e^{-x}$ I am being asked to find a Maclaurin series for $x^6 \cdot e^{-x}$ manually for a homework question and am being asked to do it via a table:
http://www.webassign.net/scalcet/11-10-030.gif
I have no idea how to approach this question. I don't want the answer (I need to DIY) but does anyone have any tips on how to actually go about solving this?

A: It's not too hard to build it from other series.  Your table has the series for $e^x$, so it's a simple matter to change all the $x$'s to $-x$'s and you have the series for $e^{-x}$.


text:
Q: Cannot resolve all parameters for AppPage in app.page.ts (?) Here's the code for my AppComponent -- note that I'm calling it AppPage because it will evolve into a "smart" component later:

import { Component } from '@angular/core';
import { AuthService } from '@app/core';

@Component({
  selector: 'slctr-root',
  template: `<router-outlet></router-outlet>`
})
export class AppPage {
  constructor(private authService: AuthService) {
    authService.handleAuthentication();
  }
}

In WebStorm, @Component is underlined with the following error: Cannot resolve all parameters for AppPage in app.page.ts (?)
My tsconfig.json file has "emitDecoratorMetadata": true and "lib": [ "es2017", "dom" ] and the app does build correctly.
What am I missing?
Update: Showing CoreModule and AppModule code:

@NgModule({
  imports: [ CommonModule ],
  declarations: [LandingPageComponent],
  providers: [
    // App singleton services
    AuthService
  ],
  exports: [
    // 3rd party libraries
    // Components
    LandingPageComponent
  ]
})
export class CoreModule {
  // make sure CoreModule is imported only by one NgModule: the AppModule
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error('CoreModule is already loaded. Please import it in the AppModule only.');
    }
  }
}

@NgModule({
  declarations: [
    AppPage
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CoreModule
  ],
  providers: [],
  bootstrap: [AppPage]
})
export class AppModule {
}

Update: Adding AuthService code:

import { Injectable } from '@angular/core';
import { environment } from '@env/environment';
import * as auth0 from 'auth0-js';

@Injectable()
export class AuthService {

  auth0 = new auth0.WebAuth({
    clientID: environment.auth0.clientId,
    domain: environment.auth0.domain,
    responseType: 'token id_token',
    audience: environment.auth0.audience,
    redirectUri: environment.auth0.redirectUri,
    scope: 'openid email profile'
  });

  public static loggedIn(): boolean {
    // Check whether the current time is past the access token's expiry time
    return new Date().getTime() < JSON.parse(localStorage.getItem('expires_at'));
  }

  public login(): void {
    this.auth0.authorize({});
  }

  public handleAuthentication(): void {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        // Set the time that the access token will expire at
        localStorage.setItem('expires_at', JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime()));
        localStorage.setItem('id_token', authResult.idToken);
        // Route to
      } else if (err) {
        console.log(err);
      }
    });
  }
}

A: Looks like this is a known issue that will be fixed in Angular v5.1.0: https://github.com/angular/angular/issues/16382
Update, Dec. 7, 2017: I confirm, this was fixed in v5.1.0


text:
Q: Elasticsearch profile api in python library Elasticsearch has a very useful feature called profile API. That is you can get very useful information on the queries performed. I am using the python elasticsearch library to perform the queries and want to be able to get those information back but I don't see anywhere in the docs that this is possible. Have you managed to do it someway?

A: adding profile="true" to the body did the trick. In my opinion this should be an argument like size etc in the search method of the Elasticsearch class


text:
Q: The equivalent definition of compactness I am studying topology. I know that compact is equivalent to closed and boundes in R^n.
That lead me to two questions.
Under what conditions:
(1)compact is equivalent to closed?
(2)compact is equivalent to closed and bounded?
What i know is that compact implies closed in Hausdorff space. But the converse doesnt holds. What assumption should be add to make those two statements become true?

A: A set is a compact set if and only if whatever net (that is, generalized sequence) you choose made up of elements from the set has a converging subnet with a limit belonging to the set.
A set is closed if and only if whatever converging net of elements of the set you choose, all its limits belong to the set. (Thanks to Andreas Blass for correcting me here)
In non-Hausdorff spaces, convergent nets (and sequences) can have more than one limit and the singletons of each of the limits of a given convergent net are not separated by neighborhoods and there are no other points whose singleton is not separated-by-neighborhoods from the singletons of the limits, that is given a convergent net each limit and no other point is an accumulation point of every set for which one of the other limit is an accumulation point.
That means that if a point belongs to a closed set then all the limits of a net of elements of the set converging to the given point must belong to the set, because all those limits are accumulation points for the closed set.
For a set to be compact instead it is only needed that some limit of the subnet belong to the set, so a compact set may not be closed.
All that tries to answer to your point (1). As to the point (2) read next.
Compactness is thought to impose some regularity to the behaviour of nets: a net of point of a compact set may not converge only because it is "made up" of more than one convergent net, so it is possible to extract, for each cluster point of the net, subnets converging to the cluster point.
Nets not converging for other reasons (that can exist only in non-compact sets) have no cluster point at all or are "made up" of convergent nets and nets with no cluster points.
In metric spaces, non-convergent sequences (sequences suffice, instead of nets, to characterize metric topology) can be further decomposed into two categories: non-converging fundamental sequences and non-converging non-fundamental sequences. If a set is complete all fundamental sequences of its elements converge to a point of the set; if a set is totally bounded there are no sequences that are non-fundamental. In finite-dimensional Euclidean spaces equipped with the ordinary topology, those last two things are equivalent to saying: if a set is closed all fundamental sequences of its elements converge to the set; if a set is bounded there are no sequences that are non-fundamental.
In topological linear space, the situation is analogous to that of the metric space, but here we need to revert back to using nets and not simply sequences.
Hope this help.

A: Recall that the general definition of compact is that every open cover has a finite subcover.
1) If the space is compact Hasdorff for example, but also in the trivial topology it's true (which normally isn't Hasdorff).
2) Obviously this has to be a metric space (since bounded requires a metric). It's well known that this is true in $\mathbb R^n$, but it's not in general true (for example there are infinit dimensional cases where it fail).

A: 1) In a compact Hausdorff space, any closed subset is compact. Obviously, it is a necessary condition ($X$ is a closed subset of $X$).
2) I don't know what a necessary condition would be, but in a finite dimensional normed vector space over a locally compact metric field $K$, then a closed and bounded set is compact.


text:
Q: Add "Related Questions" type search capability to search box I'd like a way to capture the "Related Questions" functionally when you ask a question in the search box at the top of the page. The only non-UI change I can think of is a specific search character(s) to tell the engine you're looking for a question title, so:
My proposal is to allow some specific character (such as "?") at the beginning of a search string to tell the engine you're looking for question titles. For instance, you might type the following in the search box:

?What do you need to program on a
  boat?

The results would be the same as if you'd typed the same question into the Title field of a new question and got "Related Questions" results.


text:
Q: Maven generated JAR file can't be deployed to Wildfly I am trying to build simple JAR to deploy to Wildfly, but whenever I try to deploy a lot of ClassNotFoundExceptions are thrown.
Only dependency I have is:
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-elasticsearch</artifactId>
  <version>2.0.2.RELEASE</version>
</dependency>

Build I am using for JAR is:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>2.4.3</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>shade</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <createDependencyReducedPom>false</createDependencyReducedPom>
  </configuration>
</plugin>

On the other hand, when I build the same project as WAR with:
<plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <archive>
    </archive>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <webResources>
      <resource>
        <directory>target/classes/META-INF</directory>
        <targetPath>WEB-INF</targetPath>
        <includes>
          <include>jboss-web.xml</include>
          <include>jboss-deployment-structure.xml</include>
        </includes>
      </resource>
    </webResources>
  </configuration>
</plugin>

everything works fine.
If I am not mistaken, this issue arises due to classloading.
What causes this difference in classloading and what can I do to avoid it?

A: You should deploy the jar that is generated by the shade plugin.
Once you are done with the clean install, you will get two jars. One is the regular jar with just the compiled classes of your source and the other jar (which will be created by the shade plugin) will have both your compiled classes as well as the classes from all your dependencies. This is the jar that you should deploy to your server. Since this jar will include the classes from all your dependency jars, you won't get any ClassNotFoundExceptions.


text:
Q: How to access different boot2docker instance in a virtual box I created two boot2docker instances in virtual box:
"boot2docker-vm" {8674bb87-b7ba-4179-9a09-c779611b1d9a}
"boot2docker-work" {53ffd6d6-2fc4-4c4f-b34e-c2f8dd87dd40}
They use different boot2docker.iso and different profiles.
The first vm is default, so if you run 'docker images' outside the virtual machine, it will use the first one by default.
But how can I access the second boot2docker "boot2docker-work", I know 'boot2docker ssh' works, but I want to run docker command outside the virtual machine.
I tried to set DOCKER_HOST and ca, cert for the second vm, but has the following errors:
An error occurred trying to connect: Get https://192.168.59.110:2376/v1.19/containers/json: dial tcp 192.168.59.110:2376: i/o timeout
Any ideas?

A: Ok,I find a solution.
when we create a VM, it will connect to a vboxnet with IP, if the ip is 192.168.59.103, it will add 192.168.59 to routing table
192.168.58         link#10            UC              3        0 vboxnet
then if we start the vm, 192.168.58.103 will be added to the routing table with right gateway:
192.168.58.103     8:0:27:1e:d1:24    UHLWI           0     3120 vboxnet    210
But if we create another vm with ip 192.168.58.104, then it will not have a right gateway:
192.168.58.104         link#10            UC              3        0 vboxnet
This makes the vm not working.
So my solution is that, use 192.168.59, or 192.168.60, then all problems gone.
But can anyone explain the routing mechanism of this?


text:
Q: Flutter build iOS - BoringSSL-GRPC/, undeclared 'SSL_get_secure_renegotiation_support'; 'GRPC_SHADOW_SSL_get_secure_renegotiation_support'? In trying to run a basic Flutter demo for Firebase Auth, running into this error output:
error: use of undeclared identifier
'SSL_get_secure_renegotiation_support'; did you mean 'GRPC_SHADOW_SSL_get_secure_renegotiation_support'?
      !(SSL_get_secure_renegotiation_support(ssl) &&
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        GRPC_SHADOW_SSL_get_secure_renegotiation_support

Steps I take, but still same error:

*

*Run flutter clean

*Run flutter build ios

*Follow steps for pod update from this post: https://stackoverflow.com/a/59073131/2162226
Full error output:
Running pod install...                                             20.8s
Running Xcode build...
(This is taking an unexpectedly lon
Xcode build done.                                           346.8s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳

/Users/gene/git/flutter_wifi/ios/Pods/BoringSSL-GRPC/src/ssl/t1_lib.cc:3319:9: error: use of undeclared identifier
'SSL_get_secure_renegotiation_support'; did you mean 'GRPC_SHADOW_SSL_get_secure_renegotiation_support'?
      !(SSL_get_secure_renegotiation_support(ssl) &&
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        GRPC_SHADOW_SSL_get_secure_renegotiation_support
In file included from /Users/gene/git/flutter_wifi/ios/Pods/BoringSSL-GRPC/src/ssl/t1_lib.cc:109:
/Users/gene/git/flutter_wifi/ios/Pods/BoringSSL-GRPC/src/include/openssl/ssl.h:4662:5: note: expanded from macro
'SSL_get_secure_renegotiation_support'
    SSL_get_secure_renegotiation_support
    ^
/Users/gene/git/flutter_wifi/ios/Pods/BoringSSL-GRPC/src/include/openssl/ssl.h:1590:20: note:
'GRPC_SHADOW_SSL_get_secure_renegotiation_support' declared here
OPENSSL_EXPORT int SSL_get_secure_renegotiation_support(const SSL *ssl);
                   ^
In file included from <built-in>:1:
/Users/gene/git/flutter_wifi/ios/Pods/Target Support Files/BoringSSL-GRPC/BoringSSL-GRPC-prefix.pch:2489:46: note:
expanded from macro 'SSL_get_secure_renegotiation_support'
#define SSL_get_secure_renegotiation_support GRPC_SHADOW_SSL_get_secure_renegotiation_support

A: Run this set of commands, where the pod commands are run from <flutterProject>\ios:
rm -rf ~/Library/Developer/Xcode/DerivedData/
rm -rf ~/Library/Caches/CocoaPods/
pod deintegrate
pod update

Thanks to post: https://stackoverflow.com/a/63997424/2162226
After doing this, then running flutter build ios, the error described in OP does not occur.
The other delta - though not sure if it's relevant, is that these changes are being applied to an SSD drive, upgraded from standard hard drive since OP.
Notice in the screenshot, the pod updates includes this line Installing BoringSSL-GRPC (0.0.7) , which I wonder if that's what in fact resolves the issue.

A: temporarily you can comment below lines in: ios/Pods/BoringSSL-GRPC/src/include/openssl/ssl.h
// #define SSL_CTX_set_tlsext_servername_callback \
    SSL_CTX_set_tlsext_servername_callback

// #define SSL_get_secure_renegotiation_support \
    SSL_get_secure_renegotiation_support

and rebuild it should work. It appears to be the firebase problem but I haven't found a permanent solution yet...

A: UPDATE Regarding Work-Around Solution
I am running the builds on a Mac Mini that can take up to 10 minutes to complete a build for the code at hand.  When I run flutter clean, it regenerates the ssl.h file and so those 2 lines need to be commented out again.
Having a "smart" text editor open to the code, where the text-editor shows you when the file system has changed (eg, Sublime), I can see that those lines are not commented once flutter build ios gets going.  Soon as I see that, I can comment out the lines once again and apparently if I do so in time the build will complete successfully.  Before I was letting the build fail after every flutter clean, and then commenting out those lines.  It really compounds the build time, so this additional consideration helps in working with the issue here.


text:
Q: Passing structs into a method and making assingments with scanf_S I am brand new to C and have begun a small project to practice and refine some basics.
Right now, I am having trouble assigning the name variable in stuct player. Specifically, I want to do this by passing the player struct into the method titleScreen and make the assignment there.
I want to do this with scanf, but nothing seems to work and I have hit a wall.
Is there something wrong with the way I have passed the pointer?
Please help
Thanks
typedef struct player {
    char name[20];
    int health;
} player;

void titleScreen(player *u) {
    printf("Press Enter: \n");
    scanf_s("Press Enter");
    printf("                                                |>>>\r\n"
         "                                                |\r\n"
         "                                            _  _|_  _\r\n"
         "                                           |;|_|;|_|;|\r\n"
         "                                           \\\\.    .  /\r\n"
         "                                            \\\\:  .  /\r\n"
         "                                             ||:   |\r\n"
         "                                             ||:.  |\r\n"
         "                                             ||:  .|\r\n"
         "                                             ||:   |       \\,/\r\n"
         "                                             ||: , |            /`\\\r\n"
         "                                             ||:   |\r\n"
         "                                             ||: . |\r\n"
         "              __                            _||_   |\r\n"
         "     ____--`~    '--~~__            __ ----~    ~`---,              ___\r\n"
         "-~--~                   ~---__ ,--~'                  ~~----_____-~'   `~----~~");
    printf("Name your hero: ");
    scanf_s(" %s", u->name); //Error occurs here

}

int main(int argc, char* argv[]) {
    player user;  //The User
    player *uPtr; //Pointer to user
    uPtr = &user;
    user.health = 100;

    titleScreen(uPtr);
    return 0;
}


text:
Q: How to convert an array into an object of specific format? Although it is a common problem but I couldn't find any lead to get the desired result. So here is the problem. I have the following array:
[
    [ 'a' ]
    [ 'a', 'b' ]
    [ 'a', 'c' ]
    [ 'a', 'c', 'd' ]
    [ 'a', 'c', 'd', 'e' ]
]

And what I want as an end result is an object like this:
{
  a: {
    b: {},
    c: { d: { e: {} } }
  }
}

I don't understand which approach would be better to get this result and how to achieve it.

A: You need a double reduce, one for the outer array and one for the keys and the nesting objects.

var data = [['a'], ['a', 'b'], ['a', 'c'], ['a', 'c', 'd'], ['a', 'c', 'd', 'e']],
    result = data.reduce((r, keys) => {
        keys.reduce((o, k) => o[k] = o[k] || {}, r);
        return r;
    }, {});

console.log(result);


text:
Q: How to execute system commands using raspberry pi pico I wanted to know if it is possible to run system commands on computer using raspberry pi pico when plugging it into the USB?
I've tried to do it like a normal C program  :
#include "pico/stdlib.h"
#include <stdlib.h>
#include <stdio.h>

int main() {
    printf("Start");
    stdio_init_all();
    char *cmd = "ls";
    system(cmd);
    return 0;

}

Although printf works very well, system functions (eg: readfile) doesn't work.
Is there any way that i could run some kind of actions on PC using pico usb output ?
Also, there is a project called picoducky which allows the pico to run commands on system but unfortunately it has written in python and i'm looking for c code.

A: Pico communicates with Pc using usb-to-serial and vice versa. Unless there is a server on Pc that interprets data send through serial than executes a cmd command, its not possible with the convetional way. However, you can make Pico emulate a USB HID device and send keystrokes. Check Tinyusb and this pico-superkey-board project

A: To be able to run system() function call in C in an embedded system, you need to know several things first:

*

*system() calls the user shell with the string passed as argument as a parameter.  Are you running an operating system at all?  A shell is normally an operating system component, and it is not normally present in many embedded systems.

*system() requires /bin/sh normally to work.  To run ls, you need in adition to have it (the ls command) installed.

You don't say what operating system you have in your Raspberry pi pico, but I'm afraid it is not linux (or any unix flavour) so probably all of this is forbidden to you.
Normally, the requirements to have a unix like environment in a small system impede to use a high technology operating system in such systems.  Linux requires large amoutns of memory (as there are in the normal raspberry pi, but not in the small versions), a large capacity storage system (bein a usb disk, flash memory card, etc.  but normally several Gb for a minimum installation)
In your case, 264kb of ram are very small to have a non-mmu handled microprocessor, capable of addressing virtual memory spaces.  Also 2Mb of flash gives you to write large programs, but not to install an operating system like linux.
Had you an emulator of system() you should be able to run other programs, but how?  A raspberry pi pico has space to run just one program (the one you write to the flash and nothing else)  Even if you write a kernel of a multitasking operating system, you would lack space to run filesystem stored programs, as you normally have limited access to the flash where programs are installed.


text:
Q: RowIndex returning null when trying to find I'm trying to find the rowIndex of the row that had the delete button that was clicked. However when the delete button is clicked it doesn't find the ID instead it returns null and errors out.
I have tried this:
$("#delete").on("click", function (e) {

        var row = $(this).closest("tr");
        row.remove();

        return false;
    });

but this solution doesn't post. Then I have also tried this:
<input type="submit" formaction="/LansingMileage/DeleteEntry/@item.RowIndex" value="Delete" name="Deletebtn" id="delete" />

which is causing my null issue.
My Controller:
[HttpPost]
       public ActionResult DeleteEntry(string rowIndex)
        {
           // try
            {
                //rowIndex = Request.Form["Deletebtn"];
                using (db)
                {
                    LansingMileage lansing = db.LansingMileages.Find(rowIndex);
                    db.LansingMileages.Remove(lansing);
                    db.SaveChanges();

                    LansingMileageViewModel model = new LansingMileageViewModel();
                    model.Records = db.LansingMileages.OrderBy(
                        //will need to change to a select all
                        //I'm not following the Take command
                        m => m.RowIndex).ToList();
                    model.SelectedLansingMileage = null;
                    model.DisplayMode = "";

                    return View("Index", model);
                }

            }
           // catch(Exception e)
            {
                ///Debug.WriteLine(e);
            }

        }

My Index.cshtml:

                Action
                Row ID
                Expense Month/Yr
                Travel Date
                Travel Type

            @foreach (var item in Model.Records)
            {
                if(Model.SelectedLansingMileage != null)
                {
                    if(item.RowIndex == Model.SelectedLansingMileage.RowIndex)
                    {
                        @:

                    }
                    else
                    {
                        @:

                    }
                }
                else
                {
                    @:

                }
                <input type="submit" formaction="/LansingMileage/DeleteEntry/@item.RowIndex" value="Delete" name="Deletebtn" id="delete" />
                @item.RowIndex
                @item.ExpMonthYr
                @item.TravelDate
                @item.TripType

                @:

                @*

                      Delete
                      @item.ExpMonthYr
                      @item.TravelDate
                      @item.TripType

*@
             }

The desired result is that when the user clicks on the delete button it removes the row and post to the database.

A: You can use the Select overload, something like:
@foreach (var item in Model.Select((item,index)=>new{item,index})
{

        <input type="submit" formaction="/LansingMileage/DeleteEntry/@item.index" value="Delete" name="Deletebtn" id="delete" />

}

Or do it manually like this:
@{int RowNo = 0;}
@foreach (var item in Model) {

    <input type="submit" formaction="/LansingMileage/DeleteEntry/@RowNo" value="Delete" name="Deletebtn" id="delete" />

Note: Why not use the @id for the row? If it's possible that rows are added while one is being deleted, bad things can happen.


text:
Q: How to connect Kafka consumer to Django app? Should I use a new thread for consumer or new process or new docker container? I have Django app which should consume Kafka messages and handle it with my handlers and existing models.
I use https://kafka-python.readthedocs.io/en/master/usage.html library.
What is the right way to connect KafkaConsumer to Django app. Should I user a new daemon thread? Or a new process? Or a separate docker container maybe?
Where to place the code (new Django app?) and how to start it automatically when Django app is ready. And how to update topics which it listen dynamically: should I kill old consumer and start new one each time in new thread?

A: Had a similar problem, what I did was create a custom Django command, then proceed to do add a handler method for your functionality.
In deployment, you can launch it as a sidecar container.
class Command(BaseCommand):
    def handle(self, *args, **options):

        consumer = kafka.KafkaConsumer(KAFKA_TOPIC_NAME,bootstrap_server=["localhost:9092"],group_id=KAFKA_CONSUMER_GROUP)

        for message in consumer:
            handler_method(message)

As a sidecar it would pick any messages in the consumer when it starts.

A: I know it's a late answer.
Regarding this issue you might give a try to Faust, it's a stream processing library and can be integrated with Django.
In Docker, initiate two different containers that share the same code base, except one of these containers runs a command which starts a Faust worker
version: '3.3'

services:
  backend_service: &backend_service
    container_name: your_container_name
    build:
      context: .
      dockerfile: Dockerfile
    image: backend_service_image
    volumes:
      - ./your_codebase:/your_container_codebase_path
    ports:
      - "8000:8000"
    env_file: .env

  kafka_consumer:
    <<: *backend_service
    image: kafka_consumer_image
    container_name: kafka_consumer
    command: faust -A <your_project_root>.kafka:app worker -l info

Notice in kafka_consumer container, a command is run: faust -A <your_project_root>.kafka:app worker -l info, where <your_project_root> is the namespace of the folder which holds the settings.py file.
In this folder create a file kafka.py, as following
import os
import faust
from django.conf import settings

# eventlet is used as a bridge to communicate with asyncio
os.environ.setdefault('FAUST_LOOP', 'eventlet')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<your_root_namespace>.settings')

app = faust.App('set_a_name_here', broker=f"kafka://{settings.KAFKA_URL}")

# Specify a topic name
new_topic = app.topic("topic_to_process")

# define a method to process the above topic
@app.agent(new_topic)
async def process_topic(stream):
    async for event in stream:
        ...  # process event

Bear in mind that this process is executed in async, so you might have issues when working with Django ORM, in order to properly implement a consumer which uses ORM you can use sync_to_async wrapper.
Or use it as a decorator:
# kafka.py
from asgiref.sync import sync_to_async

@sync_to_async
def _do_something(event):
    random_model_id = event.get('random_model_id')
    random_model = RandomModel.objects.get(id=random_model_id)

@app.agent(new_topic)
async def process_topic(stream):
    async for event in stream:
        await _do_something(event)

Then you can debug kafka_consumer container to check what is going on. To reflect the changes you need to restart the container.
If you are not using Docker, you need to install a supervisor and configure this command faust -A <your_project_root>.kafka:app worker -l info to run on your supervisord.conf file.


text:
Q: php sendmail doesn't work after I changed the router I'm running a web server that uses PHP sendmail function, which is directly connected to a router and after I replaced my old router to a new router it doesn't work anymore.
Old router - Cisco RV082 - regular firmware
New router - Netgear R7000 - DD-WRT v3.0-r30700M kongac
I tried with all ports open and firewalls off but still didn't work.
Please help.
Here is the part of the log.
Oct 11 is the working one and Oct 13 is not.
/var/log/mail.log
Oct 11 13:58:08 localhost sm-mta[3613]: STARTTLS=client, relay=aspmx.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-AES128-GCM-SHA256, bits=128/128
Oct 11 13:58:08 localhost sm-mta[3613]: u9BKw7pL003611: to=<joe@ctclogis.com>, ctladdr=<www-data@localhost.localdomain> (33/33), delay=00:00:01, xdelay=00:00:01, maile$
Oct 11 13:58:09 localhost sm-mta[3613]: u9BKw7pL003611: to=<export@ypusa21.com>, ctladdr=<www-data@localhost.localdomain> (33/33), delay=00:00:02, xdelay=00:00:02, mai$
Oct 11 13:58:09 localhost sm-mta[3613]: STARTTLS=client, relay=alt1.aspmx.l.google.com., version=TLSv1/SSLv3, verify=FAIL, cipher=ECDHE-RSA-AES128-GCM-SHA256, bits=128$
Oct 11 13:58:10 localhost sm-mta[3613]: u9BKw7pL003611: to=<joe@ctclogis.com>, ctladdr=<www-data@localhost.localdomain> (33/33), delay=00:00:03, xdelay=00:00:03, maile$

Oct 13 19:20:26 localhost sm-mta[6369]: u9E2KQ20006369: from=<>, size=2122, class=0, nrcpts=1, msgid=<201610140220.u9E2K13e006368@localhost.localdomain>, proto=ESMTP, $
Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9E2K13e006368: to=www-data, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31509, relay=[127.0.0.1] [127.0.0.1], dsn$
Oct 13 19:20:26 localhost sm-mta[6370]: u9E2KQ20006369: to=<www-data@localhost.localdomain>, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=32350, dsn=2.0.0, stat=$
Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9DM8URU004818: u9E2K13f006368: sender notify: Warning: could not send message for past 4 hours

A: Marc B is correct in his comment. This is not the best site for you to be asking this kind of question on. Try the Network Engineering Stack Exchange or something similar.
Now if this is a PHP issue then yes you have posted to the correct site but need to re-word your question to be more compliant. If this is the case have you double checked all the cautions from the PHP manual on the send mail function? From a programming stand point your error could be simply in how you are trying to send the emails. The old router may have just ignored your errors (incorrectly formatted messages) and sent stuff out anyway; from my experience this is not the case because your router usually has nothing to do with this except doing its job of routing or forwarding depending on your setup.
More specifically I'm trying to pick apart your log and I think on the PHP side of things you may have made a few errors.

Oct 13 19:20:26 localhost sm-mta[6369]: u9E2KQ20006369: from=<>, size=2122, class=0, nrcpts=1, msgid=<201610140220.u9E2K13e006368@localhost.localdomain>, proto=ESMTP, $

Your server didn't log a From email address on this line. In your PHP script using the mail function did you forget to set one?

Oct 13 19:20:26 localhost sm-msp-queue[6368]: u9E2K13e006368: to=www-data, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31509, relay=[127.0.0.1] [127.0.0.1], dsn$
  Oct 13 19:20:26 localhost sm-mta[6370]: u9E2KQ20006369: to=, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=32350, dsn=2.0.0, stat=$

I could be reading this wrong (again this is a programming site) but your mail relay is setup as your localhost. Why? Your old logs from the 11th show you using a google relay.
It seems that either in a PHP script your using to send the emails or your PHP configuration/ server itself has been mis-configured.

A: if you can ping remove server from your network, you should be able to send mail also, however verify the configuration from your new router to see if there is something preventing smtp port 25 out


text:
Q: Extract Text from Two-Column PDF with R I have a lot of PDFs which are in two-column format. I am using the pdftools package in R. Is there a way to read each PDF according to the two-column format without cropping each PDF individually?
Each PDF consists of selectable text, and the pdf_text function has no problem reading the text, the only issue is that it will read the first line of the first column, then proceed to the next column, instead of moving down the first column.
Thank you very much in advance for your help.

A: There is a much easier way to do this using tabulizer::extract_text(file) function.
It works with PDF text contained in a single column and PDF text contained in 2+ columns. Yes, it's that simple!

A: I'd the same problem. What I did was to get the most frequent space values for each of my pdfs pages and stored it into a Vector. Then I sliced it using that value.
library(pdftools)
src <- ""
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

QTD_COLUMNS <- 2
read_text <- function(text) {
  result <- ''
  #Get all index of " " from page.
  lstops <- gregexpr(pattern =" ",text)
  #Puts the index of the most frequents ' ' in a vector.
  stops <- as.integer(names(sort(table(unlist(lstops)),decreasing=TRUE)[1:2]))
  #Slice based in the specified number of colums (this can be improved)
  for(i in seq(1, QTD_COLUMNS, by=1))
  {
    temp_result <- sapply(text, function(x){
      start <- 1
      stop <-stops[i]
      if(i > 1)
        start <- stops[i-1] + 1
      if(i == QTD_COLUMNS)#last column, read until end.
        stop <- nchar(x)+1
      substr(x, start=start, stop=stop)
    }, USE.NAMES=FALSE)
    temp_result <- trim(temp_result)
    result <- append(result, temp_result)
  }
  result
}

txt <- pdf_text(src)
result <- ''
for (i in 1:length(txt)) {
  page <- txt[i]
  t1 <- unlist(strsplit(page, "\n"))
  maxSize <- max(nchar(t1))
  t1 <- paste0(t1,strrep(" ", maxSize-nchar(t1)))
  result = append(result,read_text(t1))
}
result


text:
Q: Extracting PCA components with sklearn I am using sklearn's PCA for dimensionality reduction on a large set of images. Once the PCA is fitted, I would like to see what the components look like.
One can do so by looking at the components_ attribute. Not realizing that was available, I did something else instead:
each_component = np.eye(total_components)
component_im_array = pca.inverse_transform(each_component)

for i in range(num_components):
   component_im = component_im_array[i, :].reshape(height, width)
   # do something with component_im

In other words, I create an image in the PCA space that has all features but 1 set to 0. By inversely transforming them, I should then get the image in the original space which, once transformed, can be expressed solely with that PCA component.
The following image shows the results. On the left is the component calculated using my method. On the right is pca.components_[i] directly. Additionally, with my method, most images are very similar (but they are different) while by accessing the components_ the images are very different as I would have expected
Is there a conceptual problem in my method? Clearly the components from pca.components_[i] are correct (or at least more correct) than the ones I'm getting. Thanks!

A: Components and inverse transform are two different things. The inverse transform maps the components back to the original image space
#Create a PCA model with two principal components
pca = PCA(2)
pca.fit(data)
#Get the components from transforming the original data.
scores = pca.transform(data)
# Reconstruct from the 2 dimensional scores
reconstruct = pca.inverse_transform(scores )
#The residual is the amount not explained by the first two components
residual=data-reconstruct

Thus you are inverse transforming the original data and not the components, and thus they are completely different. You almost never inverse_transform the orginal data. pca.components_ are the actual vectors representing the underlying axis used to project the data to the pca space.

A: The difference between grabbing the components_ and doing an inverse_transform on the identity matrix is that the latter adds in the empirical mean of each feature. I.e.:
def inverse_transform(self, X):
    return np.dot(X, self.components_) + self.mean_

where self.mean_ was estimated from the training set.


text:
Q: How do I change the name of a resampled column? I have a dataframe with the price fluctuations of the Nasdaq stock index every minute.
In trading it is important to take into account data on different time units (to know the short term, medium and long term trends...)
So I used the resample() method of Pandas to get a dataframe with the price in 5 minutes in addition to the original 1 minute:
df1m = pd.DataFrame({
'Time' : ['2022-01-11 09:30:00', '2022-01-11 09:31:00', '2022-01-11 09:32:00', '2022-01-11 09:33:00', '2022-01-11 09:34:00', '2022-01-11 09:35:00', '2022-01-11 09:36:00' , '2022-01-11 09:37:00' , '2022-01-11 09:38:00' ,
       '2022-01-11 09:39:00', '2022-01-11 09:40:00'],
'Price' : [1,2,3,4,5,6,7,8,9,10,11]})
df1m['Time'] = pd.to_datetime(df1m['Time'])
df1m.set_index(['Time'], inplace =True)

df5m = df1m.resample('5min').first()

I renamed the column names to 5min :
df5m.rename(columns={'Price' : 'Price5'})

Unfortunately the change of column names is no longer taken into account when the two dataframes (1 and 5 min) are put together:
df_1m_5m = pd.concat([df1m, df5m], axis=1)

How to rename definitively the columns created for the 5min data and avoid having twice the same column name for different data?

A: You can use:
df5m = df1m.resample('5min').first().add_suffix('5')
df_1m_5m = pd.concat([df1m, df5m], axis=1)

Output:
>>> df_1m_5m
                     Price  Price5
Time
2022-01-11 09:30:00      1     1.0
2022-01-11 09:31:00      2     NaN
2022-01-11 09:32:00      3     NaN
2022-01-11 09:33:00      4     NaN
2022-01-11 09:34:00      5     NaN
2022-01-11 09:35:00      6     6.0
2022-01-11 09:36:00      7     NaN
2022-01-11 09:37:00      8     NaN
2022-01-11 09:38:00      9     NaN
2022-01-11 09:39:00     10     NaN
2022-01-11 09:40:00     11    11.0

You forgot to reassign the result to your dataframe:
df5m = df5m.rename(columns={'Price' : 'Price5'})

# OR

df5m.rename(columns={'Price' : 'Price5'}, inplace=True)

Output:
>>> df5m
                     Price5
Time
2022-01-11 09:30:00       1
2022-01-11 09:35:00       6
2022-01-11 09:40:00      11

A: Believe your issue is you are missing option inplace=true in your rename. By default it's false, so it generates a copy of the DataFrame rather than editing your existing DataFrame. Setting it to true will edit your existing DataFrame df5m
df5m.rename(columns={'Price' : 'Price5'},inplace=True)

Output of df_1m_5m:
                     Price  Price5
Time
2022-01-11 09:30:00      1     1.0
2022-01-11 09:31:00      2     NaN
2022-01-11 09:32:00      3     NaN
2022-01-11 09:33:00      4     NaN
2022-01-11 09:34:00      5     NaN
2022-01-11 09:35:00      6     6.0
2022-01-11 09:36:00      7     NaN
2022-01-11 09:37:00      8     NaN
2022-01-11 09:38:00      9     NaN
2022-01-11 09:39:00     10     NaN
2022-01-11 09:40:00     11    11.0

A: Agree with Stephan and Corralien. You can also try this:
df1m['Price5'] = df1m.resample('5T').first()


text:
Q: Isomorphism from Natural numbers to the Odd Natural numbers Prove there exists an isomorphism from the semigroup of natural numbers under multiplication to the semigroup of odd natural numbers under multiplication.
An example would be helpful.

A: Here is some help.
The natural numbers under multiplication are generated by the set of primes and also have an identity.
How are the odd numbers generated?


text:
Q: WPF DataTrigger to display and hide grid column XAML I have an WPF application that contains a grid. The grid is split into 3 columns with the 3rd grid having zero width upon loading.
I have two datagrids in the other two columns. When the selected item in one of the datagrid changes the other datagrid changes it display values, i.e. a master detail template. This all works fine.
There is one value in the datagrid that if selected I wish this 3rd column to changes its width from zero to 2*. I don't know how to do this?
I wish to achieve this through XAML. I have been looking at data triggers & value converters. I written some code below quickly to test. I have read that setting the column to width=0 there is probably higher on the dependency property setting precedence list. Is there anyway to do this or will I need to use code behind?
 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="0"/>
    </Grid.ColumnDefinitions>

    <DataGrid Grid.Column="0"
              ItemsSource="{Binding OrderList}"
              SelectedItem="{Binding OrderSelected}"
              AutoGenerateColumns="True">
    </DataGrid>

    <TextBox Grid.Column="1" Text="{Binding OrderSelected.Name}">
    </TextBox>

    <Grid x:Name="columnHideSeek" Grid.Column="2" Background="Blue">
        <Grid.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding OrderSelected.Name}" Value="Mark">
                        <Setter Property="Grid.Width" Value="10"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
    </Grid>

</Grid>

A: Using the correct DataTrigger, this is totally possible. First, add the Trigger to the UI element that you want to change... the ColumnDefinition, not the Grid:
<ColumnDefinition>
    <ColumnDefinition.Style>
        <Style TargetType="{x:Type ColumnDefinition}">
            <Setter Property="Width" Value="10" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding OrderSelected.Name}" Value="Mark">
                    <Setter Property="Width" Value="2*" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ColumnDefinition.Style>
</ColumnDefinition>

Next, don't set the Width on the ColumnDefinition element, but in the Style instead. Otherwise the Width on the ColumnDefinition element will override the value set from the DataTrigger.


text:
Q: Is there a way to put a whole Random Forest into one graph instead the single estimators one for one? I tried to visualize the whole RandomForestClassifier rfclf
export_graphviz(rfclf, out_file='Graphs/rfclfWhole.dot',
                feature_names = x.columns,
                class_names = y,
                rounded = True, proportion = False,
                precision = 2, filled = True)

instead to do the following for visualizinig one tree of it as usual:
export_graphviz(rfclf.estimators_[5], out_file='Graphs/rfclfWhole.dot',
                feature_names = x.columns,
                class_names = y,
                rounded = True, proportion = False,
                precision = 2, filled = True)

and got

NotFittedError: This RandomForestClassifier instance is not fitted
  yet. Call 'fit' with appropriate arguments before using this method.

But I DO call rfclf.fit before


text:
Q: Scanning character in a while loop char player_select(void){

    char player = 'n';

    while(player == 'n'){
        printf("Select your player (X or O): ");
        scanf("%c\n", &player);

        if(player != 'X' && player != 'O'){
            printf("Invalid input. Try again.\n");
            player = 'n';
        }
    }

printf("Your character input is: %c\n", player);
exit(0);
return player;
}

I am getting some weird output here:
Select your player (X or O): X
Invalid input. Try again.
Select your player (X or O): i
Your character input is: X

A: Incorrect use of scanf()
// scanf("%c\n", &player);
scanf(" %c", &player);

The '\n' in "%c\n" does not do what you think.  '\n' tells scanf() to consume white-space like '\n' and ' ' until non-white-space occurs.  You input was not as described.
Since stdin is buffered, text by itself, will not typically get read until a '\n' follows.
It gets complicated to explain in detail why things failed.  So briefly, use " %c" instead of "%c\n".  Or better yet, use fgets().
buffer player[10];
fgets(ch, sizeof ch, stdin);
if(player[0] != 'X' && player[0] != 'O') { ...

A: I hope this will work for you.
I have removed the \n inside the scanf and i have added while(getchar()!='\n'); for emptying stdin.
char player_select(void){

char player = 'n';

while(player == 'n'){
    printf("Select your player (X or O): ");
    scanf("%c", &player);

    if(player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }
    while(getchar()!='\n');
}

This is the output:
Select your player (X or O): A
Invalid input. Try again.
Select your player (X or O): X
Your character input is: X

A: Try:
    if (scanf("%c\n", &player) == 1 && player != 'X' && player != 'O'){
        printf("Invalid input. Try again.\n");
        player = 'n';
    }

Bring scanf into the if, removing from your above code, and check its return value == 1.
You can try removing the \n from scanf mask if this won't suffice.


text:
Q: Back button text colour reverts to default I am having an issue in my app with a particular back button changing font colour for no apparent reason. I have been through all of my code and I can't see any reason for it, but when launching my app and segueing to the problem view controller, the text colour seems to be set to the default blue colour.
If I tap to go to a different tab and then go back to this view controller, then the font returns to the correct colour (white) and this is despite not having any code in viewWillAppear/Disappear viewDidAppear/Disappear.
The code I am using to set the navigation bar text colour is:
override func awakeFromNib() {
    var attributes = [NSForegroundColorAttributeName: UIColor.whiteColor(),NSFontAttributeName: UIFont(name: "Avenir", size: 24)!]
    self.navigationController?.navigationBar.titleTextAttributes = attributes
}

And this is in the view controller that is segued from when going to the view controller with the back button. I have tried adding this code into viewWillAppear() but even this doesn't make a difference.
Does anyone know why, on launch, my app doesn't set the back button text colour and requires a tab switch for it to update?

A: Please Try to  write same code in  view will apear method.Than  it should persist style to back button

A: I think this code will work
self.navigationController?.navigationBar.barTintColor = UIColor.someColor()
//This sets the background colour of the navigation bar

self.navigationController?.navigationBar.tintColor = UIColor.someColor()
// This sets the colour for navigation and bar button items

self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "someFont", size: 20)!,  NSForegroundColorAttributeName: UIColor.blackColor()]
//This sets the attributed text for the title of the navigation bar

UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont(name: "someFont", size: 17)!], forState: .Normal)
//And this sets the attributed text for the bar button item(s) on the navigation bar (So that includes the back button)

Call it in the viewWillAppear
I hope this works :)


text:
Q: value repeats in next loop function attribute_manager() {
$checkattr = $this->connection->query("SELECT * FROM attribute_grup");
while ($attrs = $checkattr->fetch_object()) {
    $id = $attrs->att_gr_id;
    $checkattrs = $this->connection->query("SELECT * FROM product_attribute WHERE att_group = $id");
    while ($values = $checkattrs->fetch_object()) {
            $valuez .= $values->att_name.', ';
    }

    $linkz_header = '

Attribute Titel

Optionen

Werte

';
                    $linkz .= '

'.$attrs->att_gr_name.'

                                id.'">Bearbeiten
                                id.'">Löschen

'.$valuez.'

';
}
return '
'.$linkz_header.$linkz.'
';

}
}

This is the result, as you can see the values from FARBE join with the values for Größe:

What is the proper way to solve this?

A: If I'm reading this correctly, You just need to initialize the variable in the initial loop...
while ($attrs = $checkattr->fetch_object()) {
    $id = $attrs->att_gr_id;
    $valuez = "";

That way it clears out for each iteration.

A: You need to reset the value of $valuez in each iteration.
while ($attrs = $checkattr->fetch_object()) {
    $valuez = ""; // Add this line
    $id = $attrs->att_gr_id;


text:
Q: adding a lot of custom nodes to scene takes a long time to load I am building a scenekit app however I am having issues with some of the finer details. I created a scene and I am adding custom geometry to it and it works fine until the number of nodes gets to about 100. It is ideal to add a large number of nodes to a scene and is there a cleaner way to do it?
    for i in 0..<modelArr!.count {
        let model = modelArr![i]

        let pos: [SCNVector3] = Parser.loadPosition(model)
        let norm:[SCNVector3] = Parser.loadNormals(model)
        let ind:[CInt] = Parser.loadIndices(model)

        let src = SCNGeometrySource(vertices: pos, count: pos.count)
        let norSrc = SCNGeometrySource(normals: norm, count: norm.count)

        //let indexData = NSData(bytes: ind, length: sizeof(CInt) * ind.count)
        let indexData = NSData(bytes: Array<CInt>(0..<CInt(ind.count)),
                               length: ind.count * sizeof(Float))

        let element = SCNGeometryElement(data: indexData,
                                         primitiveType: .Triangles,
                                         primitiveCount: pos.count / 3,
                                         bytesPerIndex: sizeof(Float))

        let geo = SCNGeometry(sources: [src, norSrc], elements: [element])
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.redColor()
        material.specular.contents = UIColor.whiteColor()

        let cubeNode = SCNNode(geometry: geo)
        cubeNode.geometry?.firstMaterial = material
        emptyNode.addChildNode(cubeNode)
    }
    scn.rootNode.addChildNode(emptyNode)
}

I have a large number of indices, normals, and positions.

A: One thing you can do is split up the load using Grand Central Dispatch, and dispatch_apply (to distribute the computation) and a serial dispatch queue (to update emptyNode with each new cubeNode. A thorough explanation of this approach (using a different problem space, but still trying to speed up an expensive operation) can be found in this answer.
What will help a lot is to do the loading in a separate utility program. After you've created your scene, archive it. Embed that scene in your user-facing program. Unarchiving the scene is much faster than creating it from scratch.


text:
Q: setInterval in Javascript Running To Fast I have seen this sort of information floating around but I cannot figure out why my particular setup is flashing through the function so fast.
Here is what I am trying to do:
I have squares on a page that I need to glow in order, but 500 milliseconds apart. I store the jQuery identifier in an array and cycle through it.
function glow(source) {// glows
  $(source).addClass("square-active")
  setTimeout(function() {
    $(source).removeClass("square-active");
  }, 500);
}

function iterator() {
  var y = 0;
    setTimeout(function() {
     for (var t=0; t<newComp.slice(0, numTurn).length; t++) {
          glow(squareArr[newComp[t]].div)
       y = y + 1
}
    }, 500 * y)
      }

I know that the squares are being iterated through properly because I have that logged to the console for verification purposes. I can see the squares flash in order, but it is insanely fast.
When I attempt to wrap the glow() function in setInterval I do not believe it works either.
What am I doing wrong?

A: You need to move your setTimeout to inside of the for loop
function iterator() {
  var y = 0;
  for (var t=0; t<newComp.slice(0, numTurn).length; t++) {
setTimeout(function() {
        glow(squareArr[newComp[t]].div)
       y = y + 1
},500);
      }

A: Basically you want to schedule (using setTimeout) a set of functions which capture the index of each square, 500 msec apart to highlight the square.
function iterator() {
    for (let t=0; t<newComp.slice(0, numTurn).length; t++) {
        setTimeout(function() {
             glow(squareArr[newComp[t]].div)
        }, 500 * t)
    }
}

uses the let keyword to capture the value of t in the lexical scope record of the nested function which calls glow. If you want to reinstate the y variable go ahead - it just seems to have the same value as t.
Usage of let is important. See the frequently asked question JavaScript closure inside loops – simple practical example for ways of capturing the value of loop variables within a closure without using let.

A: That is because everytime the glow() function is called, a new instance of the anonymous function() is created which is completely different from the previous instance, it so happens that just when the timeout of instance x of the anonymous function finishes, instance y also completes, which means you have newComp.slice(0, numTurn).length anonymous functions each with their own timeout of 500ms creating a very fast glow.


text:
Q: Error when uploading large file with Paperclip and AWS My rails app on heroku allows a user to upload a photo to be stored on amazon web services S3 using paperclip.
When the photo's size is above 1.5MB the app seems to time out. What is the best way to solve this problem?
Here is the stack trace if that helps?
E, [2013-10-07T14:15:57.018396 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.12/lib/action_dispatch/middleware/static.rb:62:in `call'
2013-10-07T14:15:57.018974+00:00 app[web.2]: E, [2013-10-07T14:15:57.018430 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in `forward'
2013-10-07T14:15:57.018974+00:00 app[web.2]: E, [2013-10-07T14:15:57.018772 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:143:in `pass'
2013-10-07T14:15:57.018974+00:00 app[web.2]: E, [2013-10-07T14:15:57.018946 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:71:in `call!'
2013-10-07T14:15:57.019152+00:00 app[web.2]: E, [2013-10-07T14:15:57.018983 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in `call'
2013-10-07T14:15:57.019152+00:00 app[web.2]: E, [2013-10-07T14:15:57.019100 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/airbrake-3.1.12/lib/airbrake/user_informer.rb:16:in `_call'
2013-10-07T14:15:57.019279+00:00 app[web.2]: E, [2013-10-07T14:15:57.019147 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/airbrake-3.1.12/lib/airbrake/user_informer.rb:12:in `call'
2013-10-07T14:15:57.019279+00:00 app[web.2]: E, [2013-10-07T14:15:57.019183 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-timeout-0.0.4/lib/rack/timeout.rb:16:in `block in call'
2013-10-07T14:15:57.019279+00:00 app[web.2]: E, [2013-10-07T14:15:57.019217 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-timeout-0.0.4/lib/rack/timeout.rb:16:in `call'
2013-10-07T14:15:57.019279+00:00 app[web.2]: E, [2013-10-07T14:15:57.019252 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.12/lib/rails/engine.rb:479:in `call'
2013-10-07T14:15:57.019469+00:00 app[web.2]: E, [2013-10-07T14:15:57.019326 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.12/lib/rails/application.rb:223:in `call'
2013-10-07T14:15:57.019469+00:00 app[web.2]: E, [2013-10-07T14:15:57.019369 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.12/lib/rails/railtie/configurable.rb:30:in `method_missing'
2013-10-07T14:15:57.019648+00:00 app[web.2]: E, [2013-10-07T14:15:57.019502 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:552:in `process_client'
2013-10-07T14:15:57.019710+00:00 app[web.2]: E, [2013-10-07T14:15:57.019594 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:632:in `worker_loop'
2013-10-07T14:15:57.020069+00:00 app[web.2]: E, [2013-10-07T14:15:57.019940 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:500:in `spawn_missing_workers'
2013-10-07T14:15:57.020154+00:00 app[web.2]: E, [2013-10-07T14:15:57.020083 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:142:in `start'
2013-10-07T14:15:57.020271+00:00 app[web.2]: E, [2013-10-07T14:15:57.020153 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/bin/unicorn:126:in `<top (required)>'
2013-10-07T14:15:57.020372+00:00 app[web.2]: E, [2013-10-07T14:15:57.020263 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/bin/unicorn:23:in `load'
2013-10-07T14:15:57.020484+00:00 app[web.2]: E, [2013-10-07T14:15:57.020370 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/bin/unicorn:23:in `<main>'
2013-10-07T14:15:57.022713+00:00 heroku[router]: at=info method=POST path=/shares host=mentionengine.com fwd="105.228.65.98" dyno=web.2 connect=2ms service=15098ms status=500 bytes=0
2013-10-07T14:15:57.017996+00:00 app[web.2]: E, [2013-10-07T14:15:57.017963 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/multipart/parser.rb:116:in `get_current_head_and_filename_and_content_type_and_name_and_body'
2013-10-07T14:15:57.018284+00:00 app[web.2]: E, [2013-10-07T14:15:57.018362 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/lock.rb:15:in `call'
2013-10-07T14:15:57.018284+00:00 app[web.2]: E, [2013-10-07T14:15:57.018294 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
2013-10-07T14:15:57.017996+00:00 app[web.2]: E, [2013-10-07T14:15:57.017931 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/tee_input.rb:84:in `read'
2013-10-07T14:15:57.017884+00:00 app[w
eb.2]: E, [2013-10-07T14:15:57.017831 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/stream_input.rb:51:in `kgio_wait_readable'
2013-10-07T14:15:57.018284+00:00 app[web.2]: E, [2013-10-07T14:15:57.018262 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/methodoverride.rb:14:in `call'
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018154 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/request.rb:336:in `parse_multipart'
2013-10-07T14:15:57.019942+00:00 app[web.2]: E, [2013-10-07T14:15:57.019819 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.6.147/lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:22:in `block (4 levels) in <top (required)>'
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018074 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/multipart/parser.rb:17:in `parse'
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018004 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/multipart/parser.rb:19:in `block in parse'
2013-10-07T14:15:57.018284+00:00 app[web.2]: E, [2013-10-07T14:15:57.018327 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.12/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018038 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/multipart/parser.rb:17:in `loop'
2013-10-07T14:15:57.017884+00:00 app[web.2]: E, [2013-10-07T14:15:57.017899 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/stream_input.rb:51:in `read'
2013-10-07T14:15:57.017884+00:00 app[web.2]: E, [2013-10-07T14:15:57.017867 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.3/lib/unicorn/stream_input.rb:51:in `kgio_read'
2013-10-07T14:15:57.018284+00:00 app[web.2]: E, [2013-10-07T14:15:57.018231 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/methodoverride.rb:26:in `method_override'
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018191 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/request.rb:201:in `POST'
2013-10-07T14:15:57.019827+00:00 app[web.2]: E, [2013-10-07T14:15:57.019712 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.6.147/lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:22:in `call'
2013-10-07T14:15:57.017884+00:00 app[web.2]: E, [2013-10-07T14:15:57.017704 #5] ERROR -- : app error: execution expired (Timeout::Error)
2013-10-07T14:15:57.018170+00:00 app[web.2]: E, [2013-10-07T14:15:57.018114 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/multipart.rb:25:in `parse_multipart'
2013-10-07T14:15:57.018974+00:00 app[web.2]: E, [2013-10-07T14:15:57.018809 #5] ERROR -- : /app/vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:155:in `invalidate'

A: Heroku has a 30 second timeout on all request processing through the Router Mesh to your dyno.
It looks like your upload is large enough it needs more time to complete, you can't run a request of that size/length through Heroku.  Docs are here, explaining their policy: https://devcenter.heroku.com/articles/request-timeout
One way to work-around this limitation is to create an Amazon S3 bucket with public-write allowed that your clients can upload to directly, with JS or a rich client.
Here's a separate question explaining how to us JS to upload directly to S3: Uploading Image to Amazon s3 with HTML, javascript & jQuery with Ajax Request (No PHP)


text:
Q: disable click on context menu items i'm tring to disable one item into my context menu. i wrote this:
public boolean onContextItemSelected(MenuItem item) {
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

                switch (item.getItemId()) {

                case MYCASE:
                    if(mBoolean) {
                        item.setEnabled(false);
                        item.setCheckable(false);

                    }
                    break;

But the item is always clickable. How can i fix?

A: try:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.getItem(2).setEnabled(false);//2 is index of the item
}