text:
Q: R Shiny: use boostrapPage app within navbarPage (combine ShinyChat and DataTable Options examples) Thank you in advance for reading...
I am trying to create a data management site where I can give people data updates and keep a discussion going with them to resolve data-related questions that come up. The more I use Shiny, the more convinced I am that it is the answer to life.. The syntax is still difficult for me on the more complicated apps, though.
I'm trying to combine the below [awesome] examples from the Shiny Gallery, and build from there (and I bow down to everyone who has contributed code to the Gallery and GitHub repository... super impressive stuff in there):
DataTable Options http://shiny.rstudio.com/gallery/datatables-options.html
ANDShinyChat http://shiny.rstudio.com/gallery/chat-room.html
Basically- I want to force the reactive ShinyChat app to be the first tab of the DataTable Options app. My frustration lies in combining the ui.R and server.R scripts correctly. I am going to post both full [read: extensive] ui.R and server.R scripts so no one has to go hunting for info in order to help me, but be advised that other files require download to get ShinyChat to run.
The DataTable Options ui.R script is:
library(shiny)

shinyUI(navbarPage(
  title = 'DataTable Options',
  tabPanel('Display length',     dataTableOutput('ex1')),
  tabPanel('Length menu',        dataTableOutput('ex2')),
  tabPanel('No pagination',      dataTableOutput('ex3')),
  tabPanel('No filtering',       dataTableOutput('ex4')),
  tabPanel('Individual filters', dataTableOutput('ex5')),
  tabPanel('Function callback',  dataTableOutput('ex6'))
))

The DataTable Options server.R script is:
library(shiny)

shinyServer(function(input, output) {

  # display 10 rows initially
  output$ex1 <- renderDataTable(iris, options = list(pageLength = 10))

  # -1 means no pagination; the 2nd element contains menu labels
  output$ex2 <- renderDataTable(iris, options = list(
    lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
    pageLength = 15
  ))

  # you can also use paging = FALSE to disable pagination
  output$ex3 <- renderDataTable(iris, options = list(paging = FALSE))

  # turn off filtering (no searching boxes)
  output$ex4 <- renderDataTable(iris, options = list(searching = FALSE))

  # turn off filtering on individual columns (3rd and 4th column)
  output$ex5 <- renderDataTable(iris, options = list(
    columnDefs = list(list(targets = c(3, 4) - 1, searchable = FALSE)),
    pageLength = 10
  ))

  # write literal JS code in I()
  output$ex6 <- renderDataTable(
   iris,
    options = list(rowCallback = I(
      'function(row, data) {
        // Bold cells for those >= 5 in the first column
        if (parseFloat(data[0]) >= 5.0)
          $("td:eq(0)", row).css("font-weight", "bold");
      }'
    ))
  )
})

The ShinyChat ui.R script is:
library(shiny)

