text:
Q: getting file not found error in ios Hi I am new to iOS development.
Here is my problem.
I am given a mac machine with 10.6.X and Xcode for the same.
I am given a pre-written project for iPhone.
I wanted to run the project on my iPhone so I had to upgrade my mac and Xcode to 10.7.x and the xcode for the same. I had to do this as my iPhone was running on iOS 5.1.
So my problem is that before upgrading the project was getting compiled and running properly on simulator but now after upgrade I am getting the following error
 /usr/include/objc/objc-class.h file not found

I googled a lot, but all the search if pointing to the same link as given in this link
This link did not work for me as when I try to change the import statement it leads to more 5 to 6 errors.

A: Not sure if that will help, but sometimes XCode messes up the cached data when changing the imported .h files. Try to delete the project derived information, e.g. organizer->projects->Derived Data. Then clean the project and rebuild.
Also, the solution that you reference is system specific, which may explain why it doesn't work for you. In particular:
#import </usr/include/objc/objc-class.h>

Notice the /usr/ at the beginning of the import. This means that the file will be loaded from an absolute path starting from the root folder /, which may be different on Mac or various flavors of Linux. Try to find where exactly the file objc-class.h is located in your system and either add that path to the Header Search Path (XCode Targets -> Build Settings, section Search Paths) or add the import with location specific for your system.

A: Replace these :
 #import </usr/include/objc/objc-class.h>

with :
#import <objc/objc-class.h>

A: After xcode 4.6 this breaks again. I just fixed this like this :
cd /usr/include/
sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/usr/include/objc .

Now it works like a charm

A: Got this issue with Xcode 5. I had to remove and re-add the library to my project in order for it to work. I deleted (moved to trash) and then re-added.

A: You just have to replace this #import /usr/include/objc/objc-class.h with only #import folderName/objcClassName.h


text: Q: Nightmare debugging UNIX program in windows I've a stripped binary file in UNIX ELF32-i386 format , I don't have its source, I need to debug it and perform dynamic analysis on it,its a study project. I've successfully disassembled it using IDA PRO free and was able to run it on Portable Ubuntu program. but I cannot find a way to debug it step by step on Windows 7 (32-bit) and Intel processor. I've tried MinGw gdb but its not running the program gives error 193. If anybody could please suggest a free solution to this problem, that would be of help. Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel found unreachable content I have working on a piece where I give option to user for uploading and later download .xls(MS 2003) and .xlsx(MS 2007) files.
No issues I find while uploading, but while downloading the content, I get below mentioned dialog box while opening the downloaded .xlsx.
Excel found unreachable content.Do you want to recover the contents of this workbook? If you trust the source of this workook, click 'Yes'.
I have set right MIME type for both MS excel types.
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")     - for .xlsx
AND
response.setContentType("application/vnd.ms-excel")   - for .xls
then I used mentioned below snippet to set header.
response.setHeader("Content-disposition", "attachment;filename=" +fileName)

Any suggestions/corrections you think I need to go for??


text:
Q: Overpass-API request does not get executed completely : particular results lead to mistakes I have some issues with the following request via overpass-turbo.eu. Only the last expression works. In other words, only the very last expression will be performed and all the others are ignored.
[out:csv(::id,::type,::lon,::lat,amenity,name,"addr:postcode","addr:city","addr:street","addr:housenumber","contact:website",website,"contact:email")]
[timeout:600];
rel[boundary=administrative][admin_level=6][name="München"] -> .city;
(nwr[amenity=hospital][name](around.city:2000);
nwr[amenity=school][name](around.city:2000););
nwr[amenity=childcare][name](around.city:2000);
nwr[amenity=kindergarten][name](around.city:2000);
nwr[amenity=nursing_home][name](around.city:2000);
nwr[amenity=college][name](around.city:2000);

out center;

In fact only this term will be executed:
nwr[amenity=college][name](around.city:2000);

This is given back:
@id @type   @lon    @lat    amenity name    addr:postcode   addr:city   addr:street addr:housenumber    contact:website website contact:email
2354666181  node    11.5557656  48.1274889  college EAM-Europa Akademie München - School Of International Business  80337   München Adlzreiterstraße    6
3324407853  node    11.5551400  48.1264588  college Akademie Deutsche POP   80337   München Adlzreiterstraße    18a     http://www.deutsche-pop.de/standort/muenchen
3324407854  node    11.5713030  48.1285751  college Akademie Deutsche POP   80469   München Klenzestraße    67      http://www.deutsche-pop.de/standort/muenchen
4379246720  node    11.5629942  48.1469822  college Hochschule für Politik München  80333   München Richard-Wagner-Straße   1
4448465264  node    11.4461165  48.1488143  college DEKRA Akademie GmbH                     https://www.dekra-akademie.de/de/muenchen/
4984543723  node    11.5998193  48.1353510  college Münchner Volkshochschule – Einstein 28  81675   München Einsteinstraße  28      https://www.mvhs.de/ueber-uns/standorte/gasteig-einstein-28-stadtbereich-mitte/
5542020160  node    11.6368555  48.0790856  college Fakultät für Betriebswirtschaftf
5542020161  node    11.6348063  48.0806016  college Fakultät für Betriebswirtschaft
5542020162  node    11.6336959  48.0810352  college Fakultät für Betriebswirtschaft
18940172    way 11.4648639  48.1127381  college Haus A Genzentrum der LMU und Institut für Biochemie    81377   München Feodor-Lynen-Straße 25      https://www.genzentrum.lmu.de/
19329687    way 11.5817581  48.1500346  college Herzogliches Georgianum 80539   München Professor-Huber-Platz   1       http://www.herzoglichesgeorgianum.de/Herzogliches_Georgianum/Home.html
27959435    way 11.5929977  48.1424114  college Bayerische EliteAkademie    80538   München Prinzregentenstraße 7       http://www.eliteakademie.de
44615795    way 11.5806579  48.1550310  college Priesterseminar St. Johannes der Täufer                 http://www.priesterseminar-muenchen.de/
166433609   way 11.5888108  48.1304498  college Collegium Carolinum
867729755   way 11.6027411  48.1324959  college Katholische Stiftungshochschule München                     https://www.ksh-muenchen.de

Well I wonder if there must be missing something in the request.

A: The following request works for me. I basically only changed the position of the brackets.
[out:csv(::id,::type,::lon,::lat,amenity,name,"addr:postcode","addr:city","addr:street","addr:housenumber","contact:website",website,"contact:email")]
    [timeout:600];
    rel[boundary=administrative][admin_level=6][name="München"] -> .city;
    (
    nwr[amenity=hospital][name](around.city:200);
    nwr[amenity=school][name](around.city:200);
    nwr[amenity=childcare][name](around.city:200);
    nwr[amenity=kindergarten][name](around.city:200);
    nwr[amenity=nursing_home][name](around.city:200);
    nwr[amenity=college][name](around.city:200);
    );

    out center;


text:
Q: Checking condition in upper level tag in xslt v2.0 I have this requirement that I only need to populate the <Group> tag under the
, if the <Group> tag under the <Data> is not present. I can't get the correct output that I want. For example:
INPUT
<Record>
<Data>
    <ID>1234DFD57</ID>
    <Group>
        <abc-KD>243fds</abc-KD>
    </Group>

        <ID>33-2311</ID>
        <Group>
            <abc-KD>NORM</abc-KD>
        </Group>
        <Date>2017-03-25</Date>

    <Date>2017-03-25</Date>
</Data>
</Record>

EXPECTED OUTPUT
<Record>
<Data>
    <ID>1234DFD57</ID>
    <Group>
        <abc-KD>243fds</abc-KD>
    </Group>

        <ID>33-2311</ID>
        <Date>2017-03-25</Date>

    <Date>2017-03-25</Date>
</Data>
</Record>

XSLT:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="Section">
    <xsl:copy>
        <xsl:copy-of select="ID"/>
        <xsl:if test="normalize-space(string(../Group)) = ''">
            <xsl:copy-of select="Group"/>
        </xsl:if>
        <xsl:copy-of select="Date"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Your feedback is highly appreciated.
Regards,

A: Your current stylesheet does the work. More efficient way would be:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Section[normalize-space(parent::Data/Group) != '']/Group"/>
</xsl:stylesheet>

The identity transform template is the one that copies every node in the xml, while recursively processing them in document order, as it is.
The second template matches the Group elements with the desired condition and does nothing for it, hence omitting them in the output.
The x-path in the @match does the trick:
Section[normalize-space(parent::Data/Group) != '']/Group
It matches those Section/Group elements under Data whose Group doesn't exist or has null value(excluding space characters).


text:
Q: QFileDialog under OSX dumps many errors to console Trying to use QFileDialog under OSX 10.6.8, Qt 4.7:
QFileDialog *dialog = new QFileDialog(0,tr("Load Band Recordings"),qbh,tr("Wave Files (*.wav)"));
dialog->setFileMode(QFileDialog::ExistingFiles);

if (dialog->exec())
{
QStringList fileNames;
    fileNames = dialog->selectedFiles();
    qs = fileNames[0];
}
else
{
    return(0);
}

It works, but many errors are dumped to the console:
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: _CGSFindSharedWindow: WID -1
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorFailure: Set a breakpoint @ CGErrorBreakpoint() to catch errors as they are logged.
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: CGSDeviceCreate: Invalid window
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: Failed to create window context device
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGWindowContextCreate: failed to create context delegate.
2012-05-13 11:03:41.445 SdrDx[18982:903] _initWithWindowNumber: error creating graphics ctxt object for ctxt:0x31197, window:0xffffffff
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextSaveGState: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextTranslateCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextScaleCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextAddRect: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: doClip: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextRestoreGState: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: _CGSFindSharedWindow: WID -1
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: CGSDeviceCreate: Invalid window
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: Failed to create window context device
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGWindowContextCreate: failed to create context delegate.
2012-05-13 11:03:41.533 SdrDx[18982:903] _initWithWindowNumber: error creating graphics ctxt object for ctxt:0x31197, window:0xffffffff
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextSaveGState: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextTranslateCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextScaleCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextAddRect: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: doClip: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextRestoreGState: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: _CGSFindSharedWindow: WID -1
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: CGSDeviceCreate: Invalid window
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: Failed to create window context device
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGWindowContextCreate: failed to create context delegate.
2012-05-13 11:03:41.576 SdrDx[18982:903] _initWithWindowNumber: error creating graphics ctxt object for ctxt:0x31197, window:0xffffffff
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextSaveGState: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextTranslateCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextScaleCTM: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: CGContextAddRect: invalid context 0x0
Sun May 13 11:03:41 machine-mac-pro.local SdrDx[18982] <Error>: doClip: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextRestoreGState: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: _CGSFindSharedWindow: WID -1
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: CGSDeviceCreate: Invalid window
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: Failed to create window context device
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGWindowContextCreate: failed to create context delegate.
2012-05-13 11:03:41.616 SdrDx[18982:903] _initWithWindowNumber: error creating graphics ctxt object for ctxt:0x31197, window:0xffffffff
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextSaveGState: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextTranslateCTM: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextScaleCTM: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextAddRect: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: doClip: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextRestoreGState: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: _CGSFindSharedWindow: WID -1
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: kCGErrorIllegalArgument: CGSDeviceCreate: Invalid window
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: Failed to create window context device
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGWindowContextCreate: failed to create context delegate.
2012-05-13 11:03:41.638 SdrDx[18982:903] _initWithWindowNumber: error creating graphics ctxt object for ctxt:0x31197, window:0xffffffff
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextSaveGState: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextTranslateCTM: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextScaleCTM: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextAddRect: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: doClip: invalid context 0x0
Sun May 13 11:03:41 -mac-pro.local SdrDx[18982] <Error>: CGContextRestoreGState: invalid context 0x0

