text:
Q: How to mock ** parameter in OCMock in ARC One of the parameter of my method is **error and my project is in ARC mode. When writing stub for this method to call a mock method i set parameter to below possible values. Either it causes compile error or failing to match the argument to call the mock method.

*

*OCMOCK_ANY

*[OCMArg anyPointer]

*Created a NSError object error and said [OCMArg setTo:error].

Nothing works.
How to mock such method? Please advice.
Edit
-(id)init{

    self = [super init];

    if (self) {
        id wcm = [OCMockObject partialMockForObject:self];
        [[[wcm stub] andCall:@selector(mockGetWakeupCallsForRoomNumber:error:)    onObject:self] getWakeupCallsForRoomNumber:OCMOCK_ANY error:((NSError __autoreleasing **)    [OCMArg anyPointer])];
        //[[[wcm stub] andCall:@selector(testMockMethod) onObject:self] testMethod];

    }
    return self;

}

-(void)testMethod
{
    NSLog(@"Original");
}

-(void)testMockMethod
{
    NSLog(@"Mock");
}
-(NSArray*)mockGetWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error
{
    @throw @"Mock method called";
}

-(NSArray*)getWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error
{
}

Mock on testMockMethod works.

A: You can use setTo: or anyPointer if you cast it:
[[[mockFoo expect] andReturn:nil] someMethodWithError:((NSError __autoreleasing **)[OCMArg anyPointer])];

or:
NSError *error;
[[[mockFoo expect] andReturn:nil] someMethodWithError:((NSError __autoreleasing **)[OCMArg setTo:error])];

Here's a test case that passes with the method you've posted:
@interface Foo : NSObject{}

-(NSArray*)mockGetWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error;
-(NSArray*)getWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error;

@end

@implementation Foo

-(NSArray*)mockGetWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error
{
    return @[@"bar"];
}

-(NSArray*)getWakeupCallsForRoomNumber:(NSString*)roomNumber error:(NSError**)error
{
    return nil;
}

@end

@interface SomeTest : SenTestCase {}
@end

@implementation SomeTest

-(void)testMethod
{
    Foo *foo = [Foo new];
    id wcm = [OCMockObject partialMockForObject:foo];
    [[[wcm stub] andCall:@selector(mockGetWakeupCallsForRoomNumber:error:) onObject:foo] getWakeupCallsForRoomNumber:OCMOCK_ANY error:((id __autoreleasing *)[OCMArg anyPointer])];
    NSError *error;
    NSArray *calls = [wcm getWakeupCallsForRoomNumber:@"foo" error:&error];
    STAssertEquals(calls[0], @"bar", @"should match");
}

@end

A: Finally this is what i implemented.
[
 [[wcm stub]
           andCall:@selector(getWakeupCallsForRoomNumber:error:serverMessage:)
   onObject:self]
   getWakeupCallsForRoomNumber:OCMOCK_ANY
                         error:((NSError *__autoreleasing *)[OCMArg anyPointer])
                 serverMessage:((NSString *__autoreleasing *)[OCMArg anyPointer])];


text:
Q: Call protected method from a subclass of another instance of different packages I want to invoke a protected method of another instance from within a subclass of the class providing this protected method. See the following example:
public class Nano {

    protected void computeSize() {
    }

}

public class NanoContainer extends Nano {

    protected ArrayList<Nano> children;

}

public class SomeOtherNode extends NanoContainer {

    // {Nano} Overrides

    protected void computeSize() {
        for (Nano child: children) {
            child.computeSize();            // << computeSize() has protected access in nanolay.Nano
        }
    }

}

javac tells me that computeSize() has protected access in Nano. I can't see the reason for this (I thought I was already doing this in some other code). I'd like to keep this method being protected, what can I do?
javac version "1.7.0_09"

Edit
I wanted to provide a stripped down version, but I didn't think about the fact, that the classes lie in different packages.
nanolay.Node
nanolay.NanoContainer
nanogui.SomeOtherNode

A: You could access the protected methods either by subclassing and overriding; also when they are available in the same package. I will add some details.
You can read details here.
The example that you have is on lines of the protected clone() method available in the Object class in java; you cannot directly call it on any object (although all object implicitly extend from the Object class).

A: Don't know the rationale, but JLS confirms this in 6.6.2. Details on protected Access (emphasis mine):

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

So:
package P2;
public class P2 {
    protected void foo() {}
}

.........

package P2A;
class P2A extends P2.P2 {
    void bar(P2.P2 other) {
        this.foo(); // OK
        other.foo();  // ERROR
    }

    void bar2(P2A other) {
        other.foo(); //OK
    }
}

In P2A.bar a call to this.foo() is accessible because this is responsible for implementation of P2 but other.foo() is not accessible because other may not be a P2A. bar2 on the other hand has a P2A so it is all good.
Now, why all is OK if they are all the same package but not if they are different packages? What is the rationale? I don't know and would like to know.
Meta-Comment I have rolled back a recent update by another user as it substantially changes the answer and is probably more suitable as a top level answer itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How not to reload footer on page navigation I have music application in which I have simple player in footer. User can choose songs from main page list and play it in footer. Now requirement is even if user moves fro home page to other pages(profile, bookmarks) in application the footer player should not get reloaded and should keep playing audio selected on home page initially.
How do I do that? DO I need to load pages through ajax?
Edit:
I forgot to mention that development is 80% completed and footer reloads on every page load. How much of rework is needed if I have to use Ajax now?

A: Use PJAX. Reload just the parts of the page that you want: https://github.com/rails/pjax_rails
It's already integrated with Rails and everything you put outside of this block will not be reloaded:
<div data-pjax-container>
  <!-- PJAX updates will go here -->
</div>

A: Here's another solution similar to PJAX and Turbolinks
https://github.com/igor-alexandrov/wiselinks

A: Some very good answers already, but i just wanted to explain your problem better.
HTTP requests is "stateless", which means that each request are fully independent and their is no way you can know anything about how the page was before you requested a new page. This makes it impossible not to reload the footer on each request, using only HTTP.
You can use cookies to keep information between request, so you could start the player where it stopped before the request, but it will still reload (and stop for a short duration).
You can also have the rest of the page in a iframe, and only change the content of the iframe.
However these solutions is not very good for various reasons, so i would strongly recommend the last and best solution: ajax.
The simples solution is properly pjax as @aledalgrande suggested (or wiselink as suggested by @adbeel). This will i practice make your site a "one-site-application" where you use ajax to replace specific parts of the page instead of the whole page. It should however be fairly simple to integrate, even in a existing rails application.

A: Since you put jQuery as a tag I suggest you either look at http://api.jquery.com/load/.

A: You can using plain old HTML and making it easier & faster to deploy since the app is almost 'done'. Later you should implement a better (ajax) option.
Simplified: index.html
<iframe id="mainframe" src="other.html"></iframe>
<footer>
    Don't reload me pls :D
</footer>

on page navigation (links) you act only on the mainframe, leaving the footer not reloaded.
NOTE: This is ugly and may will give you problems but might serve you to do minimal modification and having your site live asap.
Then rewriting the whole thing to using ajax could be 'some work required' to 'heavy work required' depending on how the app is already implemented. note that will never be 'few or no work required'.


text:
Q: How should I partition Ubuntu-Win 10 dual boot? I know usually it's not a big deal because: install Win 10, make free space for Ubuntu then install it. But in my case it's a little bit more complicated. Right now I have Win 10 on a 240 GB SSD that's my C: partition. Beside that I have a 1 TB HDD with partitions D: for programs and E: and F: for personal data. I want to install Ubuntu as my main os and reinstall Win 10 because I need it sometimes. The only partitions I want to delete are C: and D: because I need my personal files. So my question is: How would you do this if you were me? I was thinking that I put my Ubuntu root on the SSD, I cut my D: partition in two halves, on 100 GB I'd put Windows on the other 200 GB my /home and then I'd mount my E: and F: in Ubuntu. I know it's very very messy but when I made my current setup I wasn't thinking enough. Of course I will backup my data asap and delete all these unnecessary partitions and make one big /home but right now I don't have other choice if nobody can recommend me something better.
Thank you for reading my post, I'm looking forward to your answers.

A: In a dual-boot system, I prefer having my personal files in an NTFS partition to be able to access them from both OS's. Home partition cannot be formatted as NTFS, so I would have at least two separate partitions.
I wouldn't reinstall Windows 10. I would install Ubuntu alongside it on the 240Gb SSD and leave your data on the 1Tb drive.
Depending on the size of drives E: and F:, you could reformat one of them as ext4 and use it as Home partition.
Then there's the possibility of using a Swap partition roughly the size of your RAM.
So on your SSD you may have

*

*120 Gb for Win 10 (NTFS)

*120 Gb for Ubuntu. (ext4)

Then on the HDD:

*

*D: for Win programs (NTFS -unchanged)

*current E: for home (ext4)

*(optional) a Swap partition

*F: for personal files (NTFS)

Partitioning is a question of personal taste. Some would suggest having separate partitions for /boot, etc., so inform yourself before taking a decision.

A: I would:

*

*Shrink Windows in SSD to allow a new ~60GB partition

*Install Ubuntu to the 60GB partition accepting the default partition options (/home, /boot, /swap... everything will go there)

60GB for Ubuntu should be enough if you store your data in a different partition, and you said that you do. If you have an SSD is worth using it for the OS and sometimes making it smaller helps with the good habit of storing data that you want to backup elsewhere.

A: If I were you my approach to this would be the following :

*

*search C: for all files that you want to keep. put them in a folder called "oldwindows" on E: or F: depending on which has the most space.

*create a windows 10 install usb with your windows and get ready to reinstall it.

*create an ubuntu install disk with rufus make sure your rufus is configured for UEFI : https://i.stack.imgur.com/bFCGU.png (you can wait untill april 18th to do this entire guide as ubuntu 19.04 releases then)

*unplug D: E: and F: as a safety measure. not only to make installing both windows and ubuntu easier but to avoid windows placing multiple efi boot partitions on each drive as it has a tendency to do durring the install process.

*install your windows 10, no need to get creative with partitioning just create a new partition table and allow windows to take all of it. This is the right way to go as ubuntu knows how to repartition durring install.

*in your booted newly installed Windows open up a powershell with admin rights (right click on the icon "run as administrator") and type in powercfg -h off then open up your settings and in the updates tab go to "recovery" and select the third option "restart now" with your ubuntu installer usb plugged in.

*now  install ubuntu, durring the install process ubuntu will recognize windows 10 is installed and give you a slider to slide between the windows 10 side and the ubuntu side to determine the size of ubuntu's partition (and reduce window's accordingly) the slider locks at window's written files, give windows some leeway though, don't slide it right against windows's written files or windows will experience problems with low disk space. Half for each (120Gb) sounds right to me.