shinyUI(
  bootstrapPage(
    # We'll add some custom CSS styling -- totally optional
    includeCSS("shinychat.css"),

    # And custom JavaScript -- just to send a message when a user hits "enter"
    # and automatically scroll the chat window for us. Totally optional.
    includeScript("sendOnEnter.js"),

    div(
      # Setup custom Bootstrap elements here to define a new layout
      class = "container-fluid",
      div(class = "row-fluid",
          # Set the page title
          tags$head(tags$title("ShinyChat")),

          # Create the header
          div(class="span6", style="padding: 10px 0px;",
              h1("ShinyChat"),
              h4("Hipper than IRC...")
          ), div(class="span6", id="play-nice",
            "IP Addresses are logged... be a decent human being."
          )

      ),
      # The main panel
      div(
        class = "row-fluid",
        mainPanel(
          # Create a spot for a dynamic UI containing the chat contents.
          uiOutput("chat"),

          # Create the bottom bar to allow users to chat.
          fluidRow(
            div(class="span10",
              textInput("entry", "")
            ),
            div(class="span2 center",
                actionButton("send", "Send")
            )
          )
        ),
        # The right sidebar
        sidebarPanel(
          # Let the user define his/her own ID
          textInput("user", "Your User ID:", value=""),
          tags$hr(),
          h5("Connected Users"),
          # Create a spot for a dynamic UI containing the list of users.
          uiOutput("userList"),
          tags$hr(),
          helpText(HTML("
Built using R & Shiny.
Source code available on GitHub."))
        )
      )
    )
  )
)

The ShinyChat server.R script is:
library(shiny)
library(stringr)

# Globally define a place where all users can share some reactive data.
vars <- reactiveValues(chat=NULL, users=NULL)

# Restore the chat log from the last session.
if (file.exists("chat.Rds")){
  vars$chat <- readRDS("chat.Rds")
}

#' Get the prefix for the line to be added to the chat window. Usually a newline
#' character unless it's the first line.
linePrefix <- function(){
  if (is.null(isolate(vars$chat))){
    return("")
  }
  return("
")
}

shinyServer(function(input, output, session) {
  # Create a spot for reactive variables specific to this particular session
  sessionVars <- reactiveValues(username = "")

  # Track whether or not this session has been initialized. We'll use this to
  # assign a username to unininitialized sessions.
  init <- FALSE

  # When a session is ended, remove the user and note that they left the room.
  session$onSessionEnded(function() {
    isolate({
      vars$users <- vars$users[vars$users != sessionVars$username]
      vars$chat <- c(vars$chat, paste0(linePrefix(),
                     tags$span(class="user-exit",
                       sessionVars$username,
                       "left the room.")))
    })
  })

  # Observer to handle changes to the username
  observe({
    # We want a reactive dependency on this variable, so we'll just list it here.
    input$user

    if (!init){
      # Seed initial username
      sessionVars$username <- paste0("User", round(runif(1, 10000, 99999)))
      isolate({
        vars$chat <<- c(vars$chat, paste0(linePrefix(),
                        tags$span(class="user-enter",
                          sessionVars$username,
                          "entered the room.")))
      })
      init <<- TRUE
    } else{
      # A previous username was already given
      isolate({
        if (input$user == sessionVars$username || input$user == ""){
          # No change. Just return.
          return()
        }

        # Updating username
        # First, remove the old one
        vars$users <- vars$users[vars$users != sessionVars$username]

        # Note the change in the chat log
        vars$chat <<- c(vars$chat, paste0(linePrefix(),
                        tags$span(class="user-change",
                          paste0("\"", sessionVars$username, "\""),
                          " -> ",
                          paste0("\"", input$user, "\""))))

        # Now update with the new one
        sessionVars$username <- input$user
      })
    }
    # Add this user to the global list of users
    isolate(vars$users <- c(vars$users, sessionVars$username))
  })

  # Keep the username updated with whatever sanitized/assigned username we have
  observe({
    updateTextInput(session, "user",
                    value=sessionVars$username)
  })

  # Keep the list of connected users updated
  output$userList <- renderUI({
    tagList(tags$ul( lapply(vars$users, function(user){
      return(tags$li(user))
    })))
  })

  # Listen for input$send changes (i.e. when the button is clicked)
  observe({
    if(input$send < 1){
      # The code must be initializing, b/c the button hasn't been clicked yet.
      return()
    }
    isolate({
      # Add the current entry to the chat log.
      vars$chat <<- c(vars$chat,
                      paste0(linePrefix(),
                        tags$span(class="username",
                          tags$abbr(title=Sys.time(), sessionVars$username)
                        ),
                        ": ",
                        tagList(input$entry)))
    })
    # Clear out the text entry field.
    updateTextInput(session, "entry", value="")
  })

  # Dynamically create the UI for the chat window.
  output$chat <- renderUI({
    if (length(vars$chat) > 500){
      # Too long, use only the most recent 500 lines
      vars$chat <- vars$chat[(length(vars$chat)-500):(length(vars$chat))]
    }
    # Save the chat object so we can restore it later if needed.
    saveRDS(vars$chat, "chat.Rds")

    # Pass the chat log through as HTML
    HTML(vars$chat)
  })
})

A: Maybe I come a bit late... But the easiest thing to do is two tabPanel()'s one containing the Chat and another the DataTable.
Also, it would be easy to make all of it inside a splitLayout() like this in the ui.R:
shinyUI(fluidPage(
  splitLayout(
    #here include the DataTable,
    #here include the Chat
  )
))

I think it should work even pasting the code in server.R, because there are no name conflicts.


text:
Q: How sorted python dictionary while value is list? I have a dict like this:
d = {
    "Meter": ["000413031", "000413032", "000413034", "000413035"],
    "Account": ["314113801", "314113802", "314114140", "314114221"],
    "AcceptedDate": ["20210226", "20210226", "20210226", "20210226"],
    "EulaVersion": ["2018v01FXRSSWO", "2018v01FXRSSWO", "2018v01FXRSSWO", "2018v01FXRSSWO"],
    "SoftwareVersion": ["FXRS1810", "FXRS1810", "FXRS1810", "FXRS1810"],
    "CompanyName": ["SN2000 TEST", "SN2000 TEST", "SN2000 TEST", "SN2000 TEST"],
    "MachGuid": ["{B2B94738-B031-46B2-9D94-F54EEF46BE82}", "{B2B94738-B031-46B2-9D94-F54EEF46BE82}", "{B2B94738-B031-46B2-9D94-F54EEF46BE82}", " {B2B94738 - B031 - 46 B2 - 9 D94 - F54EEF46BE82}"]
}

Because I need to dramatically insert it into db, so I first get all the column names by:
keys = ','.join(d.keys())

and I get:
Meter,Account,AcceptedDate,EulaVersion,SoftwareVersion,CompanyName,MachGuid

And this is just what I want.
The value of the dict are all lists.
so I need get it one by one.
When I tried:
test =','.join(str(d[x][0]) for x in sorted(d))

which means just get the first value in the list,but I received:
20210226,314113801,SN2000 TEST,2018v01FXRSSWO,{B2B94738-B031-46B2-9D94-F54EEF46BE82},000413031,FXRS1810

This is not in the order.Any friend can help?

A: for record in zip(*d.values()):
    print(record)

gives you each 'record' as a list of values, for example:
columns = ','.join(d)
placeholders = ','.join('?' for _ in d)

for record in zip(*d.values()):
    sql = f'INSERT INTO table({columns}) VALUES({placeholders})'
    your_db.execute(sql, record)

A: Using zip you can read the list of data by rows, to build the rows to send to the DB. Then with cursor.executemany you can pass a list of values that will be used in the parametrized query
keys = ','.join(d.keys())
param_placeholder = ','.join(['%s'] * len(d.keys()))
values = list(zip(*d.values()))
query = f"INSERT INTO MY_TABLE ({keys}) VALUES ({param_placeholder})"

cursor.executemany(query, values)

That is the same as
query = f"INSERT INTO MY_TABLE ({keys}) VALUES ({param_placeholder})"
for row in zip(*d.values()):
    cursor.execute(query, row)

A: Here, you're sorting the dict based on keys ->
test =','.join(str(d[x][0]) for x in sorted(d))

The result of sorted(d) is ->
['AcceptedDate',
 'Account',
 'CompanyName',
 'EulaVersion',
 'MachGuid',
 'Meter',
 'SoftwareVersion']

Now, if you take the 1st value from this sorted list you'll get ->
20210226,314113801,SN2000 TEST,2018v01FXRSSWO,{B2B94738-B031-46B2-9D94-F54EEF46BE82},000413031,FXRS1810

If you don't perform the sort operation and join ->
test =','.join(str(d[x][0]) for x in d)
# prints '000413031,314113801,20210226,2018v01FXRSSWO,FXRS1810,SN2000 TEST,{B2B94738-B031-46B2-9D94-F54EEF46BE82}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: AdonisJS doesn't start after installing another npm package I'm developing an AdonisJS API, everything was going well until I install vimeo npm package, after this I cannot set server up appearing this error:

$ adonis serve --dev

 SERVER STARTED
> Watching files for changes...

Error: Cannot find module '@adonisjs/framework/providers/AppProvider'

1 requireStack
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/require-stack/src/index.js:44

2 _.uniq.map
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/@adonisjs/fold/src/Registrar/index.js:104

3 arrayMap
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/lodash/lodash.js:639

4 Function.map
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/lodash/lodash.js:9554

5 interceptor
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/lodash/lodash.js:16997

6 thru
  /mnt/c/Users/felip/Desktop/API/2019-2_DevWeb01/API/node_modules/lodash/lodash.js:8795

I'm using WSL and node 8.9.3, also tried in node 10.17.0.
Also tried to install manually '@adonisjs/framework' and Reinstall all packages, deleting node_modules, but didn't work.

A: can you install adonisjs package globally.
if not then install using this command.
npm i -g @adonisjs/cli

if any other query then ask

A: Make sure your project has a .env file
or run cp .env.example .env


text:
Q: How may I replace word and digit combination with blank? How to replace
url : http://www.abc.com&query_id=123&query_id1=12
to : http://www.abc.com&query_id1=12
How to replace any query_id with blank in javascript ?

A: var url = "http://www.abc.com&query_id=123&query_id1=12";
    url = url.replace(/(\?|&)query_id=[^&]*/g, "");

console.log(url); /* returns http://www.abc.com&query_id1=12 */

anyway note that you should replace the first occurence of & with a ?
http://www.abc.com&query_id=123&query_id1=12
should be written as
http://www.abc.com?query_id=123&query_id1=12


text:
Q: findOne then findMany using value from document found in findOne, in a single query const categorySlug = req.query.category;
const category = await Category.findOne({ slug: categorySlug });
const children = await Category.find({ parent: category._id });

Is it possible to combine those two queries into one? I tried doing something like
const children = await Category.aggregate([
      {
        $match: {
          slug: categorySlug,
        },
      },
      {
        // somehow use the _id field from document fetched in first stage
      }
    ]);

But I have no idea if this is even possible.
EDIT:
const document = await Category.aggregate([
      {
        $match: {
          slug: categorySlug,
        },
      },
      {
        $lookup: {
          from: 'categories',
          localField: '_id',
          foreignField: 'parent',
          as: 'children',
        },
      },
    ]);

    const desiredResult = document[0].children;

This works but is there a way to do this fully in the aggregation pipeline? Basically I want to get ONLY the "children" array, nothing else.
EDIT2: The result of above query is this array with an object which has an array of objects
[
    {
        "_id": "6051cacf8f974b3104715ec4",
        "parent": null,
        "products": [
            "60515150d6ac5e08a4e796b4",
            "6051b8b0f8c80835480b28d3"
        ],
        "isParent": true,
        "name": "Electronics",
        "description": "All kinds of devices",
        "createdAt": "2021-03-17T09:24:31.365Z",
        "updatedAt": "2021-03-20T20:42:50.699Z",
        "slug": "electronics",
        "__v": 4,
        "children": [
            {
                "_id": "6051cb588f974b3104715ec5",
                "parent": "6051cacf8f974b3104715ec4",
                "products": [],
                "isParent": true,
                "name": "Cameras",
                "description": "description",
                "createdAt": "2021-03-17T09:26:48.220Z",
                "updatedAt": "2021-03-17T09:29:35.608Z",
                "slug": "cameras",
                "__v": 0
            },
            {
                "_id": "6051cb5f8f974b3104715ec6",
                "parent": "6051cacf8f974b3104715ec4",
                "products": [
                    "60515150d6ac5e08a4e796b4",
                    "6051b8b0f8c80835480b28d3"
                ],
                "isParent": true,
                "name": "Computers",
                "description": "description",
                "createdAt": "2021-03-17T09:26:55.364Z",
                "updatedAt": "2021-03-20T20:42:50.779Z",
                "slug": "computers",
                "__v": 4
            },
            {
                "_id": "6051cb6f8f974b3104715ec7",
                "parent": "6051cacf8f974b3104715ec4",
                "products": [],
                "isParent": false,
                "name": "Car Electronics",
                "description": "description",
                "createdAt": "2021-03-17T09:27:11.108Z",
                "updatedAt": "2021-03-17T09:27:11.108Z",
                "slug": "car-electronics",
                "__v": 0
            },
            {
                "_id": "6051cb768f974b3104715ec8",
                "parent": "6051cacf8f974b3104715ec4",
                "products": [],
                "isParent": false,
                "name": "TV",
                "description": "description",
                "createdAt": "2021-03-17T09:27:18.422Z",
                "updatedAt": "2021-03-17T09:27:18.422Z",
                "slug": "tv",
                "__v": 0
            }
        ]
    }
]

What I want to get is the whole "children" array inside that object
[
    {
        "_id": "6051cb588f974b3104715ec5",
        "parent": "6051cacf8f974b3104715ec4",
        "products": [],
        "isParent": true,
        "name": "Cameras",
        "description": "description",
        "createdAt": "2021-03-17T09:26:48.220Z",
        "updatedAt": "2021-03-17T09:29:35.608Z",
        "slug": "cameras",
        "__v": 0
    },
    {
        "_id": "6051cb5f8f974b3104715ec6",
        "parent": "6051cacf8f974b3104715ec4",
        "products": [
            "60515150d6ac5e08a4e796b4",
            "6051b8b0f8c80835480b28d3"
        ],
        "isParent": true,
        "name": "Computers",
        "description": "description",
        "createdAt": "2021-03-17T09:26:55.364Z",
        "updatedAt": "2021-03-20T20:42:50.779Z",
        "slug": "computers",
        "__v": 4
    },
    {
        "_id": "6051cb6f8f974b3104715ec7",
        "parent": "6051cacf8f974b3104715ec4",
        "products": [],
        "isParent": false,
        "name": "Car Electronics",
        "description": "description",
        "createdAt": "2021-03-17T09:27:11.108Z",
        "updatedAt": "2021-03-17T09:27:11.108Z",
        "slug": "car-electronics",
        "__v": 0
    },
    {
        "_id": "6051cb768f974b3104715ec8",
        "parent": "6051cacf8f974b3104715ec4",
        "products": [],
        "isParent": false,
        "name": "TV",
        "description": "description",
        "createdAt": "2021-03-17T09:27:18.422Z",
        "updatedAt": "2021-03-17T09:27:18.422Z",
        "slug": "tv",
        "__v": 0
    }
]

Like I mentioned this can be done with const desiredResult = document[0].children; but I would like to do this in the query itself.
EDIT3: It seems that aggregate will always return an array of documents even if there is only one document and I can choose how the documents will look like, however I can't only return a field itself, without the document. That's fine for what I'm trying to do - I can assign that document (or a specific field of it) to a variable.

A: Use https://mongoosejs.com/docs/populate.html

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, a plain object, multiple plain objects, or all objects returned from a query. Let's look at some examples.

get the full array
{ $project: { _id:0, children: 1 } }

Use this for getting 1st element
Extract the first element from the array in the aggregation project pipeline
{ $project: { _id:0, children: { $arrayElemAt: [ "$children", 0 ] } } }

if(document && document[0] && document[0].children) { // your logic }

$arrayElemAt
$project
combined query
const document = await Category.aggregate([
  {
    $match: {
      slug: categorySlug,
    },
  },
  {
    $lookup: {
      from: 'categories',
      localField: '_id',
      foreignField: 'parent',
      as: 'children',
    },
  },
  { $project: { _id:0, children: { $arrayElemAt: [ "$children", 0 ] } } }
]);


text:
Q: Implementing path compression in a disjoint set data structure? Here is my Objective-C implementation of a disjoint set.
- Positive number point to parent.
- Negative number indicate root & children count. (So they each start disjointed at -1.)
- The index acts as the data I am grouping.
Seems to work ok... just had a couple questions.

*

*find: How can I compress the path? Because I am not doing it recursively, do I have to store the path and loop it again to set after find root?

*join: I am basing join on children count instead of depth!? I guess that is not right. Do I need to do something special during join if depths equal?
Thanks.
DisjointSet.h
@interface DisjointSet : NSObject
{
    NSMutableArray *_array;
}

- (id)initWithSize:(NSInteger)size;
- (NSInteger)find:(NSInteger)item;
- (void)join:(NSInteger)root1 root2:(NSInteger)root2;

@end

DisjointSet.m
#import "DisjointSet.h"

@implementation DisjointSet

- (id)initWithSize:(NSInteger)size
{
    self = [super init];
    if (self)
    {
        _array = [NSMutableArray arrayWithCapacity:size];
        for (NSInteger i = 0; i < size; i++)
        {
            [_array addObject:[NSNumber numberWithInteger:-1]];
        }
    }
    return self;
}

- (NSInteger)find:(NSInteger)item
{
    while ([[_array objectAtIndex:item] integerValue] >= 0)
    {
        item = [[_array objectAtIndex:item] integerValue];
    }
    return item;
}

- (void)join:(NSInteger)root1 root2:(NSInteger)root2
{
    if (root1 == root2) return;

    NSInteger data1 = [[_array objectAtIndex:root1] integerValue];
    NSInteger data2 = [[_array objectAtIndex:root2] integerValue];
    if (data2 < data1)
    {
        [_array setObject:[NSNumber numberWithInteger:data2 + data1] atIndexedSubscript:root2];
        [_array setObject:[NSNumber numberWithInteger:root2] atIndexedSubscript:root1];
    }
    else
    {
        [_array setObject:[NSNumber numberWithInteger:data1 + data2] atIndexedSubscript:root1];
        [_array setObject:[NSNumber numberWithInteger:root1] atIndexedSubscript:root2];
    }
}

@end

A: For the find operation, there is no need to store the path (separately from your _array) or to use recursion.  Either of those approaches requires O(P) storage (P = path length).  Instead, you can just traverse the path twice.  The first time, you find the root.  The second time, you set all of the children to point to the root.  This takes O(P) time and O(1) storage.
- (NSInteger)findItem:(NSInteger)item {
    NSInteger root;
    NSNumber *rootObject = nil;
    for (NSInteger i = item; !rootObject; ) {
        NSInteger parent = [_array[i] integerValue];
        if (parent < 0) {
            root = i;
            rootObject = @(i);
        }
        i = parent;
    }

    for (NSInteger i = item; i != root; ) {
        NSInteger parent = [_array[i] integerValue];
        _array[i] = rootObject;
        i = parent;
    }

    return root;
}

For the merge operation, you want to store each root's rank (which is an upper bound on its depth), not each root's descendant count.  Storing each root's rank allows you to merge the shorter tree into the taller tree, which guarantees O(log N) time for find operations.  The rank only increases when the trees to be merged have equal rank.
- (void)joinItem:(NSInteger)a item:(NSInteger)b {
    NSInteger aRank = -[_array[a] integerValue];
    NSInteger bRank = -[_array[b] integerValue];
    if (aRank < bRank) {
        NSInteger t = a;
        a = b;
        b = t;
    } else if (aRank == bRank) {
        _array[a] = @(-aRank - 1);
    }

    _array[b] = @(a);
}

A: You definitely should implement path compression using recursion. I would not even think about trying to do it non-recursively.
Implementing the disjoin-set datastructure should be very easy, and can be done in few lines. Its very, very easy to translate it from the pseudocode to any programming language. You can find the pseudocode on Wikipedia. (Unfortunately, I can't read Objective-C, so I cannot really judge wether your code is correct or not).

A: Yes.  To implement highest ancestor compression without recursion you need to maintain your own list.  Make one pass up the chain to get pointers to the sets that need their parent pointers changed and also to learn the root.  Then make a second pass to update the necessary parent pointers.
The recursive method is doing the same thing. The first pass is the "winding up" of the recursion, which stores the sets needing parent pointer updates on the program stack.  The  second pass is in reverse as the recursion unwinds.
I differ with those who say the recursive method is always best.  In a reasonable number systems (especially embedded ones), the program stack is of limited size. There are cases where many unions are performed in a row before a find. In such cases, the parent chain can be O(n) in size for n elements. Here collapsing by recursion can blow out the stack.  Since you are working in Objective C, this may be iOS.  I do not know the default stack size there, but if you use recursion it's worth looking at.  It might be smaller than you think.  This article implies 512K for secondary threads and 1Mb for the main thread.
Iterative, constant space alternative
Actually the main reason I'm writing is to point out that you still get O(log^* n) for n ammortized operations -- just a shade less efficient than collapsing, and still effectively O(1) -- if you only do factor-of-two compression: in the find operation, change parent pointers so that they point to the grandparents instead instead of the root.  This can be done with iteration in constant storage.  This lecture at Princeton talks about this algorithm and implements it in a loop with 5 lines of C.  See slide 29.


text:
Q: can't export a variable from execute shell in Jenkins to other project (with using properties file) I have a Jenkins project with one "Execute shell" that executes some bash commands and exports one variable to the env. variables:
#!/bin/bash

...
TARGET_FULLPATH="blablabla"
export TARGET_FULLPATH

In addition, I have configured to "Post-build Actions" with:

*

*"Trigger parameterized build on other projects"

*"Current build parameters"

*"Predefined parameters" -> FULLPATH=$TARGET_FULLPATH

But, when I run this project the other project that will start as soon the first one is finished seems that it doesn't get the parameter FULLPATH at all!
At least in the "Execute shell" (of the second project) the bash script print nothing for echo $FULLPATH! Also at the "Environment Variables" of the second project the FULLPATH is not included!
Any clue what am I doing wrong?
One more thing, i can't use a properties file to store the parameters, since the two projects are running on different servers and there are restrictions on copying files between those servers!

A: Did you have a look to this solution?
Jenkins: How to use a variable from a pre-build shell in the Maven "Goals and options"
Using a shell pre-build step + the InjectEnv plugin, you should be able to solve your problem.
Update from June 22nd, I add some screen copies.
1/ Add a first "Execute shell" script to create the properties file and an "Inject environment variables" step to load the properties file:

2/ For the demo, I add a "post-build task" step to read the variable

3/ Here is the console output, it works :)


text:
Q: Organizing a (6000,2) np array into 2-D grid I am having difficulties organizing or sorting a np array into 2-D Bins. I essentially have a 6000 by 2 datapoint array. I want to sort the array acording to it's x and y values (axis 1) over a 2-D plot ranging on either axis from 0 to 1. Meaning ultimately I need the counts of datapoints that land in the specific bin of a 10x10 grid (for a heatmap). However, I'm only interested in the values, not actually plotting the heatmap.
In a next step I would then have to organise/calculate the hits per grid for multiple 2-D arrays that are in a 3-D array and then calculate the std for each of the 10x10 bins depthwise in the 3_d array.
I would also preferre to saty in numpy rather than pandas.
I've tried using seaborn to create a heatmap and then to take the counts per grid out of that somehow, however that did not work as seaborn was just creating a heatmap based ión the individual values in the (6000,2) array on a (0,1) scale.
a = np.random.rand(6000,2)
b = np.random.rand(6000,2)

brick = np.dstack((a,b))

for i in range(len(brick[2])):
    sns.heatmap(brick[i], vmin=0, vmax=1, cmap = 'BuPu', annot=True, linewidths=0.1, cbar=True)
    plt.show()

One could oviously divide the data into the 10x10 grid with 100 if clauses, however there must be a simpler way?

A: So originally I was looking into using seaborn as seaborn can easily plot heatmaps and would then have used the values per grid to calc the std. However the organizing and sorting was my main issue. Using np.histogram2d was the key. I had previously only thought about 1D histograms, which in this case would'nt work because I first need to organize my grid to then either create a heatmap or calc the std.
check = []
heat_std = np.zeros(shape=(10,10))

a = np.random.rand(6000,2)
b = np.random.rand(6000,2)
c = np.random.rand(6000,2)

brick = np.dstack((a,b,c))

for i in range(brick.shape[2]):

    current = brick[:,:,i]
    check_pre = np.histogram2d(current[:,0], current[:,1], range = [[0, 1], [0, 1]],bins=10)
    check.append(np.asarray(check_pre[0]))

heat = np.dstack(check)
np.std(heat, axis=2, dtype=None, out=heat_std, ddof=1)
sns.heatmap(heat_std, vmin = 0, vmax = 1, cmap = 'BuPu', annot=True, linewidths=0.1, cbar=True)
plt.show()

This is what I came up with, I first create my grid values for each of the arrays in my 3D array and then dstack the grids to then calc the std and plot that as a heatmap.
Apologies for the rough start to my question. :)


text:
Q: How to get React Context Value outside React world(without consumer or useContext)? In Redux, we have store.getState().
How can I do the same thing in React Context without Consumer or useContext?
I think that it is possible, but I don't know if this against design pattern.
I want to do this thing because my context will fetch my server data, then I want to track some google analytics based on that fetched data.
If I have to create a function component just because getting those values, that will be too bad.


text:
Q: How to insert all id's from one table to another table I am trying to get and insert all of the id's from food_variety table into food table. Here is what i am trying to do.
Here i am trying to get all ID's from food_variety table
<?php
$Select_Variety = mysqli_query($con, "SELECT * FROM food_variety ORDER BY 1 ASC");
while($row=mysqli_fetch_assoc($Select_Variety)){

$variety_ids    = $row['id'];

?>

<?php echo $row['variety_name'];?> $<?php echo $row['price'];?>
<input type="text" name="variety_ids2" value="<?php echo $variety_ids;?>">

<?php } ?>

Now here i am trying to insert all ID's from food_variety into food table. But i am unable to do that.
if(isset($_POST['add_food'])){

    $food_name      = $_POST['food_name'];
    $description    = $_POST['description'];
    $category       = $_POST['category'];
    $price          = $_POST['price'];
    $tax            = $_POST['tax'];
    $diet_id        = implode(",",$_POST['diet_id']);
    $variety_ids2   = $_POST['variety_ids2'];

$insertQuery = mysqli_query($con,"INSERT INTO food VALUE(
    '',
    '$category',
    '$food_name',
    '$description',
    '$price',
    '$tax',
    '$diet_id',
    '$img',
    '$variety_ids2',
    ''
     )");

Database pictures of both tables are attached.

A: I was calling the variables outside the form. That is why it was inserting the ID values.
Then to take all IDs, I took IDs into an array and then used implode() function.
<?php
$Show_Variety = mysqli_query($con, "SELECT * FROM food_variety ORDER BY 1 ASC");
$ids = [];
while($row=mysqli_fetch_assoc($Show_Variety)){
$ids[] = $row['id'];
}
?>

Product Name

<input type="text" name="variety_id" value="<?php echo implode(", ", $ids); ?>">


text:
Q: Return string based on int Is there an easier way to return a string based on the value of an int in C# .NET2 that this, please?
        if (intRelatedItems == 4)
        {
            _relatedCategoryWidth = "3";
        }
        else if (intRelatedItems == 3)
        {
            _relatedCategoryWidth = "4";
        }
        else if (intRelatedItems == 2)
        {
            _relatedCategoryWidth = "6";
        }
        else if (intRelatedItems == 1)
        {
            _relatedCategoryWidth = "12";
        }
        else
        {
            _relatedCategoryWidth = "0";
        }

A: Dictionary<int, string> dictionary = new Dictionary<int, string>
{
    {4, "3"},
    {3, "4"},
    {2, "6"},
    {1, "12"},
};

string defaultValue = "0";

if(dictionary.ContainsKey(intRelatedItems))
    _relatedCategoryWidth = dictionary[intRelatedItems];
else
    _relatedCategoryWidth = defaultValue;

or use ternary operator, but I find it less readable:
_relatedCategoryWidth = dictionary.ContainsKey(intRelatedItems) ? dictionary[intRelatedItems] : defaultValue;

or use TryGetValue method, as CodesInChaos kindly suggested:
if(!dictionary.TryGetValue(intRelatedItems, out _relatedCategoryWidth))
    _relatedCategoryWidth = defaultValue;

A: Well, since you are only interested in special-casing consecutive small integers you can do this with an array lookup:
var values = new[] { "0", "12", "6", "4", "3" };
if (intRelatedItems >= 0 && intRelatedItems < values.Length)
{
    return values[intRelatedItems];
}
else
{
    return "0";
}

Otherwise the best option would be to go with a plain old switch/case and possibly hide it inside a method so that it doesn't clutter up the code.

A: You can use conditional operators:
_relatedCategoryWidth =
  intRelatedItems == 4 ? "3" :
  intRelatedItems == 3 ? "4" :
  intRelatedItems == 2 ? "6" :
  intRelatedItems == 1 ? "12" :
  "0";

This way of writing it emphasises that everything boils down to an assignment to the _relatedCategoryWidth variable.

A: You can use an int[] or Dictionary<int, string>, depending on your keys.
For example:
int[] values = new int[] {100, 20, 10, 5};
return values[intRelatedItems];

Obviously that only works when intRelatedItems can only take values from 0 to values.Length -1.
If that is not the case you can use a 'Dictionary'. Both solutions can throw exceptions if the key was not found.

A: Dictionary<int, string> dictLookUp = new Dictionary<int, string>();
dictLookUp.Add(4, "3");
dictLookUp.Add(3, "4"};
dictLookUp.Add(2, "6"};
dictLookUp.Add(1, "12"};

int defaultVal = 0;

if (dictLookUp.ContainsKey(intRelatedItems))
{
    relatedCategoryWidth  = dictLookUp[intRelatedItems];
}
else
{
    intRelatedItems = defaultVal;
}


text:
Q: Problem Customizing People Refinement Panel I am creating a web part page that uses People Search Core Results and People Refinement Panel to display our People Search in table view. The problem I am having is that my People Refinement Panel will only show the default Filter Category Definition despite it being changed and Use Default Configuration being unchecked.
What could be causing this to happen? How can I fix it?
Please note: Mapped properties are already setup and full crawl was ran. Also, they are setup to be used in scopes.

A: Found something that worked for me. I deleted my People Search Core Results webpart and then put it back in. After that the Refinement Panel showed my changes.
I guess the Refinement Panel needed to be setup/configured before the People Search Core Results webpart is used in a page.


text:
Q: How to got difference between 2 date in Years ,Month , Days is sql I want to got difference between 2 date in Years ,Month , Days for
Example :
Hirring Date : 25/7/1998
CurrentDate : 30/9/2017
The resulte to be like :  19 Years – 2 Month – 11 Days

A: If you are open to a Table-Valued Function.  This approach is very precise and performant.  You'll never have to worry about the various date calculations.
Example or dbFiddle
Declare @YourTable table (ID int, hiredate date)
Insert Into @YourTable values
(1,'1998-7-25')

Select A.ID
      ,B.*
 From @YourTable A
 Cross Apply [dbo].[tvf-Date-Elapsed](A.HireDate,GetDate()) B

Returns (You can ignore or omit Hours, Minutes, and Seconds)
ID  Years   Months  Days    Hours   Minutes Seconds
1   19      2       8       15      21      47

The UDF if Interested
CREATE FUNCTION [dbo].[tvf-Date-Elapsed] (@D1 DateTime,@D2 DateTime)
Returns Table
Return (
    with cteBN(N)   as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cteRN(R)   as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
         cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,@D1))From cteRN R Where DateAdd(YY,R,@D1)<=@D2),
         cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D))  From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=@D2),
         cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D))  From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=@D2),
         cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D))  From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=@D2),
         cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=@D2),
         cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=@D2)

    Select [Years]   = cteYY.N
          ,[Months]  = cteMM.N
          ,[Days]    = cteDD.N
          ,[Hours]   = cteHH.N
          ,[Minutes] = cteMI.N
          ,[Seconds] = cteSS.N
          --,[Elapsed] = Format(cteYY.N,'0000')+':'+Format(cteMM.N,'00')+':'+Format(cteDD.N,'00')+' '+Format(cteHH.N,'00')+':'+Format(cteMI.N,'00')+':'+Format(cteSS.N,'00')
     From  cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[tvf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())