The docs say provide the parent widget; doesn't seem to matter.
Anyone have any idea how to CORRECTLY use the Qt 4.7 QFileDialog class under OSX so that it doesn't vomit errors to the console?
Btw, both the static and the constructed versions of the file and directory dialogs do this. I've asked over on the Qt forums, but received no answer. Hoping someone here has figured it out.


text:
Q: In a Javascript ternary operator, can you loop through an array? I have a ternary operator which sees if values in an array are the same as my targeted value. Is there an easy way to do what I'm trying to do to save me a lot of time and hard coding in array indexes. Is there a way to not use a lot of or operator?
I essentially have a long list of array indexes to compare against like this:
(price[0] === this.props.result.cost ||
 price[1] === this.props.result.cost ||
 price[2] === this.props.result.cost ||
 price[3] === this.props.result.cost ||
 price[4] === this.props.result.cost )
? this
: that

I feel like there is something basic that I'm missing or some other way completely to make this an easier task to do.

A: If you are checking for primitives (integers, strings) in your array, then Array.prototype.includes is the simplest choice. It also successfully determines the presence of NaN in the array:

const price = [1, 2, 'str', 3, NaN, {'foo': 'bar'}];

//true
console.log(price.includes(3));
//true
console.log(price.includes('str'));
//true
console.log(price.includes(NaN));
//false
console.log(price.includes({'foo': 'bar'}));

In the above snippet all except the check for the object returns true, in case of object the reference is not the same so it returns false.

You can use Array.prototype.some for the test checking the presence of a particular attribute of an object:

const price = [1, 2, 'str', 3, 4, NaN, {'foo':'bar'}, 5];

let cost = 5;
//true
console.log(price.some((obj) => obj === cost));

//for checking if there is an object in the arrray with the attribute value 'foo' which has the value 'bar'

cost = 'bar';
//true
console.log(price.some((obj) => obj.foo == cost));

Or a ES6 Set can be used for constant time lookup, if the input array is big enough:

 const price = [1, 2, 3, 4, 5];

const cost = 5;

console.log(new Set(price).has(cost));


text:
Q: Stanford NLP: punctuation error identification I've just started working with Stanford NLP core.
My problem is that many of the sentences in my corpus do not end with a period (full stop).
Frankly, a bit of string parsing with regular expressions could probably fix the issue, but with some degree of error.
I am curious as to whether Stanford NLP can identify missing periods.

A: It looks like edu.stanfordn.nlp.process.DocumentPreprocessor can be used to split paragraphs into sentences, though I am not sure how well it works without proper punctuation.
There are many other sentence-level tokenizers which you can use to preprocess your corpus , check out NLTK's nltk.tokenize.punkt module which uses a ML algorithm to make sentence tokens in the absence of good  capitalization/punctuation.


text:
Q: Handle variables with nested function in r f1 <- function(x){
pass[4]+x
}
f2 <- function(x,y){
pass=y
f1(x)
}
f2(x=3,y=c(1,2,3,4,5))

The pass variable cannot be passes to f1 function; can anyone help me to explain why? And how can I do with the case?

A: pass is declared within the scope of f2, so it is only available within the scope of f1. if you want to reference it in f1, you must pass it to f1 as an argument.
f1 <- function(x, pass) {
    pass[4]+x
}
f2 <- function(x,y) {
    pass=y
    f1(x, pass)
}

A: check environment objects in the function scope
f1 <- function(x){
    print('f1: ')
    print(ls(envir = environment()) )
    # pass[4]+x
}
f2 <- function(x,y){
  pass=y
  print('f2: ')
  print(ls(envir = environment()) )
  f1(x)
}
f2(x=3,y=c(1,2,3,4,5))

try:
f2 <- function(x,y){
  f1 <- function(x){
    pass[4]+x
  }
  pass=y
  f1(x)
}


text:
Q: Python constraint inverse I am looking for a solution to use the numbers 2,3,4,5 for 10 times to get an exact sum of 40; so I have written the following code
from constraint import Problem, InSetConstraint, ExactSumConstraint
problem = Problem()
problem.addVariables(range(10), range(10))
problem.addConstraint(InSetConstraint([2,3,4,5]))
problem.addConstraint(ExactSumConstraint(40))
solutions = problem.getSolutions()
print(solutions)

which works well, but what I want is the other way around to limit the result meaning my variables should be [2,3,4,5] & they have a value equals to how many times each is used, I am unable to figure out how it works I have tried the following
from constraint import Problem, ExactSumConstraint
problem = Problem()
problem.addVariables([2,3,4,5], [1,1,1,1])
problem.addConstraint(ExactSumConstraint(10))
solutions = problem.getSolutions()
print(solutions)

How can I get it to multiply the key by value & where to add the constraint of 40 here?

A: I have found the solution, using the following code:
from constraint import Problem, ExactSumConstraint
problem = Problem()
MaximumSum = 10
MaxMultiplicationSum = 40
Variables = ("a", "b", "c", "d")
realKeys = {'a': 2, 'b': 3, 'c': 4, 'd': 5}
for Variable in Variables:
    problem.addVariable(Variable, range(1, MaximumSum - len(Variables)))
problem.addConstraint(ExactSumConstraint(MaximumSum), Variables)
problem.addConstraint(lambda a,b,c,d: 2 * a + 3 * b + 4 * c + 5 * d == MaxMultiplicationSum)
solutions = problem.getSolutions()
for solution in solutions:
    print(dict((realKeys[key], value) for (key, value) in solution.items()))


text:
Q: Reverting back pvresize command for a partition on a single disk While I was trying to extend my lvm for the / filesystem I made a mistake. And I am not sure if it is a mistake as well.
Instead of creating new partition and adding it to pv,vg, and expanding the lv afterwards, I started with the command "pvresize" for the current partition which is being served for the root file system.
The command that i executed was:
[root@...]pvresize /dev/sda3 --setphysicalvolumesize 40G

Then I tried to extend the vg with the following:
 [root@...]# vgextend titan /dev/sda3
  /dev/sdc: open failed: No medium found
  WARNING: Device /dev/sda3 has size of 58351616 sectors which is smaller than corresponding PV size of 83884032 sectors. Was device resized?
  WARNING: One or more devices used as PVs in VG vg have changed sizes.
  Physical volume '/dev/sda3' is already in volume group 'vg'
  Unable to add physical volume '/dev/sda3' to volume group 'vg'
  /dev/sda3: physical volume not initialized.

Just after seeing the output above I realized that I had to create another partition on the single disk that I am operating on and add it to the pv group, extend the volume group then grow my logical volume for the root file system.
Question: How can I safely revert back the physical volume size to the point where I started in order to make this WARNING about size change disappear?
Here you can find the info that I think you would need for further guidance to the solution:
[root@...]# lsblk -b
NAME           MAJ:MIN RM          SIZE RO TYPE MOUNTPOINT
sda              8:0    0  480103981056  0 disk
├─sda1           8:1    0     629145600  0 part /boot/efi
├─sda2           8:2    0    1073741824  0 part /boot
└─sda3           8:3    0   29876027392  0 part
  ├─lv-root 253:0    0   21474836480  0 lvm  /
  └─lv-swap 253:1    0    8396996608  0 lvm  [SWAP]

[root@t...]# pvdisplay -m -v
    WARNING: Device /dev/sda3 has size of 58351616 sectors which is smaller than corresponding PV size of 83884032 sectors. Was device resized?
  WARNING: One or more devices used as PVs in VG titan have changed sizes.
  --- Physical volume ---
  PV Name               /dev/sda3
  VG Name               vg
  PV Size               <40.00 GiB / not usable 3.00 MiB
  Allocatable           yes
  PE Size               4.00 MiB
  Total PE              10239
  Free PE               3117
  Allocated PE          7122
  PV UUID               FgC2QI-pRpK-LZNS-di9w-Jc1d-XGXZ-2QxZI2

  --- Physical Segments ---
  Physical extent 0 to 5119:
    Logical volume  /dev/lv/root
    Logical extents 0 to 5119
  Physical extent 5120 to 7121:
    Logical volume  /dev/lv/swap
    Logical extents 0 to 2001
  Physical extent 7122 to 10238:
    FREE

A: After spending time on internet and having no clue about what I am going to do, i just noticed the error itself and taught that I can use the exact sector size mentioned over there. So I executed the command:
[root@...] pvresize --setphysicalvolumesize 58351616s

And it worked flawless.
[root@t...]# pvdisplay
   --- Physical volume ---
  PV Name               /dev/sda3
  VG Name               vg
  PV Size               27.82 GiB / not usable 3.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              7122
  Free PE               0
  Allocated PE          7122
  PV UUID               FgC2QI-pRpK-LZNS-di9w-Jc1d-XGXZ-2QxZI2

  --- Physical volume ---
  PV Name               /dev/sda4
  VG Name               vg
  PV Size               20.00 GiB / not usable 4.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              5119
  Free PE               0
  Allocated PE          5119
  PV UUID               n5CdvZ-0s9A-iZoz-A2i7-icF9-Wv42-CsL3s9


