text:
Q: A question involving the expansion of $(x+2)^n$ I have the following question:

In the expansion of $(x+2)^n$, $n$ is a positive integer greater than $2$. Given that the ratio between the coefficient of the $x^3$ term and the coefficient of the $x$ term is $7:4$, find $n$.

I know I have to use binomial theorem, but I'm not too sure how to go from there. I get that the coefficient of the $x^3$ term is $\binom{n}32^{n-3}$ and the coefficient of the $x$ term to be $n*2^{n-1}$. So I get the equation:$$\frac{\binom{n}32^{n-3}}{n*2^{n-1}}=\frac74$$Am I on the right track? I'm also not too sure how to solve this equation, so could someone help me with that?

A: What you have done is correct. To complete just write down $\binom {n} {3}$ as $\frac {n(n-1)(n-2)} 6$ to get the equation $n^{2}-3n-40=0$ which gives $n=8$.

A: ${n \choose 3} = \frac{n!}{(n-3)! \ 3!} = \frac{1}{6}n(n-1)(n-2)$. Therefore, after cancelling you have:
$$\frac{(1/6)(n-1)(n-2)}{4} = \frac{7}{4}.$$

A: As the expansion contains powers of $2$ and the terms in question are spaced by two positions, you need to find two binomial coefficients in the ratio $7$.

As the ratios go increasing, this is the only solution.


text:
Q: Installing R on Linux: configure: error: libcurl >= 7.28.0 library and headers are required with support for https My issue is this:
Rigth now i have R 3.2 wooden xmas tree version, but theres some packages I need that dosent work on this version, so when i try to install the newest version, with
./configure

It returns the next error
configure: error: libcurl >= 7.28.0 library and headers are required with support for https

I have a package called libcurl3 installed. And its already in the last version.
Ill appreciate any help.
Note: I'm using Ubuntu based Peppermint 7 OS

A: I had the same problem on centos 7. I fixed it by installing the libcurl-devel. The mistake I had made was that I just had libcurl installed and not it's development packages.

A: I had similar problem, and I solve it by installing libcurl4-openssl-dev. This is one of packages, which R could use (R manual https://cran.r-project.org/web/packages/curl/index.html)

A: I had the same problem on Ubuntu 16.04LTS. Unfortunately installing libcurl4-openssl-dev did not solve the issue. However, installing libcurl4-gnutls-dev did work.

A: In my case, it was due to libcurl installed in anaconda2 package, whose libcurl version did not support https.
I removed the path to anaconda2 from PATH variable, and it was all fixed.

A: I solved my problem like this:

*

*download curl-7.77.0 and run code: ./configure --with-ssl

*Then I download R version 4.1.0, run ./configure again

A: Supposing that you have a sudo privileges, run the following command to download the latest version of libcurl
sudo apt-get install libcurl4-openssl-dev

A: I had the similar problem. First, you need to look into the config.log file to find out the real error. For example, mine is shown as:

/usr/include/string.h:548:5: error: unknown type name '__locale_t'
       __locale_t __loc)

Which would be a problem due to the gcc I used. Then you can solve the problem based solving this issue, in my case, change another version of gcc works for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Почему Всегда выводит True Проблема в том что когда я ввожу пароль(Правильный) он Выводит True и неправильный(Пароль) он тоже Выводит True Почему и как это исправить ??
def vk_auth():
    login = 'login'
    password = 'password'
    vk = vk_api.VkApi(login,password)
    try:
        vk.auth()
    except vk_api.AuthorizationError as error_msg:
        print('Password not')
    else:
        print('password True')

    return vk
vk_auth()

A: Исправь эту строчку
 except vk_api.AuthorizationError as error_msg:

на
except vk_api.AuthError as error_msg:

A: vk это элемент класса, а не статус авторизации. Даже при неправильном логине или пароле он все равно существует и вернет True
def vk_auth():
    login = 'login'
    password = 'password'
    vk = vk_api.VkApi(login,password)
    try:
        vk.auth()
    except vk_api.AuthorizationError as error_msg:
        result = True
        print('Password not')
    else:
        result = False
        print('password True')
    return result
vk_auth()


text:
Q: Limit of ${2^nn! \over n^n}$ I am looking for
$$\lim \limits_{n \to \infty}{2^nn! \over n^n}$$
I check by inspection that the limit is $0$. My first suspicion is that we might be able to use the following fact:
$${a_{n+1} \over a_n} \to g \implies \sqrt[n]{a_n} \to g$$
I rewrite
$${2^nn! \over n^n} = \sqrt[n]{\left({2^nn! \over n^n}\right)^n}$$
set
$$a_n=\left({2^nn! \over n^n}\right)^n$$
and compute
$${a_{n+1} \over a_n}={2^{2n+1}n! \over (n+1)^n}\left({1 \over 1 + {1 \over n}} \right)^{n^2}$$
The second term seems to be a natural candidate for a limit with $e$, however, I can't figure out the limit for the first term.
Alternatively, there might be an obvious candidate for the squeeze theorem for the original limit which I'm missing.

A: Notice the series
$$ \sum \frac{ 2^n n! }{n^n} $$ converges by the ratio test since
$$ \frac{ a_{n+1} }{a_n} = \frac{2^{n+1} (n+1)!}{(n+1)^{n+1} } \frac{n^n}{n! 2^n} = 2 \left( \frac{n}{n+1} \right)^n \to \frac{2}{e} <1 $$
Thus,
$$\boxed{ \lim_{n \to \infty}\frac{ 2^n n! }{n^n} = 0 }$$

A: For very large $n$ you can use Stirling approximation for the factorial:
$$n! \approx \sqrt{2\pi n} \frac{n^n}{e^n}$$
hence your limit becomes
$$\lim_{n\to +\infty} \frac{2^n}{n^n}\sqrt{2\pi n} \frac{n^n}{e^n}$$
$$\lim_{n\to +\infty} 2^n \frac{\sqrt{2\pi n}}{e^n}$$
$$\sqrt{2\pi} \lim_{n\to +\infty} \frac{2^n n^{1/2}}{e^n}$$
We can solve this sending all into the exponential representation
$$2^n = e^{n\ln (2)}$$
$$n^{1/2} = e^{1/2\ ln(n)}$$
So
$$\sqrt{2\pi} \lim_{n\to +\infty} \frac{e^{n\ln (2) + 1/2\ \ln(n)}}{e^n}$$
Unifying all the exp
$$\sqrt{2\pi} \lim_{n\to +\infty} e^{n\ln (2) + 1/2\ \ln(n) - n}$$
$$\sqrt{2\pi} \lim_{n\to +\infty} e^{n[\ln(2) - 1] + 1/2 \ln(n)}$$
The quantity $\ln(2) - 1$ is negative, and we will call it $-\alpha$. Numerically it is $-0.3068...$
Hence
$$\sqrt{2\pi} \lim_{n\to +\infty} e^{-\alpha n + 1/2 \ln(n)}$$
$n$ wins over $\ln(n)$ so the limit is basically
$$\lim_{n\to +\infty} e^{-\alpha n} = \boxed{0}$$


text:
Q: A question about the NSP order of a matrix A matrix $D$ is said to have the NSP order of $\Omega$ if
$$\forall v \neq 0 \text{ with } Dv = 0 \\
\sum_{j \in T} |v_j|< \sum_{j \notin T} |v_j| \text{ for all } T\in \{1, 2, \cdots, M\} \text{ with } \#T \leqslant \Omega
$$
In a research paper, I learned that if any two columns
 of $D$ are a multiple of each other, the NSP has surely violated already for $\Omega = 2$
I don't understand what does it mean the NSP will be violated, does it mean the matrix will not have the NSP of any order if any two columns are correlated?

A: Sure: Say the $j$ 'th column of $D$ is $d_j$ and the $j '$ th column is $\lambda d_j$ for some $\lambda\in\mathbb{C}$ . Then $v$ where $v_j=-\lambda$ and $v_{j'}=1$ and all other entries are $0$ is in the null space of $D$. Now take $T=\{j,j'\}$ and You will see that the null space property is violated for $\Omega=2$ and therefore the matrix does not have the NSP for all $\Omega\geq 2$.


text:
Q: Set a select by option value with optgroups We do business in the US and Canada, so on a registration form I have a select that has optgroups to separate the US states from the Canadian provinces. I use the two character codes and store them in the database. When I want to edit the customer information, I want the same options available as on the registration form; however, I cannot seem to find the state or province by the value and then mark it selected.
Here is an example of the select:
<select id="company-state">
     <option value="">Select One</option>
     <optgroup label="United States">
          <option value="AK">Alaska</option>
          <option value="AL">Alabama</option>
          ...
          <option value="WV">West Virginia</option>
          <option value="WY">Wyoming</option>
     </optgroup>
     <optgroup label="Canada">
          <option value="AB">Alberta</option>
          <option value="BC">British Columbia</option>
          ...
          <option value="SK">Saskatchewan</option>
          <option value="YT">Yukon Territory</option>
     </optgroup>
</select>

I have tried numerous solutions, such as, trying to find the option by value or by ordinal and nothing seems to work.

A: Simple jQuery answer:
var value = "foo";
$('#company-state option[value="' + value +'"]');

Live DEMO
To "mark it as selected" you can add to the selector:
$('#company-state option[value="' + value +'"]').prop('selected', true);

A: Just set the value of dropdown using the .val operator and you are good to go.
Please check the fiddle.
var value = "SK";
$("#company-state").val(value);
alert($('#company-state').val());

https://jsfiddle.net/2t48cqho/


text:
Q: iOS6 UIImage causes crash Since iOS6 I have a very weird issue with UIImages that causes the application to crash.
The full method is like this:
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/users/show.json"];

NSDictionary *parametros = [NSDictionary dictionaryWithObjectsAndKeys:account.username, @"screen_name", nil];

SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                            requestMethod:SLRequestMethodGET
                            URL:url
                            parameters:parametros];
[request setAccount:account];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        if ([urlResponse statusCode] == 200) {
            NSError *error_ = nil;
            NSDictionary *userInfo = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_];
            UIImage *image = [UIImage imageWithData:[userInfo objectForKey:@"profile_image_url"]];
            UIImage *image = [UIImage imageWithData:[userInfo objectForKey:@"profile_image_url"]];
            dispatch_sync(dispatch_get_main_queue(), ^{
                [_imageCache setObject:image forKey:account.username];
                [ListAccount reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:NO];
            });
        }
    }];

The problem occur in this line
UIImage *image = [UIImage imageWithData:[userInfo objectForKey:@"profile_image_url"]];

This was no problem in iOS5. I can't seem to find why or someone that had the same problem. Any suggestion will be really appreciated
The crash is the following:
2012-09-28 17:30:53.600 Catalogo[7321:c07] -[__NSCFString bytes]: unrecognized selector     sent to instance 0x10eaf180
2012-09-28 17:30:53.601 Catalogo[7321:c07] *** Terminating app due to uncaught exception     'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to     instance 0x10eaf180'
*** First throw call stack:
(0x2aed012 0x1a28e7e 0x2b784bd 0x2adcbbc 0x2adc94e 0x2a75390 0x203630c 0x2035e7e 0x2035d98     0x10dc23d 0xf991f3 0xf98ef4 0x6c54e 0x1b9e731 0x1bad014 0x1b9d7d5 0x2a93af5 0x2a92f44     0x2a92e1b 0x2dd87e3 0x2dd8668 0xf7765c 0x79cd 0x2d45)
libc++abi.dylib: terminate called throwing an exception

