text:
Q: Как не допустить создания дубликатов в БД Предположим есть следующий класс, который символизирует таблицу в БД:
public class Operation
{
    public string Detail { get; set; }
    public string Number { get; set; }
    public int EquipmentId { get; set; }
}

При создании пользователем данной сущности необходимо информировать о попытке создания дубликата.
Дубликатом считается наличие объекта в бд с такими же значениями приведенных полей
Как это можно сделать?

A: Наиболее предпочтительным является способ проверки на дубликат средствами самой бд.
В Entity Framework это может выглядеть например так:
воспользуемся средствами fluent api
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Operation>()
        .Property(x => x.Detail)
        .IsRequired()
        .HasColumnAnnotation("Index",
            new IndexAnnotation(new IndexAttribute("IX_Operation", 1) { IsUnique = true }));
    modelBuilder.Entity<Operation>()
        .Property(x => x.Number)
        .IsRequired()
        .HasColumnAnnotation("Index",
            new IndexAnnotation(new IndexAttribute("IX_Operation", 2) { IsUnique = true }));
    modelBuilder.Entity<Operation>()
        .Property(x => x.EquipmentId)
        .IsRequired()
        .HasColumnAnnotation("Index",
            new IndexAnnotation(new IndexAttribute("IX_Operation", 3) { IsUnique = true }));
}

При помощи атрибута Index
public class Operation
{
    [Index("IX_Operation", 1)]
    public string Detail { get; set; }
    [Index("IX_Operation", 2)]
    public string Number { get; set; }
    [Index("IX_Operation", 3)]
    public int EquipmentId { get; set; }
}

будет создан индекс на основании необходимых полей и попытка вставить дубликат выкинет исключение.
Использовать это необходимо так:
Метод добавляющий запись в бд должен быть обернут в блок try
try
{
    _operationService.Add(operation);
}
catch(Exception ex)
{
    //Здесь обрабатываем возникшее исключение
}

если же возможность изменить структуру таблицы есть но в бд уже есть дубликаты, то тогда необходимо сначала избавиться от дубликатов и потом создать индекс.
Если же по какой либо причине изменить бд(создать необходимый индекс) невозможно то тогда можно делать проверку перед вставкой в бд, но стоит помнить что такой вариант является менее эффективным(исключение составляет когда с бд работает один пользователь), так как после проверки и перед вставкой другой пользователь может добавить запись, выглядеть это может например так:
public static bool OperationIsExist(this IQueryable<Operation> src, Operation operation)
{
    return src
    .Where(x=>x.Detail.Equals(operation.Detail, StringComparison.InvariantCultureIgnoreCase))
    .Where(x=>x.Number.Equals(operation.Number, StringComparison.InvariantCultureIgnoreCase))
    .Where(x=>x.EquipmentId==operation.EquipmentId)
    .Any();
}

A: Создать уникальный индекс в базе данных. Железная гарантия, что дубликатов не будет, даже если в программе будет ошибка, даже если кто-то попытается забить дубликат напрямую через sql-консоль.


text: Q: Military sci-fi series about a human combat unit on their ship specially bred for their roles Back in the 1980s or 90s, I read the first book in a military science fiction series that dealt with a human combat unit in the far future. The novel mostly took place on their ship, and the humans were genetically bred according to their combat arm (Infantry was big and strong, pilots had fast reflexes, Intel-types had huge brains, etc). The living spaces were communal, their language was coarse, and there was lots of sexual innuendo but no sex. The characters kind of reminded me of Battletech Clans, but there were no Mechs in this book that I can remember.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i make a button that gets value from a server respond quicker to users? I am building a social networking application with flutter and Node.js. I used a socket io for real-time connections but for example, when a user clicks on the like a button, there is a little wait time after pressing. is there a trick I can do on the frontend to make it respond to user first then process in the background?

A: Just play the animation immediately after the user presses the button and send the request to your server in background. If the request failed — you could probably use a toast with an error message, and "retrack" the local like.


text:
Q: Have I reached a hard-coded limit of tshark? I am using tshark to dump bittorrent.piece.data and appear to have hit some internal limit within tshark.
tshark -r 2-live.pcap -R "bittorrent.piece.data and ip.dst_host == 192.168.3.14" -T fields bittorrent.piece.data > dumped

This should dump the piece data (32Kbyte pieces) as colon separated bytes in hex without leading 0x so for example:
    7f:00:ab:cd.... and so on for 32Kbytes.
One piece is written to the stdout per line which I am simply redirecting to a file, but the piece data is truncated somehow to a line length of 65540, where I am expecting 90-100KBytes per line/piece, given the 3 characters-per-byte required by the output format chosen by tshark (7f: == 1 byte)
Running with strace I can see that tshark is writing 4096 bytes and then 61444 for each piece.
I don't know if this is a hard-wired limitation of tshark with regard to outputing fields of a protocol read from a pcap file, or whether my Linux configuration is limiting this at a lower-level. I strongly expect it is the former but would welcome advice.
Do I need to patch wireshark/tshark code or is there command-line or configuration option I am missing?
Note: I can successfully dump 32768 KBytes payload data from the GUI wireshark tool so the data is definitely in the pcap file. But I am keen to automate this process and need tshark to give me all the bytes...

A: I'd rather suggest you to write raw packet data to a file with -w tshark switch (which should work fine) and then convert them to your desired format with hexdump -v -e '1/1 "%02x:"' <dump.raw >dump.hex.


text:
Q: how do i feed printf as input to a C program using a file? I know you can give input to a C program in linux like this
me $ printf "some input" | ./someProgram

I want to do the same thing using input from a file, like this
me $ myProgram < myFile.txt

myProgram has two gets statements that I want to fill w/printfs as input.
  printf("...."); fflush(stdout);
  gets(var1);
  printf("...."); fflush(stdout);
  gets(var2);

The program behaves as expected when I fill the vars from an input file like this
"12345"  //expect to fill var1 w/ 12345 and it does
"12345"  //expect to fill var2 w/ 12345 and it does

But the program does not behave as expected when my input file looks like this
printf "12345"  //expect to fill var1 w/ 12345 but it does not
printf "12345"  //expect to fill var2 w/ 12345 but it does not

Clearly, C is not interpreting the print command in the same was as if I gave the command as input and then piped it into the program.
What's going on? What do I fix? How can I give printf input from a file?

A: C isn't interpreting any commands at all. When you use ... < file to redirect stdin, the contents of that file become the input to your program - verbatim. So if the file contains
"12345"
"abc"

, then var1 will be "12345" (not 12345) and var2 will be "abc" (not abc). Similarly, if the file contains
printf "12345"
printf "12345"

, then var1 will be printf "12345" and var2 will be printf "12345".
As I see it, you have two choices: Either you put
12345
12345

in the file and use ./someProgram < myFile.txt, or you put
printf "12345\n"
printf "12345\n"

in the file and use sh myFile.txt | ./someProgram (executing the contents of myFile.txt as a shell script).

A: You are missing the trailing newline.
printf "12345\n" should work well.


text:
Q: Adding confidence bands for log growth curve I'm working with data that shows a log growth curve. I was able to fit a non-linear mixed effects regression using the nlme package nicely. However, I am uncertain as to how to add confidence bands around the estimated lines. Can anyone help?
 Please find data and code below:
Data:
Harvest Plot Irrigation Graft Rep AwtRun 1 11b 1 b 1 0 2 11b 1 b 1 1.6 3 11b 1 b 1 7.67 4 11b 1 b 1 11.96 5 11b 1 b 1 18.82 6 11b 1 b 1 31.43 11b 1 b 1 41.84 8 11b 1 b 1 45.08 9 11b 1 b 1 48.09 10 11b 1 b 1 48.8 11 11b 1 b 1 51.73 12 11b 1 b 1 54.13 13 11b 1 b 1 60.56 14 11b 1 b 1 63.44 15 11b 1 b 1 65.44 16 11b 1 b 1 67.33 1 11c 1 c 1 0 2 11c 1 c 1 0.86 3 11c 1 c 1 1.6 4 11c 1 c 1 5.41 5 11c 1 c 1 10.17 6 11c 1 c 1 20.4 7 11c 1 c 1 23.32 8 11c 1 c 1 23.99 9 11c 1 c 1 25.23 10 11c 1 c 1 25.89 11 11c 1 c 1 27.71 12 11c 1 c 1 29.64 13 11c 1 c 1 30.81 14 11c 1 c 1 33.09 15 11c 1 c 1 35.66 16 11c 1 c 1 36.59 1 11s 1 s 1 0.82 2 11s 1 s 1 0.82 3 11s 1 s 1 1.19 4 11s 1 s 1 4.39 5 11s 1 s 1 11.77 6 11s 1 s 1 15.81 7 11s 1 s 1 21.9 8 11s 1 s 1 28.16 9 11s 1 s 1 33.63 10 11s 1 s 1 45.22 11 11s 1 s 1 49.45 12 11s 1 s 1 51.71 13 11s 1 s 1 54.82 14 11s 1 s 1 57.44 15 11s 1 s 1 57.61 16 11s 1 s 1 58.38 1 12b 2 b 1 0 2 12b 2 b 1 0.9 3 12b 2 b 1 2.19 4 12b 2 b 1 7.1 5 12b 2 b 1 10.98 6 12b 2 b 1 26.48 7 12b 2 b 1 32.08 8 12b 2 b 1 37.58 9 12b 2 b 1 40.45 10 12b 2 b 1 48.27 11 12b 2 b 1 53.03 12 12b 2 b 1 55.05 13 12b 2 b 1 55.05 14 12b 2 b 1 55.75 15 12b 2 b 1 56.57 16 12b 2 b 1 57.57 1 12c 2 c 1 0 2 12c 2 c 1 0 3 12c 2 c 1 5.05 4 12c 2 c 1 10.08 5 12c 2 c 1 13.65 6 12c 2 c 1 25.03 7 12c 2 c 1 26.9 8 12c 2 c 1 27.47 9 12c 2 c 1 28.66 10 12c 2 c 1 31.98 11 12c 2 c 1 34.79 12 12c 2 c 1 35.2 13 12c 2 c 1 36.65 14 12c 2 c 1 38.41 15 12c 2 c 1 38.68 16 12c 2 c 1 38.94 1 12s 2 s 1 0 2 12s 2 s 1 0 3 12s 2 s 1 0.39 4 12s 2 s 1 4.59 5 12s 2 s 1 8.02 6 12s 2 s 1 17.45 7 12s 2 s 1 25.83 8 12s 2 s 1 33.04 9 12s 2 s 1 35.87 10 12s 2 s 1 52.42 11 12s 2 s 1 57.91 12 12s 2 s 1 57.91 13 12s 2 s 1 57.91 14 12s 2 s 1 57.91 15 12s 2 s 1 57.91 16 12s 2 s 1 58.38 1 21b 1 b 2 0 2 21b 1 b 2 0 3 21b 1 b 2 1.36 4 21b 1 b 2 6.2 5 21b 1 b 2 10.08 6 21b 1 b 2 17.53 7 21b 1 b 2 21.36 8 21b 1 b 2 24.92 9 21b 1 b 2 31.62 10 21b 1 b 2 47.42 11 21b 1 b 2 50.85 12 21b 1 b 2 50.85 13 21b 1 b 2 53.27 14 21b 1 b 2 53.66 15 21b 1 b 2 53.93 16 21b 1 b 2 56.48 1 21c 1 c 2 0 2 21c 1 c 2 0 3 21c 1 c 2 0.74 4 21c 1 c 2 6.44 5 21c 1 c 2 13.8 6 21c 1 c 2 20.12 7 21c 1 c 2 20.75 8 21c 1 c 2 23.58 9 21c 1 c 2 23.58 10 21c 1 c 2 28.69 11 21c 1 c 2 30.4 12 21c 1 c 2 31.74 13 21c 1 c 2 33.86 14 21c 1 c 2 34.06 15 21c 1 c 2 35.15 16 21c 1 c 2 36 1 21s 1 s 2 0 2 21s 1 s 2 0 3 21s 1 s 2 1.67 4 21s 1 s 2 3.41 5 21s 1 s 2 8.36 6 21s 1 s 2 16.97 7 21s 1 s 2 23.85 8 21s 1 s 2 28.16 9 21s 1 s 2 30.54 10 21s 1 s 2 37.33 11 21s 1 s 2 40.11 12 21s 1 s 2 40.41 13 21s 1 s 2 42.03 14 21s 1 s 2 42.03 15 21s 1 s 2 42.03 16 21s 1 s 2 42.03 1 22b 2 b 2 0 2 22b 2 b 2 2.06 3 22b 2 b 2 3.99 4 22b 2 b 2 6.7 5 22b 2 b 2 9.67 6 22b 2 b 2 14.8 7 22b 2 b 2 20.64 8 22b 2 b 2 28.33 9 22b 2 b 2 34.15 10 22b 2 b 2 44.86 11 22b 2 b 2 53.06 12 22b 2 b 2 54.44 13 22b 2 b 2 57.14 14 22b 2 b 2 60.16 15 22b 2 b 2 61.32 16 22b 2 b 2 61.32 1 22c 2 c 2 0 2 22c 2 c 2 0 3 22c 2 c 2 1.55 4 22c 2 c 2 4.93 5 22c 2 c 2 13.63 6 22c 2 c 2 21.98 7 22c 2 c 2 26.7 8 22c 2 c 2 27.23 9 22c 2 c 2 30.56 10 22c 2 c 2 40.73 11 22c 2 c 2 42.01 12 22c 2 c 2 45.52 13 22c 2 c 2 51.7 14 22c 2 c 2 53.59 15 22c 2 c 2 53.59 16 22c 2 c 2 53.59 1 22s 2 s 2 0 2 22s 2 s 2 0 3 22s 2 s 2 1.15 4 22s 2 s 2 9.27 5 22s 2 s 2 13.5 6 22s 2 s 2 23.78 7 22s 2 s 2 24.38 8 22s 2 s 2 27.7 9 22s 2 s 2 33.63 10 22s 2 s 2 41.23 11 22s 2 s 2 44.84 12 22s 2 s 2 48.26 13 22s 2 s 2 51.96 14 22s 2 s 2 54.83 15 22s 2 s 2 54.83 16 22s 2 s 2 54.83 1 31b 1 b 3 0 2 31b 1 b 3 0 3 31b 1 b 3 0 4 31b 1 b 3 0 5 31b 1 b 3 1.32 6 31b