*now you can plug your D: E: and F: and you can put your files back into windows folder (you can do this from ubuntu without issue).

the above will result in a dual-bootable windows-ubuntu system.
I chose not to do anything funcky with the partitioning because simple is often better and in this case I think you'll be confortable with it.
ubuntu reads and writes to NTFS (windows) partitioning shema with disconcerting ease, it's hard to find any performance increase in ex4.
so keep ex4 for ubuntu itself but for storing files keep NTFS.
the reinstalling of windows is not necessary but I deduced from your tone that it had been a long time coming. Windows does have a tendency to pick up dust and a yearly reinstall keeps it purring.
if you don't see the use, though you're perfectly free to skip steps 1., 2., 5. and 6. it will work just as well. (given your current windows is installed in UEFI mode, if it's in legacy, you'll have to creeate your ubuntu install disk in legacy mode as well to match it, durring step 3.)
to make booting faster as I often don't choose to boot on my windows either, I use grub-customizer
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

I use it to lower the coutdown time or even hide grub entirely and boot instantaneously. I can then run it again should I want to reboot to windows.
Also, if you have good hardware and two screens, thanks to virtualbox, you can have both systems running simultaneously. This is what I am writing this post from. My windows partiotion is booted by the virstualbox installed on my ubuntu and occupies my second screen.


text:
Q: Чем обусловлен минимальный предельно допустимый размер объекта? В стандарте указан рекомендованный минимальный предельно допустимый размер для объекта — 262144. Чем обусловлено именно это магическое число? Почему не меньше/больше?

A: Конечным продуктом  кода, является машинный код, что генерируют компиляторы. Вы можете прочитать как работают компиляторы, например тут
И станет понятно почему для внутренней реализации(создания объектного файла), для каждого объекта нужно больше  памяти для информации о типе и других, которая будет  храниться в этом машинном  коде объекта. Так вот, этот набор бит, насколько стало понятно, рекомендуется количеством  в 19 (минимум 19 нулей и единиц). Эта информация в таблице  указана в виде числа(минимальное  значение 19 битовом поле). Это есть
(1 << 18)  == 262144

на один больше максимального значения 18 битового поля.
Конечно это внутренняя реализация и не касается исходного кода. Сам объект будет хранится в памяти в нужном выравненном виде.


text:
Q: How to Show NStimer's countdown at UILabel for 9 min 59 sec with Minitue and Second format? I have a task to add a timer on my apps which is appear on exam mode page. I have done every thing but can't convert total time into min:sec format. Please Anyone can help me.

A: You can use modulo arithmetic:
int totalSecondsRemaining = // however you obtain it
int minutesRemaining = totalSecondsRemaining / 60; // integer division, truncates fractional part
int secondsRemaining = totalSecondsRemaining % 60; // modulo division

someLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutesRemaining, secondsRemaining];

(Remark: this is elementary school maths...)


text:
Q: Amerpsand format flag in java I have existing java code that is used to format a string. This code fails for the below format - java.util.FormatFlagsConversionMismatchException:..Based on other SO issues, I see its more related to Java version thats used.
Question..

*

*What does the '%1$#' format does..Mostly Im not able to find the '$' & '#' format rules while I googled.

*How to fix this issue?
Java code
String test = String.format("%1$#" + 2 + "s", 01);

A: From the docs of java.util.Formatter:

The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion

So %1$#2s means an argument_index of 1, a flags value of # ("The result should use a conversion-dependent alternate form"), a width of 2, and a conversion of s (string).
For %s conversions, the alternate form is used by passing it to Formattable:

If the argument is null, then the result is "null". If the argument implements Formattable, then its formatTo method is invoked. Otherwise, the result is obtained by invoking the argument's toString() method.
If the '#' flag is given and the argument is not a Formattable , then a FormatFlagsConversionMismatchException will be thrown.

I suspect you don't really want # in this case.

A: You can read about formatting here. The error in your code is that# is invalid FormatFlag in your case(# mean The result should use a conversion-dependent alternate form). You can use for e.g. s or d to print like this
System.out.println(String.format("%1$d" + 2 + "s", 01));


text:
Q: Would like to apply sort to filtered results I would like to filter entries in my database, then apply an ascending/descending sort to filtered results. However, I don't know how to do this! I can either filter or sort, but if I filter, then apply the sort, the filter is cleared.
My controller:
public async Task<IActionResult> Index(string sortOrder, string searchString, string cityString, string specialtyString)
{
    ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
    ViewData["nameFilter"] = searchString;
    ViewData["cityFilter"] = cityString;
    ViewData["specialtyFilter"] = specialtyString;

    var providers = from p in _context.Provider
                    select p;

    if (!String.IsNullOrEmpty(searchString))
    {
        providers = providers.Where(s => s.ProviderName.Contains(searchString));
    }

    if (!String.IsNullOrEmpty(cityString))
    {
        providers = providers.Where(s => s.City.Contains(cityString));
    }

    if (!String.IsNullOrEmpty(specialtyString))
    {
        providers = providers.Where(s => s.ProviderType.Contains(specialtyString));
    }

    switch (sortOrder)
    {
        case "name_desc":
            providers = providers.OrderByDescending(m => m.ProviderName);
            break;

        default:
            providers = providers.OrderBy(m => m.ProviderName);
            break;
    }

    return View(await providers.AsNoTracking().ToListAsync());
}

-and the corresponding view (partial):

    @Html.DisplayNameFor(model => model.ProviderName)

I would like for the filter parameter(s) to persist until the user clicks an affordance to clear them.
Thank you for the insights and advice!