The following:
[userInfo objectForKey:@"profile_image_url"]

return the url of a twitter profile image

A: You need to convert [userInfo objectForKey:@"profile_image_url"] into NSData, then pass it to imageWithData:.
NSString * profileImageString = [userInfo objectForKey:@"profile_image_url"];
NSData * profileImageData = [profileImageString dataUsingEncoding:NSUTF8StringEncoding];

Than use:
UIImage *image = [UIImage imageWithData:profileImageData];


text:
Q: Makefile with variable number of targets I am attempting to do a data pipeline with a Makefile. I have a big file that I want to split in smaller pieces to process in parallel. The number of subsets and the size of each subset is not known beforehand. For example, this is my file
$ for i in {1..100}; do echo $i >> a.txt; done

The first step in Makefile should compute the ranges,... lets make them fixed for now
ranges.txt: a.txt
   or i in 0 25 50 75; do echo  $$(($$i+1))'\t'$$(($$i+25)) >> $@; done

Next step should read from ranges.txt, and create a target file for each range in ranges.txt, a_1.txt, a_2.txt, a_3.txt, a_4.txt. Where a_1.txt contains lines 1 through 25, a_2.txt lines 26-50, and so on... Can this be done?

A: You don't say what version of make you're using, but I'll assume GNU make.  There are a few ways of doing things like this; I wrote a set of blog posts about metaprogramming in GNU make (by which I mean having make generate its own rules automatically).
If it were me I'd probably use the constructed include files method for this.  So, I would have your rule above for ranges.txt instead create a makefile, perhaps ranges.mk.  The makefile would contain a set of targets such as a_1.txt, a_2.txt, etc. and would define target-specific variables defining the start and stop values.  Then you can -include the generated ranges.mk and make will rebuild it.  One thing you haven't described is when you want to recompute the ranges: does this really depend on the contents of a.txt?
Anyway, something like:
.PHONY: all
all:

ranges.mk: a.txt   # really? why?
        for i in 0 25 50 75; do \
            echo 'a_$$i.txt : RANGE_START := $$(($$i+1))'; \
            echo 'a_$$i.txt : RANGE_END   := $$(($$i+25))'; \
            echo 'TARGETS += a_$$i.txt'; \
        done > $@

-include ranges.mk

all: $(TARGETS)
$(TARGETS) : a.txt   # seems more likely
        process --out $@ --in $< --start $(RANGE_START) --end $(RANGE_END)

(or whatever command; you don't give any example).


text:
Q: get data from Console to create log entries for log4net I have some external libraries that I am using that are logging to the console. I want these to log via log4net.
NOTE: I am NOT wanting to log to console from log4net, that should be straight forward.
What I have discovered thus far:
1) Console.setOut method allows using a different file stream.
1.1) Overriding memorystream seemed promising but there isn't a chance for raising an event to notify of changes
2) Writing to a file from Console seems like a work around, where I can read the file to update the UI textbox with new logs
3) FileStreams can autoflush, this means automatic updating of information. This sort of concept is similar to what I am after?
Whats the best way to get the console information put into log4net so that it can publish console log items the same way as log4net is configured? Currently my log4net puts logs into the eventlog, into a databinded wpf textbox, and into a file.

A: Personally don't know any other solution for this case other then you wrote:

*

*ovewrite output of console pointing it to a file

*read the file and add to a logger
To be notified about the change you can try to use FileSystemWatcher http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx.
Or if you don't want "real time notification", canopen file only for read and check with the timer if there is any row after last saved reader pointer position.
But I think, the first option is much easier.
Hope this helps.


text:
Q: React Hooks: Best practise in passing state between children of hook component I'd like to access an object set to a child component's state, and pass it to its sibling component:

*

*Child 1 (TextDetection) is a react-dropzone component that receives an image file, which is passed to an OCR API.

*Child 1 will then receive the transcription from the API and set that returned transcription to its local state.

*Child 2 (TextTable) needs to access this same object, where it will be displayed.

Child 1
function TextDetection({ textToParent }) {
  const [data, setData] = useState([])

  const uploadImage = async (image) => {
    var formData = new FormData();
    formData.append('photo', image[0])
    const response = await fetch('/upload', {
      method: "post",
      body: formData
    })
    const body = await response.json();
    setData(body.split(/\r?\n/))
    textToParent(data)
  }

  return (
    <Grid container className="App" direction="column" alignItems="stretch">
      <Container id="dropzoneContainer">
        <Card variant="outlined">
          <Dropzone uploadImage = {uploadImage}/>
        </Card>
      </Container>
    </Grid>
  );
}

The intention is the make this transcription available to the sibling component. As you can see in the snippet below, I am currently accessing the child's state by passing a callback to it via props.
Parent
export default function App() {
  const [text, setText] = useState([])

  function handleChange(newText) {
    setText(newText)
  }

  return (

      <Grid item xs={12} sm={4}>
        <TextDetection textToParent={handleChange}/>
      </Grid>
      <Grid item xs={12} sm={8}>
        <TextTable segments={text}/>
      </Grid>

  );
}

Passing a callback to a child to access its state doesn't align with the concept of Lifting State Up.
Is there a means of applying that principle in this case, given that the TextDetection child is receives the object set to state?

A: In your example you don't use data in Child component at all. In this case you can run function in Parent component
function TextDetection({ textToParent }) {
  return (
    <Grid container className="App" direction="column" alignItems="stretch">
      <Container id="dropzoneContainer">
        <Card variant="outlined">
          <Dropzone uploadImage = {textToParent}/>
        </Card>
      </Container>
    </Grid>
  );
}

Parent:
export default function App() {
  const [text, setText] = useState([])

  function handleChange(newText) {
     var formData = new FormData();
     formData.append('photo', image[0])
     const response = await fetch('/upload', {
        method: "post",
        body: formData
     })
     const body = await response.json();
     setText(body.split(/\r?\n/))
  }

  return (

      <Grid item xs={12} sm={4}>
        <TextDetection textToParent={handleChange}/>
      </Grid>
      <Grid item xs={12} sm={8}>
        <TextTable segments={text}/>
      </Grid>

  );
}

Note: This is concept, not tested.

A: The TextDetection component should handle everything related to OCR, which includes parsing the text. However, it shouldn't have a local state. When done parsing it should call textToParent.
function TextDetection({ textToParent }) {
  const uploadImage = async (image) => {
    var formData = new FormData();
    formData.append('photo', image[0])
    const response = await fetch('/upload', {
      method: "post",
      body: formData
    })
    const body = await response.json();
    textToParent(body.split(/\r?\n/));
  }

  return (
    <Grid container className="App" direction="column" alignItems="stretch">
      <Container id="dropzoneContainer">
        <Card variant="outlined">
          <Dropzone uploadImage = {uploadImage}/>
        </Card>
      </Container>
    </Grid>
  );
}