text:
Q: How to show a style at the start of the Style Gallery in Word 2013 I have a query wrt to getting the styles in word to show in the style gallery.
I have created a style (Table Heading Cond) that i use often, and i would like it to show in the first row of the styles gallery -- next to the heading styles. presently, it shows right at the bottom of the gallery.

Can you please provide me guidance on how i can accomplish this?
I have tried this via 'Manage Styles' but im not able to connect the dots.

A: You're so very close with the 'Manage Styles' screen:
From where you are on the screenshot.

*

*Highlight the style

*Click 'Show'

*Click 'Assign Value...' and change it to 1.

*Click OK to close the Window.

*Once it appears in the Styles window (Ctrl+Alt+Shift+S, or click the pop-out icon under the gallery if not showing), right-click it and select 'Add to Quick Style Gallery'.

*You're done!


text:
Q: Shifting a PySpark dataframe column by a variable value in another column I have a PySpark dataframe that looks like this

Date
Value
Shift_Index

2021/02/11
50.12
0

2021/02/12
72.30
4

2021/02/15
81.87
1

2021/02/16
90.12
2

2021/02/17
91.31
1

2021/02/18
81.23
2

2021/02/19
73.45
1

2021/02/22
87.17
0

I want to lead the offset (On the basis of the values in the Shift_Index column here) which I have to pass depends on a particular Column of type Integer.
Can we somehow use an offset value that depends on the column value in lead/lag function in spark SQL ?
I wanted somewhat like this, which works fine in SQL server, but unfortunately throws exception in Spark SQL.
Create table test_table(ID int identity(1,1), Value float, shift_col int, New_Value float)

SELECT Value, shift_col,
ISNULL(LEAD(Value, shift_col) OVER(ORDER BY ID ASC), Value) AS New_Value
FROM test_table

The final result that I need looks something similar to this :

Date
Value
Shift_Index
New_Value

2021/02/11
50.12
0
50.12

2021/02/12
72.30
4
81.23

2021/02/15
81.87
1
90.12

2021/02/16
90.12
2
81.23

2021/02/17
91.31
1
81.23

2021/02/18
81.23
2
87.17

2021/02/19
73.45
1
87.17

2021/02/22
87.17
0
87.17

The following exceptions are encountered

*

*Py4JJavaError: An error occurred while calling o77.sql.

*: org.apache.spark.sql.AnalysisException: cannot resolve 'lead(sample_data_temp.shift_col, NULL)' due to data type mismatch: Offset expression 'shift_col#2835' must be a literal

Any help will be really appreciated.
Thanks in advance.

A: You could do so with a window and lead. If you have very spread out values for Shift_index you could do a select distinct to determine which shifts you need instead of everything up to the max shift.
Ideally you have something to partition your window by otherwise this can be very heavy for large datasets. Spark provides a warning:
WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
Edit: solution without join, still not partitioning means this doesn't parallelize well.
from pyspark.sql import functions as f
from pyspark.sql.window import Window

w = Window().orderBy(f.col('Date'))

max_shift = df.agg(f.max('Shift_index')).collect()[0][0]

for shift in range(1, max_shift+1):
    df = df.withColumn('Value' + str(shift), f.lead(f.col('Value'), shift).over(w))

case_shift = 'CASE Shift_index WHEN 0 THEN Value ' + ' '.join([f'WHEN {i} THEN Value{i}' for i in range(1, max_shift + 1)]) + ' ELSE NULL END'

df = df.select(
    f.col('Date'),
    f.col('Shift_index'),
    f.col('Value'),
    f.expr(case_shift).alias('New_Value')
)

df.show()

+----------+-----+-----------+---------+
|      Date|Value|Shift_index|New_Value|
+----------+-----+-----------+---------+
|2021/02/11|50.12|          0|    50.12|
|2021/02/12| 72.3|          4|    81.23|
|2021/02/15|81.87|          1|    90.12|
|2021/02/16|90.12|          2|    81.23|
|2021/02/17|91.31|          1|    81.23|
|2021/02/18|81.23|          2|    87.17|
|2021/02/19|73.45|          1|    87.17|
|2021/02/22|87.17|          0|    87.17|
+----------+-----+-----------+---------+


text:
Q: Google Drive, auto delete files older than 7 days in specific folder I'm using Google drive to store my daily made backup from my linux machine.
But i need a script that auto delete's the files in a specific folder after 7 days.
So that there are 7 backups in the folder.
The file that get's backup is called world-$(date +%d-%m-%Y).tar.gz
it replaces the %d %m and %Y with the day month and year it created the backup.
so let's say it created one today it would be called world-14-09-2018.tar.gz
it get's stored inside a folder called backups
Is there any way to have it auto delete the files so not store the inside the trash but delete's them completely after 7 days.
I'm not really familair with those kind of scripts. So if anyone could help me that would be really awesome.

A: You'll want to use the REST API for Google Drive. There are official client libraries for several languages, listed here
Authenticate your account via OAuth2. Depending on the client library you use, there are different tools to do this. I'm most familiar with the Python SDK, and I use Google's oauth2client. The run_flow() command is a simple way to get an OAuth2 refresh token that you can then use to authenticate API calls. Here's the full documentation for authenticating to Google Drive via OAuth2.
Once you're authenticated, you can call the files list endpoint. By default, this will list all files in your my drive. You can limit the search to just those files so you don't have to iterate through all your files each time using a search query. If you have more backups than can fit on a single page (it doesn't seem like it, esp. with the max pageSize of 1000), you will have to paginate your calls.
You can then filter your results by either the filename (as you indicated) or by the createdTime parameter in files.list in your code. Make sure to include createdTime in your fields, by setting the fields parameter to a comma-separated list of parameters, ie "files(id,createdTime,name,mimeType)" or, simply, "*" to get every field. Get a list of all files older than 7 days, then call files.delete. You can then run this script on a cron job every night, however you want to deploy it.
Alternatively, you could use the unofficial Drive command line tool, which will take care of a lot of this for you.


text:
Q: APC 1500 - F01 Code - no battery overload I have an APC 1500 - About a year ago, I could hear the battery back up kick in and a message would say that I was now on battery back up. There was/is no power failure and no reason for the battery to kick in. This happens about 5 times a week.
I only have a Mac Pro, 2 monitors on battery back up and a G-Drive on surge protection.
Starting a few days ago, the APS 1500 just started to have an F01 failure kicking the Mac & monitors off.  The alarm sounds.  When I go to reset, everything works fine.
The battery shows 100%.  I am using about 345 watts and the system is at 38% capacity.  It also shows that the battery will last about 13 minutes with that power.  Plenty of time to shut down normally if there is a power failure.  I can not figure out what is wrong.  There is no battery overload. Could my APC 1500 be going bad?

A: Same Problem, Brand new Batteries, (nothing wrong with one year old batteries) the Dealer says if not the batteries ,some charger problem.
My honest opinion, APC the company, has out lived its useful life. There solution is to buy a new UPS unit.


text:
Q: Why does my controller keep expecting to retrieve data even though I cleared out the database I am making a rails app, using postgresql as the database, where you can connect with users and message them from their posts. My seeds file creates 10 test users and I was checking out the functionality to message other users but ran out of users to test on so I hopped on the rails console and cleared out the conversations and messages table so I could delete all relations in the database but ever since then I keep getting this error:
    ActiveRecord::RecordNotFound in PagesController#index
    Couldn't find all Private::Conversations with 'id': (14, 2, 3, 5, 6, 8, 9,
    10, 11, 1) (found 3 results, but was looking for 10).

This is the code in my PagesController index action:
def index
    @hobby_posts = Post.by_branch('hobby').limit(8)
    @study_posts = Post.by_branch('study').limit(8)
    @team_posts  = Post.by_branch('team').limit(8)
  end

Why does this error keep popping up?
I have tried to completely drop the database, recreate the database, re-run migrations but that doesn't seem to clear out the conversations
this is the code in my ApplicationController:
def opened_conversations_windows
    if user_signed_in?
      session[:private_conversations] ||= []
      @private_conversations_windows = Private::Conversation.includes(:recipient, :messages)
                                        .find(session[:private_conversations])
    else
      @private_conversations_windows = []
    end
  end

the code seems to "work" when I change the if line to
if (user_signed_in? && @private_conversations_windows)

but when I do this and create a new chat with a user the creation of the new chat relation hits the database but the chat window doesn't show up.
Update:
class Private::ConversationsController < ApplicationController

  def create
    recipient_id = Post.find(params[:post_id]).user.id
    @conversation = Private::Conversation.new(sender_id: current_user.id,
                                             recipient_id: recipient_id)
    if @conversation.save
      Private::Message.create(user_id: current_user.id,
                              conversation_id: @conversation.id,
                              body: params[:message_body])

      add_to_conversations unless already_added?

      respond_to do |format|
        format.js {render partial: 'posts/show/contact_user/message_form/success'}
      end
    else
      respond_to do |format|
        format.js {render partial: 'posts/show/contact_user/message_form/fail'}
      end
    end
  end

  def close
    @conversation_id = params[:id].to_i
    session[:private_conversations].delete(@conversation_id)
    respond_to do |format|
      format.js
    end
  end

  private

  def add_to_conversations
    session[:private_conversations] ||= []
    session[:private_conversations] << @conversation.id
  end

  def already_added?
    session[:private_conversations].include?(@conversation.id)
  end

end

A: session variables live for the the duration of the browser session. So this error means that you deleted database records while signed in, and you haven't adjusted session[:private_conversations] appropriately.
You either need to remove the deleted ids from session[:private_conversations], or adjust your find to be okay with only not finding some.
I would change your code to this:
def opened_conversations_windows
  if user_signed_in? && session[:private_conversations].present?
    @private_conversations_windows = Private::Conversation.includes(:recipient, :messages)
                                        .where(id: session[:private_conversations])

    # Update the session variable to only have the existing values
    session[:private_conversations] = @private_conversations_windows.map(&:id)
  else
    @private_conversations_windows = []
  end
end

Note that I turned find() into where(id: ). find expects that all ids provided will exist. where does not require any records to be returned; it just searches and you get what you get.
Additionally, I have it only doing a database query when the user actually has private conversations open. This is important because it would otherwise run the wrong query if you were signed in but had no private conversations. (WHERE id IS NULL or something like that)
Lastly, I have it do a little cleanup on the session variable, to set it to only the ones that still exist in the database.
Now later on whenever you set session[:private_conversations], (presumably when someone closes/opens a new conversation) you can set it to only the ones that still exist.
You mention that the following seemed to work:
if (user_signed_in? && @private_conversations_windows)

