text:
Q: Rearrange order of sections in r markdown pdf based on score I have two data frames like these full of info about candidates for a job:
Scores<-structure(list(Name = c("John Smith", "Jane Doe",
"John Doe", "Jan Jenkins", "Lauren John", "Jennifer Patty",
"Zachary Gala"), `Applicant Name` = c(1, 18, 5, 6, 3, 4, 2),
    `Sum-100` = c(75, 85, 97, 53, 61, 31, 85), `Edu.-20` = c(12,
    19, 20, 10, 14, 8, 18), `Personality-15` = c(10, 14, 15,
    8, 8, 7, 12), `Verbal-15` = c(12, 12, 14, 7, 6, 6, 13), `Maturity-15` = c(14,
    11, 15, 8, 8, 5, 13), `Research-15` = c(13, 10, 14, 10, 13,
    4, 14), `Intellect-15` = c(16, 19, 19, 10, 11, 1, 15), `LOR-10` = c(NaN,
    9, 3, 8, 6, 4, NaN), `PS-10` = c(NaN, 8, 3, 8, 5, 4, NaN)), row.names = c(NA,
-7L), groups = structure(list(Name = c("John Smith", "Jane Doe",
"John Doe", "Jan Jenkins", "Jennifer Patty", "Jennifer Patty",
"Zachary Gala"), .rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L,
    7L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), row.names = c(NA, 7L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"))

Comments<-structure(list(`Applicant Name` = c(1, 1, 2, 2, 3, 2, 2, 3, 3,
4, 5, 6, 3, 3, 1, 1, 18), Name = c("John Smith", "John Smith",
"Zachary Gala", "Zachary Gala", "Lauren John", "Zachary Gala",
"Zachary Gala", "Lauren John", "Lauren John",
"Jennifer Patty", "John Doe", "Jan Jenkins", "Lauren John",
"Lauren John", "John Smith", "John Smith",
"Jane Doe"), Overall = c("overall good  and bla bla bla this is a very long comment because I want to see how it works etc. etc. bla",
"cant do it", "breathtaking", "fdwdf wfew", "joke was funny",
"Interesting person", "asdfd asdasf dasjlfoeiwna osdnkdasjbfiabdk hfhajh dsfklhdsakl hfawei uhdk jashfiaw ulhfk jldbkla hbvliub",
"Dumb", "sfdgsv", "do not take this person", "incredible opportunity for us",
"medium plus", "bla", "goao", "dfg", "ffohfosfdosfdifof", "Silly"
)), row.names = c(NA, -17L), class = c("tbl_df", "tbl", "data.frame"
))

And I'm compiling all this data and showing graphs and tables about it in a pdf that I'll probably be printing and physically handing to a bunch of people that will be reviewing the candidates.  There is a section about each candidate that looks like this:

And I just had one of the people who is a reviewer ask me if I could reorganize the document so that applicants with higher scores would have their sections near the top of the document.  Is there a way to do that with code?  Worth mentioning I don't actually have their scores and data yet (will come from a redcap database at the last second), so Ideally the second I get the raw data, I could code it to automatically move everything around.  To physically reorganize where their section is in the pdf.   I can imagine some sort of filter in this code:
kable(School%>%filter(applicant_name=="2")%>%select(-applicant_name))%>%
  kable_paper("hover", full_width = F)

That would filter to the person with the "second best" score or something, but how could I reorganize what photo of what applicant went where? And what name went in the section header? Is it even possible?

A: You could first arrange the tibble by the score of interest, then generate dynamic sections using \section{} (LaTeX) in a loop.
Something along these lines would accomplish it, assuming kableExtra-tables is handled the same way as knitr::kable
---
output: pdf_document
---

```{r, results='asis', echo=FALSE, message=FALSE, warning=FALSE}
library(dplyr)
library(knitr)
library(kableExtra)

Scores<-structure(list(Name = c("John Smith", "Jane Doe",
"John Doe", "Jan Jenkins", "Lauren John", "Jennifer Patty",
"Zachary Gala"), `Applicant Name` = c(1, 18, 5, 6, 3, 4, 2),
    `Sum-100` = c(75, 85, 97, 53, 61, 31, 85), `Edu.-20` = c(12,
    19, 20, 10, 14, 8, 18), `Personality-15` = c(10, 14, 15,
    8, 8, 7, 12), `Verbal-15` = c(12, 12, 14, 7, 6, 6, 13), `Maturity-15` = c(14,
    11, 15, 8, 8, 5, 13), `Research-15` = c(13, 10, 14, 10, 13,
    4, 14), `Intellect-15` = c(16, 19, 19, 10, 11, 1, 15), `LOR-10` = c(NaN,
    9, 3, 8, 6, 4, NaN), `PS-10` = c(NaN, 8, 3, 8, 5, 4, NaN)), row.names = c(NA,
-7L), groups = structure(list(Name = c("John Smith", "Jane Doe",
"John Doe", "Jan Jenkins", "Jennifer Patty", "Jennifer Patty",
"Zachary Gala"), .rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L,
    7L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), row.names = c(NA, 7L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"))
```

```{r, results='asis', echo=FALSE}
#Arrange tibble by the Sum-100 column in descending order.
arrangedScores <- Scores %>%
  arrange(desc(`Sum-100`))

#Extract the names in descending order to iterate through in the for loop
arrangedNames <- arrangedScores$Name

#Uncomment to include images
#arrangedScores$img <- "example_image.png"

for(i in arrangedNames){
  tableFrame <- arrangedScores %>%
    dplyr::filter(Name == i)

  #Create section header with name and score
  cat(paste0("\\section{",i, ". Score: ",tableFrame$`Sum-100` ),"}")

  #Uncomment to include images
  #cat("![](",tableFrame$img,")")

  #Print table. Need print() to print kable in loop, ref
  #https://bookdown.org/yihui/rmarkdown-cookbook/kable.html#generate-multiple-tables-from-a-for-loop
  print(kable(tableFrame))

  #Remove this to not generate new page for each application
  cat("\\newpage")

}
```


text:
Q: Typo3: Repository->findAll() returns only one entry I have created an extbase extension, using the extension builder.
But when i call findAll() it returns the first row of the mapped table, but again and again. The number of results is correct but all of them are only the first row.
Mapping:
config.tx_extbase {
    persistence {
        classes {
            Vendor\ExtName\Domain\Model\Word {
                mapping {
                    tableName = table_name
                    columns {
                        id.mapOnProperty = id
                        string.mapOnProperty = string
                    }
                }
            }
        }
    }
}

listAction():
public function listAction() {
    $words = $this->objRepository->findAll();
    $this->view->assign('obj', $objects);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Layer ModuleWrapper has arguments ['module', 'method_name'] in `__init__` and therefore must override `get_config()` I have created a simple ann like this:
`from keras.models import Sequential
import tensorflow
from tensorflow.python.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
model = Sequential()
model.add(Dense(20, input_dim=2, kernel_initializer='uniform', activation='relu'))
model.add(Dense(1))
model.compile(loss='mse', optimizer = 'adam', metrics= tf.keras.metrics.RootMeanSquaredError())
n_epochs = 1000
n_batch = 6
model.fit(x_train_norm, y_train, epochs=n_epochs, batch_size=n_batch, verbose = 1)
`
And when I try to save the model: (already installed h5py)
model.save("model.h5")
I get the next error message:
Layer ModuleWrapper has arguments ['module', 'method_name']
in `__init__` and therefore must override `get_config()`.

Example:

class CustomLayer(keras.layers.Layer):
    def __init__(self, arg1, arg2):
        super().__init__()
        self.arg1 = arg1
        self.arg2 = arg2

    def get_config(self):
        config = super().get_config()
        config.update({
            "arg1": self.arg1,
            "arg2": self.arg2,
        })
        return config

I've read NotImplementedError: Layers with arguments in `__init__` must override `get_config`
but I don't know how to apply it to my problem because It's a very simple ann, I don't youse encoder like in the example above


text:
Q: How to unbind a gpu /sys/bus/pci How do I unbind an Nvidia GPU in /sys/bus/pci/driver/nvidia/unbind in order to use it for virtualization
I am using sudo echo "0000:09:00.0" > unbind but I get bash: unbind: Permission denied
I am following the docs from IBM,but can't seem to figure out to unbind the gpu
the os I am using is ubuntu 22.04
when running the command echo "0000:09:00.0" | sudo tee /sys/bus/pci/drivers/nvidia/unbind this cause the terminal to hang and I can't use it anymore
even trying to kill the process fails
root        8646  0.0  0.0  14356  5912 pts/0    S+   09:07   0:00 sudo tee /sys/bus/pci/drivers/nvidia/unbind
root        8647  0.0  0.0  14356   956 pts/1    Ss+  09:07   0:00 sudo tee /sys/bus/pci/drivers/nvidia/unbind
root        8648 11.5  0.0   8380  1024 pts/1    R    09:07   0:14 tee /sys/bus/pci/drivers/nvidia/unbind


text:
Q: Which effects do not persist to a new game? In the original Diablo, after defeating Diablo (or whenever you feel like it) you can start a new game with the same character retaining your character stats and items. Except that some things do not persist to the new game.
The ones I know about are:

*

*Effects from the Gloomy shrine

*Effects from the Weird shrine

*The unique Lightforge mace (according to Jarulf's Guide, this morphs into a different item when you start a New Game)

Are there others?
Note 1: Not sure if there would be differences between single-player and multi-player, but I'm playing single-player.
Note 2: Obviously, available quests, quest status, monsters, dungeon-layout, and whatnot all do not persist to a new game. I am asking specifically about items, item stats, and character stats/spells.

A: I've read completely through a couple of guides and tried many things out for myself. Here is what I have learned:
Character Modifications
There is really nothing that changes for your character between games. The only one that does is that you lose any spell effects that you currently have, which you would anyway for simply entering town.

*

*Modifications to your max mana via Sacred, Ornate, and Fascinating shrines persist to the new game

*Modifications to your max health via Black Death zombies persist

*Items you are wearing and carrying persist. Items left on the ground in town do not.

*Spells effects do not persist such as Infravision and Mana Shield.

*Any town portal you have does not persist.

*Openings to Caves, Catacombs, and Hell are based on your level in multiplayer and therefore appear in the new game. In single player, these openings are always closed on a new game.

Item Modifications
Not all item stats persist to a new game!

*

*The Lightforge mace morphs when you carry it to a new game. (I haven't seen this happen and have no idea what it morphs into)

*Effects from the Weird shrine do not persist to a new game. This was doubted (for good reason), so here is some proof:

Sword affected by Weird Shrine:

Same sword after starting new game:

*

*Effects from the Gloomy shrine do not persist to a new game. This was also doubted, so here is more proof:

Helm affected by Gloomy Shrine:

Same Helm after starting new game:

*

*Effects from Hidden Shrine do persist. The helm pictured above was also affected by a Hidden Shrine.

*Changes based on Warrior's Repair skill and Sorcerer's Recharge skill persist.

*Current durability and spell charges persist

Note: Any effect received from a Goat Shrines or Cauldron will persist in the same manner as one from the named shrine.

A: I realize that this thread is long dormant, but I found another exception worth noting. The Constricting Ring morphs when carried over to a new game as well.  I was wearing it when I defeated Diablo and when I started a new game, it had morphed into the Ring of Engagement, which...ironically, I already had in my inventory.   The really weird part though is that the max resistance was permanent.  I was maxed out across the board even when I took the ring off.

A: Just to add 5 cents: you only carry items that you have in inventory. OK this was obvious and you learn this first time you beat the game. BUT: you only carry items that you had from your last save, not when you killed Diablo.
And since Diablo may drop something juicy, here's advice. You cannot move when you kill Diablo, you are stuck while he is bleeding and then final animation starts. You can pick up item if it is next to you. What I did to get the Diablo's item is to spawn tons of guardians, then cast Telekinesis spell so pointer is changed and ready to fire the spell. Then wait and hope guardians will finish Diablo. When they do and your Telekinesis is ready, just fire it and get the item. Now you have to save to get this item in new game. And now you have Diablo's item in new game and you can identify it to see what it is.
Btw, I doubt I ever kept his item as I usualy already had something better, but they did sell for lot of gold.


text:
Q: How to select the partial view page by default using angular.js I have one problem.I have a login page.When user will logged in the home page is coming.In that home page i have some options which called its respective partial view page.Let me to explain my code first.

user.html:

div class="navbar-header navbar-brand">
{{deptName}}

Home

Plan

Subject

User Management

User Role

Time Table

Faculty

WDS

After login the above page is coming. Check my below routing path:
.state('user',{
        url: '/user',
        templateUrl: 'userview/user.html',
        controller: 'userController'
    })
    .state('user.plan',{
        url: '/plan',
        templateUrl: 'userview/plan.html',
        controller: 'planController'
    })
    .state('user.profile',{
        url: '/profile',
        templateUrl: 'userview/profile.html',
        controller: 'userProfileController'
    })

Here I need when user will logged in the plan.html will set up by default inside the ui-view of user.html.

A: Well, it seems like a "default redirection issue". And there are solutions, this one I do like the most:
Redirect a state to default substate with UI-Router in AngularJS
where we can mark any state with its default redirection target:
.state('user',{
    url: '/user',
    templateUrl: 'userview/user.html',
    controller: 'userController',
    // here is new marker
    redirectTo: 'user.plan'
})

And with this small code snippet it will start to do the magic:
app.run(['$rootScope', '$state', function($rootScope, $state) {

    $rootScope.$on('$stateChangeStart', function(evt, to, params) {
      if (to.redirectTo) {
        evt.preventDefault();
        $state.go(to.redirectTo, params)
      }
    });
}]);

There is even working example


text:
Q: Design of programming with databases for DB tables with many columns I'd like to share & ask for your help on the following design issue:
I have a DB table which contains 11 columns
Whenever I approach these conditions in any programming language,
I am stuck with the question:
"how do I create a function to insert a row, without the function having 11 parameters?"
my issue is, that it's a problem of bad design (since it's a lot of parameters in one function)
can anyone tell me how to redesign this?
Do I have to change my DB scheme?
or can I leave it the way it is, and just build my application differently?
Note:
I have found a lot of similar questions, but they all focused on the Database itself & the number of columns.
As far as I know & read, as long as it's the same entity, a table can hold many columns.
I am more concerned with the function itself.
meaning if I have a class called DB, and a function called insertToTable(Params...)
how can I do it differenty?
if I send one big object to the DB class, doesn't it affect "low coupling high cohesion"?
and isn't it kind of stupid, setting the parameters in the object, then sending it to the DB class, and then getting them back in order to build this huge query?

A: You can consider creating several insert methods that accept different number of parameters based on the default values, what data is updated and such.
If you frequently update only 2 or 3 columns why not write a function that will only accept these 3 parameters and keep everything else the same.
Yes, you will need to have one function that does accept all parameters but you can deal with that by creating a class that represents a table and then passing just one parameter - object of that class.


text:
Q: Highcharts - Exporting with credits in IE 7/8 I'm having problems getting the credits to show up properly on my exported Highcharts chart in IE 7 and 8. I'm using a custom Highcharts module (https://github.com/imclem/Highcharts-export-module-asp.net), and it's causing the y-axis to be displayed down in the credits section.
Taking a look at the demos on the Highcharts page, I'm not convinced the export module is at fault. All of the examples found here set credits to disabled. If I change the JSFiddle to enable credits, exporting in IE 7 and 8 still leaves out the credits altogether (works fine in Chrome, Firefox, and IE 9+). For example, if you enable credits on this JSFiddle, run that on IE 7 or 8, and export the chart to a PNG, you should see the credits are missing from the image.
Here's the JavaScript for the example with credits enabled:
$(function () {
$('#container').highcharts({

    chart: {
    },

    credits: {
        enabled: true
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }],

    exporting: {
        filename: 'custom-file-name'
    }

});

});
This leads me to believe this is a known issue, but I have not been able to find mention of it anywhere. Should the credits work when exporting to an image?
Thanks!

A: This is known issue with 3.0.7 version. It's already fixed on master branch:
<script src="http://github.highcharts.com/highcharts.js"></script>

Fix will be included in next release, within a few weeks (3-4).


text: Q: Mathematica 10.2 Notebooks Freezing I've been having a problem with notebooks in Mathematica 10.2 freezing up on my Windows 8.1 laptop.  It seems to happen when I am typing input.  The notebook freezes (become unresponsive) for 30 secs or so, sometimes it resolves but often Window reports "Mathematica 10.2 not responding" and closes Mathematica.  The laptop is only a couple months old and should have plenty of RAM (8 GB) for what I am doing.  I don't have this problem with Mathematica 10 on my Windows 7 machine.  Anyone else have this problem?  Any fixes?


text:
Q: How to browse a drive on a different network? We have 2 different network structures and need to browse and map a network share from other network. (I have a windows share that I can reach and map from my local network and want the same thing from our other network.)
How can I do that? Which port should I open on the firewall? (I can't open NetBIOS for security reasons.)

A: Given the constraints that you have listed in the comments, I suggest using web sharing (WebDAV) for the remote share, since Windows supports it natively. Your firewall administer will probably be more amenable to opening HTTP traffic (port 80) instead of a standard file sharing protocol like CIFS/SMB. You will need to connect via IP or DNS name as browsing won't really work in the absence of a service location protocol like NetBIOS.


text:
Q: How could I use R to pull a few select lines out of a large text file? I am fairly new to stack overflow but did not find this in the search engine. Please let me know if this question should not be asked here.
I have a very large text file. It has 16 entries and each entry looks like this:
AI_File 10
Version
Date    20200708 08:18:41
Prompt1 LOC
Resp1   H****
Prompt2 QUAD
Resp2   1012
TransComp   c-p-s
Model   Horizontal
### Computed Results
LAI 4.36
SEL 0.47
ACF 0.879
DIFN    0.031
MTA 40.
SEM 1.
SMP 5
### Ring Summary
MASK    1   1   1   1   1
ANGLES  7.000   23.00   38.00   53.00   68.00
AVGTRANS    0.038   0.044   0.055   0.054   0.030
ACFS    0.916   0.959   0.856   0.844   0.872
CNTCT#  3.539   2.992   2.666   2.076   1.499
STDDEV  0.826   0.523   0.816   0.730   0.354
DISTS   1.008   1.087   1.270   1.662   2.670
GAPS    0.028   0.039   0.034   0.032   0.018
### Contributing Sensors
### Observations
A   1   20200708 08:19:12   x   31.42   38.30   40.61   48.69   60.28
L   2   20200708 08:19:12   1   5.0e-006
B   3   20200708 08:19:21   x   2.279   2.103   1.408   5.027   1.084
B   4   20200708 08:19:31   x   1.054   0.528   0.344   0.400   0.379
B   5   20200708 08:19:39   x   0.446   1.255   2.948   3.828   1.202
B   6   20200708 08:19:47   x   1.937   2.613   5.909   3.665   5.964
B   7   20200708 08:19:55   x   0.265   1.957   0.580   0.311   0.551

Almost all of this is junk information, and I am looking to run some code for the whole file that will only give me the lines for "Resp2" and "LAI" for all 16 of the entries. Is a task like this doable in R? If so, how would I do it?
Thanks very much for any help and please let me know if there's any more information I can give to clear anything up.

A: I've saved your file as a text file and read in the lines. Then you can use regex to extract the desired rows. However, I feel that my approach is rather clumsy, I bet there are more elegant ways (maybe also with (unix) command line tools).
data <- readLines("testfile.txt")

library(stringr)
resp2 <- as.numeric(str_trim(str_extract(data, "(?m)(?<=^Resp2).*$")))
lai <- as.numeric(str_trim(str_extract(data, "(?m)(?<=^LAI).*$")))

data_extract <- data.frame(
  resp2 = resp2[!is.na(resp2)],
  lai = lai[!is.na(lai)]
)

data_extract

  resp2  lai
1  1012 4.36

A: A solution based in the tidyverse can look as follows.
library(dplyr)
library(vroom)
library(stringr)
library(tibble)
library(tidyr)

vroom_lines('data') %>%
  enframe() %>%
  filter(str_detect(value, 'Resp2|LAI')) %>%
  transmute(value = str_squish(value)) %>%
  separate(value, into = c('name', 'value'), sep = ' ')

#   name  value
#   <chr> <chr>
# 1 Resp2 1012
# 2 LAI   4.36


text:
Q: How to bulkify this code The below code working and doing what is suppose to do but I know that the below code is not optimized/bulkify, how can I bulkfiy this code
public void SchedulingClass(List<Reading__c> reading)
    {
        for(Reading__c r : reading)
        {
            List<Reading__c> readings = [SELECT  Id, Name .... FROM Reading__c WHERE Id__c =: r.Id];

            if(readings.size() > 0)
            {
                List<Motor__c> motors = [SELECT Id,Name ... FROM Motor__c WHERE Id =: m.Id__c];

                If(motors.size() >0 )
                {
                    List<Scheduling__c> sList = [SELECT Id, Name ...FROM Scheduling__c WHERE Id__c =: r.Id__c];
                    for(Scheduling__c pm : sList)
                    {
                      //
                    }
            }
        }
    }

A: A generous use of collections will help. The key is using the right Map Keys and properly creating the collections prior to use.
Now, you are missing some code on how you use them so there may be better ways to use them but given the limited code you provided this should get you started:
public void SchedulingClass(List<Reading__c> reading)
    {

        //Get a map of ID to reading records
        Map<ID,Reading__c> readings = New Map<ID,Reading__c>([Select ID, Name ... From Reading__c Where ID__c IN :reading]);

        //Get motors and map then to the ID of reading
        Map<ID,motor__c[]> readingToMotor = New Map<ID,Motor__c[]>();

        //This pattern could be put in a utility class using sObjects but thats another lesson
        for(Motor__c m : [Select ID, Name, ... From Morot__c Where ID__c IN :readings.keySet]){
            Motor__c[] tmp = readingToMotor.get(m.ID__c);
            if(tmp == null)
                readingToMotor.put(m.ID__c,New Motor__c[]{m});
            else
                readingToMotor.get(m.ID__c).add(m);
        }

        //Get Schedule records mapped to the reading records
        Map<ID,Scheduling__c[]> readingToSchedule = New Map<ID,Scheduling__c[]>();

        for(Scheduling__c s : [Select ID, Name, ... From Scheduling__c Where ID__c IN :readings.keySet]){
            Scheduling__c[] tmp = readingToSchedule.get(s.ID__c);
            if(tmp == null)
                readingToSchedule.put(s.ID__c,New Scheduling__c[]{s});
            else
                readingToSchedule.get(s.ID__c).add(s);

            readingToSchedule.put(s.ID__c,s);
        }

        for(Reading__c r : readings.values())
        {
                //Not sure why you had this here as you are not looping over them or using it anywhere but.....
                List<Motor__c> motors = readingToMotor.get(r.id);

                If(readingToMotor.containsKey(r.id))
                {
                      if(readingToSchedule.containsKey(r.id){
                         for(Scheduling__c pm : readingToSchedule.get(r.id))
                           {
                             //
                           }
                      }
                    }
            }
        }
    }


text:
Q: to get a hired knife vs to get hired I was reading the comic book Batman The Long Haloween and I came across a question involving the verb ''to get'' in the following excerpt: ''It seems like only yesterday when The Roman tried to get a hiered knife slid between his nephew's ribs''.
What is the meaning of the verb "to get" in this sentence? The writer was just being sarcastic with the idea that The Roman "tried to stick a rented knife" between his nephew's ribs or there wasn't any kind of sarcasm regarding the verb "to get" and in this case "to get a rented knife" does it mean that he hired someone (in the literal sense) to threaten his nephew with a knife? would it be the same thing as ''to get hired''?

A: To "get something done" means to cause that thing to happen. So, you're correct, if he tried to "get a hired knife slid between his nephew's ribs," it sounds like he tried to cause a "hired knife" - i.e., a knife held by someone he hired - to be slid between his nephew's ribs.
To answer your other point - to "get [adjective/past participle]" would be a slightly different grammatical structure. It means, simply, to become [adjective], so to "get hired" would mean to become hired - i.e., to be hired by someone.
A side point. I don't love the writing here. A "hired knife" sounds to me like it should refer to a person - i.e., a gangster that uses a knife. A "hired gun" is sometimes used this way. Instead, the author is referring to the weapon itself as the "hired knife."

A: A "hired knife" is akin to a "hired gun", it does not refer to a literal weapon, but rather the person who uses it, i.e. a mercenary engaged in illicit work, in this case an assassin. The writer is being metaphorical by referring to the hired killer by his weapon.
The verb "to get" here doesn't have to do with acquiring something, but causing a thing to be done on your behalf (see definition 9 under the transitive verb). As in "getting somebody to move" by nudging them, or "getting somebody to be quiet" by shushing them.
So you can read the passage this way:

It seems like only yesterday when The Roman tried to hire an assassin to murder his nephew.


text:
Q: Get Selected Row in DataGridView not working VB.Net I have a pretty standard DataGridView and have already used
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False

in order ensure the entire row is selected.
Situation : I need to obtain the selected row in order to load the data in the row to another screen to "Modify" the data. I am using the following to get the Selected Row.
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
    Try
        If e.RowIndex >= 0 Then
            Dim row As DataGridViewRow
            row = Me.DataGridView2.Rows(e.RowIndex)
            GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
            MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)

            'textboxTst.Text = row.Cells("Description").Value.ToString
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Question : The problem is that most of the time when one clicks on the data within the DGV the code above is run and sets the e.RowIndex - BUT when I hit any white space on the row nothing happens and so results in the problem of using the previous row selected, which is in fact the wrong row.?
Any ideas would be appreciated.
Thanks in advance

A: I think what you are looking for is DataGridView CellClick instead of CellContentClick. CellContentClick does not fire when white space around the cell content is clicked.
Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick
Try
    If e.RowIndex >= 0 Then
        Dim row As DataGridViewRow
        row = Me.DataGridView2.Rows(e.RowIndex)
        GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
        MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)

        'textboxTst.Text = row.Cells("Description").Value.ToString
    End If
Catch ex As Exception
    MsgBox(ex.Message)
End Try
End Sub

A: Your problem is about the event you're using: CellContentClick. Instead of it, use: SelectionChanged. This would be more useful for your purpose.
SelectionChanged
In this event, the sender e stops being a cell, so you can change this access to: yourListviewName.SelectedRows, that gives you a Collection with the selected rows.
Since you have disabled multiselect property, you only need to access to the first item of it.


text:
Q: angular.filter's groupBy filter : Unknown provider: groupByFilterProvider <- groupByFilter error I am new to angular, I need to use the angular.filter's groupBy filter but I am not sure how to include it. I followed the first 2 steps specified here: https://github.com/a8m/angular-filter#groupby but can't follow the third step, i.e Add 'angular.filter' to your main module's list of dependencies.
This is the html file where I want to use it:

            Review ID
            Reported Count
            Type of Review
            Link to review
            Expand/Collapse

            {{key}}
            {{value.length}}
            type goes here
            view
            expand

Error: [$injector:unpr] Unknown provider: groupByFilterProvider <- groupByFilter
JS file is as follows:
var admin = angular.module('admin', ['ngRoute']);
var delayTimer;

admin.config([
  '$routeProvider',
  '$locationProvider',
   function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/reported', {
        templateUrl: 'view/reported_reviews.html',
        controller: 'reportedController'
      })
   }
 ]);

A: You need to add angular-filter as a dependency and the reference
var admin = angular.module('admin', ['ngRoute','angular.filter']);

Reference


text:
Q: I need to parse images array to json with GSON The method where I get the images
private List<HashMap<String, RequestBody>> getUserDocumentsPhoto(File[] images){

    HashMap<String, RequestBody> userDocumentsPhoto = new HashMap<>();
    List<HashMap<String, RequestBody>> photos = new ArrayList<>();

    for (File image : images) {
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        userDocumentsPhoto.put("filename=\"" + image.getName(), fileBody);
    }
    photos.add(userDocumentsPhoto);
    return photos;

When parse to json I need to get
"document_photos": [
"/system/attachments/files/000/000/110/original/photo20160726_120701-1392731703.jpg?1469524104",
"/system/attachments/files/000/000/111/original/photo20160726_120814-2041790628.jpg?1469524105"]

But when it parsed, "document_photos []" has null

A: You must create model class. Which the structure of this class is like this:
public class Model {
    ArrayList<String> items = new ArrayList<>();

    public ArrayList<String> getItems() {
        return items;
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
    }
}

and your activity like this:
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Model model = new Model();
        model.getItems().add("first");
        model.getItems().add("second");
        Gson gson = new Gson();
        String json = gson.toJson(model);
        Log.e("json",json);
    }
}

Add Gson library in your build.gradle as dependency.


text:
Q: Is it possible to directly link to a google drive folder in preview mode? I am trying to use Google Drive's api to essentially host and link to images from an external site.
The problem I'm encountering, is when people upload a bunch of photos in the provided folder, I seem to only be able to use the webViewLink to view individual photos. I noticed that in the google drive folder, there is a very convenient photo preview that lets you click left and right to browse photos.
I was wondering if this preview view is possible to be linked to directly. It doesn't seem like the url changes but if this is possible, any help to achieve this would be greatly appreciated.
Thanks!

A: If your user has permission to view the folder, you can use the embedded folder view to embed a view of the folder, which should show all the images contained within.
The URL pattern looks like https://drive.google.com/embeddedfolderview?id={{folderId}}#grid where {{folderId}} is the ID of the drive folder.
That gives a nice preview, but requires the user has view access on the folder. If they do not, you'll need to auth the request with your own token so that it will render properly for the end user.


text:
Q: Cannot verify facebook messenger webhook, curl_errno = 28 i want to configure webhook for facebook application.during the development process i was using ngrock, which was working perfectly, today i cann't establish connection. Address is
https://.........ngrok.io , which works and returns ok
i try to add webhook https://.......ngrok.io/webhook to the facebook application , getting error like this
The URL couldn't be validated. Callback verification failed with the following errors: curl_errno = 28; curl_error = Operation timed out after 6001 milliseconds with 0 out of 0 bytes received; HTTP Message = Unknown Response Code
Can you help, what can i do?

A: I've spend 2 hours to fix it. And final, I find it is a bug :)
Facebook fixed it.


text:
Q: mutate_at using function lag but keep first row I am using dplyr in R (with great joy) and want to get the differential of the columns mpg to gear in mtcars. The first row then returns NA (for obvious reason). Instead of this first row being NA I would like it to stay the original value.
I am looking for a clean and efficient way to achieve this (not using join to add the first row to the differntiated values since the code on my own dataset contains many filters and grouped variables).
my code is as follows:
mtcars %>% mutate_at(vars(mpg:gear), funs(. - lag(., 1)))

I expect the first row to be mtcars[1] and the rest to be the differential

A: We can specify the default parameter with 0, otherwise, it would be NA
library(dplyr)
mtcars %>%
   mutate_at(vars(mpg:gear), list(~ . - lag(., default = 0)))

Or another option is diff with concatenating the first element
mtcars %>%
    mutate_at(vars(mpg:gear), list(~ c(first(.), diff(.))))

NOTE: The funs is getting deprecated.  Instead of that we are using list


text:
Q: Multiple instances of header() + die() in single code line I'm trying to manipulate a PHP script so that it redirects to a particular URL instead of giving me a MySQL error. So I went from this...
$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;") or die('MySQL error: '.mysql_error());

...to this:
$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;") or header("Location: http://www.example.com");

Which works, but there are two things that concern me. Firstly, it defaults to a 302 redirect, and I would prefer a 301 redirect. Secondly, I'm worried that by removing die() from this line, the script isn't properly exiting after the redirect.
Now, I've done a bit of homework here, but I can't quite figure out if it's possible to combine die() with two instances of header() in that single line of code (i.e. without changing what's around this particular line).