The parent should hold the state created by TextDetection, and supply it to the TextTable` (and any other child that needs it).
export default function App() {
  const [text, setText] = useState([])

  return (

      <Grid item xs={12} sm={4}>
        <TextDetection textToParent={setText}/>
      </Grid>
      <Grid item xs={12} sm={8}>
        <TextTable segments={text}/>
      </Grid>

  );
}


text:
Q: Python list doesn't seem to be updating I'm fairly new to python and I'm trying to create blackjack. However, when I'm trying to print out what the player's hand is, I run into a few difficulties.
This is my code for hitting (drawing a card):
def hit(card, deck):
    global money, choice

    choice = input("How much would you like to bet?\n")
    money -= int(choice)
    print("You have decided to bet $" + str(choice))
    card = card.drawCard(deck.deck)
    card.getPt()
    deck.addScore(card)
    deck.addCard(card)
    c = str(card)
    p = str(deck)
    print("You have drawn: " + str(c) + "\n")
    print("The player has:\n" + str(p) + "\n")
    print("Total score:", deck.score)

And this is my code for printing my cards out:
def __str__(self):
    for i in range(0, len(self.deck)):
        self.print = self.print + "\n" + str(self.deck[i])
    return self.print

The first thing my code does is draw two cards for the dealer and the player, which runs fine. However, after the player draws a card is where it gets a bit wonky. The output is something like this:
The player has drawn Card A
The player has drawn Card B
Total score: number

How much would you like to bet?
number

You have bet number
You have drawn Card B

Player has:
Card A
Card B
Card A
Card B
Card B

When I draw a new card, the card doesn't change, it stays the last card I drew. Then, when I print my deck, it prints my old deck and my new deck. However, the score is correct, which indicates that my list is only three cards long. What is going on, and why is it printing five cards?
Full code
Example output

A: Well, to get to the answer in short: you never reset Deck.print. So it keeps accumulating at each call to __str__
But in general this code could be improved significantly
E.g. your __str__ function is far from being pythonic. Something along the lines of
return '\n'.join(self.deck)

would look much better.
In general there is no need to prepend each variable with "self." if they are used within the function only. In most cases in a class method you either update an object variable (self.something) or return some value from the function, but not both.
There may, of course, be exceptions to this, but it seems in your case this is the rule and not the exception.
Using globals is also something you should avoid whenever possible.


text:
Q: ng-pattern not working in angular js I have a regex pattern as (http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)? which is working fine if I use some online tool to check it but when i use it in ng-pattern as ng-pattern="(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?" it is throwing error?
Invalid regular expression: /^(http(s)?://)?([w-]+.)+[w-]+(/[w- ;,./?%&=]*)?$/: Range out of order in character class

I have searched many questions over this issue but none seems to be working

A: change it to
(http(s)?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w- ;,.\/?%&=]*)?

A: You have to assign:
$scope.regex = "(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?";

And then write:
ng-pattern="{{regex}}"


text:
Q: Screen brightness slider disappeared on Windows 7. How do I bring it back? So I can't find the screen brightness slider or any brightness adjustment option in my power plan options. All I can do is determine when to put the laptop to sleep and when to turn off the display.
It seems like the common solution for many was to go to Device Manager and uninstall the driver under Monitors, then scan for hardware changes. I did that and it didn't work. If it helps, under my Monitors section it says "Generic PnP Monitor".
Update: I've since found a semi-solution. I can adjust the brightness by holding the Fn key and pressing up/down on my arrow keys. However, the brightness sliders are still missing.

A: If it is a laptop, it will most likely come back if you reinstall manufacturer's management tools software. The are usually full of unwanted stuff, but if you uninstall them, those on screen goodies like screen brightness indicator will go away too.

A: I have been having the same problem and I just found out a really easy and fast way to find the slider. It wont even take a minute.
Just go to control panel, then hardware and sound, then power options. In the power options window, wether you use the balanced or power saver plan, you will find a "change plan settings" button.
Press that, then below the display adjustments, press the "change advanced power settings". A little box will appear, and you will find a "change settings that are currently unavailable" button. Press that, and then scroll down until you find display. Click on the plus sign on the left side of it, then click the plus sign of the "Display Brightness". From there you can adjust it to your liking.
               Hope that helps.
Best of luck to all of you,
Contributer

A: Never mind - I see the slider you talk about..
Here -
It is in the Power Plan information.
I am sure it is in Control Panel too.


text:
Q: Flex / Yacc program causing breakpoint on free instruction in VC++ I have Flex / Yacc program that is causing a breakpoint when it is run in the VC++ 2012 IDE.  The breakpoint occurs on the instruction (in pre_lxr.l below):
free(pre_fname);

The project contains the lexer (.l file), the yacc file (.y) and an interface file (which sits between the parser and the C++ part of the program).  The problem seems to be related to memory corruption / leak.  See code below (I've included as much relevant code as I think is necessary).  I'm also not sure about the yyterminate call.
/* pre_prs_ifc.h */
#define MAX_PRE_ERR 120
#define MAX_BANKS 16
#define MAX_PRES 512

typedef struct
{
    char *bank;
    char *name;
} preStruct;

void initPrePrs();
void appBank(int line_num, const char *name);
void appPre(int line_num, const char *bank, const char *name);
void freePrePrs();

char pre_err[MAX_PRE_ERR];
int num_banks;
int num_pres;
char* pre_fname;
int pre_lnum;
char* bank[MAX_BANKS];
preStruct pre[MAX_PRES];

/* pre_prs_ifc.c */
#include "pre_prs_ifc.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void initPrePrs()
// initialises parser variables
{
    pre_err[0] = 0;
    num_banks = 0;
    num_pres = 0;
    pre_lnum = 1;
}

void appBank(int line_num, const char *name)
{
    if (num_banks < MAX_BANKS)
        bank[num_banks++] = _strdup(name);
    else
        sprintf(pre_err, "Error on line %d: maximum number of banks
exceeded.", line_num);
}

void appPre(int line_num, const char *bank, const char *name)
{
    if (num_pres < MAX_PRES)
    {
        pre[num_pres].bank = _strdup(bank);
        pre[num_pres++].name = _strdup(name);
    }
    else
        sprintf(pre_err, "Error on line %d: maximum number of presets
exceeded.", line_num);
}

void freePrePrs()
// frees parser variables
{
    int i;
    for (i = 0; i < num_banks; i++)
        free(bank[i]);
    for (i = 0; i < num_pres; i++)
    {
        free(pre[i].bank);
        free(pre[i].name);
    }
}

/* pre_lxr.l */
%{
    #include "pre_prs_ifc.h"
    #include "pre_prs.h"
    #include <stdio.h>
%}

%option outfile="pre_lxr.c" header-file="pre_lxr.h"
%option prefix="pre"
%option warn reentrant noyywrap never-interactive nounistd bison-bridge
%option debug

%%

"banks"|"BANKS" { return banks; }
"presets"|"PRESETS" { return presets; }

"{" { return l_bracket; }
"}" { return r_bracket; }
";" { return semicolon; }

\"([^\\\"\n]|\\.)+\" {
    yylval->str = (char*)malloc(strlen(yytext) - 1);
    strncpy(yylval->str, &yytext[1], strlen(yytext) - 2);
    return quoted_str;
}

[ \t] { }
[\r\n] { pre_lnum++; }

<<EOF>> {
    free(pre_fname);
    if (!YY_CURRENT_BUFFER)
        yyterminate();
}

%%
int preerror(const char *msg)
{
    sprintf(pre_err, "Error in %s on line %d.", pre_fname, pre_lnum);
    return 0;
}

/* pre_prs.y */
%{
    #include "pre_prs_ifc.h"
    #include "pre_prs.h"
    #include "pre_lxr.h"
    int preerror(yyscan_t scanner, const char *msg);
%}

%code requires
{
    #ifndef YYSCAN_T
        #define YYSCAN_T
        typedef void* yyscan_t;
    #endif
}

%output  "pre_prs.c"
%defines "pre_prs.h"
%name-prefix "pre"
%define api.pure
%lex-param   { yyscan_t scanner }
%parse-param { yyscan_t scanner }
%error-verbose

%union
{
    char ch;
    char* str;
}

%destructor { free($$); } <str>

%token<ch> l_bracket r_bracket semicolon
%token<str> quoted_str
%token<num> banks presets

%%
cmds:
    | cmds cmd
    ;

cmd:
    bank_list
    |
    pre_list
    ;

bank_list:
    banks l_bracket bank_decls r_bracket
    ;

bank_decls:
    | bank_decls bank_decl
    ;

bank_decl:
    quoted_str semicolon
    {
        fprintf(stderr, "append bank %s\n", $1);
        appBank(pre_lnum, $1);
        free($1);
    }
    ;

pre_list:
    presets l_bracket pre_decls r_bracket
    ;

pre_decls:
    | pre_decls pre_decl
    ;

pre_decl:
    quoted_str quoted_str semicolon
    {
        fprintf(stderr, "append preset, bank %s, name %s\n", $1, $2);
        appPre(pre_lnum, $1, $2);
        free($1);
        free($2);
    }
    ;

%%

/* C++ using the above code */
extern "C"
{
    #include "pre_prs_ifc.h"
    #include "pre_prs.h"
    #include "pre_lxr.h"
}
int yyparse(yyscan_t scanner);
...
bool CMainDlg::loadBankPre(std::string fname)
// load bank and preset lists
{
    int err, i;
    yyscan_t scanner;
    FILE *src;
    std::string name_str;
    CListBox* bank_lb;
    bool ret_val;
    pre_fname = _strdup(fname.c_str());
    if (prelex_init(&scanner))
    {
        m_err = "Error initialising scanner.";
        return false;
    }
    src = fopen(fname.c_str(), "r");
    if (src == NULL)
    {
        m_err = "Could not open file: " + fname;
        ret_val = false;
    }
    else
    {
        preset_in(src, scanner);
        initPrePrs();
        err = preparse(scanner);
        if (err)
        {
            m_err = pre_err;
            ret_val = false;
        }
        else
        {
            if (pre_err[0] == 0)
            {
                bank_lb = (CListBox*)GetDlgItem(IDC_LI_BANK);
                for (i = 0; i < num_banks; i++)
                    bank_lb->AddString(bank[i]);
                ret_val = true;
            }
            else
            {
                m_err = pre_err;
                ret_val = false;
            }
        }
        fclose(src);
    }
    pre_delete_buffer(0, scanner);
    prelex_destroy(scanner);
    return ret_val;
}
CMainDlg::~CMainDlg()
// destructor
{
    freePrePrs();
}

A: You should never define global variables in a header file. The header file must declare them as extern, and they need to be defined in precisely one translation unit.
As written, each translation unit has its own definition of the global variables, including pre_fname. That's undefined behaviour and there is no guarantee that the names used in different translation units refer to the same storage locations. Even better than fixing the declarations would be to pass them through to the parser and scanner so as to avoid using globals.
In any event, pre_fname is created (with strdup) in CMainDlg::loadBankPre and it makes most sense to also free it in the same function, ideally using a smart pointer. In you did that, you wouldn't need an <<EOF>> rule at all.
Also, strncpy really is not a good idea here. As @PaulOgilvie points out in a comment, it leaves the copied string unterminated, with the consequence that the later strdup in appBank will copy an undetermined number of extra bytes, possibly referencing invalid memory. (By the way, you don't need to call strlen on yytext. Flex provides the variable yyleng for precisely this purpose, which saves an extra scan over the token.)
On the other hand, when you are formatting into a fixed-length buffer (sprintf(pre_err...)), you should use snprintf instead. Otherwise you might overrun pre_err, which could end up overwriting pre_fname.
Also, your prototype for preerror does not agree with its definition. So if it is called, something bad will happen.
And finally, your <<EOF>> rule (which is unnecessary, see above), does not return 0, so the lexer will keep on trying to scan. <<EOF>> rules must either return 0 or provide a new input buffer. (Or otherwise exit.) In this case, since the <<EOF>> rule calls free, the second (and subsequent) activations of the rule will free the same storage multiple times.

A: I found out that the EOF section is called over and over resulting in an infinite loop, which can be stopped by including a call to yypop_buffer_state.
<<EOF>> {
    yypop_buffer_state(yyscanner);
    free(pre_fname);
    if (!YY_CURRENT_BUFFER)
        yyterminate();
}

So the free was causing a crash on the second time around the EOF section.  As rici pointed out though (in this case) the EOF section is not needed at all if the free is moved to the function loadBankPre.


text:
Q: Redirect public IP address to the domain name in Amazon AWS EC2 I have deployed a web using Jetty Web Server on AWS EC2. I've registered the custom domain (mydomain.com) on Route 53 as well. It works perfect.
But I can still access my website through Public IP Address (1X.2XX.3XX.4XX)
How do you make it so that when a user accesses the Public IP Address it automatically redirects to the registered domain?
Or at least I can block direct access to the web via Public IP Address.


text:
Q: How to generate a set of dummy variables dependent on values in several other columns with same prefix in R? I have a data frame I am trying to put in a format I can use for my analysis that looks the following:

ID
Name
Year
K1
K2
...
K50

1
Contract XYZ
2000
transport
elephants

2
Agreement ABC
2003
pens
music

3
Document 123
2003
elephants

4
Empty Space
2004
music

transport

Basically, I have documents with a unique ID and the year they were signed plus a set of variables name K_1 to K_50 that contain unordered keywords. For each of the keywords I would like to generate a dummy variable (i.e. named transport, pens...) that is one if any of the K_1 to K_50 entries contains that particular string.
I have tried the code below which creates the dummy with the name transport if K1 or K2 contain the code but for 50 keywords in 50 columns it is a lot of manual work.
Ideally, I would be able to use the string as the variable name and run through all 50 columns to identify all keywords and create dummies that will be one if the keyword is present in either column for a particular ID. I would, however, also be happy with manually creating dummies and being able to look at all 50 keywords without typing it all in.
document_dummies <- mutate(document,
                  transport = case_when(
                    K_1 == "transport" | K_2 == "transport" ~ 1,
                    TRUE ~ NA_real_
                  ))

A: Does this help you?
library(tidyverse)

document <- data.frame(
  stringsAsFactors = FALSE,
  ID = c(1L, 2L, 3L, 4L),
  Name = c("Contract XYZ","Agreement ABC",
           "Document 123","Empty Space"),
  Year = c(2000L, 2003L, 2003L, 2004L),
  K1 = c("transport", "pens", "elephants", "music"),
  K2 = c("elephants", "music", NA, NA),
  K50 = c(NA, NA, NA, "transport")
)
document %>%
  pivot_longer(starts_with("K")) %>%
  select(-name) %>%
  filter(! is.na(value)) %>%
  mutate(has_property = 1) %>%
  pivot_wider(names_from = value, values_from = has_property)
#> # A tibble: 4 x 7
#>      ID Name           Year transport elephants  pens music
#>   <int> <chr>         <int>     <dbl>     <dbl> <dbl> <dbl>
#> 1     1 Contract XYZ   2000         1         1    NA    NA
#> 2     2 Agreement ABC  2003        NA        NA     1     1
#> 3     3 Document 123   2003        NA         1    NA    NA
#> 4     4 Empty Space    2004         1        NA    NA     1

Created on 2021-09-21 by the reprex package (v2.0.1)

A: We can use the fastDummies package, with the dummy_columns function.
With the example data from @danlooo
document %>% pivot_longer(matches('K\\d+'), names_to = NULL) %>%
        filter(!is.na(value)) %>%
        fastDummies::dummy_columns('value') %>%
        rename_with(~str_remove(.x, '^value_'), starts_with('value_'))

# A tibble: 7 x 8
     ID Name           Year value     elephants music  pens transport
  <int> <chr>         <int> <chr>         <int> <int> <int>     <int>
1     1 Contract XYZ   2000 transport         0     0     0         1
2     1 Contract XYZ   2000 elephants         1     0     0         0
3     2 Agreement ABC  2003 pens              0     0     1         0
4     2 Agreement ABC  2003 music             0     1     0         0
5     3 Document 123   2003 elephants         1     0     0         0
6     4 Empty Space    2004 music             0     1     0         0
7     4 Empty Space    2004 transport         0     0     0         1

data
document <- data.frame(
        stringsAsFactors = FALSE,
        ID = c(1L, 2L, 3L, 4L),
        Name = c("Contract XYZ","Agreement ABC",
                 "Document 123","Empty Space"),
        Year = c(2000L, 2003L, 2003L, 2004L),
        K1 = c("transport", "pens", "elephants", "music"),
        K2 = c("elephants", "music", NA, NA),
        K50 = c(NA, NA, NA, "transport")
)

> document
  ID          Name Year        K1        K2       K50
1  1  Contract XYZ 2000 transport elephants      <NA>
2  2 Agreement ABC 2003      pens     music      <NA>
3  3  Document 123 2003 elephants      <NA>      <NA>
4  4   Empty Space 2004     music      <NA> transport


text:
Q: Check if Facebook user exists using Javascript I'm looking for a way to check if there is a Facebook user with a particular ID.
I know that there is an Graph API which can return Facebook user's profile picture for given ID, it works like this:
https://graph.facebook.com/#USER_ID_HERE#/picture
and I see that if I enter ID that doesn't exists it returns error, however I'm still very new to JavaScript so I don't really know how to "read" that error message.

A: Try this code by using jQuery.
var pictureUrl= "https://graph.facebook.com/" + userId + "/picture";
$.ajax({
    url : pictureUrl,
    statusCode: {
        200: function() {
            alert("user exist");
        },
        404: function() {
            alert( "user not exist" );
        }
    }
});


text:
Q: Cannot set headers after they are sent to the client in Express js I'm getting this error while running this code. The API is running fine, after that it is throwing this error.
app.post('/api', async (req, res) => {
    try {
        channelTwo.consume(queue, async (data) => {
            if (data) {
                const _data = JSON.parse(data.content);
                const SavedData = new User(_data);
                await SavedData.save();
                channelTwo.ack(data);
                if (SavedData) {
                    res.status(200).json({ message: 'Date Saved to db', SavedData });
                }
                res.status(400).json({ message: 'Cant save data' });
            }
            res.status(400).json({ message: 'Cant find data' });
        });
    } catch (error) {
        res.status(400).json({ message: error });
    }
})

;

A: You have to return after calling res.status(<>).json() otherwise it will be called multiple times.
This will try to set a response header code although already json body has already been sent causing your error


text:
Q: How to access the orbeon form data id on client-side? In my application, I render my own page and inject the content of Orbeon URL /orbeon/fr/appname/formname/new?orbeon-embeddable=true in a div.
On save, I need to create a relationship between the form_data_id and my entity id. I can capture the click event on the save button but I haven't found the form_data_id on the Form DOM or any Orbeon JavaScript object.
Where is the form_data_id, or how expose it? Do you have another approach to create a relationship with the form_data_id?

A: If you're referring to Orbeon's document id, and you can use JavaScript in your own page, then use the following function call.
ORBEON.xforms.Document.getValue("fr-parameters-instance-document")

This will return a string, e.g. "4a1ae3c34a8e14e70c8fc3a02234a847d13896a9".


text:
Q: Can we create n no.of NSMutableArray dynamically? I'm getting the n value from the user, according to it I want to create n number of NSMutableArray .

A: Yes you can, just add the arrays to another NSMutableArray. Use this code:
NSMutableArray *outerArray = [NSMutableArray arrayWithCapacity:n];

for (int i=0; i<n; i++) {
    NSMutableArray *innerArray = [[NSMutableArray alloc] init];
    [outerArray addObject:innerArray];
}

A: int n= 5; // or whatever user gives you
count = 0;
NSMutableArray *arrayOfArrays = [NSMutableArray array];

while(count < n)
{
   NSMutableArray *anArray = [NSMutableArray array];
   [arrayOfArrays addObject: anArray];
   count ++;
}

A: By using an array of arrays:
NSMutableArray *arrays = [NSMutableArray new];

while (gotMoreInput) {
    NSMutableArray *array = [NSMutableArray new];
    [array addObject:@"Some data"];
    [arrays addObject:array];
}


text:
Q: convert json datetime format (2018-01-05T22:58:23.937 ... "T" within datetime-value to be stored in sql database) how to convert a date/time value received by "json decoding"

2018-01-05T22:58:23.937  (value of $TimeStamp)

to insert into a SQL-Database-Field type of DATETIME
$query = "INSERT INTO database (date1,...) VALUES ($ddate1, ...)

this won't work:
$ddate1 = date_format(new datetime($TimeStamp), 'y.m.d H:i:s');

removing 'T' won't work either
$ddate1 = strtr($TimeStamp,"T"," ");
$ddate1 = date_format(new datetime($ddate1), 'y.m.d H:i:s');

UPDATE 6.01.2018
$now = date("y.m.d H:i:s"); $TimeStamp = $fgc['result'][$i]["TimeStamp"];  // (result of json)

echo "OK:" .$now .'
';
echo "nOK: (format of source) sorce" .$TimeStamp .'
';
$dt1 = date('Y.m.d H:i:s', strtotime($Timestamp)); echo "convert:" .$dt1 .'
';
$dt2 = date('Y-m-d', strtotime($Timestamp)); echo "convert:" .$dt2 .'
';

Result:
OK:

18.01.06 12:48:39

(sample stored correcrtly in database)

nOK: (format of source) sorce2018-01-06T11:48:40.207

convert:1970.01.01 01:00:00

convert:1970-01-01

thanks for any hints
Stefan

A: This should do the trick:
$date = '2018-01-05T22:58:23.937';
echo date('Y-m-d', strtotime($date)); // 2018-01-05

Alternatively, you can use OOP style DateTime class as follows:
$dt = new DateTime('2018-01-05T22:58:23.937');
echo $dt->format('Y-m-d');

A: problem solved (just the same coding as in my first post ... must have been an different error ... sorry!)

$TimeStamp      = $fgc['result'][$i]["TimeStamp"];

converted by

$DatumUpdate    = date_format(new datetime($TimeStamp ), 'y.m.d
  H:i:s');

stored correctly in database

A: make a function like blew what u need im not coded just exple it u need make it wt u need..
    function shortDu($t) {
$sam = str_replace('PT','',$t);
$sam = str_replace('H',':',$sam);
$sam = str_replace('M',':',$sam);
$sam = str_replace('S','',$sam);
return $sam;}

apply this shortDu(); on your current value then get perfect result then input in db


text:
Q: Hay alguna manera de hacer los diccionarios de python en js? pues eso, hay algúna manera o algo parecido que pueda hacer esto pero en js:
diccionario = {'a': 'b', 'c': 'd'}

esto es de python y estoy buscando alguna manera de hacerlo en js ya que no estoy acostumbrado a este lenguaje, por lo que tengo entendido se puede hacer con un map, pero lo veo algo incomodo, hay alguna otra manera?, o se puede usar python en el frontend?


text:
Q: Box around equations in align environment and no indentation I have the following code and I want to do two things to it.First, I want to have the output maximally on the left, that is I do not want any indentation of the stuff in the align environment, I want them to be in the same alignment as my text.The second thing I want to do is place a box around the entire content of the align environment. If anyone has any suggestions, I would be most grateful!
I want this to be left-aligned in the same position as the following equations.

\documentclass{article}
\usepackage[margin= 1in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{tree-dvips}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage[affil-it]{authblk}
\usepackage{tipa}
\usepackage{tabularx}
\usepackage{enumitem}
\usepackage{parcolumns}
\usepackage{natbib}
\usepackage{gb4e}
\usepackage{stmaryrd}
\usepackage{amssymb, amsmath}
\usepackage{qtree}
    \tikzset{small/.style={level distance=25pt,sibling distance=0pt}}

\usepackage{hyperref}
\begin{document}
\begin{flalign*}
&\llbracket \text{before} (\mathscr{B} \vee \mathscr{C}) \rrbracket                         \\
&\equiv \lambda t. \Big(\neg \exists t' \big[t' \le t \wedge \llbracket (\mathscr{B} \vee \mathscr{C}) \rrbracket(t') \big] \Big)                        \tag{definition}\\
&\equiv \lambda t. \Big(\forall t' \neg \big[t' \le t \wedge \llbracket (\mathscr{B} \vee \mathscr{C}) \rrbracket(t') \big] \Big)                    \tag{$\neg (\exists x)[\mathscr{P}(x)] \equiv  (\forall x)\neg[\mathscr{P}(x)]$}\\
&\equiv \lambda t. \Big(\forall t' \neg \big[t' \le t \wedge (\llbracket \mathscr{B}) \rrbracket(t') \vee \llbracket \mathscr{C}) \rrbracket(t') ) \big] \Big)                   \tag{point-wise disjunction}\\
&\equiv \lambda t. \Big(\forall t'  \neg \Big[ \Big(t' \le t \wedge \llbracket \mathscr{B}) \rrbracket(t') \Big) \vee \Big(t' \le t \wedge \llbracket \mathscr{C}) \rrbracket(t') \Big) \Big] \Big)                           \tag{$\mathscr{A}\wedge(\mathscr{B} \vee \mathscr{C}) \equiv (\mathscr{A} \wedge \mathscr{B}) \vee (\mathscr{A} \wedge \mathscr{C}))$}\\
&\equiv \lambda t. \Big(\forall t'  \Big[ \neg\Big(t' \le t \wedge \llbracket \mathscr{B}) \rrbracket(t') \Big) \wedge \neg\Big(t' \le t \wedge \llbracket \mathscr{C}) \rrbracket(t') \Big) \Big] \Big)   \tag{De Morgan}\\
&\equiv \lambda t.  \Big[ \forall t'\neg\Big(t' \le t \wedge \llbracket \mathscr{B}) \rrbracket(t') \Big) \wedge \forall t'\neg\Big(t' \le t \wedge \llbracket \mathscr{C}) \rrbracket(t') \Big) \Big]          \tag{$\forall x[\mathscr{P}(x) \vee \mathscr{R}(x)] \equiv \forall x[\mathscr{P}(x)] \vee \forall x[\mathscr{R}(x)]$}\\
&\equiv \lambda t.  \Big[ \forall t'\neg\Big(t' \le t \wedge \llbracket \mathscr{B}) \rrbracket(t') \Big) \Big] \wedge \lambda t. \Big[ \forall t'\neg\Big(t' \le t \wedge \llbracket \mathscr{C}) \rrbracket(t') \Big) \Big] \tag{point-wise conjunction}\\
&\equiv \lambda t.  \Big[ \neg\exists t'\Big(t' \le t \wedge \llbracket \mathscr{B}) \rrbracket(t') \Big) \Big] \wedge \lambda t. \Big[ \neg\exists t'\Big(t' \le t \wedge\llbracket \mathscr{C}) \rrbracket(t') \Big) \Big] \tag{$\neg (\exists x)[\mathscr{P}(x)] \equiv  (\forall x)\neg[\mathscr{P}(x)]$}\\
& \equiv \llbracket \text{before} (\mathscr{B}) \wedge \text{before} (\mathscr{C})\rrbracket \tag{definition}
\end{flalign*}
\end{document}

A: Here is an example of using falling and tikzmark to place a box around he entire set of equations:

Notes:

*

*This does require two runs. First one to determine the locations, and the second to do the drawing.

*Also note the trailing & on the F = ma. This is required to get the equations al the way to the left.

Code:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage{showframe}
\usetikzlibrary{calc}
\usepackage{tikzpagenodes}

\newcommand{\mytikzmark}[1]{\tikz[overlay,remember picture] \node[baseline] (#1) {\strut};}
\newcommand*{\xSep}{2.0pt}
\newcommand*{\DrawBox}[3][]{%
    \begin{tikzpicture}[remember picture, overlay]
        \coordinate (Right Side) at (#3.south -| current page text area.north east);
        \draw [#1]
            (#2.north) rectangle %(current page text area.east);
            (Right Side);
    \end{tikzpicture}%
}%

\begin{document}
I want this to be left-aligned in the same position as the following equations,
with no indentation from the left margin
\begin{flalign*}
\mytikzmark{start}
F & = ma &&\text{Newtons famous equation.} &\\
E &= mc^2 && \text{Einstein's discovery!}\mytikzmark{end}
\end{flalign*}
\DrawBox[draw=red, thick]{start}{end}%
\end{document}

A:
\documentclass{article}
\usepackage{empheq}

\begin{document}
I want this to be left-aligned in the same position as the following equations,
with no indentation from the left margin
\begin{empheq}[box=\fbox]{flalign*}
F & = ma    &&  \text{Newtons famous equation.} &   \\
E &= mc^2   &&  \text{Einstein's discovery!}
\end{empheq}
\end{document}

This is slightly simplified and less fancy than what proposed in @Peter Grill answer.
I used empheq package. As stated in package documentation:

The empheq package can best be described as a visual markup extension to amsmath. In short it offers a) a multi line equivalent of \boxed from amsmath and b) a way to produce arbitrary delimiters that span entire math displays.


text:
Q: Can't install software, apparently installed packages have unmet dependencies I've got a DELL n5110 laptop, with intel i3-2330m cpu @ 2.20GHz x 4, 64 bit OS system, ubuntu 14.04 LTS operating system.
The error that comes up is upon start up, and it gives me the option of cancel or send report.  After passing that hurdle, I then get an icon in the top of my screen, red circle with white line through it, sat alongside the volume display and other icons. That icon reads:

An error occurred, please run Package Manager from the right click menu or apt-get in a terminal to see what is wrong. The error message was: "Error: BrokenCount > 0".  This usually means your installed packages have unmet dependencies.

When I open Software Centre, I get the option of repairing the installed packages, but it usually fails at the last moment, with the comment:
The following packages have unmet dependencies:

linux-image-extra-3.13.0-66-generic: Depends: linux-image-3.13.0-66-generic but it is not installed
linux-image-extra-3.13.0-79-generic: Depends: linux-image-3.13.0-79-generic but it is not installed
linux-image-generic: Depends: linux-image-3.13.0-79-generic but it is not installed

A warning once came up about disabling third party repositories, and I tried doing this via terminal using the command sudo software-properties-gtk, and it took me to the Software Centre, with a list of boxes ticked and some strange long looking clever words which I've never thought to use before in my life.
The update says the following
Errors were encountered while processing: /var/cache/apt/archives/linux-image-3.13.0-79-generic_3.13.0-79.123_amd64.deb /var/cache/apt/archives/linux-image-3.13.0-66-generic_3.13.0-66.108_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

and these
Unpacking linux-image-3.13.0-66-generic    (3.13.0-66.108) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-3.13.0-66-generic_3.13.0-66.108_amd64.deb
 (--unpack): cannot copy extracted data for './boot/vmlinuz-3.13.0-66-generic' to '/boot/vmlinuz-3.13.0-66-generic.dpkg-new':
failed to write (No space left on device) No apport report written because the error message indicates a disk full error

A: I can't help with the strange long looking clever words, as you don't list them. But, from what I can see, the system is trying to install some linux-image-extra packages that depend on some linux-image-generic packages already being installed.
Certain packages depend on other packages in order to work, and apt-get does a very good job at managing this and making sure, when you install a package, that all other required packages are installed at the same time. However, maybe another method has been used to install the linux-image stuff or maybe apt-get has stumbled on this occasion. It is rare, but I guess it is possible.
I pretty much echo what muru says.
Open a terminal and update your local repository cache.
sudo apt-get update

Now try upgrading your installed packages.
sudo apt-get upgrade

Before the upgrade begins, and you are prompted with a "y/n" to proceed, you will see a line showing you how many packages are being upgraded and how many are not being upgraded.
If you have packages that are not being upgraded, they will be listed. Are the linux-image-generic files in that list ?
There are now two ways to proceed. You can either do a system upgrade, which is the next step up to the package upgrade
sudo apt-get dist-upgrade

Or you can install the missing dependencies manually.
sudo apt-get install linux-image-3.13.0-66-generic
sudo apt-get install linux-image-3.13.0-79-generic

I would probably do the system upgrade, as I do that regularly anyway and have had no issues. However, I don't know the exact setup of your system so you might not want to go down that route.
To see what apt-get upgrade and apt-get dist-upgrade do, check out this link.
https://help.ubuntu.com/community/AptGet/Howto
Finally, muru also gives you the command for fixing missing dependencies.
sudo apt-get install -f

I don't actually use this option a great deal, but I have in the past and it has indeed installed missing dependencies.


text:
Q: objects in the try catch block Take this code sample:
string status = "ok";
SqlCommand cmd=null;
SqlTransaction trans=null;
try
{
    cmd = defs.prepquery("");
    trans = cmd.Connection.BeginTransaction();
    cmd.Transaction = trans;

}
catch (Exception ex)
{
    status = defs.logerror("initalizing sql transaction:" + ex.ToString());
    return status;
}

try
{
    if (oper == "submit")
    {
        cmd.CommandText = "update DCM_Mapping_Sessions set StatusID=2 " +
            "where MappingSessionID=" + mpsid + "";
        cmd.ExecuteNonQuery();
    }
    else if (oper == "delete")
    {
        // .......etc etc
    }
    catch(Exception ex2)
    {
        //rollback , close the connection
       // handle the ex
    }

    // if everything is ok , comit the transaction and close the connection
}

So my question is: What happens with the objects in the try block when an exception occurs ?
Does C# allows me to be lazy and destroys the objects(destroying the pending transaction meaning rollback) and closes the connection if an exception occurs ?
I come from a C\C++ background so i am doing my stuff as above to be safe and not end with a transaction open if an exception occurs somewhere below.

A: Have a look at try-finally.
It does exactly what you're asking for.
So your code looks like:
try
{
   //try something
}
catch(Exception ex2)
{
   // handle the ex
}
finally
{
    //rollback , close the connection
}

A: You should be disposing/closing the connection and transaction.
The best way to do so is to wrap the creation in a using statement.

Provides a convenient syntax that ensures the correct use of IDisposable objects.

In essence a using statement wraps the creation of the objects in try{}finally{} blocks to ensure proper disposal.
    using(var cmd = defs.prepquery(""))
    using(var trans = cmd.Connection.BeginTransaction())
    {

    }

A: Short answer, no.
Longer answer, yes but far too late.
This is why we have the finally clause and the using block. You are responsible for calling the close or dispose.
They will get closed or disposed later when the garbage collector is forced to do this "slowly" for you but, there will be an indeterminate period where your expensive resources are wasted unesscessarily.
Something like this would be preferable
using(var connection = defs.GetConnection())
using(var cmd = new SqlCommand())
{
    cmd.Connection = connection;
    switch(oper)
    {
        case "submit":
             cmd.CommandText = "update DCM_Mapping_Sessions" +
                               "set StatusID=2" +
                               "where MappingSessionID=" + mpsid;
        case "...
    }

    try
    {
        cmd.ExecuteNonQuery();
    }
    catch(SomeSpecificExceptionIShouldActuallyHandleHere ex)
    {
       ...
    }
}

Possible injection attack aside.


text:
Q: OneToMany relationship does not store entity field When saving my entities, child entities that work through the @OneToMany relationship are not saved to their tables. I can't understand what's the matter.
Employee:
@Entity
@Table(name = "EMPLOYEE", schema = PUBLIC)
public class Employee {

private String name;

private String lastname;

@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
List<EmployeePhoneNumber> employeePhoneNumbers = new ArrayList<>();

}

EmployeePhoneNumber:
@Entity
@Table(name = "EMPLOYEE_PHONES", schema = PUBLIC)
public class EmployeePhoneNumber {

    @Id
    @SequenceGenerator(allocationSize = 1, name = "SEQ_EMPLOYEE_PHONES", schema = PUBLIC,
            sequenceName = "EMPLOYEE_PHONES_ID_SEQ")
    @GeneratedValue(generator = "SEQ_EMPLOYEE_PHONES", strategy = GenerationType.SEQUENCE)
    @Column(name = "ID", unique = true, nullable = false)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "employee_id", referencedColumnName = "id",
            nullable = false, insertable = false, updatable = false)
    private Employee employee;

    @Column(name = "PHONE_NUMBER", unique = true, nullable = false)
    private String phoneNumber;

    @Enumerated(EnumType.STRING)
    @Column(name = "NUMBER_TYPE", nullable = false)
    private PhoneNumberType phoneNumberType;
}

How I set those fields and then save the entity:
        EmployeePhoneNumber workPhone = new EmployeePhoneNumber();
        workPhone.setPhoneNumber(workPhone);
        workPhone.setPhoneNumberType(PhoneNumberType.WORK_PHONE);

        EmployeePhoneNumber mobilePhone = new EmployeePhoneNumber();
        mobilePhone.setPhoneNumber(mobilePhone);
        mobilePhone.setPhoneNumberType(PhoneNumberType.MOBILE_PHONE);

        EmployeePhoneNumber corporatePhone = new EmployeePhoneNumber();
        corporatePhone.setPhoneNumber(corporatePhoneNumber);
        corporatePhone.setPhoneNumberType(PhoneNumberType.CORPORATE_PHONE);

        List<EmployeePhoneNumber> employeePhoneNumbers = employee.getEmployeePhoneNumbers();
        employeePhoneNumbers.add(workPhone);
        employeePhoneNumbers.add(mobilePhone);
        employeePhoneNumbers.add(corporatePhone);

        employee.setEmployeePhoneNumbers(employeePhoneNumbers);

        employeeRepository.save(employee);

Upon completion of the method, I do not have a single error, everything works out correctly, only the tables are not filled - why?

A: You must also set the Employee reference in EmployeePhoneNumber because Hibernate will use this to save it.
workPhone.setEmployee(employee);
mobilePhone.setEmployee(employee);
corporatePhone.setEmployee(employee);

The best solution would be to create an addEmployeePhoneNumber method on the Employee like this:
 public void addEmployeePhoneNumber(EmployeePhoneNumber phoneNumber) {
     phoneNumber.setEmployee(this);
     employeePhoneNumbers.add(phoneNumber);
 }

That way you will not forget to set both sides of the relationship.


text:
Q: How to resolve missing Lua DLL when using LuaBinaries and LuaBridge? I'm trying to embed Lua into C++ (and learn Lua), starting off with Elias Daler's training wheels method here. I'm using MSVC 14.0, LuaBinaries 5.3.2 - Release 1 (specifically, lua-5.3.2_Win32_dllw4_lib.zip here), and LuaBridge 2.0.
I've added the following Additional Include Directories:

C:\lua-5.3.2_Win32_dllw4_lib\include;C:\LuaBridge

And the following Additional Dependency:

C:\lua-5.3.2_Win32_dllw4_lib\liblua53.a

And I'm using the following source (pared down as far as it can):
#include "stdafx.h"
#include <LuaBridge.h>

int main() {
    luabridge::lua_State* L = luabridge::luaL_newstate();
}

That source compiles and links fine, but the application itself causes a standard missing DLL system error:

The program can't start because lua53.dll is missing from your computer. Try reinstalling the program to fix this problem.

lua53.dll is in C:\lua-5.3.2_Win32_dllw4_lib\ —what am I missing?

A: According to the official Microsoft documentation, Windows searches for DLLs in the following directories:

*

*The directory where the executable module for the current process is located.

*The current directory.

*The Windows system directory. The GetSystemDirectory function retrieves the path of this directory.

*The Windows directory. The GetWindowsDirectory function retrieves the path of this directory.

*The directories listed in the PATH environment variable.

So, one way to solve the problem would be to add C:\lua-5.3.2_Win32_dllw4_lib to the current user's PATH.
Compared to the other options, this has the advantages of not requiring admin privileges and not requiring lua53.dll to be in either the current directory or the same directory as your executable.


text:
Q: Kак связать устройство CD/DVDROM c назначенной буквой по HDEVINFO и SP_DEVINFO_DATA Необходимо получить параметры CD-ROM (имя, производителя и т.д.). С получением этих параметров отлично справляется код:
HDEVINFO hDevInfo = NULL;
SP_DEVINFO_DATA DeviceInfoData;
hDevInfo = ::SetupDiGetClassDevs(
    NULL,
    0,
    0,
    DIGCF_PRESENT | DIGCF_ALLCLASSES
);
if(hDevInfo != INVALID_HANDLE_VALUE)
{
    DeviceInfoData.cbSize = sizeof( SP_DEVINFO_DATA );
    for(int i = 0; ::SetupDiEnumDeviceInfo( hDevInfo, i, &DeviceInfoData ); i++)
    {
    // получаем для класса CDROM все необходимые локализованные параметры, кроме буквы диска
    }
}

Как получить букву диска устройства?
Букву CD/DVD-ROM можно получить с помощью GetLogicalDriveStrings, GetDriveType
Но как связать устройство с назначенной буквой?

A: Как я решил данный вопрос:
GetLogicalDriveStrings - получение букв всех дисков
GetDriveType - поиск CD/DVD-ROM
SetupDiGetClassDevs, SetupDiEnumDeviceInfo - поиск девайсов по классу "CDROM"
RegOpenKeyEx( HKEY_LOCAL_MACHINE, L"SYSTEM\\MountedDevices" .....
RegQueryValueEx( hKey, L"\\DosDevices\\буква CD/DVD-ROM

приведение devces_id из реестра и полученный из SetupDiEnumDeviceInfo к единому формату для соотнесения буквы и девайса.
Пишите, если есть более изящное решение.


text:
Q: DHCPv4 connection considered critical, ignoring request to reconfigure it I am seeing these log on a server but don't know what does it mean?
systemd-networkd[3423]: eth1: Link DOWN
systemd-networkd[3423]: eth1: Lost carrier
systemd-networkd[3423]: eth1: DHCPv4 connection considered critical, ignoring request to reconfigure it.

Does it mean someone/something is requested to change the eth1 config but systemd reject to accept it?

A: The starting point is that the network connection failed - there could be many reasons for this including a hardware problem. This would normally lead systemd-networkd to release the ip address internally, but because you have it marked as 'critical' (e.g. if you use netplan, you have 'critical: true' in your /etc/netplan/config.yaml), it did not do so, it held on to the ip address internally even though there was no external connection.
This is probably the behaviour you want if network connection failures are likely to be very brief and/or you never want that ip address to change.


text:
Q: Multiple Strategy Design Pattern I want to be able to gather several pieces of validation entities, all sharing same interface. This  is what I came up with:
public interface Ivalidateable
{
  bool IsValid(IValidateParam param);
}

public interface IValidateParam
{

}

public abstract EmployeeStrategy: Ivalidateable
{
  public abstract bool IsValid(User user);
}

public abstract SpreadStrategy: IValidateable
{
 public abstract bool IsAvlid(Campaign campaign);
}

public class User: IValidateParam
{}

public class Campaign: IValidateParam
{}

public EmployeeTypeStragtegy: EmployeeStrategy, IValidateable
{
 public bool IsValid(User user)
 {
  if  (new[]{'e',a','b}.Contains(user.userId.first().toString()))
  return true;

  return false;
 }
}

public TrailSpreadStrategy: SpreadStrategy, IValidateable
{
 public bool IsValid(Campaign campaign)
 {
  //logic goes here
 }
}

public EvenpreadStrategy: SpreadStrategy:, IValidateable
{
 public bool IsValid(Campaign campaign)
 {
  //logic goes here
 }
}

public class ValidationFactory
{
 private static List<IValidateable> stragtegies;

 static ValidationFactory
 {
  strategies = new List<IValidateable>();
  strategies.Add(new EmployeeTypeStragtegy());
  strategies.Add(new TrailSpreadStrategy());
 }

 public bool IsValid(//Need to pass User/Campaign)
 {
  //what do I do here?
 }
}

What is the best way to pass User / Campaign so that I can loop strategies and check IsValid?

A: Here's how I'd do it:
// campaign object class, and it's separate validator logic

public class Campaign
{
}

public class CampaignValidator : IValidationStrategy<Campaign>
{
    public bool IsValid(Campaign test)
    {
        return true;
    }
}

// framework stuff

public interface IValidationStrategy<T>
{
    bool IsValid(T test);
}

public static class ValidationFactory
{
    private readonly static Dictionary<Type, object> _typeValidators;

    static ValidationFactory()
    {
        _typeValidators = new Dictionary<Type, object>();
        _typeValidators[typeof(Campaign)] = new CampaignValidator();
    }

    public static bool IsValid<T>(T obj)
    {
        return ((IValidationStrategy<T>)_typeValidators[typeof(T)]).IsValid(obj);
    }
}

After that, you can call ValidationFactory.IsValid(myObject); and if the type is in the factory static constructor, it will give you true/false.
The validation factory is doing a kind of DI/IOC thing, i.e. you could use Ninject, Castle etc to achieve mapping a type to a validator type.
You could do things dynamically or differently without having to build the dictionary in the same way - look at the generic type parameter of the interface the validator implements, or search for IValidationStrategy<>-based classes and again look at the generic type parameter.  But the above is quick and simple.
Is there a reason you want separate validator classes?

A: I would recommend having a look at FluentValidation's nesting and collection validation capabilities. This should work fine without an extra factory and interfaces - if your strategies hold references to the other entities you want to validate along with them.

A: How about this?
Change all of your IsValid to use this prototype (User user, Campaign campaign), for example:
public EmployeeTypeStragtegy: EmployeeStrategy, IValidateable
{
 public bool IsValid(User user, Campaign campaign)
 {
    return (new char[]{'e','a','b'}.Contains(user.userId.first().toString());
 }
}

And then handle each by the appropriate type, that way they all accept the same arguments. and then:
public bool IsValid(User user, Campaign campaign)
 {
   bool valid;

   foreach (IValidateable iv in strategies)
   {
      if (!iv.IsValid(user, campaign))
          valid = false;
   }

   // This returns true if all are valid, false if not (not sure if this is the logic you expect)
   return valid;
 }


text:
Q: wso2 apim IsAuthReqSigned has no effect Using WSO2AM 2.1.0 trying to configure SAML IdP using a file deployment. The issue is I am unable to make the SAML request signed (required by the IdP).
I assumed that the parameter IsAuthReqSigned should enable signing the SAML Request, but apparently it is not (HTTP-Redirect binding is used and there's no signature between the parameters)
having following IdP configuration (certificate and real names are blanked out):
<IdentityProvider>
    <IdentityProviderName>oamidp</IdentityProviderName>
    <DisplayName>oamidp</DisplayName>
    <IdentityProviderDescription>Ext Access Manager</IdentityProviderDescription>
    <Alias>oamidp</Alias>
    <IsPrimary/>
    <IsEnabled>true</IsEnabled>
    <IsFederationHub/>
    <HomeRealmId/>
    <ProvisioningRole/>
    <FederatedAuthenticatorConfigs>
            <saml2>
                    <Name>SAMLSSOAuthenticator</Name>
                    <DisplayName>samlsso</DisplayName>
                    <IsEnabled>true</IsEnabled>
                    <Properties>
                        <property>
                                <Name>IdpEntityId</Name>
                                <Value>https://logon-test.xxx.com/oam/fed</Value>
                        </property>
                        <property>
                                <Name>IsLogoutEnabled</Name>
                                <Value>true</Value>
                        </property>
                        <property>
                                <Name>SPEntityId</Name>
                                <Value>https://wso2am-test/sp</Value>
                        </property>
                        <property>
                                <Name>SSOUrl</Name>
                                <Value>https://logon-test.xxx.com/oamfed/idp/samlv20</Value>
                        </property>
                        <property>
                                <Name>isAssertionSigned</Name>
                                <Value>false</Value>
                        </property>
                        <property>
                                <Name>commonAuthQueryParams</Name>
                                <Value></Value>
                        </property>
                        <property>
                                <Name>IsUserIdInClaims</Name>
                                <Value>true</Value>
                        </property>
                        <property>
                                <Name>IsLogoutReqSigned</Name>
                                <Value>false</Value>
                        </property>
                        <property>
                                <Name>IsAssertionEncrypted</Name>
                                <Value>false</Value>
                        </property>
                        <property>
                                <Name>IsAuthReqSigned</Name>
                                <Value>true</Value>
                        </property>
                        <property>
                                <Name>IsAuthnRespSigned</Name>
                                <Value>true</Value>
                        </property>
                        <property>
                                <Name>LogoutReqUrl</Name>
                                <Value>https://logon-test.portofantwerp.com/oamfed/idp/samlv20</Value>
                                <!-- Value>false</Value -->
                        </property>
                </Properties>
            </saml2>
    </FederatedAuthenticatorConfigs>
    <DefaultAuthenticatorConfig>SAMLSSOAuthenticator</DefaultAuthenticatorConfig>
    <ProvisioningConnectorConfigs>
    </ProvisioningConnectorConfigs>
    <DefaultProvisioningConnectorConfig/>
    <ClaimConfig>
        <LocalClaimDialect>false</LocalClaimDialect>
        <ClaimMappings>

            <ClaimMapping>
                <LocalClaim>
                        <ClaimUri>http://wso2.org/claims/userid</ClaimUri>
                </LocalClaim>
                <RemoteClaim>
                        <ClaimUri>uid</ClaimUri>
                </RemoteClaim>
                <RequestClaim>true</RequestClaim>
            </ClaimMapping>

        </ClaimMappings>
    </ClaimConfig>
    <Certificate>MIID1T....mcrnA==</Certificate>
    <PermissionAndRoleConfig/>
    <JustInTimeProvisioningConfig>
            <UserStoreClaimUri/>
            <ProvisioningUserStore></ProvisioningUserStore>
            <IsProvisioningEnabled>false</IsProvisioningEnabled>
    </JustInTimeProvisioningConfig>
</IdentityProvider>

A: Apparently there's typo in the source code IdentityApplicationConstants, the correct parameter value should be ISAuthnReqSigned. This is an already known issue https://wso2.org/jira/browse/IDENTITY-2720


text:
Q: Getting day of week based on date provided The following code sometimes give correct output And sometimes gives wrong
For example :
7th april 1990 returns Monday which is correct
31st dec 1987 returns Sunday which is incorrect, it should be Tuesday
I have tried:
int mm=Integer.parseInt(m);
GregorianCalendar calendar = new GregorianCalendar(Integer.parseInt(y),mm,Integer.parseInt(d));
int i = calendar.get(Calendar.DAY_OF_WEEK);
String dayOfTheWeek = null;
if(i == 2){
    dayOfTheWeek = "Monday";
} else if (i==3){
    dayOfTheWeek = "Tuesday";
} else if (i==4){
    dayOfTheWeek = "Wednesday";
} else if (i==5){
    dayOfTheWeek = "Thursday";
} else if (i==6){
    dayOfTheWeek = "Friday";
} else if (i==7){
    dayOfTheWeek = "Saturday";
} else if (i==1){
    dayOfTheWeek = "Sunday";
}
Log.v("Event Week",Integer.toString(i));
return dayOfTheWeek;

A:
GregorianCalendar calendar = new GregorianCalendar(1987, 11, 31);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));

Gives output as Saturday
and

GregorianCalendar calendar = new GregorianCalendar(1990, 3, 7);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));

Gives output as Thursday
Which matches what the calendar shows.
Note: The month field is 0-index based. So, January is 0, and December is 11.
PS: The actual output to the above code is an integer. So, you will need to check the values and figure out the DAY.

A: I managed to solve my problem
The following code gives
1.Day of week based on birthdate of the coming birthday
2.Also tested with leap year Feb 29, works perfect
int checkFutureLeapYear=0;
            Calendar today=Calendar.getInstance();
              Calendar BDay=Calendar.getInstance();
              int CYear=today.get(Calendar.YEAR);
              // checking whether entered date contains Feb 29 ,if yes check whether //current year is leap years so that it can handle 29
              if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
            // if leap year leave the date as it as , since it can handle 29
        if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
                      d=d;
                }
            // if not subtract 1 from date , to make it 28 , as current year donot contains feb 29 ,so making it feb 28
                  else {
                      int date=Integer.parseInt(d);
                      date=(date-1);
                      d=Integer.toString(date);
                }
            }

            String startDate=y+"/"+m+"/"+d;
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
            Date date=null;
            try{
                  date=sdf.parse(startDate);
              }
          catch (Exception e) {
            e.printStackTrace();
         }
          BDay.setTime(date);
          int BMonth=BDay.get(Calendar.MONTH);
          int BDate=BDay.get(Calendar.DATE);
          int CMonth=today.get(Calendar.MONTH);
          int CDate=today.get(Calendar.DATE);

          BDay.set(Calendar.YEAR,today.get(Calendar.YEAR));
      // if current month is greater than birth month , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
          if (BMonth<CMonth) {
            BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
            checkFutureLeapYear=1;
         }

     // Also if current month and birth month are same , but current date is greater than birth date , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
          else if ((BMonth==CMonth)&&(BDate<CDate)) {
              BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
              checkFutureLeapYear=1;
         }
     // code to check that ,is the future year can handle feb 29, same as above conditions
          if (checkFutureLeapYear==1) {
              CYear=BDay.get(Calendar.YEAR);
              Log.v("checkFutureLeapYear",Integer.toString(CYear));
;             if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
                  if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
                      d=d;
                }
                  else {
                      int date1=Integer.parseInt(d);
                      date1=(date1-1);
                      d=Integer.toString(date1);
                      Log.v("Date 29 subtracted to ",(d));
                }
            }
                startDate=Integer.toString(CYear)+"/"+m+"/"+d;
                sdf=new SimpleDateFormat("yyyy/MM/dd");
                date=null;
                try{
                        date=sdf.parse(startDate);
                    }
                    catch (Exception e) {
                            e.printStackTrace();
                    }
                    BDay.setTime(date);
                    Log.v("dfdfgdffgfgb",Integer.toString(BDay.get(Calendar.YEAR)));
        }

        String dayOfTheWeek;
        Log.v("Birth year",Integer.toString(BDay.get(Calendar.YEAR)));
        Log.v("Birth month",Integer.toString(BDay.get(Calendar.MONTH)));
        Log.v("Birth date",Integer.toString(BDay.get(Calendar.DAY_OF_MONTH)));
        SimpleDateFormat mFormat = new SimpleDateFormat("EEEE", Locale.US);
        dayOfTheWeek = mFormat.format(BDay.getTime());
        return dayOfTheWeek;


text:
Q: Restoring files from the recycle bin in python Is there any to restore files from the recycle bin in python?
Here's the code:
from send2trash import send2trash

file_name = "test.txt"

operation = input("Enter the operation to perform[delete/restore]: ")

if operation == "delete":
    send2trash(file_name)
    print(f"Successfully deleted {file_name}")

else:
    # Code to restore the file from recycle bin.
    pass

Here when I type "restore" in the input() function, I want to restore my deleted file from the recycle bin.
Is there any way to achieve this in python?
It would be great if anyone could help me out.
EDIT:
Thanks for the answer @Kenivia, but I am facing one small issue:
import winshell

r = list(winshell.recycle_bin())  # this lists the original path of all the all items in the recycling bin
file_name = "C:\\test\\Untitled_1.txt" # This file is located in the recycle bin

index = r.index(file_name) # to determine the index of your file

winshell.undelete(r[index].original_filename())

When I run this code, I get an error: ValueError: 'C:\\test\\Untitled_1.txt' is not in list. Can you please help me out?

A: It would depend on your operating system.
Linux
it's as simple as moving it from the trash folder to the original path. The location of the trash folder differs from distro to distro, but this is where it typically is.
There is a command line tool that you can use, or dig through the code to get some ideas.
import subprocess as sp # here subprocess is just used to run the command, you can also use os.system but that is discouraged

sp.run(['mv','/home/USERNAME/.local/share/Trash/files/test.txt', '/ORIGINAL/PATH/')

macOS
On macOS, you do the same thing as you do in Linux, except the trash path is ~/.Trash
import subprocess as sp

sp.run(['mv','~/.Trash/test.txt', '/ORIGINAL/PATH/')

Note that macOS stores information about the files at ~/.Trash/.DS_Store, where Linux stores them at /home/USERNAME/.local/share/Trash/info/. This can be useful if you don't know the original path of the files.
Windows
you have to use winshell. See this article for more details
import winshell

r = list(winshell.recycle_bin())  # this lists the original path of all the all items in the recycling bin
index = r.index("C:\ORIGINAL\PATH\test.txt") # to determine the index of your file

winshell.undelete(r[index].original_filename())

A: Google Colab (you are the root user)
Import the shell utility for Python:
import shutil

Move the file from trash to a selected destination:
shutil.move('/root/.local/share/Trash/files/<deleted-file>', '<destination-path>')


text:
Q: Load style library into WPF Long Question:
I downloaded a style library (Selen.Wpf) via NuGet.
Now I want to use its styles. Frankly, this little task drove me crazy by now.
First approach - Using MergedDictionarys:
Ideally I would add the styles as follows
<Application.Resources>
<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary>
      <BitmapImage x:Key="ImgHelp" UriSource="pack://application:,,,/Resources/Help_32x.png"/>
      <!--Lots of our own stuff goes here too-->
    </ResourceDictionary>
    <ResourceDictionary Source="pack://application:,,,/Selen.Wpf.SystemStyles;component/Styles.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>

Unfortunaly this throws a runtime excpetion at startup (System.Windows.Markup.XamlParseException: "System.Windows.Media.Imaging.BitmapImage" IsFrozen must be set to false). This is not the fault of Selen.Wpf, but also happens if I move the declaration of my own Resources from <Application.Resources>...</Application.Resources> to <ResourceDictionary.MergedDictionarys>...</ResourceDictionary.MergedDictionarys>
The few other questions on SO regarding this problem had no answers, merly workarounds. With no idea how to debug this, I moved on...
Second approach - Using a Workaround:
If I get a XamlParseExpcetion doing it the proper way, then just do the ugly code behind hack, I thought.
I added the following function:
private void LoadSelen()
{
  ResourceDictionary selenDict = new ResourceDictionary()
  {
    Source = new Uri("pack://application:,,,/Selen.Wpf.SystemStyles;component/Styles.xaml")
  };

  App.Current.Resources.MergedDictionaries.Add(selenDict);
}

and called it between InitComponent and Run
[STAThread]
public static void Main()
{
  application.InitializeComponent();
  application.LoadSelen();
  application.Run();
}

But yet again this lead to a XamlParseExcpetion, but this time in DataPanel.xaml - a panel embedded into my MainWindow:
System.Windows.Markup.XamlParseException
HResult=0x80131501
Message = Specifying a value for "System.Windows.Markup.StaticResourceHolder" lead to an excpetion.
Source = PresentationFramework
Stacktrace:
 at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)

Inner Excpetion 1:
FileLoadException: The File or Assembly "System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" or a dependency of it was not found. The found manifestdefinition of the assembly does not match the assembly reference (Excpetion of HRESULT: 0x80131040)

Sorry for poor formating, dont know how to do it better. Translated!
DataPanel.xaml where this Excpetion occurs:
<UserControl x:Class="GUI.DataPanel"
             x:Name="UserControlPanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <DockPanel LastChildFill="True" Background="Transparent">
    <Border  DockPanel.Dock="Top" BorderBrush="DarkGray" BorderThickness="1">
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" />
          <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Label Content="{Binding ElementName=UserControlPanel, Path=HeaderText}" Grid.Column="0" VerticalAlignment="Center"/>
        <ItemsControl ItemsSource="{Binding ElementName=UserControlPanel, Path=Items}" Grid.Column="1">
          <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
              <StackPanel Orientation="Horizontal" FlowDirection="RightToLeft"/>
            </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
        </ItemsControl>
      </Grid>
    </Border>
    <TabControl x:Name="TabControl" ItemContainerStyle="{DynamicResource CollapseSingleTabItem}"/>
  </DockPanel>
</UserControl>

Short Question:
How can use the styles from Selen.Wpf. At this point I pretty much don't care how ugly the answer is. As long as it Compiles & Starts (Never thought I would say this outside the C++ world) I am happy.

A: It looks like that a reference to System.Windows.Interactivity coudn't be resolved.

FileLoadException: The File or Assembly "System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" or a dependency of it was not found. The found manifestdefinition of the assembly does not match the assembly reference (Excpetion of HRESULT: 0x80131040)

As it seems the Selen.Wpf nuget package needs this dependency but doesn't specifiy it in the packages description. (You can see that a reference in the Selen.Wpf.DemoApplication.csproj to it is added)
To resolve this problem you can add a reference to System.Windows.Interactivity by yourself (and use your first solution).


text:
Q: How to read a binary field within a text file I have a fixed width text file that I am using streamreader/readline() to read at the moment.
There's one field that when I open in notepad++ looks like this
[NUL][NUL][NUL][SUB]
Everything else is normal text. I know this field is meant to be 4 characters and represents a count so should look like this '0001'
How can I read it and convert into '0001'

A: I'm not sure what the "SUB" is meant to correspond to - but if it's read as U+0001, you could always use:
for (int i = 0; i < 4; i++) {
    chars[i + index] = (int) chars[i + index] + '0';
}

(Assuming you have a char[] called chars, with the 4 bytes starting at index.)
The first thing to check is whether you actually read the characters properly to start with. It's frankly a bit dodgy to have a "text" file with binary data in to start with, but if it's only bytes 0-9, then in most encodings I'd expect that to correspond to U+0000 to U+0009.


text:
Q: Ansible Tower not finding collections I am new to Ansible and very new to Ansible Tower 3.7.4 with Ansbile 2.9.15. I am trying to do a basic Template that runs an ansible script in a Git repo. Note: if I install ansible on a linux box with python, and ansible-galaxy, I can pull the collections and everything works fine. However, in Ansible Tower, it is not seeing my collections to pull from ansible-galaxy. Here is the error I am getting
ERROR! couldn't resolve module/action 'community.kubernetes.k8s'. This often indicates a misspelling, missing collection, or incorrect module path.

I have a requirements.yml file in the collections directory at the main level of my ansible playbook. This is its contenet
collections:
- name: community.aws
- name: community.kubernetes

the directory structure is
- ansible
  - collections
    - requirements.yml
  - roles
    - openshift
      - tasks
        - main.yml
  - main.yml

Here is the full output when I run the template in Ansible Tower
ansible-playbook 2.9.15
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/var/lib/awx/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible-playbook
  python version = 2.7.5 (default, Aug 13 2020, 02:51:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
Using /etc/ansible/ansible.cfg as config file
SSH password:
host_list declined parsing /tmp/awx_66_8ffiwxxz/tmp32f5fpkw as it did not pass its verify_file() method
Parsed /tmp/awx_66_8ffiwxxz/tmp32f5fpkw inventory source with script plugin
ERROR! couldn't resolve module/action 'community.kubernetes.k8s'. This often indicates a misspelling, missing collection, or incorrect module path.
The error appears to be in '/tmp/awx_66_8ffiwxxz/project/confluent/ansible/roles/openshift/tasks/main.yml': line 17, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
# Ensure namespace is created
- name: Create Confluent namespace / project
  ^ here

Any idea what I am doing wrong?


text:
Q: Creating a Heatmap using ggmap with the color scale being based on a numeric variable (not count of observation) I am using ggmap to plot a heatmap of length of NYC taxi trip durations. I would like to use the trip duration as my color scale. I have a large amount of observations that have a pickup lat/long that I am able to plot easily on a map of NYC. Trip duration is in seconds and is available for each observation.
However, I am trying to figure out the best way to utilize something like stat_density2d to plot contours around certain areas that have higher trip duration (maybe could use an average in a certain area?). I am also grouping my plots by month.
How can I accomplish this? My below code plots this but I believe my scale is in terms of # observations and not the numeric trip_duration variable.
library(ggmap)
nyc_map <- get_map(location = c(lon = median(nyc_train2$pickup_longitude), lat = median(nyc_train2$pickup_latitude)), maptype = "terrain", zoom = 13)

pickup_trip_duration_plot <- ggmap(nyc_map) +
                  geom_density2d(data = nyc_train2, aes(x = pickup_longitude, y = pickup_latitude, fill = trip_duration), size = 0.3) +
                  stat_density2d(data = nyc_train2, aes(x = pickup_longitude, y = pickup_latitude, fill = ..level.., alpha = ..level..), size = 0.01, bins = 16, geom = "polygon") +
                  facet_wrap(~ pickup_month_name, ncol = 3) +
                  scale_fill_gradient(low = "yellow", high = "red") +
                  ggtitle("Trip Duration Heatmap by Month for Pickup Locations") +
                  scale_alpha(range = c(0, 0.3), guide = FALSE)
pickup_trip_duration_plot

# I believe this may have something to do with why I am having plotting issues
# with a numeric value?
Warning message:
Ignoring unknown aesthetics: fill


text:
Q: How can I set proofing language to a language different than my keyboard layout in Word 2016? Well, I'm writing a Word document in French and want the proofing/spelling language to be the French but I actually wanna type using the English keyboard layout, so when I try to use the english keyboard layout the proofing/spelling language also becomes English!! How can I fix that?

A: I think this the wrong site, if someone could move it to the right one it would be beneficial. Anyway, I figured out the solution which is to add a language to the computer (Proofing language) and inside this language add the input layout that you want.


text:
Q: Conditionally Importing header files in Universal ios app in my Universal ios app I have two header files like FrameRates_iPad.h and FrameRates_iPhone.h which I need to import into viewcontroller class depending on the current device the app is building for, please help me in achieving this.

A: I like to use 1 controller for my universal apps. There's no need to use FrameRates_iPad.h and FrameRates_iPhone.h and write the same code twice! Here is how I use 1 controller for both iPad and iPhone specific code.
You can check out my post on how I use Macros.
One way to check what device you are running code on is to use UI_USER_INTERFACE_IDIOM(). The UI_USER_INTERFACE_IDIOM returns the interface idiom supported by the current device and is available in iOS 3.2 +.
#define IDIOM    UI_USER_INTERFACE_IDIOM()
#define IPAD     UIUserInterfaceIdiomPad   /* iPad, obviously               */
#define IPHONE   UIUserInterfaceIdiomPhone /* iPhone, to include iPod touch */

Example of using the interface idiom to determine what code to run:
This code says that if the device is an iPad, then it can autorotate, otherwise, if the device is an iPhone or equivalent, the only orientation supported will be Portrait.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if ( IDIOM == IPAD ) {
        return YES;
    }else{
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    return YES;
}

Another example on when to use this:
Set a specific size for a button, or any other object that has a frame property.
CGRect frame;
if ( IDIOM == IPAD ) {
    frame = CGRectMake(tableView.frame.size.width-105,5,30,30);
} else {
    frame = CGRectMake(tableView.frame.size.width-60,5,30,30);
}

UIButton *aButton = [[UIButton alloc] initWithFrame: frame ];

A: You can set preprocessor macro IS_IPAD = 1 for your iPad_target in xcode build settings and then:
#ifdef IS_IPAD
#import "FrameRates_iPad.h"
#endif

#ifndef IS_IPAD
#import "FrameRates_iPhone.h"
#endif


text:
Q: A-Rows in Explain Plan I'm trying to understand, why the number of rows the A-rows column of the explain plan (query executed with the hint /*+ GATHER_PLAN_STATISTICS */)
gives me a result that is very far from being real.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                                       | Name                        | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  | Writes |  OMem |  1Mem | Used-Mem |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 163 |                    TABLE ACCESS FULL            | LU_MY_TABLE                 |  29568 |   1017 |     31M|00:00:03.51 |    1094K|      0 |      0 |       |       |          |

It seems that there is a table access full on LU_MY_TABLE, but if i do
a simple select count(*) from LU_MY_TABLE the result is 10169...
Could some one help me in understanding A-Rows?
Thanks and regards.
Marco

A: A-Rows is the total number of rows produced by all starts of that operation.  But E-Rows is an estimate of the number of rows produced by a single start of an operation.  Your previous comment is correct - you probably want to divide A-Rows by Starts to determine if the cardinality estimate is good.
In your example, Oracle estimated 1017 rows per operation run.  But the actual rows per operation run was 31M (A-Rows) / 29568 (Starts) = 1048 (actual rows per start).  Those numbers are very close.
(Although I don't understand why they are so different than the actual number of rows in the table, 10169.  There is no * next to the Id in the execution plan so there is no obvious filtering on that table.  But maybe some other operation is limiting results.  Either way, this is enough information to imply that Oracle is estimating this operation well so maybe the problem is with another step.)
Test Schema
Create a table with 10 rows, then run a query that does a count on the table 10 times.
drop table test1 purge;
create table test1(a number);
insert into test1 select level from dual connect by level <= 10;
begin
    dbms_stats.gather_table_stats(user, 'TEST1');
end;
/

select /*+ gather_plan_statistics */ (select count(*) from test1 where a > b)
from (select - level b from dual connect by level <= 10);

select * from table(dbms_xplan.display_cursor(format => 'allstats last'));

Results:
The A-Rows in Id 2 is 100.  This is 10 rows per full table scan multiplied by 10 runs.
(The plan below was slightly modified to fit the screen.)
Plan hash value: 2073232735

---------------------------------------------------------------------------------------
| Id  | Operation                     | Name  | Starts | E-Rows | A-Rows |   A-Time   |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |       |      1 |        |     10 |00:00:00.01 |
|   1 |  SORT AGGREGATE               |       |     10 |      1 |     10 |00:00:00.01 |
|*  2 |   TABLE ACCESS FULL           | TEST1 |     10 |      1 |    100 |00:00:00.01 |
|   3 |  VIEW                         |       |      1 |      1 |     10 |00:00:00.01 |
|   4 |   CONNECT BY WITHOUT FILTERING|       |      1 |        |     10 |00:00:00.01 |
|   5 |    FAST DUAL                  |       |      1 |      1 |      1 |00:00:00.01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("A">:B1)


text:
Q: Remove identical row from the data frame-Pandas I am trying to remove identical row that matches between two data frames . how ever, what ever method I am trying the identical rows in same data frame also gets dropped. But i want to retain the identical rows from same data frame and drop the ones which only matches with other data frame.
Dataframe 1:

 ID             PID         PDate      Amount
AAAAAA          NN11        20210525    386
BBBBBB          A12         20210525    3300
BBBBBB          A12         20210525    3300
CCCCCC          B11         20210625    1000

Dataframe 2:

 ID             PID         PDate      Amount
AAAAAA          NN11        20210525    386

Expected output:
 ID             PID         PDate      Amount
BBBBBB          A12         20210525    3300
BBBBBB          A12         20210525    3300
CCCCCC          B11         20210625    1000

I tried concatenating and drop duplicates, merge , reseting index. All these drops off ID BBBBBB as well because the rows with this ID are identical. I want to retain them .
Can anyone help me with this?

A: Merge your two dataframes by union of the keys. Use indicator=True parameter to keep the information on the source of each row. If the value is both drop the row.
>>> pd.merge(df1, df2, how="outer", indicator=True) \
      .query("_merge != 'both'") \
      .drop(columns="_merge")

       ID  PID     PDate  Amount
1  BBBBBB  A12  20210525    3300
2  BBBBBB  A12  20210525    3300
3  CCCCCC  B11  20210625    1000

A: Try isin
df1[~df1.isin(df2).all(1)]

Output
    ID      PID PDate       Amount
1   BBBBBB  A12 20210525    3300
2   BBBBBB  A12 20210525    3300
3   CCCCCC  B11 20210625    1000


text:
Q: Plotting a sinus function I try to plot a sinus function. But it throws an error" x and y must have same first dimension, but have shapes (1,) and (51,)" I can't understand they have same dimension. Why do I get this error? Thanks in advance.
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

from math import pi
from numpy import *

# spatial domain
xmin = 0
xmax = 1
n = 50 # num of grid points

# x grid of n points
x = np.linspace(xmin, xmax, n+1);

k=2

def f1(x):
    return np.sin(2*pi*k*x)

plt.plot(f1,x)

A: Change the bottom of your program to be semantically correct:
plt.plot(f1(x),x)
plt.show()

f1 is a function object; f1(x) is a vector of return values.