text:
Q: T wave onset and offset in ecg signal using matlab I am working in a project that intended to extract ECG features. I used wavelet transform. I successfully detect all waves including R peaks. Now, I want to measure P wave duration. first, I thought to find the onset and offset of the P wave. then, I can count how many samples in duration. My question is when I used the following code it returns empty matrix !!!!!.( I tried to find the P wave onset from the point that is crossing the zero value with reference to P peaks(P peaks location. That is, I created a window of 201 samples in which I am looking for the nearest sample that it's value close to zero in this window).
Can any one help please. (Matlab code)
% P duration
pdon = [];
% y is my filtered signal
for i = 1:1:length(Ploc);
pon = Ploc(i)-200:Ploc(i);
if (y(pon)<=0 & y(pon+1)>0)
found = (pon);
pdon = [pdon found];
pdon_amp = y(pdon);
end
end
figure(111)
plot(y)
hold on
stem(pdon,pdon_amp,'r*')
hold off


text:
Q: Replacement for UIView's contentStretch? In iOS 6.0 the contentStretch property of UIView was deprecated.
How can I achieve the same functionality with new/old/other API?
The functionality I am looking for is stretching just part of an image (everything but the edges) on a UIButton.

A: Use resizableImageWithCapInsets and UIEdgeInsets to make a stretching UIButton background image. For example:
UIImage* image = [UIImage imageNamed:@"image.png"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, 20)];
[button setBackgroundImage:image forState:UIControlStateHighlighted];

I don't think you can stretch more than one pixel both horizontal and vertical.
Hope this helps.


text:
Q: Developing Azure functions locally I am leading a large team of azure functions developers. So, most of the examples quoted by Microsoft using the azure web interface don't work for me. I am developing Azure functions locally using emulators to save some costs. I publish all my functions through visual studio into my integration environment.
I am developing a bunch of azure functions that need the api gateway to handle the authentication workflows using Azure AD B2C. Now, there's no api gateway emulator or an Azure AD B2C emulator that I can run locally. My authentication workflows involve intercepting requests to the api, redirecting them to AD B2C for authentication and the subsequent addition of the auth-token to the http header and then invoking the http-triggered azure functions.
Now, the question becomes, how do I test authentication workflows?
How can I setup the api gateway to register my functions running locally in visual studio as api endpoint for my api gateway in the cloud?

A: Here is another alternative if you are developing a SPA that uses Azure-AD or Azure B2C via Easy Auth, which will do your JWT token validation for you and leaving you to do the following:
Your SPA is going to get a token even locally so do the following:

*

*Inject the ClaimPrincipal into your function

*Check if the user is authenticated (e.g., principal.Identity.IsAuthenticated) and return UnauthorizedResult if they are not.

*Check for an issuer claim.  If the principal has one, it went through Express Auth., your JWT token was validated by it and you can get your claims from it immediately.

*If there is no issuer, it's local development and you can turn to the header and pull the JWT token out yourself and get your claims.  You could also IFDEF this out for conditional build so that your doubly sure that it's local development.

Here is some example code of pulling the JWT token out of the header (HttpRequest is injected into each function):
private JwtSecurityToken ReadJwtTokenFromHeader(HttpRequest req)
{
   if (req.Headers.ContainsKey("Authorization"))
   {
       var authHeader = req.Headers["Authorization"];
       var headerValue = AuthenticationHeaderValue.Parse(authHeader);

       var handler = new JwtSecurityTokenHandler();
       return handler.ReadJwtToken(headerValue.Parameter);
   }

   return null;
}

Note:  This requires the System.IdentityModel.Tokens.Jwt NuGet package to use JwtSecurityTokenHandler.

A: Taking @David-Yates's answer I substituted Principal when running locally
module Debug = begin

    open System.IdentityModel.Tokens.Jwt
    open System.Net.Http.Headers
    open System.Security.Claims

    let setPrincipalFromBearerToken (log : ILogger) (req : HttpRequest) =
        log.LogInformation ("Reading Authorization header")
        let success, authHeader = req.Headers.TryGetValue("Authorization")
        if not success
        then log.LogWarning ("Authorization header missing")
        else
        match Seq.tryExactlyOne authHeader with
        | None -> log.LogWarning ("Authorization header has 0 or more than 1 value")
        | Some headerValue ->
            let headerValue = AuthenticationHeaderValue.Parse(headerValue);
            log.LogInformation ("Authorization header succesfully parsed")

            let handler = new JwtSecurityTokenHandler();
            let token = handler.ReadJwtToken(headerValue.Parameter);
            log.LogInformation ("JWT succesfully parsed")
            let identity =
                ClaimsIdentity(
                    req.HttpContext.User.Identity,
                    token.Claims)//,
                    //Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme),
                    //"oid", "roles")
            let principal = ClaimsPrincipal(identity)
            req.HttpContext.User <- principal
            let userIdClaim =
                principal.Claims
                |> Seq.where (fun c -> c.Type = "oid") // TODO: Use const from MS package if possible
                |> Seq.head
            log.LogInformation ("Principal succesfully updated, user ID '{0}'", userIdClaim.Value)
end

let isLocal = String.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"))
if isLocal then Debug.setPrincipalFromBearerToken log req

A: What I did:

*

*Added an "authorize" API that handles general-purpose authorization against foreign authorities.  This API returns my own JWT with my own custom claims that lasts for a some limited amount of time.

*Changed all of my other API's to use my custom JWT.

Advantages:

*

*Super easy to test locally.   I just add #if DEBUG sections to the authorization API to skip normal authorization and give me a JWT of my design.

*I can put whatever I want in the claim, so I use it as a cache to reduce external authorization calls.


text:
Q: Maps APIs: is it possible to geocode premise or building name in Malaysia Is it possible to geocode an address based on only building name in Malaysia?  I am using Maps APIs v3 geocode service with premier license but the query result always returns status:ZERO_RESULTS.
In http://maps.google.com.my/, premise search is working perfectly. Any idea if it's possible for Maps APIs?

A: It should be possible using the premise settings,  but it would depend on how robust the maps database is for Malaysia as an example:
var buildingName = "The Building Name";

geocoder.geocode( { 'premise' : buildingName }, function(results, status) {
...
}


text:
Q: Problems with Installing packages - Ubuntu 16.04 TLS I'm new to Ubuntu, and am having trouble installing some packages on 16.04 TLS. The first one is pip. When I ran sudo apt-get install python-pip, I got:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libpcl1.7 : Depends: libpcl-people1.7 but it is not going to be installed
 python-pip : Depends: python-pip-whl (= 8.1.1-2ubuntu0.4) but it is not going to be installed
          Recommends: python-all-dev (>= 2.6) but it is not going to be installed
          Recommends: python-wheel but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I tried the command with the -f flag but still it didn't help.
I then tried to install libpcl-people1.7 using sudo apt-get install libpcl-people1.7, but I got even more errors:
After this operation, 74.8 kB of additional disk space will be used.
E: Read error - read (5: Input/output error)
E: Prior errors apply to /var/cache/apt/archives/libpcl-people1.7_1.7.2-14build1_amd64.deb
debconf: apt-extracttemplates failed: Interrupted system call
(Reading database ... 283158 files and directories currently installed.)
Preparing to unpack .../libpcl-people1.7_1.7.2-14build1_amd64.deb ...
Unpacking libpcl-people1.7:amd64 (1.7.2-14build1) ...
dpkg-deb (subprocess): cannot copy archive member from '/var/cache/apt/archives/libpcl-people1.7_1.7.2-14build1_amd64.deb' to decompressor pipe: failed to read (Input/output error)
dpkg-deb (subprocess): decompressing archive member: lzma error: unexpected end of input
dpkg-deb: error: subprocess <decompress> returned error exit status 2
dpkg: error processing archive /var/cache/apt/archives/libpcl-people1.7_1.7.2-14build1_amd64.deb (--unpack):
subprocess dpkg-deb --fsys-tarfile returned error exit status 2
No apport report written because the error message indicates an issue on the local system
                                                                                Processing triggers for libc-bin (2.23-0ubuntu7) ...
Errors were encountered while processing:
/var/cache/apt/archives/libpcl-people1.7_1.7.2-14build1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I have updated the system before I ran these commands. To me the errors just look weird. What might be the cause for these errors? Any help is appreciated. Thank you.


text:
Q: Java can not load "BEGIN TRUSTED CERTIFICATE" format certificate I have a CA certificate which is generate by openssl with "trustout", so the it begins with "-----BEGIN TRUSTED CERTIFICATE-----", when I tried to read it with Java, exception throws.
Does Java supports this format of certificate? If so, how to read it?
public class TestReadCerts {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
         String sslrootcertfile = "F:\\javaworkspace\\opensource\\certs\\ca.pem";

            FileInputStream fis=null;
            try {
              fis = new FileInputStream(sslrootcertfile); // NOSONAR
            } catch (FileNotFoundException ex) {
              ex.printStackTrace();
            }
            try {
              CertificateFactory cf = CertificateFactory.getInstance("X.509");

              Object[] certs = cf.generateCertificates(fis).toArray(new Certificate[]{});

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

}

The exception:
java.security.cert.CertificateException: Unable to initialize,
java.io.IOException: extra data given to DerValue constructor
    at java.base/sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:191)
    at java.base/sun.security.provider.X509Factory.parseX509orPKCS7Cert(X509Factory.java:476)
    at java.base/sun.security.provider.X509Factory.engineGenerateCertificates(X509Factory.java:361)
    at java.base/java.security.cert.CertificateFactory.generateCertificates(CertificateFactory.java:478)
    at TestReadCerts.main(TestReadCerts.java:21)
Caused by: java.io.IOException: extra data given to DerValue constructor
    at java.base/sun.security.util.DerValue.init(DerValue.java:409)
    at java.base/sun.security.util.DerValue.<init>(DerValue.java:294)
    at java.base/sun.security.util.DerValue.<init>(DerValue.java:305)
    at java.base/sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:188)
    ... 4 more

And the certificate is as below:
-----BEGIN TRUSTED CERTIFICATE-----
MIICATCCAWoCCQDjKSwZBsrQwTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB
VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
cyBQdHkgTHRkMB4XDTE5MDQwMzE0NDcwMVoXDTIwMDQwMjE0NDcwMVowRTELMAkG
A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0
IFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyRCB
rbB/FqN6e9IAJ86WUUGxM+8vEyfQ7cn2HWca220NB/Ns3Q+QtvztSe48PUzn9w6s
MNOwsDW4+8lenPLd78J32lG59x1P1R1jpjL3GcjNTwuewW1jIsex8jALzfU9hJzO
prraO/6X+UbKbazXt6GiB7mOlUvneKsWuoGpF5MCAwEAATANBgkqhkiG9w0BAQsF
AAOBgQCN1UJF/FdT84bzEn1kmg77b+LCCrU11DsFg/s/ABvo5TKV+OmilBPj1vML
dbZ4GDQSaXKZAOyJiAp0S5BzHXlXz5YfX9sM4mfhaqZt736WAnKVSnzd55CjMlEk
GxW3TkRFL5cVm5my1UQs3Mfg4MC5QPaoer5kc+0UhMHmTlgyvTAMMAoGCCsGAQUF
BwMB
-----END TRUSTED CERTIFICATE-----

A: PEM type 'TRUSTED CERTIFICATE' is an OpenSSL-specific nonstandard format that Java can't handle out of the box. It actually contains the standard X.509 cert as one DER chunk plus another OpenSSL-defined DER chunk of trust information.
If you have OpenSSL, the simplest method is to convert to the standard 'CERTIFICATE' format with openssl x509 <in >out . You can add -outform DER as Misantorp did but it isn't needed; CertificateFactory can read the standard format in either DER or PEM as OpenSSL inexactly calls them.
If you have or can get and use bcpkix and bcprov from https://www.BouncyCastle.org , they include routines to handle this OpenSSL PEM format (and many others):
        // assumes filename in args[0], adjust as needed
        Object both = new PEMParser(new FileReader(args[0])).readObject();
        // should close the FileReader, maybe using try-resources
        byte[] cert = ((X509TrustedCertificateBlock)both).getCertificateHolder().getEncoded();
        X509Certificate good = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(cert));
        System.out.println (good.getSubjectX500Principal().getName());

Otherwise, it is possible to decompose the DER by hand but clumsy and unrobust:
        String in1 = new String(Files.readAllBytes(new File(args[0]).toPath()));
        byte[] both = Base64.getMimeDecoder().decode(in1.replaceAll("-----[A-Z ]*-----\\r?\\n",""));
        if( both[0]!=0x30 || both[1]!=(byte)0x82 ) throw new Exception("wrong!"); // or other handling
        byte[] cert = Arrays.copyOf(both, (both[2]<<8 | both[3]&0xFF) + 4);
        X509Certificate good = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(cert));
        System.out.println (good.getSubjectX500Principal().getName());

A: Please also check out the answer by dave_thompson_085 as it points out some inaccuracies in my understanding and as a result this answer

Your problem is trying to read a PEM encoded certificate with CertificateFactory which expects a DER encoding as stated in the documentation

In the case of a certificate factory for X.509 certificates, the
  certificate provided in inStream must be DER-encoded and may be
  supplied in binary or printable (Base64) encoding.

I think the quickest way to read the certificate is to convert the certificate into the appropriate encoding. Since you already mentioned using openssl to generate the certificate you can encode your current certificate to DER
$ openssl x509 -in /F/javaworkspace/opensource/certs/ca.pem -outform DER -out /F/javaworkspace/opensource/certs/ca.der

(adjust the path to ca.pem and ca.der as needed)
Lastly, don't forget to update the sslrootcertfile variable
String sslrootcertfile = "F:\\javaworkspace\\opensource\\certs\\ca.der";


text:
Q: Solve the system: $\frac{x}{\sqrt{2}}+\frac{y}{\sqrt{3}}=2$, $(\sqrt{2}-1)x+(\sqrt{3}-1)y=5-\sqrt{2}-\sqrt{3}$
Solve the system:
  $\begin{array}{|l}
 \dfrac{x}{\sqrt{2}}+\dfrac{y}{\sqrt{3}}=2 \\  (\sqrt{2}-1)x+(\sqrt{3}-1)y=5-\sqrt{2}-\sqrt{3}  \end{array}$

So, I started by multiplying the first equation by $\sqrt{2}\cdot\sqrt{3}=\sqrt{6}$:
$\begin{array}{|l}
 \sqrt{3}x+\sqrt{2}y=2\sqrt{6} \\  (\sqrt{2}-1)x+(\sqrt{3}-1)y=5-\sqrt{2}-\sqrt{3}  \end{array}$
How can I solve from here?

A: If you're comfortable with linear algebra, you have a $2\times 2$ matrix which is invertible. If not, try solving for $x$ (or $y$) in the first equation and plug it into the second equation

A: Using Cramer's method:
$$|A|=\begin{vmatrix}\frac1{\sqrt2}&\frac1{\sqrt3}\\ \sqrt2-1&\sqrt3-1\end{vmatrix}=\frac{\sqrt3-1}{\sqrt2}-\frac{\sqrt2-1}{\sqrt3}=\frac{1+\sqrt2-\sqrt3}{\sqrt6}\\
|A_x|=\begin{vmatrix}2&\frac1{\sqrt3}\\ 5-\sqrt2-\sqrt3&\sqrt3-1\end{vmatrix}=2(\sqrt3-1)-\frac{5-\sqrt2-\sqrt3}{\sqrt3}=\frac{1+\sqrt2-\sqrt3}{\sqrt3}\\
x=\frac{|A_x|}{|A|}=\sqrt2$$
Can you find $y$?