A: In addition to the "You shouldn't do this" notes, here's how you could do it:
$qs = mysql_query(...) or (header(...) xor die);

Explanation: xor is just like or with the difference that it is guaranteed that the expressions on both sides get evaluated and are not short circuited. (Okay, xor is something different from or, but for the purpose of this answer that doesn't matter.)

A: You could use an if block:
$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;");
if (!$qs) {
    header("Location: http://www.example.com");
    die('MySQL error: '.mysql_error());
}

A: $query_string = '';
$location = '';

$qr = mysql_query($query_string);
if (!$qr) {
  header ('HTTP/1.1 301 Moved Permanently');
  header ('Location: '.$location);
  die('MySQL error: '.mysql_error());
}

A: You could always:
$qs = mysql_query("blah");
if (!$qs) {
   //headers
   header('Location: blah');
   die('MySQL error: '.mysql_error());
}

A: There is no purpose to having the die message show up since any browser would catch the HTTP status code and act accordingly while ignoring the content of the document. There you should be using the exit() command which does the same thing minus echo'ing anything to the buffer.
You may be using this fallback operation so why not just make it a common fallback function:
function fallback($location='/default/path/to/somewhere') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: '.$location);
    exit();
}

$query = mysql_query('...') or fallback('/path/to/somewhere/');