--Select * from [dbo].[tvf-Date-Elapsed] ('2017-01-01 20:30:15','2018-02-05 22:58:35')


text:
Q: Batch program to delete a folder I'm trying to automate a little backup process of a folder from the computer to a network-drive. I found the code below to delete the folder on the network drive but I can't get it working because it says "Unable to find the specified file" for each files that it tries to remove. Why?
rd /s /q "\\MY SERVER\mysharename\myfolder"

A: Maybe there is a problem with concepts. It is not "\\server\folder", but "\\server\shareName". And you can not remove the share with a rd command.


text:
Q: How to deconstruct a LINQ IQueryable / Expression into the constituent parts? I am writing an extension method which is meant to help prepare a LINQ query before it is actually executed in EF Core.
For example:
var context = new SchoolContext();

var studentWithGrade = context.Students
                           .Where(s => s.FirstName == "Bill")
                           .Include(s => s.Grade)
                           .Prepare()
                           .FirstOrDefault();

I am building the Prepare() extension on the IQueryable<> interface. In the method, I need to know things about the resulting query to be executed, such as:

*

*The predicate (s.FirstName == "Bill")

*The selected fields (from the Students table, as well as any fields from s.Grade)

*The limit (an implied 1 in this case)

*... and so on.

AFAICT, the Expression on the IQueryable is transformed into a SQL query (and executed) when FirstOrDefault() is called. So this transformation is obviously possible. But I would like to examine the data in a structured way, rather than inspecting a SQL query string. My hope was that I could simply inspect the queryable (query.Limit < 0) but the actual storage of these constraints seems buried with reflection in Expression object (?) based upon MethodCallExpression.cs's source code.