Given the code that you posted, I believe you would never actually get @private_conversations_windows set to anything other than []. Reason being, you're currently trying to set that variable, so it should be nil at the moment. Because it's always nil, you can't ever fall in to the side of the if that actually queries the database. Sure, it won't error anymore, but that's because it's not doing anything useful anymore. It'd basically be equivalent to:
def opened_conversations_windows
  @private_conversations_windows = []
end


text:
Q: Trying to import requests package but getting pip error? I installed the requests package by downloading the code from GitHub and installing via command prompt in the usual way. However, attempting to import the module results in IDLE giving me this error
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import requests
  File "requests.py", line 1
    pip install requests

I had installed pip awhile back by simply running the get-pip.py file in IDLE but had never used it so I'm a little surprised to see it pop up now. I tried installing requests using pip but I always get an invalid syntax error. Anyone have a clue as to what's going on here?
Thanks for the Help
EDIT: Right so what I'm doing is simply opening command line and typing pip install requests which results in me getting a message stating that requests is already installed (becuse I installed it using the setup.py file that was included in the GitHub distrubtion)
EDIT 2: Alright, so I just found my requests.py file and it only has one line..
pip install requests


text:
Q: How do you use regular expressions with the cp command in Linux? I am attempting to only copy a subset of files from one directory to another using cp however am greeted with the message cp: cannot stat [^\.php]': No such file or directory. Is there a way to use regular expressions only using the cp command?

A: No.
The cp command does not possess the capability to process any of its arguments as regular expressions. Even wildcards are not handled by it (or most executables); rather they are handled by the shell.
cp test/* test2/ is actually expanded by bash, and all that cp really sees for its arguments are cp test/file1 test/file2 test/file3 test2/ (or whatever is appropriate based upon the actual contents of test/).
Also, I don't think your expression, [^\.php], will match what you want it to (it doesn't match only files that contain .php).
You probably want to look into the find utility to filter out a list of files based upon regular expression, and then use xargs to apply the returned file list to the cp command (presuming find doesn't have a built-in handler for copying files; I'm not intimately familiar with the tool).
You might try:
find . ! -iregex ".*\.php.*" -exec cp {} /destination/folder/ \;

This says to search the current directory recursively for files which do not contain ".php" in the path and copy them into /destination/folder/.
As requested, a more specifc breakdown of the arguments:

*

*. - Location to start the search - in this case, the current directory

*! - "Not" operator, invert the result of the next test

*-iregex - Case-insensitive regular expression test. Next argument is the expression.

*".*\.php.*" - Regular expression matching <Anything>.php<Anything> - Any file that has ".php" somewhere in the path. (Note, including being inside a folder which contains ".php" in the name, you'd need a more complex expression to match only the files)

*-exec - Execute a command if the preceding tests return true. Next argument is the command, all remaining arguments up to ; are passed to the command. the {} is a special argument representing the filename.

*cp - The command that find` should run on each of the matched path names.

*{} - The path to the file that was found, passed to cp as an argument so that it knows what file to copy

*/destination/folder/ - argument passed to cp, telling cp where it should copy the file to.

*\; - This is the ; terminator that -exec is looking for. We escape it with a \ so that your shell doesn't try to parse it and instead feeds it as an argument to the command (find)

It's rather difficult to write a regular expression which matches "strings that do not have .php", so we instead tell find to search for strings that do contain .php and then invert the results with !.

A: You may use few other tools from console, like grep and xargs.
ls -1 some_folder | egrep 'some_extended_regex' | xargs cp -t destination_folder

A: To copy 100 log files into another log2 folder of same directory, I use following
cp app.log.[0-9][0-9] log2

A: You can run following command easy to use:
find /home/usr/search_dir -iname *file_name_portion*.txt | xargs cp -t /home/usr/destination_folder

cool haa!!


text:
Q: Differentiation of summation of summation According to http://www.atmos.washington.edu/~dennis/MatrixCalculus.pdf, (45) and (46) (p. 6),
differention of
$$\alpha = \sum_{j=1}^n\sum_{i=1}^n a_{ij} x_i x_j $$
with respect to the k-th element of x yields:
$$\frac{\partial\alpha}{\partial x_k} = \sum_{j=1}^n a_{kj} x_j + \sum_{i=1}^n a_{ik} x_i $$
Note that a does not depend on x.
How is this result obtained?
From differentiation with summation symbol, I understood how to derive one summation.
The function above seems to be of form f(g(x)) to me, so I would apply the chain rule.
But how can the result contain a + then, indicating some form of the product rule was used?

A: Much simpler:
$$
\frac{\partial}{\partial x_k} \sum_{i, j} a_{i j} x_i x_j
   = \sum_{i, j} a_{i j}
             \left( \frac{\partial x_i}{\partial x_k} x_j
                      + x_i \frac{\partial x_j}{\partial x_k} \right)
   = \sum_j a_{k j} x_j + \sum_i a_{i k} x_i
$$

A: Note that all the terms $a_{ij}x_i x_j$ will vanish when neither $i$ nor $j$ is equal to $k$. So all the remaining terms are of the form $a_{ik}x_i x_k$ and $a_{kj}x_k x_j$, which when differentiated with respect to $x_k$ will yield respectively $a_{ik}x_i$ and $a_{kj} x_j$, as in the announced formula.


text:
Q: Complexification Averaging Method I want to study about Complexification Averaging Method. What books do you suggest to start with?
I want to completely understand this method and why should we use it.
Thank you.


text:
Q: How to reference GLM? Following the question here, how to I refer to GLM in my project?
Just a recap:
GLM is a general model that includes a number of regression techniques. I have used it to test the main effects of IVs (continuous and categorical) on the DV and also the IV-IV interactive effect on the DV.
I am confused about whether I should just say that I used GLM for data analysis, or is there a specific method to mention with GLM (e.g. I used SSI in GLM for data analysis).
This is necessary (in my mind) because names of other statistical tests are precise (e.g. ANOVA). I know GLM is general but there has to be some way to communicate precise information on this technique.
Many thanks for any pointers.


text:
Q: Newly brought Apple Pencil(1st generation) didn't connect with my iPad (8th generation) when I plugged it In this year I brought an iPad (8th generation). And newly brought Apple Pencil (1st generation) I tried to connect with plugging it to the IPad. Sometimes the pop up  came up and disappeared. When I tap the "pair" button it shows on the Bluetooth settings shows Connected, after 2 seconds it shows Not connected. I tried new another two Apple Pencils with the iPad but it didn't work either.
I tried all the troubleshooting methods with this problem. And I upgraded the IPad OS to Latest IPad OS 15.0.2 but didn't work.

Sometimes Apple Pencil shows on the Other Devices  when I tapped on it the error message popped-up.


text:
Q: Filtros con Macro Excel Espero puedan ayudarme con lo siguiente.
Tengo una hoja en Excel, en la que requiero hacer cierto tipo de filtros.
Criterio 1:
Columna A;
Contiene fechas y requiero filtrar la fecha más reciente. La fecha esta de esta forma "Mes y Día, ejemplo September 12".
Se como poner Autofiltros con criterios en macro pero con fechas no he podido filtrar la ultima fecha.
Ejemplo de filtro con criterios filtrando el valor 10 de la columna AG que es la No 33:
Sheets("Nombre de la hoja").select
ActiveSheet.Range("$A:$AG").Autofilter Field:=33, Criteria:="">=10" , Operator:=xlAnd

¿Alguna idea, para solo filtrar la ultima fecha?
Estos son mis datos:

Este es tu codigo que agregue a mi Macro:
 Sub FechaMax()

Dim FechaMax As Range

Sheets("CalcPromedios").Select
Sheets("CalcPromedios").Activate

With Application.WorksheetFunction
       Set FechaMax = Range("A" & .Match(.Max(Range("A:A")), Range("A:A"), 0)) 'cambiar A por la columna que tiene las fechas
End With

ActiveSheet.Range("$A$1:$AG$65536").AutoFilter Field:=1, Criteria1:=FechaMax.Value 'cambiar el área de aplicación y el número de field
Set FechaMax = Nothing

End Sub

Y subi un ejemplo a mi drive:
https://drive.google.com/file/d/17UWq1OFkFEodAq0bCkqnwmbEjHDxt6cC/view?usp=sharing
DS

A: La fecha más reciente será la fecha de mayor valor en toda tu columna de fechas. Se puede calcular, y entonces buscar su posición dentro de la columna. Una vez localizada la primera celda que contenga la fecha más reciente, entonces se aplicará el filtro.
Un ejemplo sencillo que he hecho yo:

La fecha más reciente sería 09/09/2018, que aparece 2 veces. Mi código:
Dim FechaMax As Range

With Application.WorksheetFunction
       Set FechaMax = Range("A" & .Match(.Max(Range("A:A")), Range("A:A"), 0)) 'cambiar A por la columna que tiene las fechas
End With

ActiveSheet.Range("$A$1:$B$10").AutoFilter Field:=1, Criteria1:=FechaMax.Value 'cambiar el área de aplicación y el número de field
Set FechaMax = Nothing

Y el resultado tras ejecutar la macro, es que me filtra por fecha más reciente:

Espero que puedas adaptar el código a tus necesidades.


text:
Q: How to call input variable in IDLE without using f5 everytime This is just some code, and I want to find a way to run the code without having to press f5 everytime. I'm looking for a command or way to call the input variable. Since when I put print (x) in the IDLE shell it gives me the input value. I could use an infinite loop but I'm wondering if it's possible?
x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
        print('Zero')
elif x == 1:
        print('Single')
else:
        print('More')

A: You can use an infinite loop:
while (True):
    x = int(input("Please enter an integer: "))

    if x < 0:
        x = 0
        print('Negative changed to zero')
    elif x == 0:
        print('Zero')
    elif x == 1:
        print('Single')
    else:
        print('More')


text:
Q: Information/Assistance required on reverse SSH Tunneling (Naming Conventions etc) I have multiple raspberry pi's running Arch Linux (No GUI) in which I need to access. These pi's are behind firewalls in each unique location. Currently I use openvpn to connect to these but the costs of that system is expensive per license. I use the access server from them.
As a result, I am trying to design and setup a system that allows me the ability to login to my VPN server (vps) and run a command to search for a specific name (OfficeDevice1991) such as: customcommandsearch "OfficeDevice1991" and then it then returns the IP address of the machine or something I can use to SSH into with. I am also looking for the ability to run a command to list every active connected device. It lists back the IP, name and perhaps how long it's been active for.
For this goal, I of course need to create something that includes the name of the device (in this case OfficeDevice1991) and then that pi will be able to hook into my vps public server. From the public server, I can log in and do a search of every device connected to it and return information required to ssh into.
I have been looking into reverse SSH and so far I got one of my test pi's connected and accessible from my vps using the following commands:
PI:
ssh -fN -R 12345:localhost:22 -i /publickeyfile useraccount@ip //Pi's command to connect to vpn