text:
Q: Is it possible to create a WAR and a JAR of same maven project I have  maven project which needs to be exposed as a webservice for 3rd party client but same project needs to be used as a JAR between internal modules.
Is this thing possible using different maven profiles in a single pom.

A: You can use the configuration in the maven-war-plugin via:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.6</version>
  <configuration>
    <archiveClasses>true</archiveClasses>
    <attachClasses>true</attachClasses>
  </configuration>
</plugin>

After you have configured that way you can use the generated jar file as a usual dependency except for the classifier:
<dependency>
  <groupId>myGroup</groupId>
  <artifactId>myArtifact</artifactId>
  <version>myVersion</myVersion>
  <classifier>classes</classifier>
</dependency>


text:
Q: Change order of nav items in responsive design I am using Cascade Framework and have a simple header with a logo, select, and a link to an external site.
My fiddle is here
The layout if fine as is in desktop mode. In responsive mode, it looks something like:
---------------------------------------------
Company Name
---------------------------------------------
Volvo
---------------------------------------------
Menu Here
---------------------------------------------

Whereas I'd like the following in responsive mode:
---------------------------------------------
Company Name                        Menu Here
---------------------------------------------
Volvo
---------------------------------------------

These answers suggest using flexbox or jquery. I can't use flexbox because I need ie8 support. I'd also rather not have to resort to jquery since this seems like it should be a rather straight forward css solution. Another answer on that page shows a ton of css that I've been trying to adapt to my use case and that didn't fix the issue either.