text:
Q: prepareInterstitialAds() deprecated in iOS 10 Does anyone know how I can call UIViewController.prepareInterstitialAds() in iOS 10 because it's deprecated it seems in Xcode 8.

A: iAd has been shut down since July 1.


text:
Q: How to position the images in this php code? I have this code which I am using to display random images. But the images show up at the top left corner of the site. I want to be able to position the image as I wish. What are the changes I have to do in the code order to the above mentioned.
Here's the code--

/*
 * Name your images 1.jpg, 2.jpg etc.
 *
 * Add this line to your page where you want the images to   * appear: <?php include"randomimage.php"; ?>
 */

// Change this to the total number of images in the folder
$total = "2";

// Change to the type of files to use eg. .jpg or .gif
$file_type = ".jpg";

// Change to the location of the folder containing the images
$image_folder = "sample.url.com";

// You do not need to edit below this line

$start = "1";

$random = mt_rand($start, $total);

$image_name = $random . $file_type;

echo "";

?>

Thanks in advance

A: This would be a CSS solution, PHP can't position images. With CSS you can position things in many different ways:

*

*Using margins (e.g., margin: top right bottom left;)

*Using paddings (e.g., padding: top right bottom left;)

*Using floats (e.g., float: right or left;)

*Using positions (e.g., position: absolute or relative; and then using top/left and bottom/right to position).

For example, you can center your image to the middle of the page using margins. Add this to the top of your page:

Or you can float the image to the far right of your page using a float, assuming the parent object has a width of 100%:

Or using an absolute position to position it at the bottom right:

You may want to read a CSS tutorial to learn the differences between all the positioning techniques and when to use them and where + little hacks, annoyances and incidents that come when you use each of them.
http://www.google.com/search?q=css+tutorial

A: You need to modify your html code.
In your case you need to change value of this string:
echo "";

Like this:
echo "";

Please learn some of the basics before asking on Stack Overflow.
http://www.w3.org/Style/CSS/learning.en.html css guides.