text:
Q: emacs: python auto-complete just doesn't want to work I couldn't find a specific answer to my question here, so I dare asking it at the off-chance of being directed to the answer ;)
since about two days, I am trying to get the auto-complete-mode to work for python, but I am out of luck :( I have been following the direction from this website and from this website which are both fairly outdated it would appear.
To give a brief description for those unfamiliar: According to the websites, it is apparently necessary to install first rope, rope-mode, pymacs and ropemacs before attempting to install auto-complete. I am reasonably confident, that I have done so successfully (the given tests, if any, in each manual gave the expected result), but once I install auto-complete, it just doesn't, y'know, autocomplete...
Lastly, it is entirely possible that I have done a newbie mistake, so please don't be shy and ask the blatantly obvious question here.
Thanks a lot for your help.

I am using Ubuntu 12.04 and emacs23 and I would like to use it with python2.7

A: bzr branch lp:python-mode/components-python-mode
includes auto-completion based on company-mode
That's the development branch of python-mode.el, no release so far.


text:
Q: Characteristic polynomials of matrices related How to show that the characteristic polynomials of matrices A and B are $\lambda^{n-1}(\lambda ^2-\lambda -n)=0$ and $\lambda^{n-1}(\lambda^2+\lambda-n)=0$ respectively by applying elementary row or column operations.
$A=\begin{bmatrix}
1 & 1 & 1 & \cdots & 1 \\
1 & 0 & 0 & \cdots & 0 \\
1 & 0 & 0 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
1 & 0 & 0 & \cdots & 0 \\
\end{bmatrix}$
$B=\begin{bmatrix}
-1 & 1 & 1 & \cdots & 1 \\
1 & 0 & 0 & \cdots & 0 \\
1 & 0 & 0 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
1 & 0 & 0 & \cdots & 0 \\
\end{bmatrix}$
Where $A$ and $B$ are symmetric matrices of order $n+1$.

A: About first matrix.
Lets take the bottom line. As we know :
$$\det{A} = \sum{(-1)^{i+j}\cdot a_{i,j}\cdot M_{i,j}},$$ so we got:
$$S_{n+1} = a_{n+1,n+1}\cdot (-1)^{2n+2}\cdot S_{n} + (-1)^{n+2}a_{n+1,1}S'_{n},$$ where $S'_{n}= (-1)^{1 + n} \lambda^{n-1}(-1)^{n-1}$, because of :
$S'_{n} = \begin{bmatrix}
1 & 1 & \cdots & 1 & 1\\
-\lambda & 0 & \cdots & 0 & 0 \\
0 & -\lambda & \cdots & 0 & 0\\
\vdots & \vdots & \cdots &\ddots & \vdots \\
0 & 0 & \cdots & -\lambda & 0 \\
\end{bmatrix}$

A: Use induction on $n$, we only consider the matrix $A$ because solving $B$ is similar. Before starting, I think that the characteristic polynomial of $A$ and $B$ should be of the form $\color{red}{(-1)^{n+1}}\lambda^{n-1}(\lambda^2-\lambda-n)$ and
$\color{red}{(-1)^{n+1}}\lambda^{n-1}(\lambda^2+\lambda-n)$, respectively.
For $n=1$, then
$$\det(A-tI_2)=\left\vert\begin{matrix}1-t&1\\1&-t\end{matrix}\right\vert=t^2-t-1,$$
which is done.
Now, suppose that the result holds for some $n\in\mathbb{N}$, then for $n+1$,
we have
\begin{align*}
\det(A-tI_{n+2})&=
\left\vert
\begin{matrix}
1-t&1&1&\cdots&1\\
1&-t&0&\cdots&0\\
1&0&-t&\cdots&0\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
\color{blue} 1&0&0&\cdots&\color{blue}{-t}
\end{matrix}
\right\vert_{n+2}\\
&=(-1)^{n+3}
\left\vert
\begin{matrix}
1&1&1&\cdots&1&1\\
-t&0&0&\cdots&0&0\\
0&-t&0&\cdots&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots\\
0&0&0&\cdots&0&0\\
0&0&0&\cdots&-t&0
\end{matrix}
\right\vert_{n+1}
-t
\left\vert
\begin{matrix}
1-t&1&1&\cdots&1\\
1&-t&0&\cdots&0\\
1&0&-t&\cdots&0\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
1&0&0&\cdots&-t
\end{matrix}
\right\vert_{n+1}\\
&=(-1)^{n+3}
\left\vert
\begin{matrix}
1&1&1&\cdots&1&\color{blue}1\\
-t&0&0&\cdots&0&0\\
0&-t&0&\cdots&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots\\
0&0&0&\cdots&0&0\\
0&0&0&\cdots&-t&0
\end{matrix}
\right\vert_{n+1}
-t(-1)^{n+1}t^{n-1}(t^2-t-n)\\
&=
(-1)^{n+3}(-1)^{n+2}
\left\vert
\begin{matrix}
-t&0&\cdots&0\\
0&-t&\cdots&0\\
\vdots&\vdots&\ddots&\vdots\\
0&0&\cdots&-t
\end{matrix}
\right\vert_{n}
+(-1)^{n+2}t^n(t^2-t-n)\\
&=-(-1)^nt^n+(-1)^{n+2}t^n(t^2-t-n)\\
&=(-1)^{n+2}t^n[(t^2-t-n)-1]\\
&=(-1)^{(n+1)+1}t^{(n+1)+1}[t^2-t-(n+1)].
\end{align*}
This completes the proof for the matrix $A$.


text:
Q: Change font color to Red when text has "*" in a cell - Excel In a cell I have a value e.g: "World is not fair *"

*

*In this text I want to change font color only to Red for *

*The*will be my last letter

Thanks in advance

A: This code will colour the last character of a cell red:
Range("A1").Characters(Len(Range("A1"))).Font.ColorIndex = 3

Len() gives the number of characters, then Characters() refers to this last character.

A: For a range of cells you could try something like this
Sub UpdateRange()
Dim rng1 As Range
Dim rng2 As Range
Set rng1 = [a1:a10]
For Each rng2 In rng1
If Len(rng2.Value) > 0 Then
    If Right$(rng2.Value, 1) = "*" Then rng2.Characters(Len(rng2.Value)).Font.Color = vbRed
End If
Next
End Sub

A: You can use conditional formatting to do this.
You need to select the option "use a formula to determine which cells to format".
Then you type in this formula -depending on which cell it is.
=RIGHT(A1,1)="*"
You then click on format and choose font and select colour red.


text:
Q: How to use isDisable of SelectOption I have a SelectOption and I'm populating like this:
maintNotesList.add(new SelectOption(String.valueOf('Default'),'Select Description'));
I tried to insert the isDisabled for this value so he can be the first one like this:
maintNotesList.add(new SelectOption(String.valueOf('Default'),'Select Description'), isDisabled(true));
But isn't working. I receive this error:
Method does not exist or incorrect signature: void isDisabled(Boolean).
How can I insert isDisabled for this value in a select option list?
I view this option in the documentation but I can see a example for this:
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_pages_selectoption.htm

A: The problem is that isDisabled() is not a method for the SelectOption Apex Class (as per the documentation). If you want to have a SelectOption that is disabled, you can create the SelectOption just by passing a value of true for the third parameter of the constructor:
maintNotesList.add(new SelectOption(String.valueOf('Default'),'Select Description'), true);


text:
Q: Upgrade Windows 10 Home to Pro fails with error code 0x0 I've been trying to upgrade a customer's Windows 10 Home to the Pro version but after the computer reboots to complete the upgrade I receive an unhelpful error that the upgrade couldn't be installed with an error code of 0x0.
Has anyone experienced this and any ideas what's causing the upgrade to fail? I've tried two possible methods of upgrading using the key but not the clean install method. The two methods for an "online" upgrade essentially take you to the same place - System Properties -> Change product key and the other via the Store but it brings up the same screen as the System Properties method.
I'm reluctant to do a clean install as this will add extra time I really shouldn't need to add if the "online" method worked properly.
The system is a Lenovo desktop so has all the usual bloatware.

A: Uninstalling McAfee LiveSafe has fixed it.
Concerning that the underlying OS's  built-in upgrade facility is blocked by third-party software!


text:
Q: MKMapView Delegate Methods not working I just wanted to add a Polyline to my Map which is displayed in a tableviewcell. Unfortunately
the delegate methods are not called... Would be nice if someone knows why.
My tableview.h:
#import <UIKit/UIKit.h>
#import "Route.h"
#import <MapKit/MapKit.h>
#import <QuartzCore/QuartzCore.h>

@interface RoutesDetailView : UITableViewController<MKMapViewDelegate>{
    Route *myRoute;
    MKMapView *mapView;
    // the view we create for the line on the map
    MKPolylineView* _routeLineView;

    // the rect that bounds the loaded points
    MKMapRect _routeRect;
    MKPolyline* _routeLine;
}

@property (nonatomic, retain) Route *myRoute;
@property (nonatomic,retain) MKMapView *mapView;
@property (nonatomic, retain) MKPolyline* routeLine;
@property (nonatomic, retain) MKPolylineView* routeLineView;

-(MKPolyline *) loadRoute: (Route *) theRoute;
@end

And my tableview.m:
    @implementation RoutesDetailView
    @synthesize myRoute,mapView;
    @synthesize routeLine = _routeLine;
    @synthesize routeLineView = _routeLineView;

    - (id)initWithStyle:(UITableViewStyle)style
    {
        self = [super initWithStyle:style];
        if (self) {
            // Custom initialization
        }
        return self;
    }

    - (void)didReceiveMemoryWarning
    {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];

        // Release any cached data, images, etc that aren't in use.
    }

    #pragma mark - View lifecycle

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        MKMapView *myMap = [[MKMapView alloc] initWithFrame:CGRectMake(10, 1, 300 , 300)];
        myMap.layer.cornerRadius = 10.0;
        [self setMapView:myMap];
        [mapView setDelegate:self];
        CLLocationCoordinate2D annotationCoord;
        annotationCoord.latitude = [[NSString stringWithFormat:@"%@",NSLocalizedString(@"DefaultPointLAT", nil)] doubleValue];
        annotationCoord.longitude = [[NSString stringWithFormat:@"%@",NSLocalizedString(@"DefaultPointLONG", nil)] doubleValue];
        MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
        annotationPoint.coordinate = annotationCoord;
        MKCoordinateRegion region =
        MKCoordinateRegionMakeWithDistance (annotationPoint.coordinate,[[NSString stringWithFormat:@"%@",NSLocalizedString(@"DefaultCircle", nil)] doubleValue], [[NSString stringWithFormat:@"%@",NSLocalizedString(@"DefaultCircle", nil)] doubleValue]);
        [mapView setRegion:region animated:NO];
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }

    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    }

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    }

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    }

    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
    }

    - (void)viewDidDisappear:(BOOL)animated
    {
        [super viewDidDisappear:animated];
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        // Return YES for supported orientations
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }

    #pragma mark - Table view data source

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
.
.
.

            static NSString *CellIdentifier = @"CellMap";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            [mapView setFrame:CGRectMake(10, 1, cell.frame.size.width-20 , cell.frame.size.height-1)];
            [cell addSubview:mapView];
            [mapView addOverlay:[self loadRoute:myRoute]];
            return cell;