A: How about using absolute positioning?
.menuHere {
    position:absolute;
    text-align:right;
    right:0
}

http://jsfiddle.net/6txfvvo6/3/


text:
Q: Server 2008 continues to register NIC's in DNS I have a Server 2008 R2 box running Hyper-V, hosting VM's.  I have 4 NIC's set up - the primary network NIC, 1 NIC for the SAN, and 2 NIC's for the virtual machines.  The 2 NIC's for the virtual machines continue to register in DNS despite having the Register this Connection in DNS checkbox cleared.  I am running a Windows Server 2003 Domain with AD-Integrated Zones.
Even after I delete the A records for the 2 NIC's for the virtual machines, they continue to re-appear in DNS.
I am not sure how to stop this behavior.

A: Your DHCP server may be configured to register them on their behalf.
http://technet.microsoft.com/en-us/library/ee941150%28WS.10%29.aspx

A: Palm to forehead.  I rebooted the Server 08 box and the unwanted A records disappeared from DNS.

A: FYI, you could also just restart the DNS Client service instead of a full reboot.


text:
Q: Preventing Lock screen when phone restarts, so app can run immediately I've finally got a lot of my app working over the last few weeks. The app is supposed to run at bootup, which it does. But the Lock screen that appears, when the phone restarts (say after the battery running out), prevents that from happening.
What setting or code can i use to prevent the phone starting with Lock screen?

A: Try this
//add permission to AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

WakeLock wl;//in class

//in onCreate method initiate them
PowerManager pm=(PowerManager)getSystemService(POWER_SERVICE);
wl=pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "anything");

//in onResume() method get lock
wl.acquire();

//in onPause() method release lock
wl.release();


text:
Q: How to get the content of a textarea using jquery This questions has been asked before, however, I'm unable to find an answer for my specific scenario.
I have a few checkboxes, in which if the box is checked, I want the 'Copy' to copy the content of the textareas next to the checked boxes.

function copySelect() {
  var copyString="";
  $(".category>input").each(function (index, element) {
      if (element.checked) {
          copyString += element.nextSibling.innerText + " ";
      }
  });
  copyToClipboard(copyString);
}

function copyToClipboard(text) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();
}

    <input type="checkbox" id="content1" value="state" />
      <textarea class="box" id="text1">Test content 1</textarea>

    <input type="checkbox" id="content2" value="salePrice" />
      <textarea class="box" id="text2">Test content 2</textarea>

    <input type="checkbox" id="content3" value="manager" />
      <textarea class="box" id="text3">Test content 3</textarea>

  <input id="copybtn" type="button" value="Copy" onclick="copySelect()" />

I've tried changing element.nextSibling.innerText to element.nextSibling.value or element.nextSibling.innerHTML, but they all return undefined.

A: element.nextSibling returns any kind of node, in this case it returns a text node, You should user element .nextElementSibling to get the next element (Input, textArea, select). Then you can get the text with value.
I corrected your code snippet.

function copySelect() {
  var copyString="";
  $(".category>input").each(function (index, element) {
      if (element.checked) {
          copyString += element.nextElementSibling.value + " ";
      }
  });
  copyToClipboard(copyString);
}

function copyToClipboard(text) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();
}

    <input type="checkbox" id="content1" value="state" />
      <textarea class="box" id="text1">Test content 1</textarea>

    <input type="checkbox" id="content2" value="salePrice" />
      <textarea class="box" id="text2">Test content 2</textarea>

    <input type="checkbox" id="content3" value="manager" />
      <textarea class="box" id="text3">Test content 3</textarea>

  <input id="copybtn" type="button" value="Copy" onclick="copySelect()" />

A: You can use $(this).next().val() when loop the input checkbox
function copySelect() {
  var copyString="";
  $(".category>input").each(function (index, element) {
      if (element.checked) {
          copyString += $(this).next().val() + " ";
      }
  });
  copyToClipboard(copyString);
}


text:
Q: Multiple Choice Option Cells in Python Jupyter Notebook I'd like to create a multiple choice menu within a .ipynb that determines what upcoming cell shows up. For example, I want to insert a question and have someone viewing the notebook be able to pick:
⦿ Choice A
⦿ Choice B
If the user picks A, a cell shows up. If the user picks B, a different cell shows up next.


text:
Q: Error code "object of type 'closure' is not subsettable? New to programming and can't seem to figure this error message out. Ran every line of code and turns out fine except for when I attempt to knit the rmd file to HTML. How can I fix this? Below are my answers to a problem set as well as the error message.
```{r}
dim(data)
nrow(data)
range(data$year)
range=max(2008)-min(1980)
```
```{r}
rate.actual=data$total/sum(data$VAP+data$overseas)
```

```{r}
rate.difference=rate.actual-data$ANES
mean(rate.difference)
min(rate.difference)
max(rate.difference)
plot(x=data$year,y=rate.difference)
lines(x=data$year,y=rate.difference)
```

"Error in data$total:object of type 'closure' is not subsettable calls:...handle->withCallingHandlers->withVisible->eval->eval"


text:
Q: capture the second field and the last field from string we have files with the follwing file name format
VER_{FILE NAME}_{VERSION}
example
  VER_collect_important_info.pl_1.0.2

we want to capture only the "FILE NAME" and "VERSION" number
so how to remove the first _ , and the last _  in the file name
so we can capture the "FILE NAME" and "VERSION" , ( with sed/awk or perl  one-liner )
example
 echo VER_collect_important_info.pl_1.0.2 | <some syntax>

 collect_important_info.pl  1.0.2

A: Perl comes much more naturally to me than the lighter-weight alternatives:
echo VER_collect_important_info.pl_1.0.2 | perl -pe 's/^[^_]*_(.*)_(.*)$/$1 $2/'

If it doesn't matter that this uses a heavier weight process than necessary, I'd stop there.
sed can do it however, it just feels kludgey to have to have to escape basic elements like brackets:
echo VER_collect_important_info.pl_1.0.2 | sed 's/VER_\(.*\)_\(.*\)/\1 \2/'

A: This should do the trick
$ echo VER_collect_important_info.pl_1.0.2 | sed 's/_/ /' | sed -r 's/(.*)_/\1 /' | awk -F" " '{print $2"\t"$3}'

The first sed is replacing the first occurrence of _ and second sed does that with the last occurrence of _ and finally awk to print

A: $ echo 'VER_collect_important_info.pl_1.0.2' |
    perl -F_ -lane 'print join("_", @F[1..@F-2]), " ", @F[@F-1]'
collect_important_info.pl 1.0.2

Note: perl arrays start from 0, not 1 so the array index for the second field is [1], not [2].
This splits the input into an array (@F), separated by _ underscore characters.  Then it prints the 2nd through to the 2nd-last field (@F[1..@F-2]) joined by underscores, followed by a space, and then the last field (@F[@F-1]).

A: find + bash solution:
Sample files:
$ ls -1 VER_*_[0-9]*[0-9]
VER_collect_important_info.pl_1.0.2
VER_collect_some_info.pl_3.4.2

find . -type f -name "VER_*_[0-9]*[0-9]" -exec \
        bash -c 'v=${1##*_}; f=${1#*_}; f=${f%_*}; echo $f $v' _ {} \;

The output:
collect_some_info.pl 3.4.2
collect_important_info.pl 1.0.2

A: With awk you can use:
echo VER_collect_important_info.pl_1.0.2 | awk -F '_' '{for (i=2; i<NF; i++) {{printf $i} if (i!=NF-1) printf "_"} printf " " $NF "\n"}'

A: I got mentioned result by using combination of sed and awk
echo VER_collect_important_info.pl_1.0.2 |sed -r "s/_/ /1"| sed "s/_/ /3"| awk '{print $2,$NF}'

A: Just run this perl script and pass the directory to look into as it's argument:
#!/usr/bin/perl

use strict;
use warnings;

my $dir = $ARGV[0];
my @files = `find $dir -type f -name "VER_*_[0-9]*[0-9]"`;

my $all_files;
foreach my $file (@files) {
    $file =~ /VER_(.*)_(.*)/;
    $all_files .= $1."  ".$2."\n";
}

print $all_files if ($all_files);

Example:
I ran this script by passing current directory (.) as argument to it (which contains VER_collect_important_info.pl_1.0.3).
[mask@cent ~]$ perl separate_file_version.pl .
collect_important_info.pl  1.0.3


text:
Q: Solving $a^2-4b^2 = 101$
How do you solve $a^2-4b^2 = 101$ in positive integers $a,b$?

I didn't see a nice way of solving this and was wondering if there was an easy way of find the solutions.

A: Hint: Observe
\begin{align}
a^2-4b^2 = (a-2b)(a+2b) = 101
\end{align}
and note $101$ is prime.

A: From this : $a^2−4b^2=(a−2b)(a+2b)=101$ ; we can conclude that : $a^2 > 101$, also $a-2b$ and $a+2b$ have the same sign.
So, we have two set of solutions :

1) $b < 0$ and $a < -\sqrt{101}$
  or
  2) $b > 0$ and $a > \sqrt{101}$


text:
Q: Format string %n of printf function doesn't work #include<stdio.h>

int main(){
    int a=100;
    printf("aaaaa%n",&a);
    printf("%d",a);
}