VPS:
ssh -p 12345 useraccount@localhost //command for vpn to connect to pi

This works great, but using this method, if I was to implement it, I would run into a few issues:

*

*I would need to set up unique unused ports

*Some way to keep these ports / tunnels opened

*I need to come up with a system to identify each device. I can log each port to a name in like a text file locally? It would be beneficial to be able to include that in the ssh setup for each device if possible. I would still need to make sure the ports I use are not being used by any other programs or any device already there.

What I don't want to have to do

*

*Check what ports are free to use for each RPI

*Have to manually edit .ssh/config to add a name to represent each port assigned to RPI from part 1 above.
I am writing this for information/assistance as to what to do for my goal.
Could anyone provide me with a suitable solution?

A: Here's a solution using OpenSSH >= 6.7 + socat:

*

*OpenSSH >= 6.7 can use Unix domain socket forwarding
That means the reverse tunnel endpoint will be an UNIX listening socket instead of a traditional TCP listening socket. You can then manage more easily the flotilla of RPIs with an easy naming scheme: the socket's name will be the RPI's chosen (and fixed) name, like OfficeDevice1991. It could be even be an unique property from the RPI as long as it's a valid filename (since unix socket names adhere to filename conventions). For example its hostname, the MAC address of its ethernet or wifi card ...
SSH can handle unix sockets for tunnels, not for connecting itself. It will need the help of a ProxyCommand to be able to work as unix-socket client. socat can handle many kind of connections, including unix sockets.
UPDATE:
There is also a specific issue to handle: the unix socket file is not deleted on clean exit, nor would it have been be deleted anyway for example after a crash. This require the option StreamLocalBindUnlink=yes. I didn't find initially that, as the name perhaps imply, this option must be set on the node creating the unix socket. So in the end it's set on the client with a local forward (-L) or else on the server (in sshd_config) with a remote forward (-R). OP found it there. This solution uses a remote forward.
Configuration on VPS:
mkdir /rpi-access

(as root) edit the sshd_config file (/etc/ssh/sshd_config). It requires this additional option:
StreamLocalBindUnlink yes

Depending on default options it might also require AllowStreamLocalForwarding yes
UPDATE2:
Also set in sshd_config the parameters ClientAliveInterval and ClientAliveCountMax, thus allowing to detect a disconnect in a reasonable time, eg:
ClientAliveInterval 300
ClientAliveCountMax 2

Stale ssh connections should then be detected earlier on the VPS (~10mn with the example), and the corresponding sshd process will then exit.
Usage on RPI:
ssh -fN -R /rpi-access/OfficeDevice1991:localhost:22 -i /privatekeyfile useraccount@ip

In a config file this would be similar to this:
Host ip
User useraccount
RemoteForward /rpi-access/OfficeDevice1991:localhost:22
IdentityFile /privatekeyfile

Repeating it again: the StreamLocalBindUnlink yes set on sshd on VPS side option is important: the socket just created is not removed, even upon normal exit. This option ensures that the socket is removed if it exists before use, thus allowing to be reused for further reconnections. This also means one can't consider the mere presence of the socket as meaning the RPI is connected (but see later).
Now this allows to do on VPS:
ssh -o 'ProxyCommand=socat UNIX:/rpi-access/%h -' rpiuseraccount@OfficeDevice1991

As a configuration file, considering for example RPIs have all a name starting with OfficeDevice:
Host OfficeDevice*
    User rpiuseraccount
    ProxyCommand socat UNIX:/rpi-access/%h -

*To keep the link, just use a loop
The RPI can run a loop reconnecting ssh to the VPS whenever the connections ends. For this it musn't use the background mode (no -f). A keepalive mechanism should also be used. TCPKeepAlive (system level) or ServerAliveInterval (application level) are available. I think TCPKeepAlive is useful only on the server (the side receiving the connection), so let's rather use ServerAliveInterval.
Its value (as well as ServerAliveCountMax) should probably be adapted depending on various criteria: a firewall dropping inactive connections after a certain time, the wished recovery delay, not generating useless traffic, ... let's say 300s here.
OfficeDevice1991 RPI:
#!/bin/sh
while : ; do
    ssh  -N -o ConnectTimeout=30 -o ServerAliveInterval=300 -R /rpi-access/OfficeDevice1991:localhost:22 -i /privatekeyfile useraccount@ip
    sleep 5 # avoid flood/DDoS in case of really unexpected issues
done

Even if the remote side didn't yet detect the previous connectivity failure, and for a few more time has the old ssh connection still running, StreamLocalBindUnlink yes will anyway forcefully refresh the unix socket to the new connection.