.
.
.

    }

    #pragma mark - Table view delegate
    -(MKPolyline *) loadRoute: (Route *) theRoute
    {

        MKMapPoint northEastPoint;
        MKMapPoint southWestPoint;

        // create a c array of points.
        MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * theRoute.latitude.count);

        for(int idx = 0; idx < theRoute.latitude.count; idx++)
        {

            CLLocationDegrees latitude = [[[theRoute latitude] objectAtIndex:idx] doubleValue];
            CLLocationDegrees longitude = [[[theRoute longitude] objectAtIndex:idx] doubleValue];

            // create our coordinate and add it to the correct spot in the array
            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);

            MKMapPoint point = MKMapPointForCoordinate(coordinate);

            //
            // adjust the bounding box
            //

            // if it is the first point, just use them, since we have nothing to compare to yet.
            if (idx == 0) {
                northEastPoint = point;
                southWestPoint = point;
            }
            else
            {
                if (point.x > northEastPoint.x)
                    northEastPoint.x = point.x;
                if(point.y > northEastPoint.y)
                    northEastPoint.y = point.y;
                if (point.x < southWestPoint.x)
                    southWestPoint.x = point.x;
                if (point.y < southWestPoint.y)
                    southWestPoint.y = point.y;
            }

            pointArr[idx] = point;

        }

        // create the polyline based on the array of points.
        self.routeLine = [MKPolyline polylineWithPoints:pointArr count:theRoute.latitude.count];

        _routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y);

        // clear the memory allocated earlier for the points
        free(pointArr);
        return self.routeLine;

    }

    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay
    {
        NSLog(@"DELEGATE CALL");
        MKOverlayView* overlayView = nil;

        if(overlay == self.routeLine)
        {
            //if we have not yet created an overlay view for this overlay, create it now.
            if(nil == self.routeLineView)
            {
                self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
                self.routeLineView.fillColor = [UIColor redColor];
                self.routeLineView.strokeColor = [UIColor redColor];
                self.routeLineView.lineWidth = 15;
            }

            overlayView = self.routeLineView;

        }

        return overlayView;

    }

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Navigation logic may go here. Create and push another view controller.
        /*
         <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
         // ...
         // Pass the selected object to the new view controller.
         [self.navigationController pushViewController:detailViewController animated:YES];
         */
    }

    @end

A: Try this, I was having the same issue. After trying many combinations this is the one which works.
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewController : UIViewController<MKMapViewDelegate> {

    MKMapView   *mapView;
}

and the implementation...
- (void)viewDidLoad {

    [super viewDidLoad];

    mapView = [[MKMapView alloc] initWithFrame: CGRectMakeFullScreenIphone];
    mapView.delegate = self;
    [mapView setMapType: MKMapTypeStandard];
    [self.view addSubview: mapView];

    MKCoordinateRegion newRegion;
    // configure region...
    [mapView setRegion:newRegion animated:YES];

    CLLocationCoordinate2D coordinate;
    //configure coordinate...

    MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
    [annotation setCoordinate:coordinate];
    [annotation setTitle:@"TEST"];
    [mapView addAnnotation:annotation];
}

The simple code above works fine and delegate's methods were called.

A:
if you are running the application in simulator, then the

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay

this delegate method will not get called, you need to run it on iOS Device.

A: The first Meth is
mapView:regionDidChangeAnimated:
and the second is
mapView:didUpdateUserLocation:
Header File
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;

@end

Implementation File
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.mapView.delegate = self;
    self.mapView.mapType = MKMapTypeStandard;
    self.mapView.showsUserLocation = YES;
    self.searchButton.hidden = YES;
}

- (IBAction)setMapType:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.mapView.mapType = MKMapTypeStandard;
            break;
        case 1:
            self.mapView.mapType = MKMapTypeSatellite;
            break;
        case 2:
            self.mapView.mapType = MKMapTypeHybrid;
            break;
        default:
            break;
    }
}

- (IBAction)zoomToCurrentLocation:(UIBarButtonItem *)sender {
    float spanX = 0.00725;
    float spanY = 0.00725;
    MKCoordinateRegion region;
    region.center.latitude = self.mapView.userLocation.coordinate.latitude;
    region.center.longitude = self.mapView.userLocation.coordinate.longitude;
    region.span.latitudeDelta = spanX;
    region.span.longitudeDelta = spanY;
    self.searchButton.hidden = YES;
    [self.mapView setRegion:region animated:YES];
}

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    self.searchButton.hidden = NO;
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    [self.mapView setCenterCoordinate:userLocation.coordinate animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
Q: How to access variable in angular scope? When I insert console.log($scope) into my code, I get the following result:
$get.k.$new.a.$$childScopeClass.$$childScopeClass {$$childTail: null, $$childHead: null, $$nextSibling: null, $$watchers: Array[4], $$listeners: Object…}
$$childHead: null
$$childScopeClass: null
$$childTail: null
$$listenerCount: Object
$$listeners: Object
$$nextSibling: null
$$prevSibling: $get.k.$new.a.$$childScopeClass.$$childScopeClass
$$watchers: Array[4]
$id: "005"
$parent: Object
Bad: false
Good: true
Search: function () {
address: "63146"
focus: "63146"
this: $get.k.$new.a.$$childScopeClass.$$childScopeClass
__proto__: Object

The variable I am interested in is Good: true. However, when I call console.log($scope.Good) on the next line, it returns false.
How do I call the above "Good" variable that returns true in the console?
edit:
Controller
app.controller('locationController', function ($scope) {
    $scope.Good = false;
    $scope.Bad = false;

    var mapOptions = {
        center: { lat: 38.68, lng: -90.46 },
        zoom: 8
    };

    var image = {
        url: 'app/assets/img/marker.png'
    }

    var map = new google.maps.Map(document.getElementById('map'),
        mapOptions);
    $scope.Search = function () {
        $scope.Good = false;
        $scope.Bad = false;
        var address = $scope.address;
        var radius = parseInt(50, 10) * 1000;
        var marker_start = new google.maps.Marker({
            position: { lat: 38.688757, lng: -90.464391 },
            map: map,
            icon: image,
            title: ""
        });

        var fill = '#fff';
        var populationOptions = {
            strokeColor: '#66FF99',
            strokeOpacity: 0.2,
            strokeWeight: 2,
            fillColor: fill,
            fillOpacity: 0.35,
            map: map,
            center: new google.maps.LatLng(38.68, -90.46),
            radius: 80000
        };

        var lat = '';
        var lng = '';
        var geocoder = new google.maps.Geocoder();
        var marker_user = null;

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lat = results[0].geometry.location.lat();
                lng = results[0].geometry.location.lng();
                marker_user = new google.maps.Marker({
                    position: { lat: lat, lng: lng },
                    map: map,
                    animation: google.maps.Animation.DROP,
                    title: "Your Location"
                });

                if (google.maps.geometry.spherical.computeDistanceBetween(marker_user.getPosition(), marker_start.getPosition()) < 80000)
                    $scope.$apply(function () { $scope.Good = true; });
                else
                    $scope.$apply(function () { $scope.Bad = true; });
            }
        });

        console.log($scope);
        console.log($scope.Good);
        console.log($scope.Bad);
        var cityCircle = new google.maps.Circle(populationOptions);
    };
});

A: Good becomes true only after the callback function passed to geocoder.geocode() has been called. But you're printing it before it has been called, right after having asked the geocoder to geocode.

*

*ask the geocoder to geocode. This sends an HTTP request to Google

*print Good: it's still false

*when the response from Google comes in, the callback is executed and Good becomes true


text:
Q: why nullify instance variables when destroying a stateful EJB? In an example of the @remove annotation on a stateful EJB, the annotated method nullifys the bean's instance variables. Why? Surely destroying the bean destroys its contents, i.e. any variables?
Thanks,
Jon

A: Setting all fields of an object to null has two useful effects:

*

*It provides a hard barrier against logic errors that would lead to an invalid object being reused. The application would crash instead of silently producing incorrect results.

*It helps the Java VM garbage collector by removing edges from the object reference graph, thus improving the overall performance.

A: Can you post the example source code? Or don't. Pro-actively setting null is not needed - when EJB is destroyed and garbage collected soon later, all objects it references (of course providing there are no other references to them) will be garbage collected as well.

A: If ejbRemove(), Attributes of instance are wiped clean and client still has reference to instance. Client still can access the same object. That is not desirable.


text:
Q: Rasterizing vector shapefiles using multiple burn in values I have a vector shapefile of a geographic area that contains several different object codes that I need to rasterize all as one image.

I am working with QGIS, but the Raster>conversion tool seems to be unable to do this (see below).  In the tool, it seems as though you cannot select more than one value, not to mention the tool - even when it works - appears to ignore whatever value you have set and rasterizes all values at once, in the same image.  That would be ok, but I have a large volume of output to complete, and I don't want to separate every needed raster mask into a separate layer, as this would be extremely inefficient and time consuming

So, I tried running the GDAL command it generates, and even the GDAL command, when entered in the python console, errors out.  I have never worked with GDAL before and I am way out of my depth, so I am looking for pointers.
Below is the command I started with (and that QGIS ran successfully when I attempted to rasterize using the form), and no variation of this seems to work in the console, and any edit I perform also returns a syntax error.

gdal_rasterize -l bornholm_final_OSM -a code -ts 100492.0 100492.0 -te
  14.510849428030344 54.922004004836744 15.299793055831714 55.37191520877061 -ot Float32 -of GTiff "E:/My Documents/OSM Stuffbornholm_final_OSM.shp"
  "E:/My Documents/OSM Stuff/point-5m test_qgis2.tif"

I have looked at the GDAL documentation about "gdal_rasterize", but I am truly stumped at this point.  I just need the raster to do multiple classes in one image.
Using @BenW'S answer I am now able to create a raster using GDAL, but I now need to ensure that it retains the colors.

A: I notice you have entered a field to use for the burn in value AND a fixed value to burn. I think you should only enter one or the other. If you enter a fixed value, all your vector features will be burnt to the resulting raster with that one value. If your vector layer has a numeric attribute field with certain values for each feature then you select that field to used for burn in value. Your vector features will then be rasterized with the values from the specified attribute field being burnt to the resulting raster.
If you want to run processing algorithms from the Python console you have to do something like:
import processing
processing.run(name_of_algorithm, parameters)