Code based on answer from Rob Hall @ https://stats.stackexchange.com/questions/67049/non-linear-mixed-effects-regression-in-r
#nonlinear mixed effects model with self start logistic (SSlogis) for starting values
library(nlme)
#base Model: y = (Asym+u)/(1+exp((Harvest-xmid)/scale)), u ~ N(0,s2u); (no graft)
initVals <- getInitial(sqrtawtrun ~ SSlogis(Harvest, Asym, xmid, scal), data = Data)
#base model without graft, based on starting points found earlier
baseModel<- nlme(sqrtawtrun ~ SSlogis(Harvest, Asym, xmid, scal),
                 data = Data,
                 fixed = list(Asym ~ 1, xmid ~ 1, scal ~ 1),
                 random = Asym ~ 1|Plot,
                 start = initVals
)
#creating dummy variables for graft; releveling so 's' is the reference category to match SAS code
graft.dummy=model.matrix(~relevel(Data[["Graft"]],"s"))[,2:3]
#updating to include graft in model -- same as above but allowing for diff asym, xmid, and scal vars for each graft
#starting values based on fitted base model values (for those in the base model) & zero for all new parameters
nestedModel <- update(baseModel,fixed=list(Asym ~graft.dummy, xmid ~graft.dummy, scal~graft.dummy),
                      start = c(fixef(baseModel)[1], 0, 0, fixef(baseModel)[2], 0, 0, fixef(baseModel)[3], 0, 0))

#growth curve plots -- line for each plot, colored on graft
#currently only predicted population level mean at each observed point, plotted as smooth line
ggplot(data=Data,aes(x=Harvest,y=sqrtawtrun,
                    color=Graft,na.rm=T)) +
  geom_point(cex=0.6)  +
  geom_line(aes(x=Harvest,y=nestedModel$fitted[,1],color=Graft),size=2)


text:
Q: I receive a 401 error when I access a custom method inside my Models folder I'm using Loopback to access/update/make changes to my database.  I've created a method called deleteSingleHearingTest in my common/models folder:
Account.deleteSingleHearingTest = function (req, callback) {
    console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
    Account.findById(req.accessToken.userId)
        .then(account => {
            if (!account) {
                throw new Error('Cannot find user');
            }
            console.log('account.js: deleteSingleHearingTest: req: ', req);
            return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

        })
        .then(() => {
            callback(null);
        })
        .catch(error => {
            callback(error);
        });
}

after which I created a remote method:
Account.remoteMethod(
        'deleteSingleHearingTest', {
            http: {
                path: '/deleteSingleHearingTest',
                verb: 'post'
            },
            accepts: [
                { arg: 'req', type: 'object', http: { source: 'req' } }
            ],
            returns: { "wtf": "wtf" }
        });

When I attempt to use this via fetch inside a method called deleteSingleHearingTest in my actions folder(redux) I receive a 401 status error message:
export const deleteSingleHearingTest = (hearingTestNumber) => {
    return (dispatch, getState) => {
        let state = getState();
        if (!state.user || !state.user.accessToken || !state.user.accessToken.id || !state.user.accessToken.userId) {
            console.debug('writeTestResult', state.user);
            // TODO: ERROR
            return;
        }
        dispatch({
            type: DELETE_SINGLE_REPORT_REQUEST
        });
        console.log('here is your access token', state.user.accessToken);

        fetch(SERVERCONFIG.BASEURL + '/api/Accounts/deleteSingleHearingTest?access_token=' + state.user.accessToken.id, {
            method: 'POST',
            headers: SERVERCONFIG.HEADERS,
            body: JSON.stringify({ "hearingTestId": hearingTestNumber })

        })
            .then(response => {
                if (response.status === 200) {
                    console.log('actions/user.js deleteSingleReport were in the pipe 5x5', response.json());
                }
                console.log('actions/user.js failed to delete item: response: ', response)
            })
    }
};

Two errors I'm noticing:
1.  the Account.deleteSingleHearingTest never gets reached.  I know this because the console.log never shows up in the window where I ran node .

*I get a 401 status error message on the front end.

Here is a picture of my StrongLoop gui.

here is the picture of my account.json file
Here's a picture of a method that a previous developer created that currently works with no status errors.  deleteSingleHearingTest is nearly identical.

A: From what I can tell by looking at your API Explorer screenshot, your Account model is extending LoopBack's built-in User model. The User model has ACLs configured to deny access to all methods except few explicitly allowed ones. You can find the ACL configuration in common/models/user.json.
"acls": [
  {
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "DENY"
  },
  {
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "ALLOW",
    "property": "create"
  },
  {
    "principalType": "ROLE",
    "principalId": "$owner",
    "permission": "ALLOW",
    "property": "deleteById"
  },
  {
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "ALLOW",
    "property": "login"
  },
  // etc.
]

The first entry denies access to all methods, the subsequent entries allow access to certain methods for certain groups of users. For example, anybody ($everyone) can create a new user or invoke a login method, but the details of a User model can be retrieved only by the user themselves ($owner).
Please refer to Controlling data access and Understanding the built-in User model in LoopBack's documentation to learn more.
In order to allow your users to execute Account.deleteSingleHearingTest method, you need to add a new ACL entry to your Account configuration. I believe LoopBack can merge ACL defined in the base model (User) with the additional ACL entries defined in a subclassing model (Account) as of pull request #1289. If that's the case then you need to simply add a new ACL entry in your common/models/account.json file. Assuming any logged-in user can invoke deleteSingleHearingTest, but anonymous (unauthenticated) users cannot:
{
  "name": "Account",
  "base": "User",
  // ...
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": "deleteSingleHearingTest"
    }
  ]
}


text:
Q: ReactJS bind(this) I'm following a tutorial to update states in ReactJS. I came across this line in the tutorial this.updateLanguage = this.updateLanguage.bind(this) and I don't understand what is going on. I understand the basics of this and bind, but I've never seen it done like this before. Can someone please explain? The full code:
var React = require('react');

class Popular extends React.Component {
    // constructor to set default state
    constructor (props) {
        super(props);
        this.state = {
            selectLanguage: 'All'
        };
        // I don't understand this line
        this.updateLanguage = this.updateLanguage.bind(this);
    }
    // updates state
    updateLanguage(lang) {
        this.setState(() => {
            return {
                selectLanguage: lang
            }
        });
    }
    render() {
        var languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python'];
        return (

                {languages.map((lang) => {
                    return (
                        // adds listener to current state

                            {lang}

                    )
                })}

        )
    }
}

module.exports = Popular;