*it's already handled by 1.
There's no customcommandsearch needed. With the right settings set in 1. just using ssh OfficeDevice1991 will connect to OfficeDevice1991.
If needed on the VPS, as root user only, this command:
fuser /rpi-access/*

can show which RPIs are currently connected (of course except those that recently lost the connection before detection). It won't show the stale unix socket files because there's no process tied to them.

A: This is a couple of different takes on the situation. I've omitted some of the detail here because there's nothing stopping you asking a further Question for specifics if you try either of these routes.
1. Replace OpenVPN Access Server
If cost of OpenVPN Access Server is a prohibitive issue, consider deploying your own OpenVPN server. The software is free to use; you'd just need a server endpoint (a VPS or equivalent if you have nothing locally) and the skill-set to set it up. Many tutorials are available for that, so you don't need to start from ground zero.
Once you've got this set up you can use DNS or /etc/hosts to define host names such as your OfficeDevice1991 to point to the appropriate VPN endpoint address on your server.
2. Use autossh instead of OpenVPN
Once you have your own endpoint you can use something like autossh on each of the Pi systems to ssh to a "well known" endpoint on boot (a VPS or equivalent if you have nothing locally).
Carry a reverse tunnel (ssh -R) across each, such that each Pi presents a different port number of your server that maps back to its own ssh port 22.
Judicious use of entries in ~/.ssh/config can allow you to run ssh OfficeDevice1991 and have it map automatically to something like ssh -p 12345 localhost, which in turn would correspond to a normal ssh connection to the Pi representing OfficeDevice1991.

Answering your set of questions you've added in your edit,
who or finger would give you each RPi's connected time.

*

*Ports 49152 to 65535 are yours

*That's what autossh does

*Hostnames

and

*

*As #1 above

*A short for x ... do ... done loop could autogenerate the file for you. I wouldn't want to create 1000 entries manually either.


text:
Q: iPhone detect portrait lock setting I want to detect whether the user of my app as the portrait view lock set or not. How can I figuere this out?
Thanks
Markus

A: According to the person that commented here: https://appcelerator.lighthouseapp.com/projects/32238/tickets/1329-able-to-programmatically-override-set-orientationlock-hardware-switch, it's impossible to detect the lock (at least, with any documented APIs).
The lock doesn't deactivate the accelerometer, though...you could detect the actual physical orientation of the device relative to what the orientation of the screen is to determine if it is locked in a particular orientation.


text:
Q: Combine 2 data variable in Laravel How can i combine 2 variable data in Laravel. Im trying combine data in $income1 and $income2 become $income data show all data from $income1 and $income2
Here my controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;

use App\Product;
use App\Blok;

class ProductController extends Controller
{
    public function income()
    {
    $products = Product::all();
    $income1 = \App\Pembelian::join('debitur','debitur.id','=','pembelian.debiturID')
    ->join('blok','blok.blok_id', '=', 'debitur.blokID')
    ->join('products','products.id', '=', 'blok.productID')
    ->get();

    $income2 = \App\Pembayaran::join('angsuran','angsuran.id','=','pembayaran.angsurID')
    ->join('debitur','debitur.id','=','angsuran.debiturID')
    ->join('blok','blok.blok_id', '=', 'debitur.blokID')
    ->join('products','products.id', '=', 'blok.productID')
    ->get();

    $income = collect($income1, $income2);

    $income->all();

    return view('income', compact('products', 'income'));
}
}

But it end up only showing $income1 data.

A: use array_merge
$merge = array_merge($income1, $income2);

A: Easiest way is to use
Merge
$merged = $income1->merge($income2);

$income = $merged->all();

So you will be able to use $income to refer both variable!

A: i solved it
Easiest Way use union
$payment =  Pembayaran::select("pembayaran.penyetor","pembayaran.jumlah_bayar","pembayaran.jenis","pembayaran.lsd","pembayaran.tanggal","pembayaran.keterangan","pembayaran.blok_id");

$incomes = Pembelian::select("pembelian.penyetor","pembelian.jumlah_bayar","pembelian.jenis","pembelian.lsd","pembelian.tanggal","pembelian.keterangan","pembelian.blok_id")
        ->union($payment)
        ->orderBy('tanggal', 'desc')
        ->get();


text:
Q: Using Activities from Library projects I have a Library project set up and a project which depends on this library project - Everything compiles fine and I've had the Dependent project running fine however;
I'm have an intermittent problem however while using an Activity from the Library project.
My Library project can be "unchecked" as a library project and the "picker" Activity can be run in isolation. Running the Library project in it's own right works fine with no problems.
When I use the Library project (and the "picker" Activity) from the dependent project it gives me either NullPointerExceptions (or historically DexOp) errors saying that the "picker" Activity can't find it's resources.
Can anybody tell me if they have experienced this before?
EDIT
Manually copying the layout.xml used by the Library project activity to the dependent project makes the project open the "picker" Activity correctly. Is this required?! Surely not? This further makes me wonder if there is a problem with merging/referencing the integer id's from R.java in the Library project.
EDIT
I'm not sure if this is of any consequence, but one of my Library projects is a wrapper around a set of custom views used in different front end projects.
These custom views each have an Activity so that they can be tested in isolation.
One of these view's has custom attributes, which while running in isolation work very well. However, it doesn't seem like the dependent project correctly pull's in the attributes and keep's them in their original namespace, causing the imported layout's to throw compilation errors:
[2012-05-16 12:07:28 - Project] D:\opt\workspace\CustomGlowList\res\layout\main.xml:14: error: No resource identifier found for attribute 'listId' in package 'com.company.library.glowlist'
[2012-05-16 12:07:28 - Project] D:\opt\workspace\CustomGlowList\res\layout\main.xml:14: error: No resource identifier found for attribute 'type' in package 'com.company.library.glowlist

EDIT
DexOp errors were solved by removing a duplicate file name which was present in the Dependent project. Not sure if the file name was the problem or the contents of the file.
EDIT
I've been unable to find a solution to this problem as of yet (although @yorkw's answer certainly helps with the xml attributes! Thanks).
I have managed to make this problem intermittent however:
I have gone through each of the library projects and ensured they all had their own namespace (ie, com.company.library.component1, com.company.library.component2 etc). After a couple of clean's (each project ordered with the correct precedence) this problem resolves itself, however does eventually come back when switching around library/not a library to test components.

A: not sure how you use the android library , but i've done this thing a lot of times without any problems , so please have a reading of the next things regarding using android libraries:

*

*in order for an android project to use an android library project , you can either edit the "project.properties" and add the path to the library project there , or , much easier, right click the project (that uses the library project) , choose "android" category , and choose there "add" and choose the library project.

*in order to make the android project to always open the android library project , also choose "java build path"->"projects"  and choose the library project.

*on the "project.properties" , try to set the target to the same target for both projects , and to the newest one that you have (latest now is 15) ,even if you can't test the app on this android version .

*source files and all resources files (in the res folder) are ok to be used on the library projects.

*assets folders cannot be used inside the library project . only on the android project that actually runs , the assets folder can be used . same thing goes to the proguard file .

*the manifest of the library projects almost doesn't need to have almost anything . see this post for more information: https://stackoverflow.com/a/10445630/878126 . if there are activities on the library project that you wish to be able to access via the project that use it , don't forget to include them in the manifest of the android project (no need to write them in the manifest of the android library) .

*remember to run lint before you export the app . it gives you plenty of warnings , but the most important warning is when you use too-new functions that cannot run on the range of APIs that you target . this is important for libraries since it's easy to get lost if there are multiple sources .

*if you wish to extend activities on the android library , you need some kind of a method to go between them . the only way i know of is to extend the application and let it be the manager of how to create an intent for each of the activities . i think you can do other tricks , but they are all probably similar to this one.

*if you have the same resource (any resource on the "res" folder) on both the android library and the android project, the one on the android project will replace the other one . this has advantages and disadvantages . remember that you can't have different file extensions for the same resource .

A: Cause:
Issue 9656: Library projects don't support custom XML attributes for custom classes
Solution:
Upgrade to latest SDK & ADT version (fixed was released since r17) and use http://schemas.android.com/apk/res-auto as custom attributes' namespace URI, see Revisions for ADT 17.0.0:

Added support for custom views with custom attributes in libraries. Layouts using custom attributes must use the namespace URI http://schemas.android.com/apk/res-auto instead of the URI that includes the app package name. This URI is replaced with the app specific one at build time.

Related Topic:
Help with a custom View attributes inside a Android Library Project

A: The problem was being caused by the R files from each of the Library projects not correctly being built and referenced. The resource files are built and referenced directly from the calling project.
Each of the Libraries need to have unique package as defined in the AndroidManifest.xml. This leads to each of it's resources being compiled in that unique namespace within the calling project alongside the Library jar which contains the class files.

The problem becomes intermittent when switching between a library and a runnable project because a clean and build needs to take place to regenerate these files as it isn't done automagically when unclicking the Use as library checkbox, where as the jar (and java classes) don't require as much coaxing for them to be correctly referenced as the library projects references them when acting as a Library.
This can lead to intermittent and also varying errors including missing references, DexOp and NullPointerExceptions depending on to what degree the R.java files have been mangled or partially built and what conflicts are taking places between packages.

A: I have same issue like, I have one library project and it has some activity.
When I was calling library project's Activity from my Main project, layout files resources were not getting loaded properly for the libray project's activity and giving "nullpointer exception" or "class could not be loaded", etc.
Solution: I have noticed that same layout file name is getting used in my Library project and Main project. I have just renamed those activity and it is solved.
May be this will help you.

A: I had similar issue when referencing Library project inside the Android App project. I deleted the R.java file from Library project so it generated again and App picked up the generated file. You should see the generated R.java file under your app project->gen->library_namespace_R.java.


text:
Q: "Auth fail" ( com.jcraft.jsch.JSchException) I  have written an ant script to copy files on local tomcat server (in root directory)  as follows:
<target name="temp">
     <scp todir="tomcat:tomcat@localhost:8080">
             <fileset dir="C:\Users\akhilesh.kj\Desktop\Plugin"/>
      </scp>
</target>

I have openSSH on my machine.I dont have much idea how it works.when I am running the above script, I am getting 'auth fail' exception.I have verified that username and password is correct.Below is the log:
         [scp] Connecting to localhost:22
     [scp] Connecting to localhost port 22
     [scp] Connection established
     [scp] Remote version string: SSH-2.0-OpenSSH_3.8.1p1
     [scp] Local version string: SSH-2.0-JSCH-0.1.42
     [scp] CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
     [scp] SSH_MSG_KEXINIT sent
     [scp] SSH_MSG_KEXINIT received
     [scp] kex: server->client aes128-ctr hmac-md5 none
     [scp] kex: client->server aes128-ctr hmac-md5 none
     [scp] SSH_MSG_KEXDH_INIT sent
     [scp] expecting SSH_MSG_KEXDH_REPLY
     [scp] ssh_rsa_verify: signature true
     [scp] Permanently added 'localhost' (RSA) to the list of known hosts.
     [scp] SSH_MSG_NEWKEYS sent
     [scp] SSH_MSG_NEWKEYS received
     [scp] SSH_MSG_SERVICE_REQUEST sent
     [scp] SSH_MSG_SERVICE_ACCEPT received
     [scp] Authentications that can continue: publickey,keyboard-interactive,password
     [scp] Next authentication method: publickey
     [scp] Authentications that can continue: keyboard-interactive,password
     [scp] Next authentication method: keyboard-interactive
     [scp] Authentications that can continue: password
     [scp] Next authentication method: password
     [scp] Disconnecting from localhost port 22
com.jcraft.jsch.JSchException: Auth fail

Please help !
Thanks.

A: Try
copy instead of scp.
This might work...


text:
Q: Add multiple datasets in rdlc in vs 2005 I am trying to add multiple datasets to my rdlc in vs 2005. In vs 2010, we have an option called 'Report Data' window, from there, we can add multiple datasets. But, in vs 2005, i am not finding that option. Pls suggest me, how can i add multiple datasets.

A: In Visual Studio 2005, when "editing" a report, there are three tabs above the report designer. The leftmost tab is to manage the data sources, the rightmost tab shows a report preview.
Switch to the leftmost tab and add new data sources using the controls there.


text:
Q: iTunes Store Doesn't Recognize iTunes Library About two weeks ago, iTunes stopped recognizing my iTunes library. I get this message when I go to either File → Library → Update iCloud Music Library or Update Genius:

There is no such option under File → Library. I tried disabling Genius Recommendations under my account, then turning them back on, but with no success. What is causing this and how can I fix it?
I have iTunes Match, but not Apple Music, if that matters.

A: Logging out of my iTunes account and logging back in did the trick.

*

*Account → Sign Out

*iTunes → Quit iTunes

*Wait a bit, relaunch iTunes

*Account → Sign In

*iTunes → Preferences → General → uncheck iCloud Music Library

*Click OK, wait a bit

*iTunes → Preferences → General → check iCloud Music Library
iTunes should immediately start updating your iCloud Music Library. Once that's done, everything should be working correctly.


text:
Q: how to make a jar with Maven in Intellij? I tried making and it gives an error when i opened it.
I'm using javafx.
I use many online dependences.
I first tried by going maven>lifecycle>install, after doing this when i tried to run the jar, it says that there's no manifest even though it's there.
I also tried through the artifacts but it also gives error.
P.S. I ran the jar on the CMD with java -jar "file's name".jar.


text:
Q: 403 error when inserting event with attendants in Google Calendar Api c# In a .net project, I'm trying to add an event with some attendants with google calendar v3 api. I can create an event without attendants successfully, but when I try to add attendants, it gaves me the following error:
Google.Apis.Requests.RequestError
Calendar usage limits exceeded. [403]
Errors [
    Message[Calendar usage limits exceeded.] Location[ - ] Reason[quotaExceeded] Domain[usageLimits]
]

I haven't done any previous request(actually, i have created new gmail accounts and link their respective calendars with their api credentials), and either added more than 5 events.
Here is the code to create an event
public class CalendarQuickstart
{
    private string jsonFile { get; set; }
    private string RutaCredentials { get; set; }
    private string calanderId { get; set; }

    public CalendarQuickstart()
    {
        RutaCredentials = WebConfigurationManager.AppSettings["rutaCredentials"];
        jsonFile= "credentials.json";
        calanderId = "9cp270uok8t0tq2uss3qb54dos@group.calendar.google.com";
    }

    static List<Event> DB =
         new List<Event>() {
            new Event(){
                Id = "eventid" + 3,
                Summary = "Google I/O 2015",
                Location = "800 Howard St., San Francisco, CA 94103",
                Description = "A chance to hear more about Google's developer products.",
                Start = new EventDateTime()
                {
                    DateTime = new DateTime(2019, 09, 29, 15, 30, 0),
                    TimeZone = "America/Los_Angeles",
                },
                End = new EventDateTime()
                {
                    DateTime = new DateTime(2019, 09, 30, 15, 30, 0),
                    TimeZone = "America/Los_Angeles",
                }
                ,
                  Recurrence = new String[] {
                      "RRULE:FREQ=WEEKLY;BYDAY=MO"
                  }
                 ,
                Attendees = new EventAttendee[] {

                    new EventAttendee() { Email = "gustavooguedareyes@gmail.com"}
                }
            }
         };

    public async Task crear_evento()
    {

        string[] Scopes = { CalendarService.Scope.Calendar };

        ServiceAccountCredential credential;

        string filePath = System.Web.Hosting.HostingEnvironment.MapPath(RutaCredentials + jsonFile);

        using (var stream =
            new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            var confg = Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(stream);
            credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(confg.ClientEmail)
               {
                   Scopes = Scopes
               }.FromPrivateKey(confg.PrivateKey));
        }

        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Calendar API Sample",
        });

        var myevent = DB.Find(x => x.Id == "eventid" + 3);

        var InsertRequest = service.Events.Insert(myevent, calanderId);

        try
        {
            InsertRequest.Execute();
        }
        catch (Exception e)
        {
            try
            {
                service.Events.Update(myevent, calanderId, myevent.Id).Execute();
                Console.WriteLine("Insert/Update new Event ");
                Console.WriteLine(e.ToString());
                Console.Read();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine("can't Insert/Update new Event ");

            }
        }

    }
}

A: Provided the following solution with references:
There are many possible reasons for Calendar usage limits exceeded
In your case, a likely reason is that you add an external (not from your domain) event attendee.
To prevent spamming, there seems to be a the following limit:
Free Google Apps Account For a user: 1 External Guest for 40 Minutes
Also, currently many people are experiencing a similar issue and there is already a filed bug report for this issue on Public Issue tracker.
If you are sure that you are not exceeding any quota limits, it is possible that the existing bug is the reason for your issue. In this case, I suggest you to give a "star" to the bug report to increase its visibility and hope that it will be fixed soon.


text:
Q: OpenGL ES iPhone switching from IB to initWithFrame Hey guys, I am writing a custom view for doing OpenGLES rendering. I got it working when I had a view in interface builder and set the class to my rendering view, but now I switched to creating the view with initWithFrame. (Note I can set the background color of the view and see it I just can't render anything in OpenGL not even the clear color) Everything seems to be getting called and the layer class seems ok too it just for some reason does not work outside of directly creating it with InterfaceBuilder. Any Ideas?
I have this setup code:
+ (Class) layerClass
{
    return [CAEAGLLayer class];
}

- (id)initWithCoder:(NSCoder*)coder
{
    if (self = [super initWithCoder:coder])
    {
        [self setupView];
    }
    return self;

}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self setupView];
    }
    return self;
}

- (void)setupView
{
    CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;

    eaglLayer.opaque = YES;
    eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];

    _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    if (!_context || ![EAGLContext setCurrentContext:_context])
    {
        NSLog(@"Error could not set context");
        [self release];
    }

    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(renderView:)];
    _displayLink.paused = YES;
    _displayLink.frameInterval = FPS;

    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    [EAGLContext setCurrentContext:_context];

    [self setup];
}

And then some layout code.
- (void)layoutSubviews
{
    [EAGLContext setCurrentContext:_context];
    [self destroyBuffers];
    if (![self createBuffers]){
        NSLog(@"Failed to create framebuffer!");
    }

    [self resumeRendering];
}

And some rendering code:
- (void)renderView:(CADisplayLink*)sender
{
    [EAGLContext setCurrentContext:_context];

        glBindFramebuffer(GL_FRAMEBUFFER, _viewFrameBuffer);

        glClearColor(0.5, 0.5, 0.5, 1.0);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        GLenum attachments[] = {GL_DEPTH_ATTACHMENT, GL_COLOR_ATTACHMENT0};
        glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);

        glBindRenderbuffer(GL_RENDERBUFFER, _viewRenderBuffer);

    [_context presentRenderbuffer:GL_RENDERBUFFER];

}

I can't figure out why nothing is rendering as all the same things are getting called. If anyone can help me out that would be awesome!

A: I maybe speculating too much here but switching from IB to initWithFrame has a step omitted, that is loadView in your viewController, which is where you would instantiate your custom view class instead of a standard view class.


text:
Q: How to open an existing file in a custom syscall and write to it I'm having some trouble opening and writing an existing file with a syscall. The syscall is set up correctly. The syscall itself takes in a file name as a char* but I keep getting errors
linux-2.6.22.19/mycall/mycall.c:24: undefined reference to `open'
linux-2.6.22.19/mycall/mycall.c:25: undefined reference to `write'
linux-2.6.22.19/mycall/mycall.c:26: undefined reference to `close'

What is the proper way to open and write to a file directly from a syscall if I am unable to use open, write, and close?


text:
Q: How to check if model has an attribute (OneToOneField) with queryset? I am using the default User model with Agent acting as a OneToOne profile model.  I want to create a queryset of all users who has Agent as a field.  I'm aware of hasattr but it returns a True/False boolean value so I couldn't implement that into my query.
views
class AgentSearchResults(ListView):
    model = User
    template_name = 'agent_search_results.html'

    def get_queryset(self):
        queryset = super(AgentSearchResults, self).get_queryset()
        # Write something here to check if all users in 'queryset' has 'agent'.
        return queryset

models for reference
class Agent(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='agent')

A: You can filter by check is related model's pk is null
User.objects.filter(agent__pk__isnull=False)

For your case:
def get_queryset(self):
    queryset = super(AgentSearchResults, self).get_queryset()
    # Write something here to check if all users in 'queryset' has 'agent'.
    queryset = queryset.filter(agent__pk__isnull=False)
    return queryset


text:
Q: Globally add UIImageView to UINavigationBar instead of title I want to use a logo as the title of a UINavigationBar globally across all screens in my application. How can I access the navigation bar in AppDelegate?

A: If you want to affect the whole app you should use appearance proxy in AppDelegate. Something like this should do it:
let navBar = UINavigationBar.appearance()
navBar.setBackgroundImage(UIImage(named: "yourImageName"), forBarMetrics: .Default)

A: This is what i have used
add below code in App-delegate's didFinishLaunchingWithOptions method
UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image_name_here"]];
[imgView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2,2,70,14)];
[imgView setCenter:CGPointMake(self.view.center.x,20)];
[self.navigationController.navigationBar addSubview:imgView];

or alternate way is
UIImage *image = [UIImage imageNamed:@"image_name_here"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];

A: This is impossible. The titleView is always local to a UIViewController.
However, you can:

*

*Create a subclass of UIViewController that will set your self.navigationItem.titleView to that image view and then inherit all your view controllers from this class.

*Create a subclass of UINavigationController, giving it a custom navigation bar which will always have the logo displayed inside. Then you will have to use this customized navigation controller instead of UINavigationController.

*Set it as navigation bar background image. You can actually make it globally but sometimes it's not an option (especially if you want to keep the default navigation bar appearance).
Of course, if you are using storyboads/xib, you can just put the same UIImageView with the logo everywhere.


text:
Q: SVG: get group coordinates (matrix or transform) in java I'm processing a SVG file using java.
It contains several groups that do not overlap: each group has a transform attribute with value translate(x,y) or matrix(a,b,c,d,e,f) and contains one rect and one text. The SVG file looks like a chessboard: each group is a chessboard square.
Using org.w3c.dom.* classes I'm able to open the SVG file and read its properties. I need to understand in Java if a group A is on the left/right/top/bottom of a group B.
My question: how to get and compare the position of each group?
Thanks.


text:
Q: Amcharts5 legend vertical align doesn't work I am new to Amcharts5.
This is my XY chart which has 3 series:
var chart3 = root3.container.children.push(
  am5xy.XYChart.new(root3, {
    layout: root3.horizontalLayout
  }),
);

I'm trying to put a legend on the top right of my XY chart, and I followed an official doc.
This is my configuration for a vertical alignment( which is exactly the same as in the offical doc):
var legend = chart3.children.push(
  am5.Legend.new(root3, {
    centerY: am5.percent(0),
    y: am5.percent(0),
  })
);

And here is the output:
XY Chart with Legend
I really don't know why it doesn't work...

A: Have you tried setting centerX and x also manually?
var legend = chart3.children.push(
  am5.Legend.new(root3, {
    centerX: am5.percent(100),
    x: am5.percent(100),
    centerY: am5.percent(0),
    y: am5.percent(0),
  })
);


text:
Q: PDFBox 2.0 : Invisible text from PDFTextStripper File example is here
I think I need some help from mkl again( in attached file there are some hidden () characters which PDFTextStripper extracts. For now I don't see what makes it invisible (for example see column 6 values - all they are in brackets:
Publix Liquors 1,600 2.5 1/1/2014 12/31/2018 ($ 24,000.00) ($ 4,032.00)   ($ 28,032.00)
BayCare Health Systems 3,200 5 7/30/2004 7/31/2018 ($ 51,200.00) ($ 9,648.00)   ($ 60,848.00) No rent change until Option Period 8/11/2018
..............
Could you please at least point why they are hidden in this case?
thanks in advance!

A: In this case you deal with actual transparency.
The hidden brackets are created by blocks of instructions like this
q
/Alpha3 gs
0 0 0 rg
BT
0 Tr
/Font0 14.299999 Tf
1.0 0 0 -1.0 537.66486 195.42578 Tm
0 0 Td
<037F>
Tj
ET
Q

The extended graphics state Alpha3 in the resources is declared as
14 0 obj
<<
  /CA 0
  /ca 0
>>
endobj

Thus, /Alpha3 gs sets both the stroke and the fill opacity to 0, i.e. anything drawn using fill or stroke is completely transparent.
In the PDFBox PDFTextStripper these values can be retrieved in processTextPosition from the current graphic state (getGraphicsState) as properties getAlphaConstant and getNonStrokeAlphaConstant


text:
Q: Save file from gnuradio to matlab or Gnu octave Ich want to ask how can i save the signal of the gnuradio to use it in matlab or gnuoctave.
The signal is ofdm signal from ofdm rx example in gnuradio in baseband.


text:
Q: Hiding the status bar We have hidden the status bar in our application. But when there is an error in playing the video, I get "This movie could not be played" pop up. When this pop up is getting displayed, status bar becomes visible and it stays visible always till we shut down the application.
How do we fix this

A: [ [ UIApplication sharedApplication ] setStatusBarHidden:true animated:false ];


text: Q: How wal logs work in postgres? I have to do a point in time recovery in postgres should i have all the wal logs that are generated or is it fine to have few recent wal log files  ? I tried recovery but I'm not sure if all the files are recovered


text:
Q: Finding the upper bound of a critical region
Let $X_1, \dots,X_n$ be a collection of independent and identically
distributed random variables, exponentially distributed with parameter
$\lambda$. We would like to do a hypothesis test:
$$\begin{cases} H_0: \lambda = \lambda_1 \\ H_1 : \lambda =
\lambda_2\end{cases}$$
With $\lambda_1 > \lambda_2$ constants. And the critical region
$R=\{\min \{X_1,\dots,X_n \}<k \}$ with a a significance level of
$\alpha$. Find $k$.

I know that
$$P(\min \{X_1,\dots,X_n \}<k  | H_0)=P(X_1<k;X_2<k;...;X_n<k|H_0)=\alpha$$
The random variables are independent so:
$$P(X_1<k;X_2<k;...;X_n<k|H_0)=P(X_1<k|H_0)P(X_2<k|H_0)...P(X_n<k|H_0)$$
Also, the random variables are exponentially distributed with parameter $\lambda_1$ (as I'm assuming $H_0$ is true):
$$P(X_1<k|H_0)P(X_2<k|H_0)...P(X_n<k|H_0)=(1-e^{-\lambda_1 k})^n$$
So
$$(1-e^{-\lambda_1 k})^n=\alpha \Rightarrow \boxed{k=\frac{-\ln(1-\sqrt[^n]{\alpha})}{\lambda_1}}$$
I know my mistake is somewhere when working with the $\min$ argument.
The correct answer is

 $$k=\frac{-\ln(1-\alpha)}{n \lambda_1}$$

A: $P(\min \{X_1,\dots,X_n \}<k  | H_0) \ne P(X_1<k;X_2<k;...;X_n<k|H_0)$.  The event $\min \{X_1,\dots,X_n \}<k$ is the event at least one of $X_i < k$. What you have right now is the event all $X_i < k$. Instead, express the event as
$$P(\min \{X_1,\dots,X_n \}<k  | H_0) = 1 - P( X_1 > k; X_2>k;...;X_n>k|H_0) = \alpha$$. Thus
$$
\alpha = 1 - (1 - (1 - e^{-k\lambda_1}))^n = 1 - e^{-nk\lambda_1} \implies \frac{-\ln(1-\alpha)}{n\lambda_1} = k$$.


text:
Q: I'm trying to connect to the DB, but the connect() function doesn't seem to work const express = require('express')
const app = express()
// const mysql = require('mysql')
const mysql = require('./db')()
const cors = require('cors')
require('dotenv').config();
const port = process.env.PORT || 5000

app.use(express.json())
app.use(cors())

app.listen(port, () => console.log(`${port}`))

app.get('/', (req, res) => {
  res.send("hi")
})

const connection = mysql.init()
mysql.open(connection)

This is my server.js code.
const mysql = require('mysql')
require('dotenv').config();

module.exports = function() {
  return {
    init: function () {
      return mysql.createConnection({
        host: process.env.HOST,
        user: process.env.USER,
        password: process.env.PASSWORD,
        database: process.env.DATABASE,
        port: process.env.PORT
      })
    },

    open: function(con) {
      con.connect(function(err) {
        // if (err) throw err
        // console.log('Connected!')
        if(err) {
          console.log('mysql connection error: '+err)
        } else {
          console.log('mysql is connected successfully.')
        }
      })
    }
  }
}

And this is my db.js code...
I expect the port number and message "mysql is connected successfully" to be printed when this code is executed. But when I run it, nothing is output except for the port number. Even an error message.
So I can't verify that the database connection was made properly. Why is the contents of the connect() function not executed?

A: You have used same environment variable for server port and database port. Please change variable name PORT of database port to DB_PORT in .env file. Then change the environment variable name in the database port of db.js file as well.
db.js
const mysql = require("mysql");
require("dotenv").config();

module.exports = function () {
  return {
    init: function () {
      return mysql.createConnection({
        host: process.env.HOST,
        user: process.env.USER,
        password: process.env.PASSWORD,
        database: process.env.DATABASE,
        port: process.env.DB_PORT,
      });
    },

    open: function (con) {
      con.connect(function (err) {
        // if (err) throw err
        // console.log('Connected!')
        if (err) {
          console.log("mysql connection error: " + err);
        } else {
          console.log("mysql is connected successfully.");
        }
      });
    },
  };
};

example .env file
PORT=8080
HOST=localhost
USER=root
PASSWORD=root
DATABASE=dbname
DB_PORT=3306


text:
Q: Ecological interpretation of Lotka-Volterra model I am studying Lotka-Volterra models, specifically one of prey-predator with intraspecific competition. The equation system is:
$$\frac{dx}{dt}= r_x x(1-x-\alpha y)$$
$$\frac{dt}{dt}= r_y y(\beta x + \gamma y -1)$$
where $x$ correspond to preys and $y$ to predators,
$$r_x,r_y,\alpha,\beta >0$$
and
$$\gamma \in \mathbb{R}$$
I know $r_x$ is the growth tax for preys, $r_y$ is the death tax for predators and $\alpha$, $\beta$ are their interaction taxes, all of them are real positive numbers.
$\gamma$ is the logistic term for predators, but I don't understand why it can be positive or negative. If $\gamma$ is negative, it means competition between predators, but which ecological interpretation has a positive $\gamma$ value?
Thanks in advance.

A: $\gamma y$ , according to Wikipedia, is the "loss rate of the predators due to either natural death or emigration."
Hence, a positive $\gamma$ would correspond to high immigration rates of the predator. (High, as in immigration > natural death)

A: With negative $\gamma$, this term stands for the reaction
$$
2Y\to Y,
$$
environmental pressure leads to a reduction in the population.
With $\gamma$ positive, the term stands for the reaction
$$
2Y\to 3Y,
$$
which could for instance mean that any encounter of $2Y$ leads to (in average) an increase in the population


text:
Q: Are these song lyrics correct english? I am writing song lyrics for a heavy metal song i am making, but i have some trouble to figure out whether its correct or wrong, cause the last sentence does not seem to make any sense at all. I am dutch so english is not my native language.
The song lyrics are about the plague:
Everywhere i go i see them laying on the floor.(piles of dead bodies)
Still alive, but not to save the souls of them anymore. (the victims are still alive, but are already unable to survive) Somehow it tells me that that last sentence makes no sense at all. Or does it make sense? I dont know...

A: I suggest you reword the part of your lyric which you think does not make sense. Here is one suggestion, which is in keeping with your rhyming scheme:
            Everywhere i go i see them

             Laying on the floor.

             They are still alive,

             But soon they'll be no more.

The word laying should be lying, but in a song lyric, such an error would not necessarily be considered an error!


text:
Q: Speeding up Winbind group lookups? I have an RHEL 6 server bound to an AD domain. Everything works fine but group lookups are extremely slow. Some lookups can take over 60 seconds. This is very painful when running sudo and when users ssh in and it needs to verify their group membership before granting access. Strangely, when it comes to file permissions, there is no lag when a group is used to limit access via ACL's.
It seems like when groups are looked up, every single member of each group is enumerated. Some groups have over 100,000 members.
Here is my Winbind config:
workgroup = EXAMPLE
password server = AD.EXAMPLE.ORG
realm = EXAMPLE.ORG
security = ads
idmap uid = 10000-19999
idmap gid = 10000-19999
idmap config EXAMPLE:backend = rid
idmap config EXAMPLE:range = 10000000-19999999
winbind enum users = no
winbind enum groups = no
winbind separator = +
template homedir = /home/%U
template shell = /bin/bash
winbind use default domain = yes
winbind offline logon = false


text:
Q: Django - How to loop xml tag in xml i want to save/update my xml file from my html form. There were a few option that i have to key in many data for one attribute. But i don't know how to loop the data when to save it in xml.
For example, i want to save the attributes like this
<keywords>
     <string>WFS</string>
     <string>WMS</string>
     <string>GEOSERVER</string>
</keywords>

but when i hit submit button the result was like this
<keywords>
    <string>WFS WMS GEOSERVER</string>
</keywords>

By the way, i'm using ElementTree

A: you can do it this way:
keywords = ET.Element('keywords')
for string_ in strings: # < -- your strings
    string = ET.SubElement(keywords, 'string')
    string.text = string_

ET.dump(keywords)

Tested:
>>> import xml.etree.ElementTree as ET
>>> keywords = ET.Element('keywords')
>>> strings = ['a', 'b', 'c']
>>> for string_ in strings:
        string = ET.SubElement(keywords, 'string')
        string.text = string_

>>> ET.dump(keywords)
<keywords><string>a</string><string>b</string><string>c</string></keywords>
>>>


text:
Q: SharePoint Framework Workbench Error - the requested operation is part of an experimental feature that is not supported in the current environment I've just followed the instructions for the hello world sample for the SharePoint Framework Preview and I'm getting the error in the title when attempting to run the workbench on my sharepoint dev site.
I get a page that says "Sorry, something went wrong" and then "The requested operation is part of an experimental feature that is not supported in the current environment."
I've followed the instructions here to set the environment up:
https://github.com/SharePoint/sp-dev-docs/wiki/Setup-SharePoint-Tenant
It's step 6 in these instructions that I'm having trouble with:
https://github.com/SharePoint/sp-dev-docs/wiki/HelloWorld-WebPart
Any thoughts greatly received.
Many thanks.

A: As Wictor mentions, you need a developer tenant.  It sounds like there are some issues people are facing though.  While we are sorting out the issue, does the following tenant sign up work?  https://portal.microsoftonline.com/Signup/MainSignUp.aspx?OfferId=6881A1CB-F4EB-4db3-9F18-388898DAF510&DL=DEVELOPERPACK
That should give you a 30 day trial developer tenant.

A: You MUST have an Office 365 Developer tenant at the moment to be able to use the Workbench. You get the O365 Developer tenants from your MSDN subscription, go to http://dev.office.com and follow instructions.

A: I was unable to set up a developer tenant as I had previously had one set up (about two years ago) and they only last a year.  The message you get sugegsts this is one possibility along with proxy issues and other red herrings.
On Dana's advice (she is with Microsoft support) I used a personal email address I had to set up a new developer tenancy and this worked.
In a year's time I guess I'll be setting up another email address (or using a new business email address as I'm a contractor and change clients a couple of times a year each of which give me a new address) when this one runs out.

A: Rather annoyingly, I was required to set up yet another tenant (YAT?) for development.  I used the new sign up link with a personal email address.  It seems there is no real way to tell if it will work or not until you try it...


text:
Q: jenkins.plugins.publish_over.BapPublisherException: Failed to connect and initialize SSH connection I am stuck to configure publish over ssh in jenkins.
Jenkins container to ansible container in CLI I am able to do SSH via private key, but the same private key when I am using on publish over ssh it does not work.

jenkins.plugins.publish_over.BapPublisherException: Failed to connect
and initialize SSH connection. Message: [Failed to connect session for
config [ansible]. Message [USERAUTH fail]]

A: I solved this problem yesterday morning. In the ssh configuration file I added two lines, now working perfectly.
PubkeyAuthentication yes
PubkeyAcceptedKeyTypes=+ssh-rsa