EDIT:
GDAL is a library of command line utilities, so the command as you have typed it above should be run from the OSGEO4W shell (I am assuming you are on Windows here) not from inside QGIS. The quickest way to launch it is to type "osgeo4w shell" into the search function. At the command prompt you first need to change directory to the location of your shapefile. To do this type cd followed by a space then the full path to your file. Hit enter then type your command e.g. gdal_rasterize etc and hit enter again to run the command
QGIS also provides access to GDAL utilities through the processing toolbox with a gui for entering parameters as shown in in your original post. This should also work fine for your purpose.
It is not entirely clear to me what result you are looking for. It seems from your comment that you want to rasterize all features in your vector that have the value 7502 in an attribute field "code" and burn only those features with that value to the resulting raster. You should select those features in QGIS first which you can do with the option: select features by expression and use your expression "code" = 7502. Make sure the Selected features only box is checked and enter EITHER the "code" field to use for the burn in value OR 7502 as the fixed value (not both).
EDIT 2:
From your original question I assumed that your vector layer has an attribute field "code" with a number of unique numerical values; I guess that field is what has been used to style the vector, and that you want to produce a raster where all the vector features are burnt with the corresponding raster pixels having the values from the "code" field. If that's the case then I'm not sure why you included the 'where' expression. You should include all features and just specify the attribute field "code" to use for the burn in value. You can then use those values to apply a similar colour style to your raster.

A: Here is a Python GDAL implementation for burning one value per feature (specified as a feature field in an ESRI shapefile).
The possible scenarios in terms of vector data formats and use-cases is very large. This code shows a working example for burning a raster with a different value per feature determined as a feature field. Hopefully it is useful for the community and can be easily adapted to other cases:
from osgeo import gdal
from osgeo import ogr
from osgeo import gdalconst

#This raster is the model for our output (CRS, extent)
ndsm = 'geotif_output_extent_proj.tif'
#This shapefile contains the features we want to burn
shp = 'shapefile_features_fields.shp'

data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)

geo_transform = data.GetGeoTransform()
x_min = geo_transform[0]
y_max = geo_transform[3]
x_max = x_min + geo_transform[1] * data.RasterXSize
y_min = y_max + geo_transform[5] * data.RasterYSize
x_res = data.RasterXSize
y_res = data.RasterYSize

vec = ogr.Open(shp)
lyr = vec.GetLayer(0)
pixel_width = geo_transform[1]

output = 'output.tif'
target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1, gdal.GDT_UInt32)
target_ds.SetGeoTransform((x_min, pixel_width, 0, y_min, 0, pixel_width))
band = target_ds.GetRasterBand(1)
NoData_value = 0
band.SetNoDataValue(NoData_value)
band.FlushCache()

driver = ogr.GetDriverByName('ESRI Shapefile')
for feat in lyr:
    burn_value = int(feat.GetField("FIELD_NAME"))
    datasource = driver.CreateDataSource('temp.shp')
    layer = datasource.CreateLayer('temp', lyr.GetSpatialRef(), geom_type=ogr.wkbPolygon)
    layer.CreateFeature(feat)
    gdal.RasterizeLayer(target_ds, [1], layer, burn_values=[burn_value], options=["ALL_TOUCHED=TRUE"])
    datasource.Destroy()

#This makes raster to write to disk
target_ds = None


text:
Q: Unable to get WF Service metadata when BufferedReceive is enabled for Net.Msmq I have a WF service hosted in AppFabric IIS 7/WAS. It is configured for Net.Msmq - this works fine. The client consumes the service fine. If I change the WorkflowService to allow BufferedReceive, then I can no longer navigate to the xamlx to get metadata. The error is as follows:
*

"The contract 'IInstructionServices' has at least one operation
  annotated with 'ReceiveContextEnabledAttribute', but the binding used
  for the contract endpoint at address
  'net.msmq://localhost/private/CSDInstructionProcessing/Instructions.xamlx'
  does not support required binding property 'IReceiveContextSettings'.
  Please ensure that the binding used for the contract supports the
  ReceiveContext capability"

*
Any clues why?

A: I figured this out. This was because the queue was not transactional, and the ExactlyOnce was set to false.


text:
Q: Array of objects with a particular styling in vue

new Vue({
  el: '#app1',
  data: {
  objects:[
  {
    object: {
      title: 'C',
      author: 'Denis',
      publishedAt: '1960'
    }
  },
  {
    object: {
      title: 'Vue',
      author: 'Yet To Find',
      publishedAt: '2010'
    }
  }]}
})

      {{index}}

         {{value}}

new Vue({
  el: '#app1',
  data: {
  objects:[
  {

      title: 'C',
      author: 'Denis',
      publishedAt: '1960'

  },
  {

      title: 'Vue',
      author: 'Yet To Find',
      publishedAt: '2010'

  }]}
})

      {{index}}

         {{value}}

I am able to achieve these two variations. But I am trying to achieve the below
1.
  .C
  .Denis
  .1960
2.
  .
  .
  .

How can I do it from what I have? I am trying to express bullet/number by Dot(.).

A:

new Vue({
  el: '#app',
  data: {
    objects: [{
        title: 'C',
        author: 'Denis',
        publishedAt: '1960'
      },
      {
        title: 'Vue',
        author: 'Yet To Find',
        publishedAt: '2010'

      }
    ]
  }
})
/*ignore - hide snippets console */

.as-console-wrapper {
  max-height: 0px !important;
}

      {{ index + 1 }}

        {{ index + 1 }}. {{ key }} = {{ value }}

A: Maybe so...

  {{index +1}}

        {{prop.author}}
        {{prop.title}}
        {{prop.publishedAt}}