A: DOM callbacks such as click events will set the this context to the DOM element itself, in this case the li.  Try removing the part you don't understand and see what happens - you'll see something like this.setState is not defined, because that function isn't defined in the context of the li element (it's basically looking for li.setState).
What bind is doing on that line is ensuring that whenever that function gets called, it will get called with the this context we want, in this case the Popular component - e.g. Popular.setState.
These days it's getting more and more common to see folks just using fat arrow syntax as a shorthand to preserve the this context - e.g. in this case onClick={ () => this.updateLanguage(lang) }.
(note for those concerned about performance: the fat arrow approach is cleaner but somewhat controversial since it's repeatedly declaring the function on every single render. That said, some folks claim there is minimal or no significant performance impact.)

A: If you not getting the bind(this) in constructor then its not but one of the way to avoid binding in render
Now why we need bind(this) in render let say we generally use
onChange={this.handleChange.bind(this)}
These approaches assume that you're declaring React components using ES6 classes. If you use an ES6 class, React no longer autobinds.
So, this is the One way to resolve this is to call bind in render.


text:
Q: Two nonassociated functions defining the same hypersurface? Let $X\subseteq\mathbb P^n$ be a complex, irreducible projective variety. Let $R$ be the projective coordinate ring of $X$, i.e. $R=\mathbb C[x_0,\ldots,x_n]/I$ for some homogeneous prime ideal $I$. Can there be homogeneous elements $f,g\in R$ which are irreducible, not associated and which cut out the same codimension one subvariety of $X$? In other words, can the ideals generated by $f$ and $g$ have the same radical ideal? It feels unintuitive, so I am having a hard time coming up with an example - but I see no formal reason why it can't happen.

A: Some foolish thoughts that can't fit in the comments box:
If $f$ and $g$ are prime, then $(f)$ and $(g)$ are prime ideals and hence their own radicals. Now $(f)=(g)$ implies $f=ag$ and $g=bf$ for some $a,b\in R.$ Then $f=ag=abf \implies ab=1,$ $a$ and $b$ are units and so $f$ & $g$ are associates.
This is the case if $R$ is a a UFD (in a UFD, irreducible implies prime). Consider the following:

Let $R$ be a noetherian domain. Then $R$ is a UFD if and only if every prime ideal
  of height one is principal.

This is Theorem 20.1 (on page 161) of Matsumura's Commutative ring theory, or you can also see its proof here. Geometrically, this means your $R$ is a UFD if and only if every codimension one subvariety of $V(I)$ is the set of zeros of some $f\in R.$

A: Here's an example with a smooth X. Consider $X = \mathbb{P}^1$ embedded in $\mathbb{P}^3$ in the Veronese (twisted cubic) embedding. The coordinate ring is
$$k[X,Y,Z,W] / (XW - YZ, Y^2 - XZ, Z^2 - YW)$$
(which we can think of as the ring $k[S^3,S^2T,ST^2,T^3]$ if we want, where $S,T$ are the coordinates on $\mathbb{P}^1$ from $\mathcal{O}(1)$. So $S=0$ is the point "$0$" and $T=0$ is "$\infty$".)
Then the linear polynomials $Y$ and $Z$ are evidently irreducible (being linear), and they generate different ideals, since the relations are all quadratic. (Note that $Y=S^2T$ has divisor $2[0] + [\infty]$, and $Z=ST^2$ has divisor $[0] + 2[\infty]$. So they have the same support but are not multiples of each other.)
But the quadratic relations directly state that $Y^2$ is divisible by $Z$ and $Z^2$ is divisible by $Y$. So they have the same radical (which I think is just $(Y,Z)$.)
Edit. Was not thinking clearly when I first posted this, and did it with the divisors $2[0]+[1]$ and $[0]+2[1]$ by mistake. Fixed now.


text:
Q: Possible to "listen" to a CSS value for a DOM element and tell another DOM element to match it? I'm trying to hack Drupal's colorpicker module so that as my user drags it around picking colors, he sees colors changing on the web site's  in real-time.
Right now the colorpicker's js changes the color of the picker widget in real-time.
I want to hack the js so that the color of the picker widget AND a specific DOM element change background colors at once.
Is there a way I can write some code that "listens" to the background-color setting of the colorpicker input and then changes the background-color of ?
Here's the code where Drupal is applying settings from the colorpicker widget to its input:
Drupal.behaviors.colorpicker = function(context) {
$("input.colorpicker_textfield:not(.colorpicker-processed)", context).each(function() {
var index = $('body').find('input.colorpicker_textfield').index($(this));
Drupal.colorpickers[index] = new Drupal.colorpicker($(this).addClass('colorpicker-processed'));
Drupal.colorpickers[index].init();
});

What can I add to this to tell it to "listen" to the background color of "input.colorpicker_textfield" and then set that value to "body" in real time as it changes?

A: Try using change() to apply it to the bg.
$("input").change( function () {
   //var below would obviously have to be correctly formatted.
   var newColor$(this).val();
   $(body).css({background-color: newColor});
});

A: Similar to Cole's answer with some improvements (assuming '#' is not included by the colorpicker):
$('input.colorpicker_textfield').live('change', function() {
    var color = this.value;
    if(color.search((/^[A-Fa-f0-9]{6}/) != -1) {
        body.style.backgroundColor = '#'+this.value;
    }
});

*

*Uses more specific selector

*uses the 'live' event handling method, ensuring the handler will be attached to any dynamically created colorpickers

*It will not change the background color if the input is not a hex value

*It uses the style attribute directly instead of wrapping in the jQuery object.


text:
Q: Joomla 3.4 Bootstrap carousel doesn't slide automatically Here is my webpage http://www.qkiz.pl/wege2/
I was doing all tricks from this question but nothing works. Google Chrome display error in devtools console:
Uncaught TypeError: undefined is not a function

in http://www.qkiz.pl/wege2/templates/wege2/js/karuzela-timing.js

A: Joomla imports Mootools, thus uses noConflict mode with jQuery.
Try calling the carousel like so:
jQuery(document).ready(function($) {
    $('.carousel').carousel({
      interval: 5000
    });
});


text:
Q: Ads show in AVD but not in genymotion and app on real device I am trying to use admob in a code but when I run the app on a real device or in genymotion , I got no ads, and when I run it in the AVD (emulator of android studio) I got the test ads saying that I have succesfully did it.
I don't now where I missed up and I don't know which part of code I have to send so you can help me.
I've tried to chek my Unit Code of admob but it's look correct.

A: Try this test Unit ID and test your app on real device
Banner: ca-app-pub-3940256099942544/6300978111
Interstitial: ca-app-pub-3940256099942544/4411468910

If no ad appears  change your app package name
Hope it helps


text:
Q: Javascript: Equality Function using Dynamic Programming? I want to implement an equality function in JavaScript using dynamic programming.
This is what i have come up with.
function isEqualFunction(args: any): boolean {
    // Here a1 and a2 are two objects to be compared(they cannot be lists)
    // a1a2CombinedKeys is an object that combines keys of a1 and a2,
    // comparisonArgs is an object that needs to be passed to each comparison function for
    // nested objects in a1 and a2,
    // nestedArrayOrObjCompareFunc is an object which contains comparison function for each
    // nested object in a1 or a2.
    const { a1, a2, a1a2CombinedKeys, comparisonArgs, nestedArrayOrObjCompareFunc, } = args;
    return Object.keys(a1a2CombinedKeys).every((objKey) => {
        const a1Value = a1[objKey], a2Value = a2[objKey];
        if (a1Value && a2Value) {
            if (Array.isArray(a1Value)) {
                const { isPropEqualFunction } = nestedArrayOrObjCompareFunc[objKey];
                const { a1a2NestedKeys, nestedObjComparFunc: listItemObjComparFunc } = isPropEqualFunction(comparisonArgs);
                return a1Value.every((a1ObjListItem) => a2Value.find((a2ObjListItem) => isEqualFunction({
                    a1: a1ObjListItem, a2: a2ObjListItem, comparisonArgs,
                    a1a2CombinedKeys: a1a2NestedKeys, nestedArrayOrObjCompareFunc: listItemObjComparFunc,
                })))
            } else if (typeof a1Value === 'object') {
                const { isPropEqualFunction } = nestedArrayOrObjCompareFunc[objKey];
                const { a1a2NestedKeys, nestedObjComparFunc: nestedObjComparFunc } = isPropEqualFunction(comparisonArgs);
                return isEqualFunction({
                    a1: a1Value, a2: a2Value, comparisonArgs,
                    a1a2CombinedKeys: a1a2NestedKeys, nestedArrayOrObjCompareFunc: nestedObjComparFunc,
                })
            } else {
                return a1Value === a2Value
            }
        } else if (!a1Value && !a2Value) {
            return true;
        } else {
            return false;
        }
    });
}

I cannot compare the hash of two objects as some of the nested elements have an id prop.
I am not sure if this is foolproof, but it seems good to me.
Also, I am struggling to create a typescript definition for the same. Any help on that front would also be highly appreciated.


text:
Q: Reusing Code from Another Rails App I am trying to reuse some code from another rails application I had worked on earlier. I copied over all the models / views / controller / migrations and ran rake db:create and migrate. Now when I try to run the application the initial page for this view (the one that has the list edit/delete) loads fine and shows there are 0 records. When I click new, however, it displays an error message on a bit of code created by the scaffolding in my other application...
<%= link_to 'New comment', new_comment_path %>

undefined local variable or method `new_comment_path' for #<ActionView::Base:0xb67c9690>

Should I be able to reuse this code or is their something else I need to do to make sure that I have everything moved over. I tried using grep to find where the 'new_comment_path' was being defined in my other project and I only saw it used in a similar context to what is listed above. Any help would be appreciated.

A: This error shows that you are missing routes.
Check in the conf/routes.rb file in the App you're copying from.
Most probably all you need to do is add
map.resources :comments

to your routes.rb
And add that for all the controllers that you copied.

A: If you have time, or expect to do this again, you might consider making the reuse candidates into a plugin, or use the engines feature in 2.3 (or install the rails_engines plugin for slightly older versions)


text:
Q: How to execute a published Ruby Gem CLI app I created a CLI Ruby Gem several months ago and have just gotten around to publishing it. How can I test out executing the gem to ensure it was set-up/published correctly? Typically, I run bin/run in the terminal from the gem's root directory but I'm not sure how to run it from a Rails directory with the gem installed, for example. Basically just want to make sure I did everything right and it's working as expected.
Here's the gem for reference: https://rubygems.org/gems/phl-covid-testing

A: I see some problems with this. But first, let me address your original question.
To test it on the command line (terminal):
$ gem install phl-covid-testing
$ which run
$ run

To test it in your Bundler project, add phl-covid-testing to your Gemspec/Gemfile. Then do this:
$ bundle install
$ bundle exec run

Now for the problems. The first problem you can see above is that you named your script run. This will be put on the user's path. It'd be better to rename your bin/run script to bin/phl-covid-testing or something else.
Next, I don't know if you did chmod +x on your script file in bin/, but I'll assume you did. However looking at the contents of the file, you have this:
#!/usr/bin/env ruby

require "bundler/setup"
require "./lib/environment"

PHLCovidTesting::CLI.new.call

You shouldn't use ./lib/environment, instead just do require 'environment'. You also don't need require "bundler/setup". If you're testing locally, just use bundle exec bin/run.
Next, don't use the name environment.rb. I suggest renaming this file to the name of your Gem, so it would be phl-covid-testing.rb.
Lastly, your repo has a lot of unnecessary files. Remove .DS_Store and phl-covid-testing-0.1.0.gem and also add these to .gitignore:
# .gitignore
.DS_Store
*.gem

There might be more files that you need to ignore or more problems, but these are the major ones that I see at a glance.
EDIT:
I decided to add how you can test this without uploading to RubyGems.org.
If you're using bundler and rake and you have require 'bundler/gem_tasks' in your Rakefile, then you can do this:
$ bundle exec rake install:local

This will build and install the Gem locally.
Else, you can also do this using the gem command manually:
## Remove old gems (optional).
$ rm -v *.gem

$ gem build phl_covid_testing.gemspec
$ gem install *.gem

See the official doc for more information.
Then try to run the script as I mentioned earlier:
$ phl_covid_testing
## Or with bundler:
$ bundle exec phl_covid_testing


text:
Q: definition of integration using limits In almost all if not all textbooks it begins the definition of integration by $\lim_{a \to 0} \sum_{x=a}^{b} [f(x) A]$
When we come to integration it actually uses anti-derivatives and techniques of integration, why we can't use this definition? If we do , is there some kind of reference of summations that can be used in conjunction with integrating this way?

A: It is too hard to integrate functions using the definition so for practical purposes we use antiderivatives. This method is based on fundamental theorem of calculus and Newton-Leibnitz formula as a part of this theorem:
$$\int^b_a f(x) dx = F(b) - F(a)$$
You can read more here about the theorem, formula and find proofs of them:
https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus


text:
Q: How can I find html file in Inspect Element sorry for my English
I'm using mibew messenger that is open source, I want to change title of chat page and need find source of related page to edit by using Inspect Element.   . would you help me how can i do ?

looking forward to your responses
thanks
Solmaz


text:
Q: Handling orientation change with loaders and array adapters I am using loaders to load data into a gridview . First let me show you some code:-
The Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle icic){

    View v=inflater.inflate(R.layout.thegrid, container, false);
    final GridView gv = (GridView)v.findViewById(
            R.id.thegridview);
    gv.setAdapter(upAd);//upAd is the array adapter initialized in oncreate of the fragment

    gv.setOnItemClickListener(this);
    Bundle args=new Bundle();
    args.putString("page", String.valueOf(page));
    getLoaderManager().initLoader(1, args, this);

    return v;
}
@Override
public Loader<ArrayList<HashMap<String, String>>> onCreateLoader(int loaderId,Bundle thebundle) {

    if(loaderId==1){
        String page=thebundle.getString("page");
        return new MyLoader(getActivity().getApplicationContext(),page);
    }

    return null;
}

@Override
public void onLoadFinished(Loader<ArrayList<HashMap<String, String>>> theLoader,ArrayList<HashMap<String, String>> data) {
    upAd.addAll(data);
}

Now when the fragment is displayed , it shows a grid of 10 elements downloaded.Now when the screen orientation is changed, the loader behaves well and does not download the data again but it adds the same data again to the grid.. so i end up having a grid of 20 elements the same 10 repeated twice. Well i can call :-
upAd.clear()

in onLoadFinished but i want to avoid that.Could someone tell me what would I be doing wrong here.

A: You have 20 items because ArrayList holding data in upAd already has 10 items from past. Then you are calling upAd.addAll(data);. That means you are adding another 10 identical items to that array list. So the solution is to clear adapter.

A: use this line in your Activity declaration in menifiest file.
android:configChanges="orientation|keyboardHidden"


text:
Q: Specific pattern to match and extract info from string I need to be able identifying over a string if it matches with the following patterns:
':module-name' || 'com.example.ClassName' || ':module-name:com.example.ClassName' || 'http://url';
I need to identify if the string matches one of the above patterns, lets split them into 3 groups (urls, local & none) where a url stands for a valid url string. In the other hand local must be in 3 different variants (':module-name' || 'com.example.ClassName' || ':module-name:com.example.ClassName') if this is the case I need to extract the module and component names.
The module name must be a valid nodejs package name and the component name must be a valid Class name (I got the valid class name already covered with this RegExp: /^@?[a-z_A-Z]\w+(?:.@?[a-z_A-Z]\w+)*$/).
What I need is a way to identify where the string belongs to one of the groups (url, local or none) and in case of local, extract the module and component name. The best for a regular expression solution...
Thanks

A: Can this work? See on regex101
^:.+-.+:.+\..+\..+|^:.+-.+|^.+\..+\..+|^http[s]?:\/\/.+

It matches :x-x, x.x.x, :x-x:x.x.x, http[s]://x, x being any character repeated between 1 and unlimited times. It won't match any of those if preceded by something. But it will match com.class.class.class.class and http://invalidUrl. As you said you check if class name is good. If you want only valid url, then you can replace ^http[s]?:\/\/.+ with https?:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))? or any regex validating urls. (I did not invent this one)

A: By using the amazing web tool referenced by Croutonix I was able to produce the RegExp and test it real time:
The solution is /^:([a-z][a-z_-])+:{0,1}([a-z_A-Z]\w+(?:.?[a-z_A-Z]\w+))$/gm.exec(string)


text:
Q: How do I retry a network request using retrofit, publish relay, and rxjava by clicking a button? I am trying to use a publish relay to retry an observable chain when an error occurs. This is the implementation I am using in kotlin:
 private fun getPostsFromVM(maxRes : String) : Disposable{
        return viewModel.getPostList(maxRes).
        retryWhen { attempt -> publishRelay }.
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe({//handle post response
                    Log.d("SubscribeResp",it.etag)
                    //Toast.makeText(activity,it.blogKind,Toast.LENGTH_LONG).show()
                    text.text = " ${it.blogKind } \n ${it.items.get(0).title}"
                },{
                    Log.d("ApiResponseError",it.localizedMessage)
                    if (it is HttpException){
                    retryBtn.visibility = View.VISIBLE
                    val resp = it.response()
                    when(resp.code()){
                        403 -> Toast.makeText(activity,"403 Error",Toast.LENGTH_LONG).show()
                        304 -> Toast.makeText(activity,"304 Error",Toast.LENGTH_LONG).show()
                        else -> Toast.makeText(activity,resp.message(),Toast.LENGTH_LONG).show()
                    }
                }else text.text = it.message})
}

Publish relay is instantiated in the onCreate Method. I then use a button to call the retry method:
retryBtn.setOnClickListener{
            publishRelay.retry(1)
        }

When I tested this out, I didn't get anything (I make sure there is a network error that gets called) so that I can retry by clicking the button but, nothing happens, the retry does not occur.


text:
Q: Show that $\int\limits_{-\infty}^\infty f(t)dt=0$ where $f\in H^\infty(\mathbb{H})$ The problem is stated as follows:
Let $\mathbb{H}$ denote the open upper half plane. Let $f \in H^{\infty}(\mathbb{H})$ Suppose $f$ can be extended to be continuous on $\overline{\mathbb{H}}$ with
$$\int_{-\infty}^\infty |f(t)|dt<\infty$$

Show that
  $$\int_{-\infty}^\infty f(t)dt=0$$

and, the following hint is provided:
Remark: Let $C_R$ denote the upper semicircle with radius $R$.

It is not so obvious why $\int_{C_R}f(z)dz\longrightarrow 0$ as $R\longrightarrow \infty$. A technique to overcome this is to first consider the functions $f_\epsilon(z)=f(z)e^{i\epsilon z}$ where $\epsilon>0$

It is straightforward to show that $\int_{C_R}f_\epsilon(z)dz\longrightarrow 0$ as $R\longrightarrow \infty$. The result for $f_\epsilon$ follows immediately. One then lets $\epsilon \longrightarrow 0$ and shows the convergence of the integrals."
The problem that I am having is that,Assuming $$\underset{z\in \mathbb{H}}{\max}|f(z)|=M,$$ we get
$$\begin{align}
\left|\int_{C_R}f_\epsilon(z)dz\right|&=\left| \int_{C_R}f(z)e^{i\epsilon z}dz\right| \\
&= \left|\int_{C_R}f(z)e^{i\epsilon(x+iy)}dz\right| \\
&\le \int_{C_R}\left| f(z)e^{-\epsilon y+i\epsilon x}\right|dz \\
&=\int_{C_R}\left| f(z)e^{-\epsilon y}\right|dz \\
&\le \int_{C_R} \frac{M}{e^{\epsilon y}}dz
\end{align}$$

My Question:
From here, I just don't see how to make the R.H.S. go to zero. I tried parameterizing it, but then the best I can do for an upper bound is
  $$ \int_0^\pi \frac{MR}{e^{\epsilon R \sin{t}}}dt$$

And, while this looks a little more promising, I still cant get this integral to go to zero either because, when $t=0$, $\sin{t}=0$. I asked my professor for clarification, and he replied that ``In any case, a straightforward application of ML to the integrand from 0 to π won't work. We had the same integral (after putting in absolute value etc) for one of the contour integral examples we did in class. We got a usable bound by making two very elementary observations on the sin function."
I tried to find this in my notes, but the only integral that looks similar to this one that I can find was quite a bit different, and, there, we were able to apply ML.

A:
Basically from what you did at the end it suffices to  prove that ,
  $$\lim_{R\to\infty}\int_0^\pi \frac{R}{e^{\epsilon R \sin{t}}}dt  = \lim_{R\to\infty}\int_0^\pi Re^{-\epsilon R\sin t}dt = 0$$

This is true!!! see below
First split the integral involves  at $t=\frac{\pi}{2}$ then take the change of variable $t'=\pi -t$
$$ \int_0^\pi e^{-\epsilon R\sin t}dt =2\int_0^{\frac{\pi}{2}} e^{-\epsilon R\sin t}dt$$
Afterward shows by studying the function $[0,\frac{\pi}{2}]\ni t \mapsto\frac{\sin t}{t}$ that
$$ \color{blue}{\frac{2}{\pi}t\le \sin\theta \le t,~~~~ ~~ \forall t \in [0,\frac{\pi}{2}] } $$
therefore we get that
$$\lim_{R\to\infty}\int_0^{\pi} Re^{-\epsilon R\sin t}dt =\lim_{R\to\infty}2R\int_0^{\frac{\pi}{2}} e^{-\epsilon R\sin t}dt\\\leq\lim_{R\to\infty}2R\int_0^{\frac{\pi}{2}} e^{-\frac{2\epsilon R}{\pi}t}dt =\lim_{R\to\infty}\frac{\pi}{\epsilon}(1-e^{-\epsilon R}) =0$$
see also here: https://math.stackexchange.com/q/2498579


text:
Q: Cast Exception When Using Foreach on Microsoft.SharePoint.Client.ListCollection I have exhausted my resources on this issue. I'm hoping you all can assist me.
I have an agent polling Microsoft O365 for list collections in order to walk through all the lists in a given site. Here is the code:
Microsoft.SharePoint.Client = CSOM
ListCollection lists = CSOM.web.Lists;
clientContext.Load(lists);
clientContext.ExecuteQuery();
try
{
   foreach(CSOM.List list in lists
   {
      do.stuff()
   }
}
catch(Excetion ex)
{
   // I get this excetpion in my log at CSOM.List after 'in lists' is read.
   /*System.InvalidCastException: Unable to cast object of type
    'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
     to type 'Microsoft.SharePoint.Client.List'.*/
}

When in debug and tracing through the code ex appears 'null', but I still get the excetion in my debug logs when I write ex.ToString() to a log file.
I am using .Net 4.6. This code has worked before, during dev tests, but wont work running in a service. I can't find any Namespace issues. The O365 account I amusing has 2FA disabled and has admin rights. Any thoughts would be very helpful. Thank you.


text:
Q: In boost file_sink class delay the open call The function foo() returns 5 bytes from a file on every call to it. If file_sink class is used then the file has to be opened every time foo() is called. One way is to declare the file_sink as private in the header file and then in the constructor call the open on file_sink and on every call to foo() just call read w/o the necessity to open() every time. But this seems to be not possible since the file_sink constructor expects the file path. How to solve this.

A: Have a file_sink pointer in the header file, initialize it to NULL in the constructor, and have foo create the file_sink (with a file name) the first time through.


text:
Q: Inserting a new Node at the beginning of a LinkeList in Java I have checked few posts that we have in SO.
Insert new node at the beginning of Linked-List
How do I insert a node at the beginning of a linked list?
And implemented a simple LinkedList in java that works just fine.
What I can't get my head around is how adding a new Node to the beginning of the LinkedList would actually work.
Here is how my code snippet for adding a Node to the beginning of the LinkedList looks like:
public class SinglyLinkedList
{
    //Private variable to keep tab of the HEAD of the linked list.
    private ListNode head;

    //Private variable to keep track of the node count in this singly linked list.
    private int length;
.
.
.
    /**
    * Insert a ListNode at the beginning of this List.
    */
    public synchronized void insertAtBegin(ListNode newNode)
    {
        //Set current head as the next of input ListNode
        newNode.setNext(head);

        //Set the input ListNode as the new head of this SinglyLinkedList
        head = newNode;

        //Increment the SinglyLinkedList length
        length++;
    }
.
.
.
}//End of class SinglyLinkedList

The ListNode class represents a Single Node like so:
/**
* Represents a Node of the Linked List.
*/
public class ListNode
{
    private ListNode next;
    private int data;

    /**
    * Constructors
    */
        public ListNode()
        {
            next = null;
            data = Integer.MIN_VALUE;
        }
        public ListNode(int data)
        {
            next = null;
            this.data = data;
        }

    /**
    * Accessor methods.
    */
        public int getData()
        {
            return this.data;
        }

        public void setData(int data)
        {
            this.data = data;
        }

        public ListNode getNext()
        {
            return next;
        }

        public void setNext(ListNode listNode)
        {
            this.next = listNode;
        }

        public String toString()
        {
            return Integer.toString(data);
        }

}//End of class ListNode

The 2 lines that really confuse me are:
//Set current head as the next of input ListNode
        newNode.setNext(head);
        //Set the input ListNode as the new head of this SinglyLinkedList
        head = newNode;

The more I try to analyze these two lines, I feel it will create a circular reference structure instead of pushing in the "newNode" in place of "head".
May be I don't quite understand how Java references are passed around.
Is there an explanation as to why the above two lines won't end up in a circular reference?

A: Imagine you have the following LinkedList:
2 -> 3 -> 4 -> 5

and you want to insert a node with a value of 1 at the beginning. Let's call this node newNode.
Now look at this line: newNode.setNext(head); You are making newNode's next value point to head, which in this case is pointing to the node with a value of 2. This is what your list looks like now:
1 -> 2 -> 3 -> 4 -> 5

However, head is still pointing to the node with the value of 2, so you have to fix that by making head point to the node with a value of 1, which is newNode. That is what the line head = newNode; does.

A: When your list is moving from right to left, i.e. 1 then after new node insertion it becomes 2->1 then after fresh insertion it becomes 3->2->1, In this case you need to take care of two things only : head (the first element of the list) & temporary node which is to be inserted next. Here is the pseudo code for that:
`  while(you_want_to_insert_new_node)        //temporary is the node to be inserted freshly
               {
                   Insert(temporary->data);  //Insert data in temporary node
                   temporary->next=head;
                   head=temporary;
               }
 `

When your list is moving from left to right, i.e 1->2 then it becomes 1->2->3 and so on, you need to take care of 3 things: head, the current node and the temporary. Here is the pseudo code for that:
`
  current=head;
  while(you_want_to_insert_new_node)         //temporary is the node to be inserted freshly
                      {
                                 Insert(temporary->data); //Insert data in temporary node
                                 current->next = temporary;
                                 current=temporary;
                      }

A: It seems you understand conceptually how the LinkedList gets a new head node. Your question is more related to Java itself.
Remember that Java is pass-by-value; When you are passing objects around, you aren't passing the value of the object - you are passing the value of the pointer to that object. Is Java "pass-by-reference" or "pass-by-value"?
So with that in mind, let me break down those 2 lines.
newNode.setNext(head)

The value in head is a pointer to a node. So the setNext function is receiving, in accordance to pass-by-value, a pointer to a node. It is NOT receiving a pointer to head.
head = newNode;

in this line, we reassign head's VALUE to be a POINTER to the newly created node. The value in newNode.next is still a pointer to the previous head.
You are encountering a very common confusion with Java, and believe me it is VERY VERY common (hence the 2k upvotes on the SO I referenced above). I hope this addresses your main source of confusion!


text:
Q: Is there a function of comparing one list to many in python? Let's say I have the following list:
a = ['a' , 'b' , 'c']

And I need to check if the elements of the above list, are contained in the lists below:
list2 = ['a' , 'b']

list3 = ['a' , 'c']

list4 = ['b' , 'c']

list5 = ['d' , 'f']

I need to compare the elements of one list to the elements of many lists at the same time, and the final output to be only the lists that contain these elements.
In the example, the final output would look something like:
list2,

list3,

list4

How can I do this?

A: Change them into sets and then use issubset().
def is_subset(sublst, lst):
    return set(sublst).issubset(lst)

a = ['a' , 'b' , 'c']

list2 = ['a' , 'b']
list3 = ['a' , 'c']
list4 = ['b' , 'c']
list5 = ['d' , 'f']

subsets = [l for l in [list2, list3, list4, list5] if is_subset(l, a)]
# subsets == [['a', 'b'], ['a', 'c'], ['b', 'c']]


text:
Q: How to open Youtube video link in android app? My question is not similar to other questions about how to open YouTube links. My question is how to open a YouTube link, and then when it opens in the app, it should close the YouTube app and again call my MainActivity which opens the YouTube app. It should however open the YouTube app from scrath and not just show the previous YouTube Activity which is running in the background.
MainAcitivy --> SecondActivity --> Youtube --> ThirdActivity --> Youtube
But I want the YouTube app to load again from scratch. But currently, I am getting the previously opened YouTube app which was in the background.
MainActivity
Intent intent = new Intent(MainActivity.this,ThirdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

SecondActivity
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
sleep(10000);
Intent intent=new Intent(getApplicationContext(),ThirdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

ThirdActivity
sleep(5000);
Toast.makeText(getApplicationContext(),"third",Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getApplicationContext(),SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

I want to load it each time again from scratch, but it's showing me the state where it was paused. If you don't understand my question, please be free to comment and I will try to elaborate more. Thanks in advance.

A: Kotlin version to open Youtube video
fun openYoutubeLink(youtubeID: String) {
    val intentApp = Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + youtubeID))
    val intentBrowser = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + youtubeID))
    try {
        this.startActivity(intentApp)
    } catch (ex: ActivityNotFoundException) {
        this.startActivity(intentBrowser)
    }

}

Just call
this.openYoutubeLink("Q-dNnMlaGNg")

A: The following example code will open the Youtube link in the Youtube app if this one is available, otherwise it will open it in a browser:
public static void watchYoutubeVideo(String id) {
    Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
    Intent webIntent = new Intent(Intent.ACTION_VIEW,
    Uri.parse("http://www.youtube.com/watch?v=" + id));
    try {
        startActivity(appIntent);
    } catch (ActivityNotFoundException ex) {
        startActivity(webIntent);
    }
}

EDIT: To answer your second requirement. Each time you call a new Intent with this code. It will open the application or browser for this video and it wont show the previous video loaded.

A: The below code will open the youtube app in your phone
Intent intent = new Intent(Intent.ACTION_VIEW, "your youtube url here");
                        startActivity(intent);
if you want to load the url in your activity put a webview and run the url in the webview


text:
Q: How to implement a MouseEnter Event on a Merged menustrip I'm new here and I hope to do well.
I'm working on a text editor (c#) in which I have a Father's Form and i can create several child's forms. When I open a child form his menuStrip merge whit his father's menustrip and I have all of the functionality of child's menuStrip on father's menuStrip (like some ToolStripMenuItems).
My problem is: I want to implement a MouseEnter event for those ToolStripMenuItems. This Event will change text on a toolStripStatusLabel(which is located only in Father's Form) writing on it the name of the ToolStripMenuItems who started the event. I can do it easy on all of ToolStripMenuItems of Father's menustrip but i have no idea of what can i do to started this event for all the ToolStripMenuItems of Child's menustrip. I want them to also change the ToolStripStatusLabel.
 public void ratonencima(object sender, EventArgs e)
    {
        ToolStripMenuItem aux = (ToolStripMenuItem)sender;
        this.toolStripStatusLabel1.Text = aux.Text;
    }

This is the method i call when I manage the MouseEnter event from a ToolStripMenuItem of Father's form. I want to add the event to the ToolStripMenuItem dinamically (at execution time) for not having troubles when i create a Child`s Form and his MenuStrip merge whit the fathers one.
What can i do?

A: Well, finally I found a solution for my problem.
I added dynamically the MouseEnter event to the ToolStripMenuIitems (and also i added a MouseLeave event to that ToolStripMenuItems to the text is changed to a blank string when it detects the event).
I added those methods on Father's form:
private void eventoaelementos()
 {
 foreach(ToolStripMenuItem t in this.menuStrip1.Items)
  {
    t.MouseEnter += new EventHandler(metodoMouseEnter);
    t.MouseLeave += new EventHandler(metodoMouseLeave);
    foreach(ToolStripItem t2 in t.DropDownItems)
    {
      if(t2 is ToolStripMenuItem)
      {
         //To discard the ToolStripSeparator's case in which I
        //obtain an exception
          t2.MouseEnter += new EventHandler(metodoMouseEnter);
          t2.MouseLeave += new EventHandler(metodoMouseLeave);
       }
     }
   }
}

private void metodoMouseLeave(object sender, EventArgs e)
    {
      this.toolStripStatusLabel1.Text = "";
    }

    private void metodoMouseEnter(object sender, EventArgs e)
    {
      ToolStripItem t = sender as ToolStripItem;
      if(t!=null)
        {
            this.toolStripStatusLabel1.Text = t.Text;
        }
    }

And i call to the eventoaelementos's method once i initialized the Father´s Form (On the constructor) and when I create a child's  Form (I have a "New" button on a MenuStrip on Father´s form and i added this method on the method I call when I Clicked on this button).
I hope you find this useful.
Thanks for your time.


text:
Q: Drupal 7 Theme multimple template I work with drupal 7 . I have created custom theme and I want to use different templates for different pages
My site base  link is http://localhost/new/drupal  and I want to use template for
http://localhost/new/drupal/home page , I have page-home.tpl.php file but it is not working
Can anybody help me?

A: Drupal 7 page template is jut like that -
page--[NAME].tpl.php

Change the file name "page-home.tpl.php" to "page--home.tpl.php". Don't forget to clear cache.
Here is Drupal page template tutorial. Read this tutorial before started theme develop.


text:
Q: how to locate a name-not-specified file in bash? I have a bash like this to easily upload a file to my server:
FILE=../"$1"/1.txt
scp 1.txt remoteserver #upload the file to a remote server.

The $1 is for input directory and I have a lot of directories. But the txt file in all those directories are not all named "1.txt". What I can confirm is that each directory only contains one txt file.
How do I locate that file in this situation?
Update:
I tried to type FILE=../"$1"/1.txt
but when I check the file with:
if [ -f "$FILE" ]
I notice it's getting a false even when the file exist.
I figured out that:
$FILE is ../test/1.txt
"$FILE" is ../test/*.txt
So do I have to remove the pair of "?

A: You can use the wildcard * for the name that you don't know. Let's say you set
FILE=../"$1"/*.txt

Wildcard expansion only happens outside of quotes. $FILE variable still has the asterisk in it. So,
[ -f "$FILE" ]

is equivalent to
[ -f "../test/*.txt" ]

which wants a literal asterisk in the filename, but
[ -f $FILE ]

is equivalent to
[ -f ../test/*.txt ]

which gets expanded.
It is a little bit dangerous to use $FILE to hold a pattern: if your "$1" contains a space, you cannot make it work either quoted or unquoted: quoted will keep the space, but asterisk too, but unquoted will split at the space. You could play with IFS, but in this case, an intermediate variable isn't the best idea anyway.
People will cringe at this hack, but if don't have pathological filenames, it will work. What you can do is, just force filename expansion before saving it in the variable.
FILE="$(echo ../"$1"/*.txt)"

Now, the asterisk is replaced with the actual filename, and later, you can safely use the quoted version "$FILE" to protect spaces, but the asterisk is gone.
This will fail if there is no file with that name, the asterisk will be kept literal (unless you set nullglob bash option). And if there is more than one txt file there, this won't work properly either. However, this will always work
for FILE in ../"$1"/*.txt; do whatever you want to do with `"$FILE"`; done


text:
Q: how to insert data into an sq-lite database at runtime I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me

A: Use this method :
public long saveData(Context context, String editTextValue) {
        long x = -1;
        appDb = new AppDatabase(context);
        sqliteDb = appDb.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("monthOfBirth", editTextValue);
        try {
            if (sqliteDb.isOpen()) {
                x = sqliteDb.insert("password", null, values);
                if (x >= 0)
                {
                   Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        return x;
    }

Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
    @override
    public void onClick(View v)
    {
         if(editText.getText().toString.equals(""))
         {
             Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
             return;
         }
         saveData(YourActivity.this, editText.getText().toString());
    }
}

A: Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);

And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);

A: Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);

on your datebase refence variable.
String sql =
            "INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
            db.execSQL(sql);


text:
Q: Replacing integers with NaN results in the entire column becoming float dtype First, I did
a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]]
b = pd.DataFrame(a)
print(b.head(2))

The output is
1   2   3   4   5      6
6   5   4   3   2.00   NaN
1   2   3   4   5.00   6.00
3   4   5   6   NaN    NaN

So I did
a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]]
b = pd.DataFrame(a).fillna(-1).astype(int)
print(b.head(2))

The output becomes
1   2   3   4   5   6
6   5   4   3   2   -1
1   2   3   4   5   6
3   4   5   6   -1  -1

But I don't want those -1, so I did
a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]]
b = pd.DataFrame(a).fillna(-1).astype(int)
b = b.replace(-1, np.NaN)
print(b.head(2))

The output is again same as the first time
1   2   3   4   5      6
6   5   4   3   2.00   NaN
1   2   3   4   5.00   6.00
3   4   5   6   NaN    NaN

A: Because of this:
type(np.nan)
# float

If you have NaNs in your column, the rest of your column is automatically upcasted to float for efficient computation.
pandas 0.24+
We can use the Nullable Integer Type which allow integers to coexist with NaNs:
b = b.astype('Int32')
b

   0  1  2  3    4    5
0  6  5  4  3    2  NaN
1  1  2  3  4    5    6
2  3  4  5  6  NaN  NaN

b.dtypes

0    Int32
1    Int32
2    Int32
3    Int32
4    Int32
5    Int32
dtype: object

<= 0.23
To get around that, convert the dtype to object, which I don't recommend unless it's only for display purposes (you kill efficiency this way).
u = df.select_dtypes(float)
b[u.columns] = u.astype(object)
b

   0  1  2  3    4    5
0  6  5  4  3    2  NaN
1  1  2  3  4    5    6
2  3  4  5  6  NaN  NaN

print(b.dtypes)
0     int64
1     int64
2     int64
3     int64
4    object
5    object
dtype: object


text:
Q: call store procedure using callproc do not really implement in postgresql? I have python 3.7 with postgresql:
import psycopg2
...
@app.route('/add', methods=['POST'])
def add():
    cur = get_db().cursor()
    if request.is_json:
        jdata = request.get_json()
        cur.callproc("add", (jdata['tools'], jdata['ip_begin'], jdata['ip_end']))
        result = cur.fetchall()
        print(result)
        cur.close()
        return jsonify({'result': 'add successful'})
    else:
        cur.close()
        return jsonify({'error':"invalid input json data"})

My store function is:
CREATE FUNCTION "public"."add"("tool_name" varchar, "ip_bgn" inet, "ip_end" inet) RETURNS "pg_catalog"."int8"
$$
DECLARE
mid INTEGER := 0;
ins BIGINT := 0;
BEGIN
  if ip_bgn < ip_end then
INSERT into ip_addresses(tool_name, ip_start, ip_end) VALUES (tool_name, ip_bgn, ip_end) RETURNING id into mid;
    Loop
        if ip_bgn + ins >= ip_end then
            exit;
        end if;
        INSERT into ip_pools(tool_name, ip_address, to_main, status) VALUES(tool_name, ip_bgn+ins, mid, 'free');
        ins := ins + 1;
    end Loop;
end if;
RETURN ins;
END $$

My output is:
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 [(11,)]                   ######################## I have return values
 127.0.0.1 - - [28/Dec/2020 00:37:40] "POST /add HTTP/1.1" 200 -

but when I go to the database, I find the database does not add any rows after my python code execute.
the database is the same as I execute before.
I can use plpgsql console to create real data via the same store function. But if I run via python code it does not really add rows and change tables, but the return data is OK.

A: You don't commit the changes made to the database anywhere. Assuming your connection is defined like this (seems like it is get_db, you can change it later):
conn = psycopg2.connect(host="db.host.com", user="username", password="secret")

You need to commit the changes after closing the cursor:
cur.callproc("add", (jdata['tools'], jdata['ip_begin'], jdata['ip_end']))
# some code
cur.close()
conn.commit()
# close the connection as well once done
conn.close()

From pycopg2 documentation:

Note that closing a connection without committing the changes first will cause any pending change to be discarded as if a ROLLBACK was performed (unless a different isolation level has been selected: see set_isolation_level()).


text:
Q: Why does Perl's DateTime->from_epoch return 1969-12-31 23:59:59? We are processing data from an API that is returning date/time values of the following form:
1061943540000

When I used the tool on this page it converts the value to the following correct date:
Tue Aug 26 2003 17:19:00 GMT-0700 (PDT)

We are using the following Perl code to convert the date/time in our script:
use DateTime;
my $dt = DateTime->from_epoch(epoch => $time);

However, this is producing the following output which is incorrect:
1969-12-31 23:59:59

I'm totally confused why this isn't working and would appreciate someone explaining what I'm doing wrong and what code I should be using to convert it correctly. Thanks in advance!

A: That's not an epoch time in seconds. It looks like it has milliseconds attached to it. That screws up the stuff that DateTime uses, which is seconds since the epoch. Perl, in general, has a mindset of whole seconds since the epoch  (see time, localtime, gmtime).
As given, you get a time that is far, far away. I might get a different date than you because my Perl is 64-bit and has the Y2038 fix:
$ perl -MDateTime -E 'say DateTime->from_epoch( epoch => shift() )' 1061943540000
35621-08-26T04:40:00

Dividing by 1000 gives you the right date, although in UTC:
$ perl -MDateTime -E 'say DateTime->from_epoch( epoch => shift() / 1000 )' 1061943540000
2003-08-27T00:19:00

If you go back to your online Java tool, you'll notice that it gives you the same date with 1061943540000 and 1061943540. It's guessing that one is milliseconds. That also means it gives the wrong date if 1061943540 was in milliseconds.


text:
Q: checking existence of a ruby object and testing attributes of that object in one line Kind of a newbie question here but I promise it is really hard to google for. What I want to do is test the attribute of an object and test the existence of that same object in one line. I could do this:
user = User.find_by_id(user_id)
if user
  if user.access_token == params[:access_token]
    puts "success"
  else
    puts "failure"
  end
else
  puts "failure"
end

I would like to seriously re-factor this and get rid of the nested if statements. Thing is, I can't do something like
if user && user.access_token

since in the case where user is actually nil, Ruby will throw an error when trying to evaluate nil.access_token. Anybody know the actual correct way to re-factor this into one line? Is it even possible, or are the nested if statements the only way?

A: Doing user && user.access_token is fine since Ruby will stop evaluating the expression once it encounters one false condition.
This is known as short circuit evaluation.


text:
Q: How to wait for the start of a child process? I execute a process (using Popen) and after a while, this process executes a child process.
What I'm trying to do is wait for the child process to be spawned and then continue executing my script.
The only way that I found, is using psutil and polling until the process has children.
process = psutil.Process(subprocess.Popen(command).pid)
while 0 == len(process.children()):
    time.sleep(0.2)

Is there a better way of doing it than polling on the children? Maybe waiting for some event?
I'm using windows 10 for this.

A: Based on your comment that you can have the process you're lunching write something to STDOUT when it launches its subprocess, you can easily use Popen.check_output() to pick up the STDOUT string from your parent process. For example, if your subprocess (the command) writes to STDOUT Subprocess started\n, you can do it purely through the subprocess module as:
import subprocess

response = subprocess.check_output(command)
if response.rstrip() == "Subprocess started":
    print("Woo! Our sub-subprocess was started...")

However, if your command returns multiple outputs, you might have to weed out the ones you're not interested in. You can do that by observing your subprocess' STDOUT for the aforementioned Subprocess started string, something like:
import subprocess

proc = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:  # a loop to read our subprocess STDOUT
    line = proc.stdout.readline().rstrip()  # read line-by-line
    if line == "Subprocess started":
        print("Woo! Our sub-subprocess was started...")
        break  # no need to read the STDOUT anymore

You can also capture STDERR (or pipe it to STDOUT) if you expect to be receiving error messages from your command (e.g. cannot start the subprocess or something like that).

A: I think there is no better solution for this. But you could optimize the process call:
process = psutil.Popen(command)

Popen class
A more convenient interface to stdlib subprocess.Popen. It starts a sub process and you deal with it exactly as when using subprocess.Popen but in addition it also provides all the methods of psutil.Process class. [...]

Additionally, you could use write your own event with a wait function. Wait is more CPU hungry but it is more responsive. See here for example. But it depends on your python version.

A: If the first child can write something after spawning its own child, the master script could wait for the first write.
Here is a working example (environment Python 2.7 on Windows):
Python master script:
python = r"C:\Python27\python.exe"
script = r"...\foo.py"
deb = time.clock()
child = subprocess.Popen([ python, script], stdout = subprocess.PIPE)
cr = child.stdout.read()
fin = time.clock()
print fin-deb, cr

Python (simplified) first child:
time.sleep(2)  # add a delay
# the child is supposed to be spawned here
print "Done"
sys.stdout.flush()  # flushes stdout so that caller gets it immediately
time.sleep(8)       # just to make the child live a little longer

The master script output is:
2.12153148707 Done

proving that the master script continued after the first sleep.

A: If you have control over the child process you can use some synchronization primitive between parent and child, like using a socket or a file, otherwise polling over children() in a busy loop is the only thing you can do, just make sure to exit the while loop after a while or your program may end up hanging indefinitely.


text:
Q: object does not support property or method matches react-responsive-modal in IE11 with react js I want to open my modal popup with 'react js' in IE browser, I can understand after study some blog for IE, I have to add 'react-app-polyfill' along with import statement in a very first file that is in my index.js.
for this I am following  the below github url.
https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md
but what is happening, my react js app is working fine in IE browser. but I am facing problem in my modal opening part. for modal I am using react-responsive-modal(https://www.npmjs.com/package/react-responsive-modal), it is working as expected in Chrome browser but not in IE.
I am getting error when I am opening modal in IE browser. I am attaching my error screen shot.
Please help if anyone can help to resolve this issue.

A: I try to test the issue in the IE 11 and also try to check the error messages from the picture you had posted in the original post.
From the error message, it looks like the error comes from the react-responsive-modal library files.
It looks like the repeat method is not supported in the IE browser.
So it is creating compatibility issues with the IE browser.
I suggest you try to use the library that is compatible with the IE browser or if that is not possible then you can try to identify the IE browser using JS code and inform the user to use the compatible browser with your app.


text:
Q: why my code for printing fibonacci series does not work if i have to print a large amount of them? here is my code to print fibonacci series
 #include <stdio.h>
    #include <conio.h>

int main(void)
{
 long int i,firstno=1,secondno=1;

 printf("%d\n%d\n",firstno,secondno);
 for(i=0;i<8;i++){
     int temp = secondno;
      secondno = secondno+firstno;
        firstno = temp;

 printf("%d\n",firstno);
 }return 0;
 }

it works fine if i have to print say first 90 fibonacci numbers but it starts giving large garbage values if i have to print say 200000 of them? why does this happen ?how can i stop this and improve my code?

A: Value you have giving to the variable that will exceed the maximum range of the long int. So this is the reason for printing the garbage value.

A: Because your variable exceeds the maximum range of the long int. So this is the reason for printing the garbage value.
See the table below for storage size and value range:
Type          | Storage size |  Value range
____________________________________________________________
char          | 1 byte       |  -128 to 127 or 0 to 255
unsigned char | 1 byte       |  0 to 255
signed char   | 1 byte       |  -128 to 127
int           | 2 or 4 bytes |  -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int  | 2 or 4 bytes |  0 to 65,535 or 0 to 4,294,967,295
short         | 2 bytes      |  -32,768 to 32,767
unsigned short| 2 bytes      |  0 to 65,535
long          | 4 bytes      |  -2,147,483,648 to 2,147,483,647
unsigned long | 4 bytes      |  0 to 4,294,967,295

A: You're hitting an overflow! A 64-bit value just isn't large enough once you reach fib(30) or thereabouts.
You need to use an arbitrary size integer library if you want to be able to produce arbitrary size output.
If you look at the answers you're getting, and you convert them into hexadecimal, you'll find that they're correct as far as they go: you've got the right lower-order bits, but the high bits are being lopped off every time an arithmetic operation overflows.
You'll be out by a multiple of 232, or whatever the size of a long int is on your platform.


text:
Q: Is there a way to get colored text in GitHubflavored Markdown? I need to document a library on GitHub that output colored text in the terminal.
I've tried both span <style="color:red"> and <font color="red">, but it seems to strip out both tags.
Is the only way to do this is with images of colored text?

I ended up adding screenshots to Git and using image links with GitHub relative URLs.

A: You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:
```diff
+ this text is highlighted in green
- this text is highlighted in red
```

A: You cannot include style directives in GFM.
The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.
If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

A: You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.
To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.

  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.
This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.
DEMO

A: As an alternative to rendering a raster image, you can embed a SVG:
https://gist.github.com/CyberShadow/95621a949b07db295000
Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

A: In case this may be helpful for someone who just needs to show colors rather than output, as a hackish workaround (and FYI), since GitHub supports Unicode (as Unicode, numeric character references or HTML entities), you could try colored Unicode symbols, though it depends on the font rendering them in color (as it happens to be appearing for me on Windows 10 and Mac 10.12.5, at least, though on the Mac at least, the up/down-pointing small red triangles don't show in red):

*

*RED APPLE (🍎):

*GREEN APPLE (🍏):

*BLUE HEART (💙):

*GREEN HEART (💚):

*YELLOW HEART (💛):

*PURPLE HEART (💜):

*GREEN BOOK (📗):

*BLUE BOOK (📘):

*ORANGE BOOK (📙):

*LARGE RED CIRCLE (🔴):

*LARGE BLUE CIRCLE (🔵):

*LARGE ORANGE DIAMOND (🔶):

*LARGE BLUE DIAMOND (🔷):

*SMALL ORANGE DIAMOND (🔸):

*SMALL BLUE DIAMOND (🔹):

*UP-POINTING RED TRIANGLE (🔺):

*DOWN-POINTING RED TRIANGLE (🔻):

*UP-POINTING SMALL RED TRIANGLE (🔼):

*DOWN-POINTING SMALL RED TRIANGLE (🔽):


text:
Q: Some problems with passing arguments to overloaded functions package java_coding;

public class String_Null {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String_Null string_Null = new String_Null();
    string_Null.method(null);
}

public void method(String string) {
    System.out.println("String");
}

public void method( Object object) {

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

}

The result is String. Explain why?

A: Because the most specific method is chosen, the most specific is String (compared to Object). This is in the JLS btw... I'll dig this up shortly.
According to the JLS

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run- time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.


text:
Q: How do I get a contained background image to cover the entire div? Ok, so my question is how do I make my image more responsive? I am a new coder, so I'm still trying to understand css more. I've tried using the contain value, but it doesn't cover the entire div. I also tried cover, but it doesn't show the entire image when it expands inside the div. If anybody has any ideas at all, I would love to hear from you. Thanks Also, it's not the same question as covering the entire page. I want the image to cover inside my div, and it doesn't seem to be working.

.tribute {
  margin-top: 40px;
  margin-left: 12%;
  height: 250px;
  width: 35%;
  background: url(dickgregory.jpg);
  background-size: cover;
  float: left;
}

Projects

A: Your image is taking up the full width and height of your .tribute element. The problem is that you've both added margin to the .tribute element, and restricted its width.
Removing the margins and setting width to 100% shows the image covering the full area as expected.
Note that background-size: cover may stretch or crop the image, and background-size: contain will resize the image to ensure that it is always visible.
This is best demonstrated with an example.
Contain:

.tribute {
  height: 250px;
  width: 100%;
  background: url(http://placekitten.com/310);
  background-size: contain;
  float: left;
}

Projects

Cover:

.tribute {
  height: 250px;
  width: 100%;
  background: url(http://placekitten.com/310);
  background-size: cover;
  float: left;
}

Projects

Hope this helps! :)

A: Unfortunately cover and contain are the best ways to handle an image that isn't the proportion you want. You could use an  tag instead of a div with a background image, if that would work for your use. Otherwise, I usually add a background color to the element that is similar to the image, so that it blends in better.

.tribute {
  margin-top: 40px;
  margin-left: 12%;
  height: 250px;
  width: 35%;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/7/7b/Dick_Gregory.jpg');
  background-size: contain;
  background-position: center center;
  background-repeat: no-repeat;
  background-color: #666;
  float: left;
}

Projects


text:
Q: Python property lookup with custom __setattr__ and __slots__ I have a class that uses __slots__ and makes them nearly immutable by overriding __setattr__ to always raise an error:
class A:
    __slots__ = ['a', 'b', '_x']

    def __init__(self, a, b):
        object.__setattr__(self, 'a', a)
        object.__setattr__(self, 'b', b)

    def __setattr__(self, attr, value):
        raise AttributeError('Immutable!')

    @property
    def x():
        return self._x

    @x.setter
    def x(value):
        object.__setattr__(self, '_x', value)

Here, the "private" attribute _x is a place-holder for a complex operation to interact with some custom hardware.
Since x is a property, I expect to be able to do something like
 inst = A(1, 2)
 inst.x = 3

Instead, I see my AttributeError with the message Immutable!.
There are a number of obvious workarounds here, such as to remove the custom __setattr__ (which I do not want to do) or to rewrite it as
def __setattr__(self, attr, value):
    if attr != 'x':
        raise AttributeError('Immutable!')
    super().__setattr__(attr, value)

This seems like an awkward method that has the potential to balloon out of proportion if I start adding more properties like that.
The real issue is that I do not understand why there is no conflict between __slots__ and the property, but there is one between __setattr__ and the property. What is happening with the lookup order, and is there another, more elegant workaround to this problem?

A:
The real issue is that I do not understand why there is no conflict between __slots__ and the property, but there is one between __setattr__ and the property.

Both __slots__ and property implement attribute lookup by providing a descriptor for the corresponding attribute(s). The presence of __slots__ prevents arbitrary instance attribute creation not by doing anything to __setattr__, but by preventing creation of a __dict__. property and other descriptors don't rely on an instance __dict__, so they're unaffected.
However, __setattr__ handles all attribute assignment, meaning that descriptor invocation is __setattr__'s responsibility. If your __setattr__ doesn't handle descriptors, descriptors won't be handled, and property setters won't be invoked.

is there another, more elegant workaround to this problem?

You could explicitly allow only properties:
class A:
    ...
    def __setattr__(self, name, value):
        if not isinstance(getattr(type(self), name, None), property):
            raise AttributeError("Can't assign to attribute " + name)
        super().__setattr__(name, value)

or you could explicitly reject assignment to slots, and delegate other attribute assignment to super().__setattr__:
class A:
    ...
    def __setattr__(self, name, value):
        if isinstance(getattr(type(self), name, None), _SlotDescriptorType):
            raise AttributeError("Can't assign to slot " + name)
        super().__setattr__(name, value)

# Seems to be the same as types.MemberDescriptorType,
# but the docs don't guarantee it.
_SlotDescriptorType = type(A.a)


text:
Q: Intermittent Cloud SQL, Export Failure - Code:2, Message:"UNKNOWN", severity:"ERROR" When attempting to export from Cloud SQL using a RESTful call to the Google API we've been encountering random failures, approximately 1 in 10 attempts.  The log extract below has been taken from Stackdriver and doesn't offer much insight into the root cause:
{
 insertId:  "55C4B416A7642.A1B5D8E.570939C6"
 logName:  "projects/my-dev-project/logs/cloudaudit.googleapis.com%2Fdata_access"
 protoPayload: {
  @type:  "type.googleapis.com/google.cloud.audit.AuditLog"
  authenticationInfo: {
   principalEmail:  "jsmith@mycompany.com"
  }
  authorizationInfo: [
   0: {
    authorizationLoggingOptions: {
     permissionType:  "DATA_READ"
    }
    granted:  true
    permission:  "cloudsql.instances.export"
    resource:  "instances/my-db-instance"
   }
  ]
  methodName:  "cloudsql.instances.export"
  request: {
   @type:  "type.googleapis.com/cloudsql.admin.InstancesExportRequest"
   exportContext: {
    database: [
     0:  "business_db"
    ]
    fileType:  "CSV"
    schemaOnly:  true
    selectQuery:
     "SELECT
      replace(IFNULL(`ID`,'<NULL_VALUE>'), '', '') AS `ID`,
      replace(IFNULL(`NAME`,'<NULL_VALUE>'), '', '') AS `NAME`,
      replace(IFNULL(`ADDRESS`,'<NULL_VALUE>'), '', '') AS `ADDRESS`,
      replace(IFNULL(`DOB`,'<NULL_VALUE>'), '', '') AS `DOB`
      FROM CUSTOMERS"
    table: [
     0:  "CUSTOMERS"
    ]
    uri:  "gs://my-dev-project-stage/CUSTOMERS_full.csv"
   }
   instanceName: {
    fullProjectId:  "my-dev-project"
    instanceId:  "my-db-instance"
   }
  }
  requestMetadata: {
   callerIp:  "107.178.192.158"
  }
  resourceName:  "instances/my-db-instance"
  serviceName:  "cloudsql.googleapis.com"
  status: {
   code:  2
   message:  "UNKNOWN"
  }
 }
 receiveTimestamp:  "2017-10-24T13:52:53.738754270Z"
 resource: {
  labels: {
   database_id:  "my-dev-project:my-db-instance"
   project_id:  "my-dev-project"
   region:  "europe"
  }
  type:  "cloudsql_database"
 }
 severity:  "ERROR"
 timestamp:  "2017-10-24T13:52:53.317Z"
}

The only difference between this log entry and a successful export are the three property values mentioned in the post title.  In a successful entry they are as follows:
  status: {
  }
 }
 receiveTimestamp:  "2017-10-24T14:21:44.997050352Z"
 resource: {
  labels: {
   database_id:  "my-dev-project:my-db-instance"
   project_id:  "my-dev-project"
   region:  "europe"
  }
  type:  "cloudsql_database"
 }
 severity:  "INFO"
 timestamp:  "2017-10-24T14:21:43.757Z"
}

The intermittent nature suggests the root cause is an external factor.  I.e. the exact same request with the same parameters; connection details, output file location and SQL statement will work a few minutes later.  There's no consistency to which exports are failing.
We've already discovered that Cloud SQL does not support multiple simultaneous exports and we've implemented a queuing system to avoid this issue.
The data volumes don't seem to be an influencing factor either.  An export will work for a 100,000 row file and then fail for 500 row file.  In fact smaller or even empty data sets seem to be more susceptible to failure.
If anyone has any idea's or suggestions as to a solution or avenue of investigation I'd be interested to hear them.  Thanks.


text:
Q: Ubuntu Backups consume 100% of cpu I'm using the Ubuntu pre-installed Backups software, with Ubuntu 16.04 for Desktop (but perhaps the same issue was on older Ubuntu also).

Each time it starts (once a day) it consumes 100% of cpu for several minutes. Since I was thinking that a backup software should be silent and invisible, this is quite annoying.

Would be ok if it takes four or five times more than the time it takes now to do its things, but consuming less cpu and being more quiet.
Is there a silent mode for the Backups software or a better alternative backup software for Ubuntu?

A: Honestly, I've never heard of the program you're using.
I personally prefer rsnapshot (http://rsnapshot.org/) for my backup needs.  The Ubuntu package is the same name.
Since it uses hardlinks, the first time it runs may use a lot of CPU time, but afterwards, it won't.  (Especially if you have few files that change between backups -- which is the case for most people.)  Likewise, it won't use much diskspace over time.
Having said that, I schedule backups in the middle of the night.  So other than when I'm testing the configuration file, I don't really have a chance to notice the CPU time.  This is unrelated to whether or not you are running this on a server; rsnapshot can be run on the command line.  Or, you can create a short-cut on your desktop to it.
Another suggestion is to just renice the program so that it runs at a lower priority.  If you need to do this automatically, then some short bash programming will be needed.  See, for example, https://talk.maemo.org/showthread.php?t=36870 or just search for the phrase "automatic renice".
Off the top of my head, I don't know how to do it, but my guess is that you would have to:

*

*write a bash script that finds out the process ID

*run renice on it

*put this script in a cronjob and either make it run right after your backup starts or have it run repeatedly (i.e., every hour)

I guess the script might look like this, but you really need to clean this up as it's really off the top of my head:
 #!/bin/bash
 PID=`ps -ef | grep "<program name>" | grep -v "grep" | tr -s ' ' | cut -f 2 -d ' '  | head -n 1`
 renice -10 ${PID}

The PID line does this in order:

*

*Gets a list of processes.

*Searches for .

*Removes any line that has both  and "grep".

*Replace consecutive spaces into a single space.

*Grab the second column's values using space as a delimiter.

*Take the first line.

Hope this helps get you started!

A: Ubuntu Backup a.k.a. DejaDup uses duplicity as the backend. There was a bug in duplicity in 2014 that was fixed that caused this. It still happens though, so you could report another bug in duplicity. This bug only affects one physical core, so the computer should still be responsive on multi-CPU machines. Otherwise you may consider the various other backup alternatives, or have your computer backup when you're not using it.
You could also try a larger blocksize?
duplicity --max-blocksize 4096 [full/incremental] src dest

   --max-blocksize number
          determines the number of the blocks examined for changes during the diff process.  For files < 1MB
          the blocksize is a constant of 512.  For files over 1MB the size is given by:

          file_blocksize = int((file_len / (2000 * 512)) * 512)
          return min(file_blocksize, globals.max_blocksize)

          where globals.max_blocksize defaults to 2048.  If you specify a larger max_blocksize, your difftar
          files will be larger, but your sigtar files will be smaller.  If you specify a smaller max_blocksize,
          the reverse occurs.  The --max-blocksize option should be in multiples of 512.


text:
Q: How to use Facebook URL Schemes in IOS I have been trying to use the facebook URL Schemes on stackoverflow which reference to here http://wiki.akosma.com/IPhone_URL_Schemes#Facebook (and similar sites).
I am having trouble sending the app user to another user's profile in the facebook app. I have the other users screenName (and id, but prefer to use screenName).
I have tried

*

*fb://profile/id

*fb://profile/screenname

*fb://profile?id=id
I am unsure the difference here with (initWithUID) and (fbid) of these and similiar calls:

*

*fb://profile/(initWithUID:)

*fb://profile/(initWithUID:)/addfriend

*fb://profile/(fbid)

*fb://profile/(fbid)/addfriend
All of these seem not to open the user who owns the screenname/id profile view in the facebook app.
By screenname I mean that in a browser:

*

*facebook.com/screenname sends you to their profile page and

*graph.facebook.com/screenname gives you their id

A: It's not possible. For Android it is known to work, but it is not officially supported. For iOS it doesn't work.

A: I just succeeded in opening the profile in the Facebook app with:
UIApplication.sharedApplication().openURL(NSURL(string: "https://www.facebook.com/whitehouse")!)


text:
Q: Checking if entire object exists in db with mongoose If I have the following object:
var person = {
    fname: "Joe",
    lname: "Shmoe",
    misc: {
        age: "25",
        gender: "M",
        hair: "blonde"
    }
}

and I need to check whether this exact person is in the database using mongoose. What I'd like to do is something along the lines of
Person.findOne(person, function(err, result) {
    if (!result) {
        ...
    }
}

Is there a way to check if an entire object exists as a document in the database using mongoose without manually entering in all of the fields?
edit: Here is what I'm currently doing:
Person.findOne({ fname: person.fname })
    .where('lname').equals(person.lname)
    .where('misc.age').equals(person.misc.age)
    .where('misc.gender').equals(person.misc.gender)
    .where('misc.hair').equals(person.misc.hair)
    .exec(function(err, result) {
        if (!result) {
            ...
        }
    });

A: Not really sure what you are asking here as if you just pass in the person variable you have defined as the first argument for the query then you will get the result that does exactly match. The proviso there is that the keys in "misc" must be in the same order within your actual document or you are otherwise required to use the "dot notation" if that order was not always the same:
{
    "fname": "Joe",
    "lname": "Schmoe",
    "misc.age": "25",
    "misc.gender": "M",
    "misc.hair": "blonde"
}

And that you not be hard to convert from your initial object:
var obj = {};

for ( var k in person ) {
    if ( "k" == "misc" ) {
        for ( var b in person[k] ) {
            obj["misc." + b] person[k][b];
        }
    } else {
        obj[k] = person[k];
    }
}

Then you can use obj as your query argument as it has the "dot notation" form:
Generally though the case is that it should be okay, unless you have cast to a Mongoose document with a differing _id value. Some code to demonstrate this:
var mongoose = require('mongoose'),
    async = require('async'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost');

var personSchema = new Schema({
  fname: String,
  lname: String,
  misc: {
    age: String,
    gender: String,
    hair: String
  }
});

var Person = mongoose.model( "Person", personSchema, "person" );

var data = {
  fname: "Joe",
  lname: "Shmoe",
  misc: {
    age: "25",
    gender: "M",
    hair: "blonde"
  }
};

var person = new Person( data );
var other = new Person( data );

console.log( person );

async.series([
  function(callback) {
    person.save(function(err,person) {
      callback();
    });
  },
  function(callback) {

    console.log( "This works" );
    Person.findOne( data, function(err,person) {
      console.log( "person: " + person );
      callback();
    });
  },
  function(callback) {

    console.log( "This doesn't" );
    Person.findOne( other, function(err,person) {
      console.log( "person: " + person );
      callback();
    });
  },
  function(callback) {
    console.log( "This does" );
    var obj = other.toObject();
    delete obj._id;
    Person.findOne( obj, function(err,person) {
      console.log( "person: " + person );
      callback();
    });
  },
]);


text:
Q: Rails ancestry gem + has_many I have 2 models: Post and Category
Category has_many Posts,
Post belongs_to Category,
Category model uses ancestry gem,
the goal is to get all posts that belongs_to the given category and to all its ancestors. Should I  simply use a loop for this or there is some smarter way to do this?

A: You can use this to get the posts that belong the given category or one of its ancestors:
Post.where(:category_id => category.path_ids)

A: The ancestry gem passes nested hash objects when you use it, so you can select a master node and then use the hash object as a way to iterate through & get all of its ancestors:
#controller
@category = Category.find params[:id]

#view
render partial: "category", locals: { category: @category }

#partial

    <% category.each do |category, sub_item| %>

            <%= category.name %>
            <% if category.has_children? %>
            <%= render partial: "category", locals: { category: category.children } %>
            <% end %>

    <% end %>


text:
Q: Can't Connect to Twitch IRC Server, problem with IP address, C language I'm trying to build a ChatBot for Twitch entirely in C Language. But i'm having problems in connecting to the server: irc.chat.twitch.tv with port 6667. I'm calling gethostbyname() to retrieve the ip address of the hostname, but the connect function never establish the connection, and returns "Connection Failed".
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

#include "Authentication.h"
#include "MessageHandlers.h"

int main()
{
    int sock;
    struct sockaddr_in addr;
    struct hostent * addr_info;
    char * ip;
    addr_info = gethostbyname("irc.chat.twitch.tv");

    ip = inet_ntoa(*(struct in_addr *)addr_info->h_name);
    printf("%s", ip);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6667);
    addr.sin_addr.s_addr = inet_addr(ip);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        fprintf(stderr, "\nSocket Creation Failed\n");
        exit(EXIT_FAILURE);
    }
    printf("\nConnecting to Twitch IRC Server...\n");
    if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1)
    {
        fprintf(stderr, "\nConnection Failed\n");
        exit(EXIT_FAILURE);
    }

   // SendAuthentication(sock);
/*
    while(1)
    {
     OnMessageEvents(sock);
    }
  */

   exit(EXIT_SUCCESS);
}

Is there something i'm doing wrong? The twitch resolved ip address seems to be 105.114.99.45. I searched on Google for the actual ip address, but i didn't find any answers.
I used nslookup irc.chat.twitch.tv and tried all the ip addresses, but still i got "Connection Failed".
If i use telnet irc.chat.twitch.tv 6667 i get a connection and i can perform the login.

A: Resolved in comments above. The port number in struct sockaddr_in is in network endianness (aka big endian), while your computer is likely running as little endian. To assign it, you must use
addr.sin_port = htons(6667);

instead of
addr.sin_port = 6667;