A: While the CSS answers are good, not every project will need or want CSS. This alternative solution, given your code, works just fine within the PHP tags:
(I had to put a space after the first < or it wouldn't display properly on this page. Just remove that space from each line to make it work)
Align Right:
< right>

";

< /right>

Align Center:

";

Align Left:
< left>

";

< /left>

This is technically an HTML solution, but since it works within PHP tags you can use this to effectively position anything you like.


text:
Q: Same coordinate Systems in QGIS with different extents I have a polygon shape file and a points shapefile on the same coordinate system in qgis but completely different extents. How do I fix this?
Massachusetts is in wrong place both using NAD83
.

A: Without seeing the data and it's projections it's hard to be sure, but the most likely problem is that one of your data sets is in Massachusetts State Plane feet and the other is in Massachusetts State Plane metres.
Whatever the projections you've been given they clearly are not the same.


text:
Q: ASP.NET MVC 3 - Sequester HTML.Raw Output I am working on a system where users are able to submit HTML to the system, and then 'preview' the resulting page. The HTML submitted by the user is given to the page via a call to HTML.Raw in the view, where it is displayed as part of a table with other data. In a naive implementation, it is being displayed like so:
...

@Html.Raw(UserEnteredHTMLIsFetchedHere)

...

The problem I am having is that the user-entered HTML is not guaranteed to be error-free (far from it, in fact). If a user enters an unclosed div tag in the HTML and then goes to preview it, that unclosed tag returned by Html.Raw will close on the /div outside of the Html.Raw call and create improper nesting on the entire page.
I am looking for a way to sequester the output of Html.Raw so that unclosed tags will not interfere with the rest of the page.
I have attempted to use iframe tags to accomplish this (setting the src to the encoded HTML), but it did not play nice with CSS. I would like the existing CSS of the page to be preserved within the sequestered HTML if at all possible.
I'm not sure if this is a way that Html.Raw is even supposed to be used, but this is an implementation that I am modifying, not creating, and I would like to preserve as much of the original implementation as possible.

A: The important thing to understand is that this is never a good idea, unless you are creating a CMS system (see my answer here https://stackoverflow.com/a/4146470/467198 )
Yes, CSS will not work in the iframe, but you can inject same CSS into the iframe as you did in your parent page. But obviously the parent page layout will not follow the content of the iframe (for example if there's a big div in the iframe, the parent page will not make iframe bigger)

A: Your best bet for displaying user entered HTML without it affecting your view is to use an IFrame.  You can manually set the content of an IFrame using Javascript.

A: Check out html attribute contenteditable. It assures that whoever modifies the content of the div that has this attribute applied does not have to deal with html, yet the html will be generated.
It allows for formatting as well. For example, you could press Ctrl+B and highlighted things would get bolded. Or you could type things in MS Word, format them as you want, and copy paste it in the div.
This might or might not work for you. I found it very convenient for situations when I know that person, who's going to be typing content needs it formatted, but has no idea about html.


text:
Q: No implementation found for method _init on channel plugins.flutter.io/google_mobile_ads While debugging an app build in flutter this error pops up
"No implementation found for method _init on channel plugins.flutter.io/google_mobile_ads"
Tried
flutter clean
flutter pub get

but doesn't seem to work


text:
Q: How to escape current SQLite3 query if row in table exists, but continue if it doesn't So I an integrating my Discord.JS bot with SQLite3 and I am adding a function where users can store their ID and username within a table. Currently, what I have will only create a new row in the table, if the ID and name of the user does not already exist within a row of the table, and creates a new row if the data doesn't exist. What I want to know is if there is a way to throw something out of the query if the row does exist, and for me to be able to catch it, and then do something else.
I have tried if..else statements, but I want to know if there is a simpler way to achieve this.
This is what I have currently, that functions as described above.
let userC = message.mentions.members.first()

    db.serialize(() => {
        db.run('CREATE TABLE IF NOT EXISTS user (id TEXT, name TEXT)');
        db.run(`INSERT INTO user (id, name) SELECT '${userC.id}', '${userC.user.username}' WHERE NOT EXISTS(SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '${userC.user.username}')`)
    });
    message.reply('Added the user to the database.');

Ideally, if the row does exist, message.reply('Added the user to the database.'); will not execute, and instead will continue with message.reply('That user already exists within the database'); But if the row doesn't exist, it inserts the row and data, and only continues with message.reply('Added the user to the database.');

A: According to the API docs here, you can use Database.get() instead of Database.run(). It functions the same way, but the callback will return the rows from the SQL which you can check.
In the code below, you'll notice that I've also implemented placeholders to prevent SQL injection. Consider this normal practice for user-provided variables.
const userC = message.mentions.users.first();

db.get(`SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '?'`, [userC.username], (err, rows) => {
  if (err) return console.error(err);

  if (!rows[0]) {
    db.run(`INSERT INTO user (id, name) VALUES ('${userC.id}', '?'), [userC.username], err => {
      if (err) return console.error(err);

      message.reply('Added the user to the database.');
    });
  } else return message.reply('That user already exists within the database.');
});

Make sure to also catch the promises returned by message.reply().


text:
Q: Set $PATH For /bin/false user I have a sensu user:
sensu:x:496:496:Sensu Monitoring Framework:/opt/sensu:/bin/false
Its $PATH is:
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
I want to update its PATH, so that while sensu triggers my check script, it will use my side installed python version (installed under /usr/local/bin), hence I want to set sensu's PATH to:
export PATH=$PATH:/usr/local/bin
However, I've edited both /opt/sensu/.bashrc and /opt/sensu/.profile, didn't work; I've read online (link), .bashrc will got sourced only after login for both interactive/non-interactive users, however, sensu as a /bin/false user, .profile will got sourced after user login with bash, my understanding is it doesn't have a login shell as all, but how could I achieve my goal of setting $PATH for it?
BTW, by running sudo su - sensu -s /bin/bash I saw .profile got sourced correctly, however this makes little sense for me since while sensu client runs my python check script it won't have bash.
Can I modify /etc/passwd to change /bin/false to /bin/bash, will this cause problem Please?

A: As you already noticed, the shell for your sensu user is /bin/false, so it doesn't have a shell at all. You could give it a real shell like /bin/bash, and at the same time block the account (use passwd -l) so you can't login with the account remotely, thus making it a bit more safe.

A: To update the $PATH, the following line needs to be added
export PATH=$PATH:/usr/local/bin
Depending on machine type and server/client the file name would change:
For redhat machine:

*

*sensu-client
 /etc/sysconfig/sensu-client

*sensu-server
 /etc/sysconfig/sensu-server

For debian machines:

*

*sensu-client
 /etc/default/sensu-client

*sensu-server
 /etc/default/sensu-server


text:
Q: Github workflow: invalid refspec I have a github workflow step to create an automated pull request against the shuklsh-test-2 branch if one merges a pull request against shuklsh-test-1. Here is my job code:
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          token: ${{ secrets.AUTO_COMMIT_BOT_PAT }}
      - name: Create automated PR
        if: github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged == true && ${{ github.base_ref == 'shuklsh-test-1' }}
        uses: peter-evans/create-pull-request@v4
        with:
          token: ${{ secrets.AUTO_COMMIT_BOT_PAT }}
          title: ${{ github.event.pull_request.title }}
          body: ${{ github.event.pull_request.body }}
          base: shuklsh-test-2
          branch: ${{ github.base_ref }}
          labels: Automated PR

I am running the workflow in the context of branch shuklsh-test-1. The workflow FAILS at this step with the following error.
invalid refspec ':refs/remotes/origin'

What am I missing?

A: The message appears on line 483, if you take time to squint a bit and understand the command on line 482, it says: git fetch origin :refs/remotes/origin, which is, as the error message suggests, invalid.
There probably is some value (the branch name ?) that isn't set correctly, and isn't substituted in that command (hence the empty string before the : and after the final /).
Check how your script receives the name of the branch (or tag or ref) to fetch.


text:
Q: C# do nested classes need to be instantiated? In the following scenario:
public class outerclass
{
   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

Do you need to instantiate the inner class property before assigning values to it, like this?
public class outerclass
{
   public outerclass()
     {
        this.Ic = new innerClass();
     }

   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

A: It doesn't matter in what scope class has been declared - you should always work with classes in the same manner: before interacting with a particular class instance you have to create it using new operator.

A: Yes, unlike a base class you need to instantiate an inner class if you wish to use it.
You can prove this to yourself quite easily by trying it:
public class OuterClass
{
    public InnerClass Ic { get; set; }

    public class InnerClass
    {
        public InnerClass()
        {
            Foo = 42;
        }

        public int Foo { get; set; }
    }
}

public class Program
{
    static void Main()
    {
        Console.WriteLine(new OuterClass().Ic.Foo);
    }
}

The above code throws a NullReferenceException because Ic has not been assigned.
I would also advise you to follow the Microsoft naming convention and use pascal case for type names.

A: In this case the answer doesn't depend on the fact that the class is defined inside your outer class.  Because you used the automatic getter/setter, a hidden backing field is used for the property Ic.  Like all fields of reference type, this field has a default value of null.  Thus if you try to access the members of Ic without setting it to refer to some instance, you can expect a NullReferenceException.
Everything I just said would still be true even if innerClass was defined somewhere else.

A: No, the property is an instance of the class. The set would set a new instance anyway.  No need to construct one unless you want to make sure the get never returns null.


text:
Q: Delete one picture I want to delete one picture msword using macro
The sample code is below, I am new with but not working
Dim myImage As Shape

Set myImage = ActiveSheet.Shapes("Picture 1")

myImage.Delete

A: ActiveSheet is Excel, not Word. You would use ActiveDocument for Word and your picture may either be a Shape or an InlineShape depending on whether it has text wrapping or not.
Sub DeletePicture()
   ActiveDocument.Shapes("Picture 1").Delete
   ActiveDocument.InlineShapes(1).Delete
End Sub


text:
Q: Android Retrofit Get child object of child object I'm trying to get the child object Data which is a child object of Children which if a child object of Data.
I know it sound really confusing, but here is the full JSON object:
Full JSON
Here is my code:
import java.util.List;
import retrofit.RestAdapter;
import retrofit.http.GET;
import retrofit.http.Path;

public class GitHubClient {
    private static final String API_URL = "http://www.reddit.com/r/pcmasterrace/";

    static class Data {
        String kind;
        List<Children> children;
    }

    static class Children {
        Data data;
    }

    interface Reddit {
        @GET("/hot.json?limit=1")
        List<Data> data();
    }

    public static void main() {
        // Create a very simple REST adapter which points the GitHub API endpoint.
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();

        // Create an instance of our GitHub API interface.
        Reddit reddit = restAdapter.create(Reddit.class);

        // Fetch and print a list of the contributors to this library.
        List<Data> data = reddit.data();
        for (Data child : data) {
            System.out.println(child.kind);
        }
    }
}

I keep getting this error:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

A: there are two errors with your design in itself.

*

*the JSON returned is not an Array but an object so trying to store in list is incorrect.

*the array called children is an array of Data objects not an array of Children.Data

you can handle this with one class Data only no point of having Children class.
static class Data {
    String kind;
    String modhash;
    Data data;
    List<Data> children;
}

Next up is accessing these values in main
public static void main(String[] args) {
    // Create a very simple REST adapter which points the GitHub API endpoint.
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .build();

    // Create an instance of our GitHub API interface.
    Reddit reddit = restAdapter.create(Reddit.class);

    // Fetch and print a list of the contributors to this library.
    Data data = reddit.data();
    for (Data child : data.data.children) {
        System.out.println(child.kind);

    }
}


text:
Q: React: Loadable is not working? Hi I am new in react and I want to implement routing with Loadable, But Its not working Its showing blank page when either http://localhost:3000/user or http://localhost:3000/
Could you please correct me where I am doing wrong.
I am also getting-
Warning: Failed prop type: Invalid prop component of type string supplied to Route, expected function.
My codes are:
home.js
import React, { Component } from 'react';
import { Link} from 'react-router-dom';

class Home extends Component {
    render() {
        return (

Welcome to the Tornadoes Website!

<Link to="/user">User</Link>

              );
    }
}

export default Home;

user.js:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class User extends Component {
    render() {
        return (

6/5 @ Evergreens

6/8 vs Kickers

6/14 @ United

<Link to="/">Home</Link>

        )
    }
}
export default User;

App.js:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './helpers/history';
import Loadable from 'react-loadable';
import './App.css';

const Loading = () =>
 Loading...
;

const Home = Loadable({
  loader: () => import('./components/home-component/home'),
  loading: Loading
});

const User = Loadable({
  loader: () => import('./components/user-component/user'),
  loading: Loading
});

class App extends React.Component {
  render() {
    return (
      <Router history={history}>
        <Switch>
          <Route exact path="/" component="Home" />
          <Route path="/user" component="User" />
        </Switch>
      </Router>
    );
  }
}

export default App;

index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import { BrowserRouter } from 'react-router-dom'
ReactDOM.render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'))

registerServiceWorker();

A: I see you are doing this: <Route exact path="/" component="Home" /> which should be <Route exact path="/" component={Home} /> since you want to use that variable, it's impossible to reference by String when he can't know which Component you want. I hope this helps

A: This looks to me like there is a isRequired propType that you have missed when calling your component. Can you post your components here as well?


text:
Q: How to wrap a StreamBuilder class with a Column or ListView class in Flutter? I'm having a problem with my Flutter app, I have a class that returns only a StreamBuilder, it works well, displaying data from Cloud Firestore. But, when I try to wrap this class in a Column or ListView class, it just doesn't show anything.
I need this to display the name of the current page. And the AppBar class is already with the app name, so I can't use this too.
Does anyone know how I can wrap this and keep it running?
A sample code working
  class NewCardsList extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new StreamBuilder<QuerySnapshot>(
      stream: firestore.collection('cards_list').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return const Text('Connecting...');
        final int cardLength = snapshot.data.documents.length;
        return new ListView.builder(
          itemCount: cardLength,
          itemBuilder: (int index) {
            final DocumentSnapshot _card= snapshot.data.documents[index];
            return new ListTile(
              title: new Text(_card['title']),
              subtitle: new Text(_card['description']),
            );
          },
        );
      },
    );
  }
}

A sample code not working
class NewCardsList extends StatelessWidget {

      @override
      Widget build(BuildContext context) {
        return new Column(
          children: <Widget> [
            Text("Your Card List"),
            StreamBuilder<QuerySnapshot>(
          stream: firestore.collection('cards_list').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (!snapshot.hasData) return const Text('Connecting...');
            final int cardLength = snapshot.data.documents.length;
            return new ListView.builder(
              itemCount: cardLength,
              itemBuilder: (int index) {
                final DocumentSnapshot _card= snapshot.data.documents[index];
                return new ListTile(
                  title: new Text(_card['title']),
                  subtitle: new Text(_card['description']),
                );
              },
            );
          },
        ]));
      }
    }

A: Also, you can just make the attribute shrinkWrap: true inside ListView.builder().
 return new ListView.builder(
          shrinkWrap: true,
          itemCount: cardLength,
          itemBuilder: (int index) {
            final DocumentSnapshot _card= snapshot.data.documents[index];
            return new ListTile(
              title: new Text(_card['title']),
              subtitle: new Text(_card['description']),
            );

A: Wrap Streambuilder with Flexible(),then wrap Flexible with Column() set column as body of your scaffold()

A: Use this code structure:
Scaffold
 |_Column
   |_Flexible
     |_StreamBuilder   Your StreamBuilder here

Actual Code:
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Flexible(
            child: StreamBuilder(builder: (context, snapshot) {
            ...
          },
        ))
      ],
    ));
  }


text:
Q: Bundle additional executables with py2exe I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs?

Full explanation: My script is made to execute over a network share (S:\share\my_script.exe) and it makes hundreds of calls to sigcheck and accesscheck. If sigcheck and accesschk also reside on the server, they seem to get transferred to the host, called once, transferred the the host again, called a second time, on and on until the almost 400-500 calls are complete.
I can probably fall back to copying these two executables to the host (C:) and then deleting them when I'm done... how would you solve this problem?

A: I could be wrong about this, but I don't believe this is what py2exe was intended for.  It's more about what you're distributing than about how you're distributing.  I think what you may be looking for is the option to create a windows installer.  You could probably add the executables as data files or scripts using distutils.

arggg Why can't my data_files just get bundled into the zipfile?

I've started using paver for this kind of thing.  It makes it really easy to override commands or create new commands that will allow you to put some new files into the sdist.


text:
Q: Django App Engine can't find antlr3 module I'm trying to set up a Django app to run on GAE, and am using the on_production_server test to choose between dev vs. production settings in settings.py.
However, when I run
python manage.py runserver

I get:
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    import settings
  File "/home/guillaume/myproject/settings.py", line 10, in <module>
    from djangoappengine.utils import on_production_server, have_appserver
  File "/home/guillaume/myproject/djangoappengine/utils.py", line 18, in <module>
    'Error was: %s' % e)
Exception: Could not get appid. Is your app.yaml file missing?
Error was: No module named antlr3

I tried adding the following to settings.py:
import sys
sys.path.append('/usr/local/google_appengine/lib/')

And this line to the very end of .profile:
PATH="$PATH:/usr/local/google_appengine/"

But neither gets rid of the error.  I'm really new to working with paths so I'm kind of fumbling around blindly here.  Can anyone help?

A: Python2.5v or 2.7v?
And what about GAE SDK version?
Did you try this?

A: Saw this question while having the same problem. Solved it by installing antlr 3.1.1 python runtime from Here.


text:
Q: Django form returns method as GET instead of POST I've set method='POST' but print(request.method) in my view prints GET and I don't know why, so my button won't work and save the data,
I have tried everything i know but my code doesn't get fix
This my template where I have set method as POST in form tag and also I have set action of form with the url, I have also set formmethod as POST in button tag:

            <form action="{% url 'create_production' %}" method="POST">
                {% csrf_token %}

                                تاریخ

                                    {{ form.date }}

                                نام شرکت
                                {{ form.comName }}

                                {{ form.comId }}

                                نام محصول
                                {{ form.prodName }}

                                {{ form.prodId }}

                                {{ form.gradeId }}

                                نام گرید
                                {{ form.gradeName }}

                                نوع گرید
                                {{ form.gradeType }}

                                تولید
                                {{ form.qty }}

                                ظرفیت
                                {{ form.cap }}

                                ظرفیت طراحی
                                {{ form.designCap }}

                                برنامه
                                {{ form.plan }}

                                واحد
                                {{ form.unit }}

            <button type="button" formmethod="POST" class="btn btn-primary waves-effect waves-light">تایید</button>
            </form>

and this is my views.py, code won't run the first if condition:
@login_required(login_url='login')
@allowed_users(allowed_roles=['editor'])
def create_production(request):
    print(request.method)
    if request.method == 'POST':
        comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
        form = CreateProduction(request.user, comId, request.POST)
        if form.is_valid():
            production = form.save(commit=False)
            production.user = request.user
            production.save()
            return redirect('/')
    else:
        comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
        form = CreateProduction(request.user, comId)
    return render(request, 'production/production_form.html', {'form': form})

A: So i used input tag instead of button with type equal to submit and it worked


text:
Q: How to connect the ground in this common base schematic to a breadboard? I just want to know how do I connect the ground in this common base circuit. I know how to connect two DC sources but I'm confused on how to connect the ground. I have adept knowledge about the concept of ground, I just want to know how to connect the ground (0V) in this schematic to a breadboard.

A: In order to understand the ground in this circuit or any similar circuits explaining basic concepts, you need to also look at PRACTICAL circuits using the same concepts. In this particular case, you need find a practical common-base amplifier schematic, or actually a few of them, so that you can see the various ways how this is done.  That will help you understand this "ground" concept in such circuits.
Basically, you have to do your own research and thinking, and it takes time and effort (with theoretical, conceptual and practical examples) to understand, no shortcuts.
P.S.: You keep posting very similar, almost the same questions, and you don't mark people's answers as either accepted or helpful. That's not how it works here. If people take the time and effort to answer your questions, you should take a couple seconds to show you appreciate the help.

A: In most electronic circuits, particularly battery-powered circuits, the Ground symbol just indicates the point that the designer considers as "Zero Volts", and does not imply any connection to The Earth.
You are not expected to connect that "Ground" symbol to the AC Safety Ground or other external ground point.


text:
Q: Unable to click button with Selenium - python I'm having difficulty clicking on a button using selenium. Can't seem to figure out what I'm doing wrong
self.driver.find_element(By.XPATH, "//button[contains(text(), 'Call Me ')]").click()
EDIT:
So Think the problem is the the xpath according to
https://sqa.stackexchange.com/questions/36918/xpath-text-buy-now-is-working-but-not-containstext-buy-now
However, my new function is still not able to locate the element
//button[contains(.,'Call Me')]
Thanks for the help so far.
Below is the HTML code for the button I'm trying to get to.

<fieldset data-device-index="phone1" class="">

Choose an authentication method

<input type="hidden" name="factor" value="Duo Push">

Duo Push

Recommended

<button tabindex="2" type="submit" class="positive auth-button">Send Me a Push </button>

<input type="hidden" name="factor" value="Phone Call">

Call Me

<button tabindex="2" type="submit" class="positive auth-button">Call Me </button>

A: I had this same trouble, and I tried this:
path =  'your xpath'
button = driver.find_element_by_xpath(path)
button.Click()

This work very well for me.


text:
Q: jQuery/Javascript split a text node into two or three? I have a div let's say with 3 lines of text. I want to split that div into two, so let's say I have 150 characters, I want to split it so I would end up with two equal parts by word.
So let me explain a bit more:
A text node is below... It has 6 lines in the stackoverflow wysiwyg container:

Brown the roast on all sides in a large lightly oiled skillet over high heat, before
adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring
potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length.
Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on
top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover
and cook on low for 8-10 hours. Yield: 6 servings.

Let's say I want to split that div into two divs of 52 pixels (according to my browser it is 104 pixels height). But I want to do it so it doesn't mean up the wording, meaning I don't want to splitCut into two words, so C in one div and ut in another, for example.
So I would end up with something like
Div 1

Brown the roast on all sides in a large lightly oiled skillet over high heat, before
    adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring
    potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length.

Div 2

Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on
    top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover
    and cook on low for 8-10 hours. Yield: 6 servings.

Is there a way to do this?

A: You could use
var text = $('div').text();
var tokens = text.split(' ');
var n = Math.floor(tokens.length/2);
var html = '
'+tokens.slice(0, n).join(' ') + '

' + tokens.slice(n+1, tokens.length).join(' ') + '
';
$('div').html(html);

Demonstration
Note that for a better result, especially regarding a recipe, you could also split on the dot :
var text = $('#a').text();
var tokens = text.split('.');
var n = Math.floor(tokens.length/2);
var html = '
'+tokens.slice(0, n).join('.') + '.

' + tokens.slice(n+1, tokens.length).join('.') + '
';
$('#a').html(html);

Demonstration with a split on the dot
Now, it's probable you don't want to have the same number of sentences in both paragraph but about the same length in characters. Then, here's what you can do :
var text = $('#a').text();
var sentences = text.split('.');
var sum = 0;
var lengths = sentences.map(function(v){sum+=v.length; return v.length});
var n = 0;
var ts = 0;
while (ts<sum/2) ts += lengths[n++];
var html = '
'+sentences.slice(0, n-1).join('.') + '.

' + sentences.slice(n, sentences.length).join('.') + '
';
$('#a').html(html);

Demonstration (not on jsfiddle.net because they seem to be down)


text:
Q: Loop through items and target first 3 and last items seperately Is there a better way to write this for loop?

*

*I am basically looping through a collection of divs.  (The number of divs can increase and decrease dynamically, so it's never a set number).

*If the length of the collection is greater than 4, I want to set flex styling the first 3 items.  And I want to set a width on the remaining items, from the 4th item on wards.

*If the length of the collection is less than 4, I want to set flex styling on all items.

This works at the most basic level but wondered if there was a smarter way to write this?
let divCount = document.getElementsByClassName("luggage-tile-wrapper active");

for (let i = 0; i < divCount.length; i++) {
    if (divCount.length > 3) {
        for (let i = 0; i < 3; i++) {
            divCount[i].style.flex = "1 0 22.2%";
        };
        for (let i = 3; i < divCount.length; i++) {
            divCount[i].style.width = "145px";
        };
    } else {
        for (let i = 0; i < divCount.length; i++) {
            divCount[i].style.flex = "1 0 22.2%";
        };
    };
}

Thanks,

A: Do two loops, one for the first 3, the other for the rest. If there are less than 3 divs, the second loop won't do anything.
let first3 = Math.min(3, divCount.length); // don't go past the end if less than 3
for (let i = 0; i < first3; i++) {
    divCount[i].style.flex = "1 0 22.2%";
}
for (let i = 3; i < divCount.length; i++) {
    divCount[i].style.width = "145px";
}

A: So you always want to do
divCount[i].style.flex = "1 0 22.2%";

for the first 3 items
And for every other item you want
divCount[i].style.width = "145px";

So this is it
for (let i = 0; i < divCount.length; i++) {
  if (i < 3) {
    divCount[i].style.flex = "1 0 22.2%";
  } else {
    divCount[i].style.width = "145px";
  }
}

A: I know you've already accepted an answer--and I realize I don't have all the information--but it seems like you could achieve this entirely in css, without any javascript at all.

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > * {
  flex: 1 0 22.2%;
  background: skyblue;
}

.container > :nth-child(1n + 4) {
  background: pink;
  width: 145px;
}

item

item

item

item

item

item

item


text:
Q: How to get client's computer MAC Address and IP in asp.net? I want to get client computer MAC address and IP at the time of login for purpose of uniquely identify the client computer.

A: You can get client IP address from request objects UserHostAddress property like
Page.Request.UserHostAddress

Looks like there is no straight forward way of getting client MAC address except using WMI which other answers already have pointed on.

A: To get the user's IP address you can use Request.UserHostAddress or Request.ServerVariables["REMOTE_ADDR"].
Getting the MAC address I am not sure it is so simple. It is not something that is available to the server (ASP.NET) like the IP address is. From what I know you will need to use client scripting and ActiveX or Java applets to get to that information (after multiple installation and security prompts on the users' machines).
So in other words, get IP address by Request.UserHostAddress. Avoid using MAC address and look for another solution if IP is not unique enough for your needs. Maybe combine it with browser User Agent string instead (Request.ServerVariables["HTTP_USER_AGENT"] or Request.UserAgent but the latter might not be available in older versions of .NET).

A: refer to the below link , may be they will be useful for you...
http://forums.asp.net/t/1911211.aspx?Get+Client+Mac+Address+in+Asp+Net+Web+Application
http://www.codeproject.com/Answers/187064/i-need-MAC-Address-of-client-machine-using-asp-net#answer1


text:
Q: Connect to Azure Storage Account using only SAS token? Is there a way to connect to a storage account or container only using a SAS token and the endpoint for that storage account? I've already done the demo/sample and it is using the connection string (which works) but I don't see how to connect to my storage using only the SAS?
Is there any example how to do this in java?

A: I generate SAS Token for my specific blob on the portal then download it successfully via the token.

sample code:
import com.microsoft.azure.storage.blob.CloudBlockBlob;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

public class DownloadBlobSAS {

    public static final String blobSasToken = "***";

    public static void main(String[] args) {
        try {
            CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(blobSasToken));

            InputStream input =  sasBlob.openInputStream();
            InputStreamReader inr = new InputStreamReader(input, "UTF-8");
            String utf8str = org.apache.commons.io.IOUtils.toString(inr);
            System.out.println(utf8str);

            System.out.println("print done");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output Result:

If you want to generate SAS token, you need to provide connection string first to access container or blob.
Then you could use generateSharedAccessSignature() method to create SAS token.You could refer to the sample code:
SharedAccessBlobPolicy sp = createSharedAccessPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 300);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        this.container.uploadPermissions(perms);
        Thread.sleep(30000);

        CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(this.blob.getUri().toString() + "?"
                + this.blob.generateSharedAccessSignature(null, "readperm")));

Hope it helps you.


text:
Q: When I reply to .Prompts.choice() with Direct Line API, my bot doesn't work correctly I'm making a website with Direct Line API.
http://qavppy-bot-test-123.azurewebsites.net/
But, my bot does't recognize messages, when I replay to question of .Promts.choice().
I don't know why, but bot says message of .onDefault().
It seems that bot doesn't work correctly...
When I use another ways(Slack, WebChat, etc),
bot works correctly.
Plz advices.
Capture

A: The issue was that the 'from' property in the request was not set.
Try setting the 'from' property and Prompt.Choice should work.


text:
Q: EF and Code First Migrations with MySQL - dbo.tablename does not exist I have set up entity framework to use MySQL and created a migration.
When I run update-database I get error "table dbname.dbo.tablename' does not exist. Running in -Verbose mode I see the statement that causes the error :
alter table `dbo.Comments` drop foreign key `FK_dbo.Comments_dbo.Comments_Comment_ID`

When I run the query direct in MySQL workbench is throws the same error.
The problem seems to be the dbo. prefix in the migration set. Anything in the form dbo.tablename won't run saying that table does not exist. E.g. select * from  dbo.tablename fails but select * from tablename works. The database was generated by Entity Framework and the code first migrations were generated by EF too.
However the migrations generate everything with the dbo. prefix, which does not work.
Does anyone have a solution to this?

A: I was having this problem just today as well; found my answer here:
MySqlMigrationCodeGenerator
You have to set:
CodeGenerator = new MySqlMigrationCodeGenerator();

In your context's configuration class. This will get rid of the schema gibberish for MySQL. My Configuration class looks like this:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
        SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
        CodeGenerator = new MySqlMigrationCodeGenerator();
    }
}

A: I have this same issue and I applied the solution posted by Sorio and It generated a lot of problems.
CodeGenerator = new MySqlMigrationCodeGenerator();

This code line can change all the sql that you generate, for example in my case in the sql code to apply to the database all the foreign key constraints disappear.
I am still without a solution because for me this is not acceptable and I recommend you to check the sql generate with the command before use this solution:
update-database -script


text:
Q: Is there a way to use R Fable with Spark? I've successfully built a pipeline for hierarchial time-series forecasting using the fable package. For now I've used multicore function from the future pacakge (in Databricks). And, for ~1k time series the runtime isn't too bad. Below is the code I have for that.
plan(multicore, workers = 14)
model_multicore_log_exts <- data_for_modeling %>%
    model(
          prophetML_additive_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "additive")),
          prophetML_multiplicative_lin = prophet(log(dependent_variable) ~ exogenous_var1 + exogenous_var2 + exogenous_var3 + growth("linear") + season("year", type = "multiplicative")),
          nn = NNETAR(log(dependent_variable) ~ trend() + season() + exogenous_var1 + exogenous_var2 + exogenous_var3, n_networks = 50)
          )

But, I have the need for increasing that number substantially.
So, I'm wondering if there is a way to distribute with sparkr. I cannot find anything in the fable CRAN documentation nor anything with a google search, so I am asking here.
Any suggestions/advice appreciated.
Thank you,
Brian


text:
Q: How to get parent object ID when clicking on ellipse element? If I'm interpreting correct hierarchy of elements, what I'm wanting to do would be ...
That element <ellipse> children of <svg>, <object> and
 when clicked showed me the id of your <object> parent.
this * is because the <ellipse> will be from your respective svg div.
This is how my HTML strtucture is, thoses #DOCUMENT are window.frames opened by each <object> tag.

        <object id="OneNameObject" data="../folder/fileOne.svg">
           #DOCUMENT
              <svg>
                <ellipse>I have one addEventerLinster Click here</ellipse>

             </svg>
        </object>

        <object id="TwoNameObject" data="../folder/fileTwo.svg">
           #DOCUMENT
              <svg>
                <ellipse>I have one addEventerLinster Click here</ellipse>

             </svg>
        </object>

For now I'm getting access to the <object> id when I specify the index of it to be used.

0 for svg_1 #document
1 for svg_2 #document

So I thought I'd use the this selector to call the ellipse hireararchy. But I could not, and i don't know how.
something like :
this.parent.document.querySelector('object').id;

This is the way i getting the id using index, and by this - for sure - i aways get the id from selected <object>.

window.onload = function (){

  //This is for addEventLinster on each <ellipse>.
  var obj = document.querySelectorAll('object');

   for (var x = 0; x < obj.length; x++){

    var svg = obj[x].contentDocument.querySelector('svg');
    var e = svg.querySelectorAll('ellipse');

       for ( var i = 0; i < e.length; i++){

            e[i].addEventListener('click', function(){

            var objId = parent.document.getElementsByTagName('object')[0].id;

            alert(  objId  );

            });
       }
   }
};

Working Example \ but not functional on my context.

This code is working, but it's not on my context ! Need to get that info, I am using <object> data attr to load svg files, they come on embed tags with a new window frame and a new document page. That is why i cant get they elements so easy.

Image HTML Code / DOM painel  - * detail :  ellipses is on <g> tag.

$(document).ready(function(){

         var obj = $('ellipse');

         obj.on('click', function(){

         alert($(this).parents('object').attr('id'));

         });

});
div {

width: 52px;
margin: 2px;
border-radius: 10%;
}

#svg_1:hover, #svg_2:hover {

opacity: 0.7;

}

#svg_1 {

border: 2px solid indianred;

}

#svg_2 {

border: 2px solid lightblue;

}

        <object id="redObject" data="">

 <svg width="50" height="48" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">

  <ellipse ry="14" rx="13" id="svg_2" cy="25" cx="25" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" stroke="#cd5c5c" fill="#bf2a2a"/>

</svg>

        </object>

        <object id="blueObject" data="">

 <svg width="50" height="50" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">

  <ellipse ry="14" rx="13" id="svg_2" cy="25" cx="25" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="0" stroke="#c95c5c" fill="#56aaff"/>

</svg>

        </object>

ps; I found the title of the question a bit confusing, in case someone has a better suggestion, I would appreciate it!

A: Give the below a try. (Not a tested code but should ideally work unless some syntax issues or so)
We can check if something can unnecessary can be removed.
$.each($('[id^="svg_"]'),function(){
    var eclipse = $(this).find("object").find('svg').find('ellipse');
     console.log(eclipse)
   $(eclipse).click(function (){
     alert($(this).parent().parent().attr('id'))
   })
});


text:
Q: Python Skype4Py message status remains 'SENDING' import Skype4Py

skype=Skype4Py.Skype()

skype.Client.Start()

skype.Attach()

skype.SendMessage('echo123','Test')

The code works, but for some reason, when I send a message, its status remains SENDING, therefore I am not able to send any messages.
Edit  : turns out the method sends the message as soon as the contact is online.

A: Messages are always sent when the user is online.


text:
Q: Save table to csv file where both file name and table name are variables If I want to save table table1 to csv file /tmp/table1.csv I can do it with:
`:/tmp/table1.csv 0: csv 0: table1

But what if both file name and table name come from string variables?
fname:"/tmp/table1.csv"
tname: "table1"
/ how do I save table tname to file fname?

A: This should work:
hsym[`$fname] 0: csv 0: value `$tname

https://code.kx.com/q/ref/filewords/#hsym
and valuing a symbol, returns the value of the variable it names.


text:
Q: jquery fadeIn/Out el then fadeIn/Out new el Sorry for title feel free to edit it,
Anyway this is the code I have so far
$('#foo').click(function() {

  $('#foo2').html('
Please wait...
').fadeOut('fast');

  var sful = $('#foo3').fadeIn('fast').html('
Success!
').fadeOut('slow');
  setTimeout(sful, 4000);

});

I'm trying to get #foo2 to fadeIn on click, then for it to fadeOut and #foo3 (var sful) to then fadeIn/Out after.

A: $('#foo2').html('
Please wait...
').fadeOut('fast', function() {
  var sful = $('#foo3').fadeIn('fast').html('
Success!
').fadeOut('slow');
  setTimeout(sful, 4000);
});

The callback (function() { .. will run after the animation has finished. See http://api.jquery.com/fadeOut/ (specifically the [,callback] section).

A: $('#foo2')
          .html('
Please wait...
')
          .fadeOut('fast', function() {  // callback start after fadeOut()
                             setTimeout(function() {
                                 $('#foo3')
                                       .fadeIn('fast')
                                       .html('
Success!
')
                                        .fadeOut('slow');
                              }, 4000);
                           });


text:
Q: I am having some trouble with adding checkbox column in a my datagridview I have a datagridview on my page, the datasource of which keeps changing based on records retrieved with pair of values from 2 combo-boxes,
I need to add a checkbox column to my datagrid, which has no databinding with any column from my database table, i am using this code
public void RefreshDataGrid(string query)
        {
            Buisness_logic bl = new Buisness_logic();
            dataGridView1.DataSource = bl.GetDataTable(query);
            SetUpDataGridView();
            dataGridView1.ClearSelection();
        }

        public void SetUpDataGridView()
        {

            DataGridViewCellStyle style = dataGridView1.ColumnHeadersDefaultCellStyle;
            style.BackColor = Color.White;
            style.ForeColor = Color.Black;
            dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.Columns[0].HeaderText = "Sr.No";
            dataGridView1.Columns[0].Width = 50;
            dataGridView1.Columns[1].HeaderText = "Rate";
            dataGridView1.Columns[1].Width = 70;
            dataGridView1.Columns[2].HeaderText = "Amount";
            dataGridView1.Columns[2].Width = 100;
            dataGridView1.Columns[3].HeaderText = "Mode";
            dataGridView1.Columns[3].Width = 60;
            dataGridView1.Columns[4].HeaderText = "Support";
            dataGridView1.Columns[4].Width = 80;
            dataGridView1.Columns[5].HeaderText = "Team1";
            dataGridView1.Columns[5].Width = 100;
            dataGridView1.Columns[6].HeaderText = "Team2";
            dataGridView1.Columns[6].Width = 100;
            dataGridView1.Columns[7].HeaderText = "Team3";
            dataGridView1.Columns[7].Width = 100;
                DataGridViewCheckBoxColumn column3 = new DataGridViewCheckBoxColumn();
                column3.Name = "Column3";
                column3.HeaderText = "IsCheck";
                column3.ReadOnly = false;
                dataGridView1.Columns.Add(column3);
        }

It datagridview is good when tge form loads the first time, but when i change the value of the combo-boxes and the datasource changes, the columns get messed up, and a no. of checkbox columns get added and that ruins my form,
here is the code i used to retrieve the records from table
Combo_pair pr1 = combo_match_code.SelectedItem as Combo_pair;
                int match_code_f1 = Convert.ToInt32(pr1.Text);
                Combo_pair pair = combo_name.SelectedItem as Combo_pair;
                int userid_f1 = Convert.ToInt32(pair.Value);
                string query = "Select int_sr_no,double_rate,double_amount,txt_mode,txt_support,double_team1,double_team2,double_team3 from match_transaction where int_match_code='" + match_code_f1 + "' AND int_user_id='" + userid_f1 + "' AND is_deleted=0";
                RefreshDataGrid(query);

this is the image when the form loads for the first time

and this is the image after i change the combo box values a few times

*(sorry, having trouble with images)
i really need some help with these, thanxx

A: You need to setup the gridview only once.
A good place to do this is after InitializeComponent().
Since this is a fixed column, you could also add it through the designer (Edit Columns).
That way the code would get add to InitializeComponent().
InitializeComponent() is usually called in the constructor of your form.
At present you are adding this line
dataGridView1.Columns.Add(column3);

Will cause the checkbox column to be added several times.

A: Before the answer I'm just going to restate the problem in steps (so that my solution hopefully makes more sense):

*

*You have a databound DataGridView where you want to change details of columns

*When you want refresh the data in the grid (your search criteria change) your changes to the columns are overwritten

*To fix this you update date grid datasource and remake all the changes

*This has the side effect that an unbound checkbox column you add is being added multiple times

So the problem in a nutshell is how to keep the changes to columns while also only having the one column?
The trick here is the DataGridView's AutoGenerateColumns property.
For sake of argument let is say that you first setup your grid during the form load - if not then you might need a boolean field to store if you have previously setup the grid.
public Form1()
{
    InitializeComponent();

    // So this is the first time we call your refresh grid with some default string query
    RefreshDataGrid(query);

    // Now one time only we call SetUpDataGridView()
    SetUpDataGridView();

    // Now once we have done that we set AutoGenerateColumns to false
    dataGridView1.AutoGenerateColumns = false;

}

public void RefreshDataGrid(string query)
{
    Buisness_logic bl = new Buisness_logic();
    dataGridView1.DataSource = bl.GetDataTable(query);
    // We no longer need to call SetUpDataGridView()
    // SetUpDataGridView();
    dataGridView1.ClearSelection();
}

Your SetUpDataGridView() method is pretty much identical:
public void SetUpDataGridView()
{

    DataGridViewCellStyle style = dataGridView1.ColumnHeadersDefaultCellStyle;
    style.BackColor = Color.White;
    style.ForeColor = Color.Black;
    dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;
    dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
    dataGridView1.RowHeadersVisible = false;
    dataGridView1.Columns[0].HeaderText = "Sr.No";
    dataGridView1.Columns[0].Width = 50;

    // And so on for all the columns...

    dataGridView1.Columns[7].Width = 100;
    DataGridViewCheckBoxColumn column3 = new DataGridViewCheckBoxColumn();
    column3.Name = "Column3";
    column3.HeaderText = "IsCheck";
    column3.ReadOnly = false;
    dataGridView1.Columns.Add(column3);
}

So now when the combboxes containing the query information change you can call RefreshDataGrid() but it will only update the data, not change your custom settings.

One suggestion for the RefreshDataGrid() method is to add a line like so:
public void RefreshDataGrid(string query)
{
    Buisness_logic bl = new Buisness_logic();
    // This is the new line
    dataGridView1.DataSource = typeof(List<>);
    dataGridView1.DataSource = bl.GetDataTable(query);
    // We no longer need to call SetUpDataGridView()
    // SetUpDataGridView();
    dataGridView1.ClearSelection();
}

This can reduce flicker as column widths change and also is often necessary to make changing the DataSource show at all.


text:
Q: JFrame Bug workaround I discovered something weird while programming an application:
I wanted a JFrame to be placed over the entire screen. It works perfectly with this code:
public class NativeFunctions extends JFrame {

    public NativeFunctions() throws HeadlessException {
        this.setUndecorated(true);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setBackground(new Color(0, 0, 0));
        this.setVisible(true);
    }

    public static void main(String[] args) {
        NativeFunctions n = new NativeFunctions();
    }
}

When I just change the line of code, that sets the color to a color with an alpha value, the things start get get weird:
public class NativeFunctions extends JFrame {

    public NativeFunctions() throws HeadlessException {
        this.setUndecorated(true);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setBackground(new Color(0, 0, 0, 20));
        this.setVisible(true);
    }

    public static void main(String[] args) {
        NativeFunctions n = new NativeFunctions();
    }
}

Starting the first application, the JFrame opens and covers up the screen - as expected. Try to move the mouse in the top left, top right, bottom right or bottom left corner and press a mouse key. Nothing will happen.
Do the same thing with the second application (with the alpha value) and the click will be registered. But this happens only in the outermost corner!
Can you reproduce this and would you say it is a bug? Do you have an idea for a workaround?
Edit: Also important: For all transparency values the same! Only works at the outermost corner, not in the middle of the application, so the mouse click is not generally passed by!

A:
(with the alpha value) and the click will be registered. But this happens only in the outermost corner!

You need to define "registered".
In my case, nothing happens, no matter where I click because all mouse events are just passed to the frame, but there is no listener added to the frame so I have no cue that anything just happened.
This is what I expect to happen with partial transparency (alpha values between 1 - 255).
However, with an alpha value of 0, then the mouse event is ignore by the Swing application and is passed to the desktop.
So, for example, if I click on the bottom/left where the Windows Start button is I see the Start menu popup.
If I click anywhere else then the application I click on is now activated and becomes the active window.
There is no distinction between "outermost corner" (however you define that?) and clicking in the center of the screen.

Do you have an idea for a workaround?

I'm guessing you want to prevent the mouse event from being passed to the destop when you have an alpha value between 1 - 255.
Did you try adding a MouseListener to the frame?
Maybe you can try adding a GlassPane to the frame and add a MouseListener to the GlassPane?

A: After quite a while of testing I found out what the "bug" was. There is no Bug in Java but strangely it had to do with Netbeans. Whenever I started the program from Netbeans it did not work (what I described in my question happened) but when I started the .jar file it worked out perfectly!