text:
Q: How can I resize a partition without moving it using partition manager (gparted doesn't work with KDE)? I want to resize the current Kubuntu partition, but  KDE partition manager apparently only offers the resize-and-move option. I'm afraid the next boot will fail if I move that partition, correct?
I can't use gparted.
Thank you.

A: KDE has QtParted (mind q instead of g and the extra t).

Mind you: GParted also works in KDE.

I myself made a GParted live DVD that I carry around. That might be an easier option.

A: You can use gparted why not? I am also under Kubuntu now, works for me.
sudo apt-get install gparted
sudo gparted

Move and/or resize your Kubuntu partition.


text:
Q: key combination c# other than hotkeys I am implementing shortcut key combination logic like
Ctrl + A
Ctrl + Alt + D
but now I am looking for a trick to implement keyboard key combination without hotkey combination like : A + D but not getting any right things.
So please help to implement it.
Updated
Currently I am not able to add key combination other than hotkey combination.because whenever I am pressing two keys like : **A + D** it returns only single keys ascii so I am not getting two keys combination.
I have used following stuff
http://www.codeproject.com/Articles/442285/Global-Shortcuts-in-WinForms-and-WPF

A: In the past I used the GetKeyState Api (inside a similar class for catching system wide shortcuts). Perhaps new variants are available nowadays (WPF has a KeyBoard.IsKeyDown I believe), but this should still work:
    [DllImport("user32", CharSet = CharSet.Auto,
    ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    static extern short GetKeyState(int keyCode);

    public static bool CheckKeysPressed(params Keys[] keys)
    {
        for (int i = 0; i < keys.Length; i++)
            if (!CheckKeyPressed((int)keys[i])) return false;
        return true;
    }
    public static bool CheckKeyPressed(Keys key)
    {
        return CheckKeyPressed((int)key);
    }
    public static bool CheckKeyPressed(int vkey)
    {
        short ks = GetKeyState(vkey);
        return ks == 1;
    }

Usage:  if(CheckKeysPressed(Keys.A, Keys.D)) {/*...*/}

A: Declare 2 bool variable (say IsADown and IsDDown) and "true" them on events of both A and D. Also detect on both events if other bool is down or not. If it is, then do what you have to do with both button pressed.


text:
Q: How to parse json object in an array I have a json object like this
{
  "op": "create",
  "collection": "test",
  "args": [
    { "a": 1 },
    { "b": 2 },
    { "c": 3 }
  ]
}

I want to print out all the args element and then divide them seperately. This is what I did to parse json element, I was able to get "op" or "collection" element. However, I was not failed to get "args " element. Here is what I do with the code, what output it gave.
var config= JSON.parse(item) //  I am getting item from the command line
console.log ("op is"+ config.op);
console.log("arg is"+ config.args);

The output is; op is create
args is [object Object], [object Object] ,[object Object]
By the way, I also tried to use stringfy method and it did not work as well

A: Your output args is [object Object], [object Object] ,[object Object] is merely an artifact of how you wrote the console.log command. You've used + to combine the string "args is" with config.args, so config.args is being converted to a string, and since it is an array, the resulting string is a comma-delimited series of each of its elements converted in turn to a string, and an object converted to a string becomes "[object Object]".
Instead, print it this way:

const config = {
  "op": "create",
  "collection": "test",
  "args": [
    { "a": 1 },
    { "b": 2 },
    { "c": 3 }
  ]
};

console.log("arg is", config.args);

How to parse json object in an array

You're deeply confused about the meaning of the word JSON, how to use (or not use) the term "JSON object", and what "parse" means.
"JSON" means exactly one thing: a string following a particular syntax, representing some data. Such a string representation is used because it can be passed around between computer systems, such as clients and servers, and used in different languages. As the json.org site says (my emphasis):

JSON (JavaScript Object Notation) is a lightweight data-interchange format. [...] It is based on a subset of JavaScript [...] JSON is a text format that is completely language independent

In other words, an object literal in JavaScript, such as {a: 1}, or the object which it defines, is not JSON, and will never be JSON, and it is incorrect to refer to it as JSON, or as a "JSON object"--a thing which doesn't even exist in the world, and could not, since JSON is a string. An object in JavaScript is called exactly one thing: a JavaScript object, or if the context is clear, just object (in case you were wondering, it is also never called a "hash", or a "dictionary", or an "associative array"). Such a JavaScript object may have been obtained from JSON retrieved from a server, or it may be destined to eventually be converted into JSON to be sent to a server, and it may even be stored in a variable named jsonObj to remind us of its origin or its destination, but that still does not make it JSON. It is a JavaScript object.
The term "parse" has a very specific meaning in computer science. It means to analyze some input, normally a string, according to some grammar or syntax, and to convert it into some kind of parsed representation. Wikipedia says:

Parsing is the process of analyzing a string of symbols conforming to the rules of a formal grammar.

A JavaScript object does not ever need to be parsed. It is already in the form of a JavaScript object. You can access properties directly, with the basic syntax object.property, or object["property"]. Accessing properties like this is not parsing, and should never be called parsing.
Parsing is something that applies to JSON, when that term is used in the correct sense, namely the sense of a string. We parse the string, according to JSON syntax rules, to create a parsed representation, which in the case of JavaScript will be a JavaScript object. This is what JSON.parse does. And of course JSON.stringify goes in the opposite direction.
In the normal course of JavaScript programming, you will actually find relatively few cases where you need to worry about JSON, or parsing, or stringifying. If you do find yourself worrying about those things, it likely that you're misunderstanding something about your data or your tools. Most APIs for retrieving data from a server will automatically convert JSON provided by the server into a JavaScript object, giving you something that is already parsed and can be accessed directly. Most APIs for delivering data to a server will automatically convert the JavaScript object provided by you into JSON. In neither case do you typically have to worry about parsing or stringifying, other than perhaps making sure to specify some option such as responseType: json on the XHR object. You may need to worry about parsing and stringification if you are storing JavaScript objects in "local storage", since local storage by definition stores strings.

I want to print out all the args element [sic] and then divide them seperately [sic]. This is what I did to parse json element, I was able to get op or collection element. However, I was not failed to get args element.

I understand not everyone is a native English speaker, but it is quite hard to understand this sentence. I guess you mean "print out all the elements (plural) of args". I don't know what you mean by "divide them separately". Do you mean to do something with the elements one by one?  I also don't know what you mean by "This is what I did to parse json element". This is a perfect example of the need to avoid using terms like "parse" and "json" incorrectly; you simply confuse yourself and everyone else.
If what you are saying is that you want to print out the elements of the args property one by one, the way to loop over elements of an array is covered in every basic JS tutorial and intro:

const config = { args: [{ "a": 1 }, { "b": 2 }, { "c": 3 }] };

for (const elt of config.args) console.log(elt);

The for...of form, which you should definitely learn if you don't already know it, loops over the elements of an array.
Or, of course you could also use a regular for loop to loop over the indices of the array, from 0 up to config.args.length.
But what if you want to break down the {"a": 1} property by property, and print each property and its value, one by one? (Is this perhaps what you meant when you said "divide them separately"?) In that case, we need a way to find all the properties, assuming we do not know them in advance. Finding an object's properties will also be covered pretty early in any JS intro, so we don't really need to go into the details here, but let's try writing a function to print out all an object's properties and their values:
function printObjectPropertiesAndValues(object) {
}

We can use this in the code above as follows:
for (const elt of config.args) printObjectPropertiesAndValues(elt);

Since we are just calling a function now on each element, some people might prefer to use map:
config.args.map(printObjectPropertiesAndValues);

You should make very sure you understand what the above line does and how it works.
Anyway, how do we write printObjectPropertiesAndValues? There are a couple of approaches. There are some ideas in other answers. One would be to use the for...in statement, which loops across some object's properties.
function printObjectPropertiesAndValues(object) {
  for (const prop in object) console.log("property", prop, "has value", obj[prop]);
}

You should also make sure you understand exactly what the above code does, and in particular what obj[prop] means and why it works.

A: Do you want something like this?
So the config.args is an array, so we loop throught the array (using for(var x of config.args){), to get the objects inside (E.g: { "a": 1 }), then we get the value alone from the object by looping though the keys (using for(var key in x)), which in our case is only one and get the repective value x[key] and finally push it to the output array output.push(x[key]), then we show the results in the console!

var jsonString = `{
  "op": "create",
  "collection": "test",
  "args": [
    { "a": 1 },
    { "b": 2 },
    { "c": 3 }
  ]
}`
var output = [];
var config= JSON.parse(jsonString);
console.log ("op is"+ config.op);
console.log("keys:")
for(var x of config.args){
  for(var key in x){
    console.log(x[key]);
    output.push(x[key]);
  }
}
console.log("Final Array:")
console.log(output);

A: This works for command line:
1. set your json to a var like this a={"op": "create","collection": "test","args": [{ "a": 1 },{ "b": 2 },{ "c": 3 }]}
2. pipe to jq like this `echo "$a" | jq -r .args


text:
Q: withColumn does not return negative value I am trying to add a column to a dataframe using withColumn. if the reported date or acknoledgement date is null it should return -1 otherwise it should return the difference.
I write dataframe to a csv. It adds a new column to the csv, with the date difference as mentioned in otherwise, but does not return -1 if either of the date values is null. the CSV file has blank value for the when clause. What am I doing wrong?
val df_asbreportssv2 = df_asbreportssv1.withColumn(("AckOverdueby"), when(((df_asbreportssv1("nh_reporteddate").isNull)||(df_asbreportssv1("nh_acknowledgementdate").isNull) == "true"), -1 ).otherwise( datediff((df_asbreportssv1("nh_acknowledgementdate")),(df_asbreportssv1("nh_reporteddate")))))

val TempFilePath = "adl://dldataplatformdev1.azuredatalakestore.net/DDS_Learn/DDS_ASB/temp"
df_asbreportssv2.write
                          .mode("overwrite")
                          .format("csv")
                          .option("header", "true")
                          .save(TempFilePath)

A: The first line of code is not working properly as expected and it needs some refinement as follows.
val df_asbreportssv2 = df_asbreportssv1.withColumn(("AckOverdueby"), when((df_asbreportssv1("nh_reporteddate").isNull) || (df_asbreportssv1("nh_acknowledgementdate").isNull), -1 ).otherwise( datediff((df_asbreportssv1("nh_acknowledgementdate")),(df_asbreportssv1("nh_reporteddate")))))

Hope it helps :)


text:
Q: unable to install gganimate package from Github, both automatically and manually I am currently trying to install the gganimate package but seem unable to.
I am running Win 10, Rx64 3.3.0 and Rstudio 0.99.896;
the following command:
devtools::install_github("dgrtwo/gganimate")

will throw this error:
Downloading GitHub repo dgrtwo/gganimate@master
from URL https://api.github.com/repos/dgrtwo/gganimate/zipball/master
Error in curl::curl_fetch_memory(url, handle = handle) :
  Problem with the SSL CA cert (path? access rights?)

So after a few hours of despair, I decided to try and install the package manually. I followed this link:
here
the following command:
install.packages(pkgs = "C:/Users/Superzucca/Desktop/gganimate-master.zip", repos = NULL)

results in:
    Installing package into 'C:/Users/Superzucca/Documents/R/win-library/3.3'
(as 'lib' is unspecified)

but then when I call:
library("gganimate-master") ####  -> as suggsted by R itself!!

this error is thrown:
Error in library("gganimate-master") : there is no package called 'gganimate-master'

please, help. I don't have any problems installing other pkgs and honestly don't know what else to try.
Thank you in advance,
Superzucca

A: Try out this. It's working for me.
library(devtools)
library(RCurl)
library(httr)
set_config( config( ssl_verifypeer = 0L ) )
devtools::install_github("dgrtwo/gganimate")

A: Figured out the problem, updating with an answer if anybody in the future might need it.
this LINK to another SO question partially solved my problem;
I also had to add R, Rstudio and the library folder to my AntiVirus' excption list, and of course running as administrator :)

A: I had the same problem like you but I was successful at last.
Generally, you have to deal with two issues: first, connecting to github; second, installing both Rcpp and gganimate.
    library(devtools)
    library(RCurl)
    library(httr)
    set_config( config( ssl_verifypeer = 0L ) )
    devtools::install_github("RcppCore/Rcpp")
    devtools::install_github("dgrtwo/gganimate")

A: Try the following:
install.packages("gganimate")

Note: This will depend on the version of R installed and if you are downloading from the Cran site.


text:
Q: Row height when cell contains carriage returns I'm creating a spreadsheet in C# using EPPlus, and some of the cells contain multiline text, with the lines separated by carriage returns. When I open the newly created spreadsheet in Excel, the default row height means that I can only see the first line of text in these cells, e.g.:

After editing that cell (even if I don't actually change anything), Excel automatically adjusts the row height so that the cell can now be seen in full. Note I've added green dots to show where the carriage returns are:

Is there any way to set the row height using EPPlus, so that it looks like the second image when the spreadsheet is first opened in Excel?
Note that I'm also auto-fitting the columns using worksheet.Cells.AutoFitColumns(0);, if that is relevant to the problem.
Edit: I've just made a change whereby I find the cell with the most carriage returns in each row, then multiply the row's height by cell_cr_count + 1. Here, the row height now looks "correct" when I first open the spreadsheet, but weirdly it still only displays the first line of text (until I edit the cell, as before):

Starting to think this is an Excel quirk, and not something that can be fixed using EPPlus?

A: Ok, so in the end it was fairly simple to fix (isn't it always the way after asking a question on SO?!).
If a cell contains a carriage return then I set WrapText to true using worksheet.Cells[rowNum, colNum].Style.WrapText = true.
In my defence, I had already tried applying this to every cell in the spreadsheet (thinking that it would have no effect on most cells), but it screwed up the sheet to the point where every cell was empty when I opened it in Excel.


text:
Q: is 2nd criterion of inference satisfied for the restrictions on rules governing quantifiers
these two criteria are mentioned in patrick suppes book- intro to logic.
then to account for criterion 1 , some rules of restrictions on quantifiers are given.
But about criterion 2, how do we know these rules are enough ?


text:
Q: Swift 4 Alamofire multipart upload not working I am using alamofire 4.7 and swift 4
I need to upload image and json to server.
I am using the following code below for uploading bu  I am getting result failure but data is inserting in server but not getting response, showing some serialization error as something like this
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
    ▿ failure : AFError
      ▿ responseSerializationFailed : ResponseSerializationFailureReason
  ▿ timeline : Timeline: { "Request Start Time": 548835779.066, "Initial Response Time": 548835779.074, "Request Completed Time": 548835779.127, "Serialization Completed Time": 548835779.127, "Latency": 0.008 secs, "Request Duration": 0.061 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.061 secs }
    - requestStartTime : 548835779.06617701
    - initialResponseTime : 548835779.07390201
    - requestCompletedTime : 548835779.12704694
    - serializationCompletedTime : 548835779.12748504
    - latency : 0.0077250003814697266
    - requestDuration : 0.060869932174682617
    - serializationDuration : 0.00043809413909912109
    - totalDuration : 0.061308026313781738
  ▿ _metrics : Optional<AnyObject>

=================================================================
        let auth : String = MitraModal.sharedInstance().getBasicAuthenticationString()
    let headers = ["Authorization": auth, "Content-type": "multipart/form-data"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append("\(parameters)".data(using: String.Encoding.utf8)!, withName: "data" as String)

        if (!imageArray.isEmpty) {

            for item in imageArray {
                multipartFormData.append(item!, withName: "file", fileName: "image.png", mimeType: "image/png")
            }
        }

    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in

                if let JSON = response.result.value
                {
                    print("JSON: \(JSON)")
                    onCompletion?(JSON as? JSON)

                    print("Successfully uploaded")
                }

                if let err = response.error {
                    onError?(err)
                    return
                }
                onCompletion?(nil)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            onError?(error)
        }
    }
}

Anyone help ?

A: As i'm newbie, but Few days ago, i had same problem while uploading image, you must have to accept image by using file on the server side because of your image tag consist withName: "file" .
func AlamofireUploadImages(){

    let url : String = URL_IP+"/ZameenServer/api/addNewProperty.php"
    for img in HOUSEImages{
        let data  = UIImageJPEGRepresentation(img, 0.2)!
        ImagesData.append(data)
    }

    let parameters = [
        "userId"                : "5",
        "unit"                  : "6789"
    ] //Optional for extra parameter

    Alamofire.upload(multipartFormData: { multipartFormData in
        for imageData in self.ImagesData {
            multipartFormData.append(imageData, withName: "file[]", fileName: self.randomString(length: 5)+".jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
        } //Optional for extra parameters
    },
                     to:url)
    { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON
                {
                    response in
                    print("Response :\(response.result.value)")
            }

        case .failure(let encodingError):
            print("no Error :\(encodingError)")
        }
    }

}

NOTE: As i'm uploading array of images so for uploading multile images use withName: "file[]" or for single image use withName: "file"
Might be it helps you.
Thanks

A:    let url = BaseViewController.API_URL + "uploads"
    let image = info[UIImagePickerControllerEditedImage] as? UIImage
    let imgData = UIImageJPEGRepresentation(image!, 0.2)!

    let parameters = [
                            "user_id" : UserDefaults.standard.value(forKey: "userId")!
    ]

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "uload_data",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        } //Optional for extra parameters
    },
                     to:url)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in

                self.objHudHide()
                print(response.result.value)

                let jsonDict : NSDictionary = response.result.value as! NSDictionary

                print(jsonDict)
                if  jsonDict["status"] as! String == "Success"
                {

                    let detailDict : Dictionary = jsonDict["detail"] as! Dictionary<String,Any>

                    if let getTotalPrice = detailDict["total_price"]
                    {
                        self.lblTotalPrice.text = "$ \(getTotalPrice) + Free Shipping"
                    }

                    if  let getTotalSize = detailDict["total_upload_size"]
                    {
                        self.lblTotalSize.text = "Total Size : \(getTotalSize)"

                    }
                }
               else
                {

                let alertViewController = UIAlertController(title: NSLocalizedString("Alert!", comment: ""), message:"Something Went wrong please try again." , preferredStyle: .alert)
                let okAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default) { (action) -> Void in

                }
                alertViewController.addAction(okAction)
                self.present(alertViewController, animated: true, completion: nil)

        }
            }

        case .failure(let encodingError):
            print(encodingError)
        }
    }

A: I get the similar issue as well. This may cause several reasons. In my case that was the error of parameter key of the POST request. When you are executing following line
multipartFormData.append(item!, withName: "file", fileName: "image.png", mimeType: "image/png")

withName:"file" property refers the parameter key (key of the Json request) for the image of the POST request. So you can't use whatever the text you want here. Please add the correct parameter key of the image that your API is referring instead of "file". Let's say API access the image using "fileImage" as the parameter key. So the above line should be something like this.
multipartFormData.append(item!, withName: "fileImage", fileName: "image.png", mimeType: "image/png")


text:
Q: Permutations of columns in a matrix I had a quick question! I have a matrix that has say 8 columns and about 20 rows. Each index of the matrix is filled with some letter. I was wondering if there's an efficient way to produce a permutation (columns) of the matrix? I'm working on a Column Transposition Cipher, and I wanted to essentially test out every column permutation (swapping entire columns) so I can solve the cipher.
Is there an efficient way of doing this using itertools in python or any other technique I'm unaware of? Your help is greatly appreciated!
I first initialize the array doing this:
LMATRIX = [['' for x in xrange(8)] for x in xrange(53)]

Then later on fill it with letters...
E.g
Before Permutation:
0 1 2 3 4 5 6 7
B C R H L M N O
J F K A B C D R

After ONE iteration of the permutation:
**1 0** 2 3 4 5 6 7
**C B** R H L M N O
**F J** K A B C D R

Thanks again!

A: I haven't played much with this solution but it seems to work for simple cases. The matrix is smaller for readability purpose. The idea is that itertools.permutations will produce the same permutations for each row you'll then need to zip them together to rebuild each permuted matrix. You'll need to generalize this code below for bigger matrixes. All read the itertools.permutations carefully to make sure the permutations are the "same" for all potential input
In [1]: import string

In [2]: import random

In [3]: LMATRIX = [[random.choice(string.ascii_uppercase) for y in xrange(3)] for x in xrange(2)]

In [4]: def print_mat(m):
   ...:     for row in m:
   ...:         print row
   ...:

The original matrix is:
In [5]: print_mat(LMATRIX)
['V', 'E', 'E']
['G', 'X', 'T']

In [6]: from itertools import permutations

In [7]: for perm in zip(permutations(LMATRIX[0]), permutations(LMATRIX[1])):
   ...:     print_mat(perm)
   ...:     print "\n"
   ...:
('V', 'E', 'E')
('G', 'X', 'T')

('V', 'E', 'E')
('G', 'T', 'X')

('E', 'V', 'E')
('X', 'G', 'T')

('E', 'E', 'V')
('X', 'T', 'G')

('E', 'V', 'E')
('T', 'G', 'X')

('E', 'E', 'V')
('T', 'X', 'G')


text:
Q: Inconsistency in Star Trek TNG holodeck I'm rewatching TNG, and twice have noticed that objects from the holodeck are able to exit the holodeck. Wesley gets wet and stays wet when leaving; and also has a snowball fight, throwing a snowball which exits the holodeck and hits Captain Picard. How?

A: Holograms can't exit the holodecks on the Enterprise-D, since they require holo-emitters to exist, and there aren't any in the corridors of that vessel.
Holodecks are apparently capable of transporting and/or replicating real matter, however; Data intimated as much in one of the scenes you cited (the one with Wesley Crusher, from Encounter at Farpoint):

Riker: "I didn't believe these simulations could be this real."
Data: "Much of it is real, sir. If the transporters can convert our bodies to an energy beam, then back to the original pattern..."
Riker: "Yes, of course; then these rocks and vegetations have much simpler patterns."
Data: "Correct, sir."

So apparently, the water Wesley was drenched with was real, non-holographic matter (and I'm guessing the same thing applied to the snowball).


text:
Q: How to change line length in UITableView swift I'm using a tableview in my app that has lines not reaching until the end of the row:

In my design I need some of the lines to reach all the way like in this picture:

Also another problem I have is that I see the last line in the tableview:

My question is
how do I make some of the lines all the way across like in the 2nd picture
and another question is
how do I remove the last line of the UITableView ?

A: You can use below code for the tableviewcells in which you want it to be touched to edge of tableview.
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero

Note: As tableview uses reusable cells, so if you are setting separatorInset and layoutMargins, then make sure you are setting it for all cells. Otherwise reused cell will have different separator inset then expected. So, for other cells, keep left=16 in UIEdgeInsets.
for case of hiding the separator case, you have to again play with separatorInset
 cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, UIScreen.main.bounds.width)

A: add a view with light gray background with height of 1 and append to the top of cell. customize in each cell as you needed.

A: *

*You are using custom cell so you can use label/view for line, set the label/view leading and trailing constraints or update label/view height, color according to your requirements and set the table view  separator None.

*Set the condition for last row of table in Table cellForRowAt function and hide the label/view.

A: You can change insets of seperator for last cell in tableview so it will disappear from screen.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableviewCell", for: indexPath) as! TableviewCell

    if indexPath.row == LastCount {
        cell.separatorInset = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.width*2, bottom: 1, right: -(UIScreen.main.bounds.width*3))
    }
    else
    {
        cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    return cell
}

A: to remove that last line or all other lines you have set tableView.tableFooter = UIView() in cellForRowAt


text:
Q: How to swap case with Python regex? I tried to make a one line function to swap a string cases but it doesn't work. Everything makes sense, but the function is returning the same string passed in it without any changes.
import re

def swap_case(string):
    return re.sub('([A-Z])([a-z]+)', r'\1'.lower()+'\2'.upper(), string)

A: Your regex pattern may not match the structure of the input string, e.g. if the first character be lowercase followed by the second uppercase.  Here is a version using re.sub with a callback function:
def swap_case(string):
    return re.sub(r'.', lambda x: x.group().upper() if x.group() == x.group().lower() else x.group().lower(), string)

inp = "Hello World"
print(swap_case(inp))  # hELLO wORLD

The above solution works by toggling each character from lowercase to uppercase or vice-versa.

A: Think that's the right idea, but it doesn't want to do a string conversion to .lower() or .upper() until those values are returned from the regex operation.  Not sure how you'd do that as a one-liner.  They've got a couple different iteration methods.  .findall() did alright, 'cuz you could print each letter out and see what it was doing easily.
#! /usr/bin/env python3
import re

def swap_case( string ):
    newstring = ''
    for s in re .findall( r'([\w ]{1})', string ):
        ##  print( s )
        try: newstring += re .match( r'([A-Z ])', s ) .group(1) .lower()
        except: newstring += re .match( r'([a-z])', s ) .group(1) .upper()
    return newstring

print(  swap_case( 'THIS is A string' )  )

this IS a STRING

https://docs.python.org/3/library/re.html

A: As noted in other answers, your rexexp may not match the input string. As an alternative solution, here's a simple one-liner which works by iterating over the characters of the string:
def swapcase(s):
    return ''.join(ch.upper() if ch.islower() else ch.lower() for ch in s)

Of course, you could also simply use str.swapcase(); see https://docs.python.org/3/library/stdtypes.html#str.swapcase.


text:
Q: is there an overdraw issue in ios I have to create the following layout in iOS.

in android we could use a single EditText to create this.
But in iOS we need

*

*An imageView for background

*A text field for the text

*An image view for search icon

In android this causes overdraw.
is there the same overdraw issue in iOS?

A: Consider using UISearchBar.
Or UITextField with a border (set on its layer), placeholder text and a rightView (set to an image view) for the icon.

A: You can not do without following view combination
An imageView for background
A text field for the text
An imageView for search icon

best possible way is you can loop through the search bar subview and replace or modify the curent subview to create the custom search bar
and there is nothing like over draw because they are key component for drawing a view. if you need any specific clarification then let me know