I used gcc to compile it ( :gcc a.c )
however, its output is as follows
aaaaa100

The value of a doesn't change by the printf's %n format string
I suppose it should output as follows
aaaaa5

What is the reason of this unexpected difference? Thank you


text:
Q: How to share the Image of the ImageView? I am Using this code to Share the Image that is already available in to My SDCard:
Intent picMessageIntent = new Intent(android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
//File downloadedPic =  new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"q.jpeg");
//picMessageIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(downloadedPic));

File f = new File(lastPath);
picMessageIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(picMessageIntent);
//finish();

But, Instead of that i want to use the ImageView Image file that i have set to the Imageview. And Want to Share that file. Then how it is possible to get File from ImageView and send to share with the above code ??
Thanks.

A: You can use ACTION_SEND_MULTIPLE and include a list of images an an
ArrayList<Parcelable> and use putParcelableArrayListExtra() to store
it.  Gallery does this and would be a good reference.
(answer snagged from http://groups.google.com/group/android-developers )


text:
Q: Finding pivots in circular two dimensional array the method is:
public static boolean search(int matrix[][], int key)

the method will return true if key is found in the matrix,
the matrix size will be always n x n , the matrix is circular sorted and here is example how it looks like for 4x4
example
Run time efficiency must be lower than O(n^2) , aiming for O(n log n)
This is the structure I tried to imply,the code isn`t working it just my thought process
public static boolean search1 (int [][] matrix, int num)
{

    int ROWS = matrix.length;
    int COLS = matrix[0].length;
    int end = COLS * ROWS;
    int first_quarter_pivot = matrix[0][0];
    int second_quarter_pivot = matrix[0][i];
    int third_quarter_pivot = matrix[i][0];
    int fourth_quarter_pivot = matrix[i][i];

       if(num < first_quarter_pivot)
       // if num smaller than first pivot binary search first quarter,if not found return false
       binarySearch( );

       if(num < second_quarter_pivot)
       binarySearch( );
       // if num smaller than second pivot binary search second quarter ,if not found return false
       if(num < third_quarter_pivot )
       binarySearch( );
       // if num smaller than third pivot binary search third quarter ,if not found return false
       // else search fourth quarter
       else
        binarySearch( );
       // return false if nothing found

    }

I cant find the pivots  to split the matrix to 4 quarters,I want to find the edges of each quarter,and I want to find in each quarter the bottom left corner which il compare num against in each quarter
hope I was clear,ty in advance.

A: Good question
A trick we normally use to limit a grid, is passing in the starting row index, ending row index, starting column index, ending column index.
Your header will become
public boolean search(int[][] matrix, int key, int startRow, int endRow, int startColumn, int endColumn){

The first call, startRow startColumn will be 0, the endRow and endColumn will be n-1
Every time you identify which quarter the key falls in, shrink these values accordingly for the next recursive call
Steps
first find n, which is matrix.length.
Then using n to find the row and column for the number(s) in the middle of the grid.
If n is odd (etc 5x5), then there will be a number in the middle grid,
its index is n=5, 5/2 = 2, get its value by matrix[2][2]. But I double this circular sort work on odd number matrix.
If n is even (etc 4x4), you don't have a number in the middle this time, then you need to find the 4 biggest number in each quarter.
Then use the key to compare with this middle number(s) to find which quarter. Using your example, if key is 55, how do you know which quarter it is in?
First compare with the biggest value in first quarter (6), if the key is less than 6, then it is first quarter, then compare with biggest value in second quarter (15), if it is less than 15 then it is in second quarter. Repeat for third quarter and fourth quarter.
The algorithm to find the index for the biggest number in the first quarter is matrix[value-1][startColumn] = 6, value is n/2 = 4/2 = 2
For second quarter, the matrix[value-1][value] = 15 happens to be the biggest number in second quarter, lucky.
For third quarter, index for the biggest number is matrix[endRow][startColumn] = 60
For fourth quarter, index for the biggest number is matrix[endRow][value] = 30
After you limited the quarter, you should recursively call this function again


text:
Q: Regex for SQL(sql); C# I am having some trouble with a regular expression (don't know if what I want to do is possible.)
Scenario:
I have an input area where users can write some text.
They would like to be able to also execute some SQL query where the result is then going to be displayed in the text, when the text is sent to a customer in an email.
Rough example:
#
Hi
I have attached the invoice SQL(SELECT DocNumber FROM X WHERE DocEntry IN (SELECT DocEntry FROM X););
Please provide payment for the invoice.
Regards
#
I am having some difficulties handling that the users can write () and ; in SQL.
Have anyone done something like this before with regex or am I going to do have to do some ugly split, substring and last index of in C#?
Any comments/suggestions would be much appreciated.

A: You really don't want to do this. Why not just use templating, so your user can type %%invoiceNo%% and your code looks up the invoice number using the appropriate query?


text:
Q: Storing data in a RecordSet I am writing a code to record data which will also allow me to check and see if the data is updated to the records. I have imported the javaxt.sql.Recordset as a dependencies which allow me to use the Recordset constructors.
I want to place information in a RecordSet by updating the record.
    RecordSet rs = new RecordSet();
    String db = null;//String name;

    rs.addNew();
    rs.setValue("Joe");
    rs.setValue("Brown");
    rs.setValue(25);
    rs.update();
    rs.close();

A: RecordSet is a partially sql wrapper, so you need to know sql.
Examples, how use RecordSet:
http://www.javaxt.com/javaxt-core/sql/Recordset


text:
Q: HTTP listeners without controller in Ruby class We are integrating our Rails Web Application with several HTTP data exchange services and I plan to make one class per service in lib folder.
The problem is that not only we should call a service, but service can also send us HTTP requests.
I would make controllers for these services with a strong unwillingness because I want to encapsulate as more code as possible in single *.rb file.
Is a Ruby class able to publish HTTP listeners in Rails or to eliminate/minimize usage of Rails controller in some way?


text:
Q: Excel File is not downloading in Noe JS I am not able to download excel file in Nodejs sending API from front end(angular 4). Can anyone please help me here? I am attaching the picture and source code i am using in backend in node js.
Error Screen Shot
app.controllers.getExcel = function (req, res) {
    console.log("------------------------------CHECK===========================")
    console.log("------------------------------CHECK===========================")
    console.log("------------------------------CHECK===========================")
    var include = [app.db.cases];
    var perPage = req.query.limit ? Number(req.query.limit) : 200,//showing 200 record per page
        page = req.query['page'] ? Number(req.query['page']) - 1 : 0,
        query = {};

    if (req.query.case_id) {
        query['case_id'] = Number(req.query.case_id);
    }
    query.status = {"$notIn": ['completed', 'QA-Completed', 'QA-Pending']};
    if(req.role.name == 'lea'){
        query.status = {"$notIn": ['completed', 'waiting', 'inprogress']};
    }
    if (req.query.start_date && req.query.end_date) {
        var date = new Date(req.query.start_date.substr(0, 10));
        var edate = new Date(req.query.end_date.substr(0, 10));
        edate.setDate(edate.getDate() + 1);
        edate = edate.toString();
        query.createdAt = {$gte: date, $lt: edate}
    }
    if (req.query.client_id) {
        query['client_id'] = req.query.client_id;
    }
    if (req.query.company_id) {
        query['company_id'] = req.query.company_id;
    }
    if (req.query.sort) {
        query['sort'] = req.query.sort;
    }

    let w = {}

    if (req.query.cnic || req.query.lastName || req.query.firstName || req.query.fatherName ||
        req.query.city) {
        delete query.status;
        w = {}
        if (req.query.cnic) {
            w['emp_id'] = {"$like": "%" + req.query.cnic + "%"};
        }
        if (req.query.city) {
            w['city'] = {"$like": "%" + req.query.city + "%"};
        }
        if (req.query.fatherName) {
            w['fatherName'] = {"$like": "%" + req.query.fatherName + "%"};
        }
        if (req.query.lastName) {
            w['lastName'] = {"$like": "%" + req.query.lastName + "%"};
        }

        if (req.query.firstName) {
            w['firstName'] = {"$like": "%" + req.query.firstName + "%"};
        }

        include = [
            {
                model: app.db.cases,
                where: w
            }
        ]

    }

    $where = {"$or": [{is_qa: 1}, {vo_updated: 1, qa_verified: 1}, {vo_updated: 1, qa_verified_dt: null}]};

    var requ = false;
    if (req.query.service_id) {
        $where = {}
        $where['vo'] = {"$in": req.query.service_id.split(',')}
        requ = true
    }
    if (req.query.qaStatus && req.query.qaStatus != '') {
        $where['qa_verified'] = req.query.qaStatus;
        delete query.status;
        requ = true
    }
    if (req.query.casetatus && req.query.casetatus != '') {
        $where['v_status_id'] = req.query.casetatus;
        delete query.status;
        requ = true
    }
    if (req.query.leaStatus && req.query.leaStatus != '') {
        $where['lea_status'] = req.query.leaStatus;
        delete query.status;
        requ = true
    }
    if (req.query.status) {
        query['status'] = {$or: req.query.status.split(/(?:,| )+/)};
    }

    include.push({
        model: app.db.CaseVerification,
        where: $where,
        required: requ,
        include: [{
            model: app.db.VerificationStatus,
            required: false
        }, {
            model: app.db.User,
        },]
    })

    CRUD.findPaginationWithRelation(CHECKS, page, perPage, include, async function (err, docs) {
        if (err) {
            return res.send(400, {
                code: 400,
                message: "Database Occurred Error",
                success: false,
                error: err
            });
        } else {
            if (docs) {
                var row = JSON.parse(JSON.stringify(docs.rows));

                for (let i = 0; i < row.length; i++) {

                    if (row[i].vo && row[i].vo > 0) {
                        row[i].VO_USER = await CRUD.findOneSync(app.db.User, {id: row[i].vo});
                    }
                }
                let workbook = new excel.Workbook(); //creating workbook
        let worksheet = workbook.addWorksheet('Customers'); //creating worksheet

        //  WorkSheet Header
        worksheet.columns = [
            { header: 'Id', key: 'id', width: 10 },
            { header: 'Name', key: 'name', width: 30 },
            { header: 'Address', key: 'address', width: 30},
            { header: 'Age', key: 'age', width: 10, outlineLevel: 1}
        ];
        worksheet.addRows(row);

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.setHeader('Content-Disposition', 'attachment; filename=' + 'customer.xlsx');

        return workbook.xlsx.write(res)
              .then(function() {
                    res.status(200).end();
              });
                res.send({
                    code: 200,
                    success: true,
                    message: "SuccessFully Find",
                    CHECKS: row,
                    page: page + 1,
                    totalPages: Math.ceil(docs.count / perPage),
                    count: docs.count
                });
            } else {
                console.log('--------------------------EMPTY DOC--------------------')
                res.send({
                    code: 200,
                    success: true,
                    message: "SuccessFully Find",
                    CHECKS: [],
                    page: page + 1,
                    totalPages: 0,
                    count: 0
                });
            }
        }
    }, query)
};

Unhandled rejection Error: Can't set headers after they are sent.

A: About the error "Unhandled rejection Error: Can't set headers after they are sent." you can find a good explanation at Error: Can't set headers after they are sent to the client
However, I believe this isn't the problem. TypeError: res.status(...).end is not a function error is the problem. The method "end" was removed from express 5.x. An alternative would be res.status(status).send(http.STATUS_CODES[status])


text:
Q: Regex pattern for NNNNNN-N I'm trying to match the pattern noted in the title (NNNNNN-N) where N is a digit from 0-9. I've seen plenty of partial examples but not quite what I need. I tried [0-9]{6}-[0-9] but can pass in 123456789-0 and it will pass as valid. What am I missing. BTW, haven't done Regexs in 20 years ...

A: You are missing a boundary to your regex. 123456789-0 is matching because 456789-0 fits your regex pattern.
Here are some of your options:

*

*word boundary \b[0-9]{6}-[0-9]\b.

*whitespace boundary \s[0-9]{6}-[0-9]\s.

*non-digit boundary  [^0-9][0-9]{6}-[0-9][^0-9].

*string boundary ^[0-9]{6}-[0-9]$
Try it out on Regex101
You will notice that they all match different combinations differently. You will also notice that for 2 and 3 it is also matching characters on either side... yikes! We can avoid this using parenthesis to form capture groups around the part we care about.

*non-digit boundary w/ capture groups  [^0-9]([0-9]{6}-[0-9])[^0-9].

Try it out on Regex101
One you have it in the capture group obtaining the information will depend on language and implementation. Without knowing the language it is hard to give more specific advise. The above assumed python for the regex but concept will be the same for any language, just implementation might be different.
Another thing to consider is using a the digit identifier rather than [0-9]. In python this will be \d. It matches more than just [0-9], but for most English use cases it makes no practical difference.


text:
Q: How can I measure the overall error in the edges of a triangular mesh? I look at a number of pointlike objects on a 2D plane and measure the straight line distances between them. For example:

These measurements contain individual errors. How can I measure the overall error in the mesh?
I could do this with physical simulation, by placing vertices at first-estimate coordinates and having the edges be springs, then let it settle iteratively to a minimum-energy configuration. I could then conclude that this configuration is "true" and compare the initial and final edge lengths.
That's one option, but it has a number of issues. I am wondering if, given some chosen error function, there is another, more analytical way to measure the overall error in such a mesh?
(I guess I'm asking if we can conclude whether or not the proposed measurements plausibly fit some true model, to some tolerance.)


text:
Q: Package.json in MVC template with VSCode I imported MVC template by running dotnet new mvc -lang C#. I got default template here but I noticed it's missing package.json file.
How can I add package.json in VSCode editor to this template to add other required references ?.

A: You can use npm init command from node package manager.

*

*Open Nodejs command prompt.

*Navigate to project directory.

*type npm init command.

*Specify basic details like name, version, description, entry point etc.

This will create basic of package.json. Then, you can use npm install <package> --save to install new npm packages in your project.
Other option is, you can create package.json manually.


text:
Q: How do I automatically start supervisor on boot in FreeBSD? Is there a pre-existing startup script for supervisord on FreeBSD? If not, is there a good guide for writing rc.d scripts for FreeBSD? I'm pretty new to the platform.
Thanks.
UPDATE:
I now have the following in /usr/local/etc/rc.d/supervisord, but it doesn't seem to be working. I'm not seeing anything in the startup scroll related to supervisord.
#!/bin/sh

# PROVIDE: supervisord
# REQUIRE: LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name="supervisord"
rcvar=`set_rcvar`
load_rc_config "$name"

command="/usr/local/bin/${name}"
command_args="-c /usr/local/etc/supervisord.conf"

supervisord_enable=${supervisord_enable-"NO"}
supervisord_pidfile=${supervisord_pidfile-"/var/run/supervisord.pid"}

pidfile="${supervisord_pidfile}"

run_rc_command "$1"

A: If you installed supervisord from the port sysutils/py-supervisor then this rc file is already present... (than to voretaq7 for pointing this out).
The basic framework of a rc file is:
#!/bin/sh

. /etc/rc.subr

name="supervisord"
rcvar=`set_rcvar`
load_rc_config "$name"

command="/usr/local/bin/${name}"
command_args=""

run_rc_command "$1"

Creating the file /usr/local/etc/rc.d/supervisord with the above, then chmodding it +x will get you started (probably).
I am assuming you have supervisord installed in /usr/local/bin, change that path as necessary. Also you can add any command line arguements you need (like a configuration file or whatever). I'm not familiar with supervisord, so I'm not sure what it needs.
Make sure you  have a line in /etc/rc.conf similar to supervisord_enable="YES" or the script will do precisely nothing.

A: If you installed supervisord from ports (sysutils/py-supervisor) you should have a functioning rc script in /usr/local/etc/rc.d/supervisord
Check the script for info/other configuration parameters, but simply adding supervisord_enable="YES" to /etc/rc.conf should be all you need to do to make it start automatically on boot.


text:
Q: Saved User object is Null sometimes but works perfect sometime in Windows phone 8.1 C# I'm getting a problem in my Class function. I call a function and in that function i call another function to get saved user detail. I saved detail in user object to use further. But user object some time becomes null and some time return exact value during debugging ....
Here is my Class function..
   public async void Save_Data_in_Log(string EventName, string completeUrl)
    {

        Get_User_Detail_Event();
        //Above function is another function to get User detail in   savedUserObject.

        UserId = savedUserObject.id;
        device_id_string = savedUserObject.deviceId;
        status = "System Event";
        device_type = "Windows";

        DateTime universalTime = DateTime.UtcNow;
        string universalformate = universalTime.ToString("yyyy MM dd, HH:mm:ss");

        string data_to_save_in_log_File = serial_No + " | " + universalformate + " | " + UserId + " | " + device_id_string + " | " + device_type + " | " + status + " | " + EventName + " | " + completeUrl;

    }

 private async void Get_User_Detail_Event()
    {
        if (settingsto_save_detail.LoadSetting("currentUser") != null)
        {
            savedUserObject = await settingsto_save_detail.RetrieveObjectAsync<UserDetail>("currentUser");
        }
    }

Why this function does not give exact User detail.? This works some time good but mostly give Null object.
Please guide me how to resolve this issue. Thanks

A: Thats how the await-async asynchronisation thing works. The flow is not synchronous.
change the return type to Task like this:
async Task Get_User_Detail_Event

and invoke the method like this:
await Get_User_Detail_Event();


text:
Q: In Asp.net MVC 4 multiple inline row update in single click using WebGrid I wants to do multiple inline rows update when click on Update button outside the Grid.
Below is the url of sample project I am referring.
http://www.c-sharpcorner.com/UploadFile/cd7c2e/create-an-editable-webgrid-in-mvc4-to-implement-crud-operati/
But in this sample the admin is updating each row by row. But I want all rows to be updated using update button outside the grid, so that users of my application can click on that update button after they complete editing of the entire grid.
Please help me if anyone knows how to achieve this. Also let me know if you wants any more information. The details of the application and the source code you can get from the above link.
Note :- I am using here WebGrid in ASP.MVC 4, if you know any other free grid that can be used in this scenario, please let me know.
Thanks a lot


text:
Q: How to set up the contour for $ \int_{-\infty}^{+\infty} \frac{e^{iax}}{1+x^4}dx $? I'm trying to solve the following integral:
$$ \int_{-\infty}^{+\infty} \frac{e^{iax}}{1+x^4}dx $$
From what I understand, since we have the complex exponential we consider the poles not only in the upper half plane but in the whole plane but then is the contour a circle englobing all poles or 2 semi-circles, one in the upper half plane, one in the lower half plane, each containing 2 poles? Or is it something else?
Many thanks!


text:
Q: Excel 2013, AND function I'm supposed to modify the formulas in cells B8 to B11 to display a blank if no boat ID value has been entered (cell B7). I also have to modify the formula in cell B13 to display zero if no boat ID value has been entered.
Normally I would use IF function, but in this case I have to use AND. I sincerely have no idea how to do this.

Cells B8, B9, B10, B11, B13 have the VLOOKUP function. The only difference between them is the column number.

A: Use IFERROR function with VLOOKUP function".
For B7 you can use this formula: =IFERROR(VLOOKUP($B$7,$I$3:$O$28,2,FALSE),"")

A: You do not need to use AND,
Just use an IF as in the below:
=if($B$7="","", YOU VLOOKUP HERE )

AND is used when you want more than ONE condition to be TRUE, in your case you only stateda single condition:
IF B7 is blank


text:
Q: Translation operator in QM Given the usual translation operator in quantum mechanics:
$$\hat{T}(y)=\exp\left(-\frac{i\hat{p}y}{\hbar}\right)$$
I want to show that $\hat{T}(y)|x\rangle=|x+y\rangle$, as one would hope. I've started off by inserting the identity using the completeness relation $\hat{1}=\int dp|p\rangle\langle p|$:
$$\hat{T}(y)|x\rangle=\int dp \hat{T}(y)|p\rangle \langle p|x\rangle$$
I expand out $\hat{T}(y)$ and substitute the known form of the inner product $\langle p|x\rangle$ (commuting it to the front since it's a scalar):
$$\hat{T}(y)|x\rangle=\int dp\frac{1}{\sqrt{2\pi}}\exp\left(-\frac{ipx}{\hbar}\right)\exp\left(-\frac{i\hat{p}y}{\hbar}\right)|p\rangle$$
The $\hat{p}$ operator extracts an eigenvalue from the $|p\rangle$ eigenstate, leaving:
$$\hat{T}(y)|x\rangle=\frac{1}{\sqrt{2\pi}}\int dp \exp\left(-\frac{ip(x+y)}{\hbar}\right)|p\rangle$$
Now I'm stuck. How do I show this is equal to $|x+y\rangle$? I've tried inserting another identity, Fourier transforming and so forth, but I can't seem to figure it out.


text:
Q: Versions/3.11/Resources/Python.app/Contents/MacOS/Python: can't open file '/Users/ayoubnaoui/install': [Errno 2] No such file or directory I have being using pygame module for some time, but after downloading some packages like homebrew and octave visual studio no longer recognizes pygame even though it has already been installed
below is the error -
/opt/homebrew/bin/pytho
n3.11 /Users/ayoubnaoui/Desktop/game5/main.py
Traceback (most recent call last):
File "/Users/ayoubnaoui/Desktop/game5/main.py", line 1, in
import pygame
ModuleNotFoundError: No module named 'pygame'
For the pygame module to be recognized and for the game to run


text:
Q: font-weight is not working properly? http://www.i3physics.com/blog/2010/07/dsfsdf/
Here is an example.
The part where it said "PHP" (the right top corner) remained as slim as it was.
here is part of the css code
.wp_syntax_lang {
  background-color:#3c3c3c;
  position:absolute;
  right:0;
  padding:1px 10px 3px;
  color:#ddd; font-size:9px; font-weight:800;
  text-transform:uppercase;
  -moz-border-radius-bottomleft:5px;
  -webkit-border-bottom-left-radius:5px;
  border-radius-bottomleft:5px;
}

I tried bold, bolder, 700, 800, 900 and is not working under FF.

A: font-weight can fail to work if the font you are using does not have those weights in existence – you will often hit this when embedding custom fonts. In those cases the browser will likely round the number to the closest weight that it does have available.
For example, if I embed the following font...
@font-face {
    font-family: "Nexa";
    src: url("Nexa-Regular.ttf") format("truetype");
    font-weight: 400;
    font-style: normal;
}

Then I will not be able to use anything other than a weight of 400. All other weights will revert to 400.
If you want additional weights, you need to specify them in separate @font-face declarations with those additional weights, like this.
@font-face {
    font-family: "Nexa";
    src: url("Nexa-Light.ttf") format("truetype");
    font-weight: 300;
    font-style: normal;
}

@font-face {
    font-family: "Nexa";
    src: url("Nexa-Regular.ttf") format("truetype");
    font-weight: 400;
    font-style: normal;
}

@font-face {
    font-family: "Nexa";
    src: url("Nexa-Bold.ttf") format("truetype");
    font-weight: 700;
    font-style: normal;
}

Usually each weight will have a separate font file the browser will need to download, unless you're using variable width fonts.

A: i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button.
Then I selected the font weights that I want and then embedded the updated link in my html..

A: Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.

A: Most browsers don't fully support the numerical values for font-weight.  Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.
If you need something bolder then you might want to try using a different font that's bolder than your existing one.  Naturally, you could probably adjust the font size for a similar effect.

A: If you're importing a Google font, you need to ensure you've specified all the weights that you would like to use.
In my case, I was using Google's Roboto font. I had to import it with several different weights, like this:
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto+Slab|Roboto:300,400,500,700" rel="stylesheet" />

Remember that each additional weight increases the amount of data each visitor needs to download, and can slow down the loading of your page, so only use what's necessary.

A: For me the bold work when I change the font style from   font-family: 'Open Sans', sans-serif; to Arial

A: I removed the text-transform: uppercase; and then set it to bold/bolder, and this seemed to work.


text:
Q: Why can't I get the correct value from this node? I am trying to reproduce a problem in my more complex code with a very simple code (as follows) which creates a tree and assigns keys, then traverses the tree and prints out the keys.
The output of this program should be give:
This key is 3
This key is 1

but instead it gives
This key is 3
This key is 33603600

which makes me think I am incorrectly creating my tree structure. Can anyone point out my mistake and hopefully critique my manner of creating this tree structure?
node.h:
  1 #ifndef _NODE_H_
  2 #define _NODE_H_
  3
  4 class node {
  5
  6   public:
  7     node();
  8     void assign(int keyval);
  9     int key();
 10     node* gt();
 11     node* lt();
 12
 13   private:
 14     node* _lt;
 15     node* _gt;
 16     int _key;
 17 };
 18
 19 // traverse the tree
 20 void traverse(node* pnode);
 21
 22 #endif

node.cpp:
  1 #include "node.h"
  2
  3 #include <stdio.h>
  4 #include <stdlib.h>
  5 using namespace std;
  6
  7 // default constructor
  8 node::node() {
  9   printf("Constructing node!\n");
 10   // start off as a leaf which returns no class
 11   _lt = NULL;
 12   _gt = NULL;
 13   _key = -1;
 14 }
 15
 16 // assign this key and create new nodes (if possible)
 17 void node::assign(int key) {
 18   printf("assigning key = %i!\n", key);
 19
 20   _key = key;
 21
 22   if(_key < 0) {
 23     return;
 24   }
 25   int key_lt = key-4;
 26   int key_gt = key-2;
 27   printf("key_lt = %i\n", key_lt);
 28   printf("key_gt = %i\n", key_gt);
 29   if( key_lt > 0) {
 30     node lt_node;
 31     lt_node.assign(key_lt);
 32     _lt = &lt_node;
 33   }
 34   if( key_gt > 0) {
 35     node gt_node;
 36     gt_node.assign(key_gt);
 37     _gt = &gt_node;
 38   }
 39 }
 40
 41 // simple return functions
 42 int node::key() {
 43   return _key;
 44 }
 45 node* node::gt() {
 46   return _gt;
 47 }
 48 node* node::lt() {
 49   return _lt;
 50 }
 51
 52 // traverse a node
 53 void traverse(node* pnode)
 54 {
 55   ///// same things!
 56   //printf("This key is %i\n", (*pnode).key());
 57   //printf("This key is %i\n", pnode->key());
 58   printf("This key is %i\n", pnode->key());
 59
 60   if(pnode->gt() != NULL) {
 61     pnode = pnode->gt();
 62     traverse( pnode );
 63   }
 64
 65 }

and finally, the main routine:
  1 #include "node.h"
  2
  3 #include <stdio.h>
  4
  5 using namespace std;
  6
  7 int main(int argc, char** argv) {
  8
  9   node* root = new node();
 10
 11   int key = 3;
 12   root->assign(key);
 13
 14   traverse(root);
 15 }

A: The problem is with how you are creating the lt and gt nodes in node::assign(). You are creating them on the stack, so the objects will be destroyed once execution leaves the scope they were created in.
You should allocate them on the heap (using new, like in main(), and delete them in the node destructor. Preferably, if you are using a compiler that supports C++11, you could consider using smart pointers (such as unique_ptr and shared_ptr) instead, so the nodes will be destroyed when they are no longer used.
In addition, root in main() is never destroyed. You should delete it after calling traverse() (or use a smart pointer). At least in your sample code, it isn't necessary to allocate it with new since it is only used within main().


text:
Q: How to render partial view in asp.net mvc 2 using Controller and Action?

SPORTS STORE

<% Html.RenderAction("Menu", "Nav"); %>

<asp:ContentPlaceHolder ID="MainContent" runat="server" />

This is a sample code from Steven Sandersons' book "Pro ASP.NET MVC Framework."
This code works with MVC V1 and MvcContrib. What it does, it renders a "Menu()" view of "Nav : Controller".  Since ASP.NET MVC V2 includes the Partial() and RenderPartial() functionality, I tried to implement it, but this code doesn't work. I tried to modify it in several ways, but it seems there's no overload function that renders partial views, taking as parameters:
1) Controller name
2) View name
I'm sure I'm not the first person who is implementing RenderAction() in this way, so, there must be a workaround. Please help.

A:
I found the problem. I always remove {controller}/{action} route and customize all my routes with lowercase REST like URLs. But for Html.RenderAction it is necessary to have such general route. I added that general route to the end of my routes list and it worked.  – Mahdi Feb 22 at 14:42

Although i still don't understand, how EXACTLY this works, why is suck route nessesary, and what are route's constraints. Maybe i will do some research later.

A: RenderAction is in MVC2 (docs here).  It sounds like you've changed your code to use RenderPartial instead which is completely different.  Change it back to use RenderAction and you should be ok.  If you don't have it in your version, perhaps you need to update to the latest beta?


text:
Q: Can one use Windows 10 completely by command line? I have been wondered if one can use Windows 10 completely without mouse? For example, if I see some bug in software, I can write a script to repeat it. Is there a way to move mouse cursor and push and release mouse buttons by command line?

A: How can I control the mouse from a command line?
nircmd from nirsoft can be used to control the mouse. All the following commands can be called from a batch script.
The general form of the command will be nircmd followed by one of the following commands:

setcursor [X] [Y]
Set the position of mouse cursor. The [X] and [Y] parameters specifies the desired cursor position.
Example:
setcursor 100 50

Source setcursor

movecursor [X] [Y]
move the mouse cursor. The [X] and [Y] parameters specifies the number of pixels to move.
Example:
movecursor 10 10

Source movecursor

sendmouse [right | left | middle] [down | up | click | dblclick]
sendmouse [move] [x] [y]
sendmouse [wheel] [Wheel Value]
Sends the specified mouse event to the system. The operating system will behave exactly as the user really made the specified mouse
    action.

Examples:

*

*Sent a right click (For most applications, a context menu is opened):
sendmouse right click

*Sent a double-click with the left mouse button:
sendmouse left dblclick

*Press the left mouse button, move the mouse cursor 20 pixels left and 30 pixels down, and then release the button:
sendmouse left down
sendmouse move -30 20
sendmouse left up

*Scroll the mouse wheel 10 units in standard wheel mouse. (On standard wheel mouse, the wheel value should be a multiple of 120).
sendmouse wheel 1200

Source sendmouse

Disclaimer
I am not affiliated with nirsoft in any way, I am just an end user of their software.
Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*wmic - Windows Management Instrumentation Command.


text:
Q: StrSubstitute for multiple replacements in a loop? I am trying to replace multiple keywords using \StrSubstitute inside a loop using foreach - but unable to accumulate all the results. The result of each \StrSubstitute call is getting lost inside the loop.
I am using the method suggested at capturing the result. Sample code is as below:
\documentclass[11pt]{article}
\usepackage{etoolbox}
\usepackage{xstring}
\usepackage{tikz}

\begin{document}

\def\KeyWords{one, two, three}
\def\MyText{This is one, followed by two later by three}
\expandarg

Original Text: \MyText\\

\foreach \keyword in \KeyWords
{
   Replacing: \texttt{\keyword}
  \StrSubstitute{\MyText}{\keyword}{\textbf{\keyword}}[\MyText]

  Now MyText: \MyText  \\ \\
}
Final: \MyText \

In the above sample, in each iteration the particular word one, two or three gets bold correctly - but when it finally comes out of the loop, the \MyText ends up being the same as original.
Even \csgdef did not work (assuming global vs local definitions is the problem).
Tried  \renewcommand{\MyText}{\StrSubstitute{\MyText}{\keyword}{\textbf{\keyword}}} to directly assign the substitution result to \MyText but it just hangs saying something like
[Loading MPS to PDF converter (version 2006.09.02).]

(I am using MikTeX 2.9 and pdflatex if that matters )
What is the correct mechanism to achieve this?
Goal is to substitute one or more comma separated supplied keywords with their respective replacement words in a given string.

A: The problem is that each cycle of \foreach is performed inside a group. So you have to globally save \MyText after the substitution; however a straightforward
\documentclass[11pt]{article}
\usepackage{etoolbox}
\usepackage{xstring}
\usepackage{tikz}

\begin{document}

\def\KeyWords{one, two, three}
\def\MyText{This is one, followed by two later by three}
\expandarg

Original Text: \MyText\\

\foreach \keyword in \KeyWords
{
  Replacing: \texttt{\keyword}
  \StrSubstitute{\MyText}{\keyword}{\textbf{\keyword}}[\temp]%
  \global\let\MyText\temp

  Now MyText: \MyText  \\
}
Final: \MyText
\end{document}

will not work, because the keywords are replaced by \textbf{\keyword}, where \keyword doesn't get expanded.
You have to expand \keyword in the substitution string; for instance with
\documentclass[11pt]{article}
\usepackage{etoolbox}
\usepackage{xstring}
\usepackage{tikz}

\begin{document}

\def\KeyWords{one, two, three}
\def\MyText{This is one, followed by two later by three}
\expandarg

Original Text: \MyText

\foreach \keyword in \KeyWords
{
  Replacing: \texttt{\keyword}
  \begingroup\edef\x{\endgroup
    \unexpanded{\StrSubstitute{\MyText}{\keyword}}
    {\noexpand\textbf{\keyword}}}\x[\temp]
  \global\let\MyText\temp
  Now MyText: \MyText  \\
}
Final: \MyText
\end{document}

I's suggest a different approach with l3regex:
\documentclass{article}
\usepackage{xparse,l3regex}

\ExplSyntaxOn
\NewDocumentCommand{\setkeywords}{m}
 {
  \gopa_set_keywords:n { #1 }
 }

\NewDocumentCommand{\changekeywords}{ O{textbf} m}
 {
  \gopa_change_keywords:nn { #1 } { #2 }
 }

\cs_new_protected:Npn \gopa_set_keywords:n #1
 {
  \seq_set_split:Nnn \l_gopa_keywords_seq { , } { #1 }
  \tl_set:Nx \l_gopa_keywords_tl { \seq_use:Nn \l_gopa_keywords_seq { | } }
  \tl_put_left:Nn \l_gopa_keywords_tl { \b( }
  \tl_put_right:Nn \l_gopa_keywords_tl { ) }
  \regex_gset:NV \g_gopa_keywords_regex \l_gopa_keywords_tl
 }

\cs_new_protected:Npn \gopa_change_keywords:nn #1 #2
 {
  \tl_set:Nn \l_gopa_sentence_tl { #2 }
  \regex_replace_all:NnN \g_gopa_keywords_regex { \c{#1}\cB\{\1\cE\} } \l_gopa_sentence_tl
  \tl_use:N \l_gopa_sentence_tl
 }
\tl_new:N \l_gopa_keywords_tl
\tl_new:N \l_gopa_sentence_tl
\seq_new:N \l_gopa_keywords_seq
\regex_new:N \g_gopa_keywords_regex
\cs_generate_variant:Nn \regex_gset:Nn { NV }
\ExplSyntaxOff

\setkeywords{one, two, three}

\begin{document}
\changekeywords{This is one, followed by two later by three}

\changekeywords[textit]{This is one, followed by two later by three}

\end{document}

The \setkeywords command defines the keywords to change; with `\changekeywords you specify the text and, optionally, the format to use (only the control sequence name, rather than a command).
How does it work? From the list of keywords, we prepare a regular expression in the form
\b ( one | two | three )

is built. Matches are replaced by \textbf{\1} where \1 represents the matching string.

A: Here's an alternate way, using stringstrings.  Downside: its a slow package.
\documentclass[12pt]{article}
\usepackage{stringstrings}
\newcounter{index}
\newcommand\emboldenkeywords[2]{%
  \getargs{#1}%
  \setcounter{index}{0}%
  \edef\thestring{#2}%
  \encodetoken[1]{\bfseries}
  \encodetoken[2]{\mdseries}
  \whiledo{\value{index} < \narg}{%
    \stepcounter{index}%
    \edef\nextkeyword{\csname arg\roman{index}\endcsname}%
    \convertword[e]{\thestring}{\nextkeyword}{\bfseries\nextkeyword\mdseries}%
  }%
  \retokenize{\thestring}%
  \thestring%
  \decodetoken[1]{\bfseries}
  \decodetoken[2]{\mdseries}
}
\begin{document}
\emboldenkeywords{one two three}{This is one, followed by two later by three}
\end{document}


text:
Q: ZFS autoreplace unavailable drive I have the fallowing ZFS test pool setup in my vm:
    NAME        STATE     READ WRITE CKSUM
    pool        DEGRADED     0     0     0
      mirror-0  DEGRADED     0     0     0
        sdb     ONLINE       0     0     0
        sdc     ONLINE       0     0     0
    spares
      sdd       AVAIL

I a trying to test the ability to replace a drive that becomes unavailable automatically in a zfs pool. For example if for some reason the drive is removed from the system the spare dive could take its place immediately upon the drives removal. I have configured a spare drive and from the reading I have done, the way I understand it is that this should accomplish my goal. I have also set the autoreplace flag to on to tell zfs to replace any bad drive if detected. When remove a drive from the vm, say sdb and recheck the status of zfs it looks like the fallowing:
    NAME        STATE     READ WRITE CKSUM
    pool        DEGRADED     0     0     0
      mirror-0  DEGRADED     0     0     0
        sdb     UNAVAIL      0     0     0
        sdc     ONLINE       0     0     0
    spares
      sdd       AVAIL

The sdb device becomes unavailable but is never replaced by the spare. Is there a way i can get my use-case to work?

A: Intro
First of all for anyone who is having the same issue on Ubuntu 16.04, it is currently an ongoing bug and as of now, to my knowledge, has not been fixed. You can visit the github conversation here to see the bug I am referencing. Secondly I am writing this post as an enthusiast and intermediate linux user, I am not a developer or currently work on linux as a profession. That being said I will provide the info I have found on this issue to the best of my knowledge.
The Issue:
The hot spare functionality built into the zfsonlinux package currently does not work as stated in the man page. zpool man page:
Hot Spares
   ZFS allows devices to be associated with pools as "hot spares".
   These devices are not actively used in the pool, but when an active
   device fails, it is automatically replaced by a hot spare.

Note: Cold spare (a spare not replaced automatically) functionality is working but only in configurations consisting of mirrors or any of the raidz's. If you have a configuration like the fallowing:
NAME      STATE     READ WRITE CKSUM
pool      ONLINE       0     0     0
  sdb     ONLINE       0     0     0
  sdc     ONLINE       0     0     0
spares
  sdd     AVAIL

Upon the failure of a drive you will be unable to replace it with the spare due to the pool I/O is currently suspended error.
Attempted Solutions:
This is a list of attempted solutions I have gone through and the results is got:

*

*ZFS auto replace: It turns out that according to the zpool man page and my understanding of it, the autoreplace functionality is not to replace a damaged drive with the spare but rather to replace the damaged drive itself with any new device found at its location. zpool man page:
If set to "on", any new device, found in the same physical location
as a device that previously belonged to the pool, is automatically
formatted and replaced.

autoreplace is good to have on, but to achieve the functionality of a hot spare I don't believe it is needed. Im not able to confirm this other than through the man page because i was unable to get the spare to work.

*ZED.rc: I later found from within the conversation on github that the ZED_SPARE_ON_CHECKSUM_ERRORS and ZED_SPARE_ON_IO_ERRORS flags needed to be set within the zed.rc. As @user121391 said in his answer to this post, the zed service/daemon is what determines the status of the pool and what is required to be done based on that status. You can see zed.d at work by running zpool events. After setting the flags, rebooting and, reconfiguring a new pool just in case, my testing of the hot spare came up negative again.

*ZED.d scripts: In @Michael Kjörling's comment he mentioned some scripts packaged with ZED that are written to help with the hot spare scenario. I did indeed find the scripts located in /etc/zfs/zed.d. You can view these scripts on the github page here. From my understanding of zed.d, when an event is triggered the ZED daemon runs one of these scripts based on its status. That being said I did try to run the io-spare.sh and checksum-spare.sh manually and judging by the time they took to execute as well as the unchanged status of the pool, they didn't seem to be running correctly. Maybe this is a potential source to the issue.
My Plans
For Ubuntu 16.04 users of ZFS, to my knowledge there currently seems to be no fix to this issue. I plan to continue to use ZFS with the configuration of a mirrored or raidz(RAID5) depending the the performance i get in testing.(mirrored will be faster but I want to see the speed of raidz) A hot spare would increase the redundancy of both these configs but unfortunately we will have to wait until further development of the zfsonlinux project.  v


text:
Q: Accessing UI from outside thread in Winforms In WPF, one could use something like:
Application.Current.Dispatcher.BeginInvoke(new Action(() => Form1.grid.Items.Refresh()));

to access UI functions outside of the main thread. In Winforms however, the same functionality isn't there. What would be the easiest way to access a BindingList that exists inside of my Form1 class from my "working" thread? Currently I getting the following error when trying to access "Form1.record_list":
System.InvalidOperationException: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

edit: I appreciate the help so far, but I'm lost on "this.Invoke". My method in the separate thread has no "Invoke".
Here's an example of my code so far.
        public static void listen(IPEndPoint server_ip)
    {
        Console.WriteLine("In listen");
        while (true)
        {
            try
            {
                byte[] received_bytes = udp_client.Receive(ref server_ip);
                string received_data = Encoding.ASCII.GetString(received_bytes);
                Record record = JsonConvert.DeserializeObject<Record>(received_data);
                Form1.record_list.Add(record); //This is where I assume the problem spawns
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }

public partial class Form1 : Form
{
    public static BindingList<Record> record_list = new BindingList<Record> { };
    public static DataGridViewCellStyle style = new DataGridViewCellStyle();
    public Form1()
    {
        InitializeComponent();
        Thread thread = new Thread(SCMClient.connect);
        thread.IsBackground = true;
        thread.Start();
        FillData();
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            for (var i = 0; i < row.Cells.Count; i++)
            {
                Console.WriteLine(row.Cells[i].Value);
                if (row.Cells[i].Value as string == "OK")
                {
                    row.Cells[i].Style.BackColor = Color.Red;
                    Console.WriteLine("IF WAS TRUE");

                }
            }
        }
    }

I think the specific problem here is when I add Records to the Forms1.record_list. I'm not sure how to add items to that list without causing the Cross-thread error...

A: You MUST access your UI from your UI Thread only. But you can use the Control.Invoke method - a Form IS a Control - to ensure your code is run from the UI Thread.
Also, you have a static BindingList, but I assume you want to display the contents of that list in an specific form. You should make the BindingList an instance member instead... or get a reference to a valid Form. The Control.Invoke method is not static.
There are several ways to do so. I would do it like so:
First, create a method in your Form class that adds the record to the list.
public void AddRecord(Record r) {
    if(this.InvokeRequired) {
        this.Invoke(new MethodInvoker(() => this.AddRecord(r)));
    } else {
        this.record_list.Add(r);
    }
}

Second, you need to have a reference to the form (in the next step, that is the theForm variable).
Then, in your listener method, invoke AddRecord method instead of adding the record in your BindingList directly.
public static void listen(IPEndPoint server_ip)
{
    Console.WriteLine("In listen");
    while (true)
    {
        try
        {
            byte[] received_bytes = udp_client.Receive(ref server_ip);
            string received_data = Encoding.ASCII.GetString(received_bytes);
            Record record = JsonConvert.DeserializeObject<Record>(received_data);
            theForm.AddRecord(record); // You need a Form instance.
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}

A: The below will work out in winforms. Have tried once. The below code helps to update the label in UI thread from another thread.
string _string = "Call from another thread";
this.Invoke((MethodInvoker)delegate {
label1.Text = _string;
});

A: You're looking for SynchronizationContext.Current, which works with both WinForms and WPF.
Note that you'll need to grab its value from the UI thread, since it's per-thread.