text:
Q: What does the >>= operator do I was reading the implementation of sort in go, and there is this particular loop in the implementation of func Sort(data Interface):
for i := n; i > 0; i >>= 1 {
    maxDepth++
}

Sort implementation : https://golang.org/src/sort/sort.go
Can someone explain to me what does the >>= operator do ?
Edit: It's simply a shift followed by an affectation. I think the fact it was in a loop bugged my mind.

A: The >> operator is the right shift operator.
>>= is a contracted form of the right shift operator and assignment:
i >>= 1

It is the same as:
tmp := i >> 1
i = tmp

And that is the same thing as (without the need to create a new variable):
i := i >> 1

A: Check:
https://golang.org/ref/spec
left shift             integer << unsigned integer

right shift            integer >> unsigned integer

The shift operators shift the left operand by the shift count
  specified by the right operand. They implement arithmetic shifts if
  the left operand is a signed integer and logical shifts if it is an
  unsigned integer. There is no upper limit on the shift count. Shifts
  behave as if the left operand is shifted n times by 1 for a shift
  count of n. As a result, x << 1 is the same as x*2 and x >> 1 is the
  same as x/2 but truncated towards negative infinity.

Similar questions:
Go << and >> operators
double less operator in Go Tour 37


text:
Q: Do synthesized properties need pointers in their class interface?
Possible Duplicate:
Is there any reason to declare ivars if you're using properties exclusively in Objective-C?

This class:
@interface MyClass
{
    Something* pointer;
}
@property (nonatomic, retain) Something* pointer;
@end

@implementation MyClass
@synthesize pointer
@end

Apparently runs the same as:
@interface MyClass
@property (nonatomic, retain) Something* pointer;
@end

@implementation MyClass
@synthesize pointer
@end

When you create a synthesized property, do you also need a pointer to it in its class interface? I noticed that my program apparently runs the same whether I have the pointer or not. Is it better to have the pointer declared or not?

A: You used to, but you don't anymore. The compiler fills it in automatically for you now, so all you need is to declare the @property and @synthesize it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find and delete value in a vector class Catalog
{
  // string StationTitle;
  string StationLocation;

 public:
  string StationTitle;
  Catalog()
  {
    StationTitle = "";
    StationLocation = "";
  }

  Catalog(string Title, string Location)
  {
    StationTitle = Title;
    StationLocation = Location
  }

  void SetTitle(string Title)  { StationTitle = Title; }
  void SetLocation(string Location) { StationLocation = Location; }

  string GetTitle()    { return StationTitle; }
  string GetLocation() { return  StationLocation; }
};

class StationList
{
  vector<Catalog> List;  //create the vector
  vector<Catalog>::iterator Transit;

 public:
  void Fill();
  void Remove();
  void Show();
};

void StationList::Remove()
{
  string ToDelete;

  cout << "Enter title to delete: " << endl;
  cin >> ToDelete;

  for(Transit = List.begin() ; Transit !=List.end() ; Transit++)
  {
    if(Transit->StationTitle() == ToDelete)
    {
      List.erase(Transit);  //line 145
      return;
    }
  }
}

I would like the user to enter in a StationTitle and for the program to locate the title and delete it if found.  This is what I have come up with so far.
It is giving me a compile error:  chief.cpp:145: error: no match for call to '(std::string) ()'

A: It seems like StationTitle is a property of the class in Transit, not a function. Can't be sure without more code.

A: Your error is here:
 if(Transit->StationTitle() == ToDelete)

Change that line to this:
if(Transit->StationTitle == ToDelete)

OR
if(Transit->GetTitle() == ToDelete)


text:
Q: UART clock into receiver and transmitter So below is a receiver diagram taken from:
https://people.ece.cornell.edu/land/courses/ece4760/PIC32/Microchip_stuff/Ref_Manual/section_21_UART.pdf
I can see that there is a clock "BAUD rate clock from baud rate generator"
It enters into the divider, is this the divided clock?
Or is it the system clock which is divided by the control signal BCLKx?
Also what is the component:
Start bit detect, parity check, stop bit detect, shift clock generator, wake logic
Thanks

A: The clock coming from the generator would be (typically) 16 times the baud rate, to allow for oversampling of input data by 16x. So each bit on bus is 16 clocks.
Start bit detection logic looks for incoming start bit to start the reception of a data frame. It typically checks that too short glitches is not considered as start of frame, while long enough logic low is considered as a start of frame, and the reception of data bits is aligned to the middle of data bits.
So as per above, the generated shift clock would load in data bits from middle of each bit.
Parity checking would make sure that when parity is used, a parity bit that matches the data and parity settings is received, otherwise a parity error is signaled along with the received byte.
Stop bit detection would check if the expected stop bit of a data frame is idle, otherwise there is something wrong with the reception and the received byte is signaled with framing error.
Wake logic can wake up MCU from sleep mode when there is a frame being received.

A:
I can see that there is a clock "BAUD rate clock from baud rate
generator" It enters into the divider, is this the divided clock?

Let's be accurate: it says Baud clock. It doesn't say BAUD rate clock
So, if you search (CTRL-F) the document for Baud clock you find this: -

So no, it is not the divided clock because normally it is 16x the baud rate. It feeds into a divider anyway so it would be pretty useless if it was toggling at the baud rate.

Also what is the component: Start bit detect, parity check, stop bit
detect, shift clock generator, wake logic

They are event flags for use by some other unspecified logic.


text:
Q: Open a new site, scrollbar at the bottom I will at my forum-system when I'm opening a new site that the scrollbar is at the bottom of the site, so that I don't have to scroll down. I have no ideas how to make a code for this, because I'm not the pro in JavaScript..

A: One way is to place a bookmark at the bottom of the page. Example:

When you open the page, include the bookmark as hash. Example:
show

A: You can use css to complete the task:

Use this code in css

You don't need to use JavaScript to hide bottom scrollbar in the html page


text:
Q: MVC view with two forms, why are both rendering to same action? @using (Html.BeginForm("Unassign", "Terminals_DataGroups"))
{
    @Html.HiddenFor(m => m.DeviceId)
    @Html.HiddenFor(m => m.DataGroupId)
    <input type="submit" value="Remove group from device" @(string.IsNullOrEmpty(Model.DataGroupName) ? "disabled=\"disabled\"" : "") />
}

@using (Html.BeginForm("Assign", "Terminals_DataGroups"))
{
    @Html.HiddenFor(m => m.DeviceId)

        @Html.LabelFor(model => model.DataGroups)

        @Html.DropDownListFor(model => model.DataGroupsSelectedItem, new SelectList(Model.DataGroups, "Value", "Text"))
        @Html.ValidationMessageFor(model => model.DataGroupsSelectedItem)

    <input type="submit" value="Assign Data Group" />
}

Yet the HTML renders as:
<form action="/Terminals_DataGroups/Assign" method="post">
    <input data-val="true"
        data-val-number="The field DeviceId must be a number."
        data-val-required="The DeviceId field is required."
        id="DeviceId"
        name="DeviceId"
        type="hidden"
        value="15" />
    <input data-val="true"
        data-val-number="The field DataGroupId must be a number."
        id="DataGroupId"
        name="DataGroupId"
        type="hidden"
        value="1" />
    <input type="submit" value="Remove group from device"  />
</form>

<form action="/Terminals_DataGroups/Assign" method="post">
    <input data-val="true"
        data-val-number="The field DeviceId must be a number."
        data-val-required="The DeviceId field is required."
        id="DeviceId"
        name="DeviceId"
        type="hidden"
        value="15" />

        Data groups

        <select data-val="true"
            data-val-number="The field DataGroupsSelectedItem must be a number."
            id="DataGroupsSelectedItem"
            name="DataGroupsSelectedItem">
            <option value="2">DataGroup2</option>
            <option value="3">DataGroup3</option>
            <option value="5">New group</option>
        </select>

    <input type="submit" value="Assign Data Group" />
</form>

A: you must added ID tag and value
sory my english ;)


text:
Q: Redundant system question so in short. I am building a redundant system of multiple atmega micro controllers.
The way it works is that they are all connected to a single bar, when the system is booted, the first micro controller will execute it's code and make the bar electrically charged. Once it has been, the system will shut down the universal power supply (The only that is powering all micro controllers at once) and only leave on the one that powers the micro controller that produced the signal.
If the first chip fails to produce the signal, because the second will try to produce a signal AFTER the first one, the second chip's power supply will be activated. Etc etc
The only problem I foresee is if micro controllers can fail and have all their digital pins turned on (Meaning that it would not be able to perform complex functions but would still leaving it's digital pins on)
So my question is, is this possible? Can a micro controller fail but still meet my power criteria.
Thanks a lot!

A: If you want to be certain that a system enters a valid state (your shutdown, if I read correctly) you need actual command-words sent between the components of the redundant system, or use signals where you can see if it is a fault or a signal.
This is because stuck pins can occur in any electronics system, so a line going high or low is not really any form of safe.
The way some equipment solves this is to use the 4-20mA protocol. This ensures that if a pin is stuck, the current in the loop will be out of this range, and it is then easy to detect a fault condition.


text:
Q: How can I solve $x^2y''+2xy'+2y=x$ using VoP? Is it possible to solve this differential equation by variation of parameters? If so, how can I compute the complementary solution? Otherwise, how should approach this problem?
$$x^2y''+2xy'+2y=x$$
My Attempt:
When I try to substitute $y=x^m$ into the equation I get the characteristic eq. as $m^2+m+2=0$ which gives $m=(−1−\sqrt 7)/2$ and $m=(−1+ \sqrt 7)/2$. Is this correct ? Thanks in advance!

A: For the homogeneous differential equation:
$$x^2y''+2xy'+2y=0$$
Substitute $y=x^m$:
$$m(m-1)+2m+2=0$$
$$m^2+m+2=0$$
it should give you complex solutions:
$$\Delta =1-8=-7$$
$$\implies m=\dfrac {-1\pm i\sqrt 7}2$$
$$y(x)=\dfrac {\sqrt x}{x}\left(A \cos \left( \dfrac {\sqrt 7}2 \ln x\right)+B
\sin \left (\dfrac {\sqrt 7}2\ln x \right)\right)$$

Note that you have:
$$x^{a+bi}=x^ax^{bi}$$
Now use Euler's formula:
$$=x^a(e^{bi \ln x})=x^a(\cos( b \ln x)+i\sin (b\ln x))$$
And you also have that:
$$x^{a-bi}=x^a(\cos( b \ln x)-i\sin (b\ln x))$$
Since $\sin (-b)=-\sin (b)$.


text:
Q: How can I skip the rest of a script without exiting the invoking shell, when sourcing the script? I have a bash script, where I call exit somewhere to skip the rest of the script when getopts doesn't recognize an option or doesn't find an expected option argument.
while getopts ":t:" opt; do
    case $opt in
        t)
            timelen="$OPTARG"
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            exit 1
            ;;
        :) printf "missing argument for -%s\n" "$OPTARG" >&2
           echo "$usage" >&2
           exit 1
           ;;
    esac
done

# reset of the script

I source the script in a bash shell. When something is wrong, the shell exits.
Is there some way other than exit to skip the rest of the script but without exiting the invoking shell?
Replacing exit with return doesn't work like for a function call, and the rest of the script will runs.
Thanks.

A: You could simply wrap your script in a function and then use return the way you describe.
#!/bin/bash
main () {
    # Start of script
    if [ <condition> ]; then
        return
    fi
    # Rest of the script will not run if returned
}

main "$@"

A: Use return.
The return bash builtin will exit the sourced script without stopping the calling (parent/sourcing) script.
From man bash:

return [n]
  Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body. … If return is used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. …

A: return exits sourced scripts (and functions).
In your case:
while getopts ":t:" opt; do
    case $opt in
        t)
            timelen="$OPTARG"
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            return 1
            ;;
        :) printf "missing argument for -%s\n" "$OPTARG" >&2
           echo "$usage" >&2
           return 1
           ;;
    esac
done

Example test:
$ cat script1.sh
echo script1
source ./script2.sh
echo script1 ends

$ cat script2.sh
echo script2

while true; do
    return
done

echo script2 ends

$ bash script1.sh
script1
script2
script1 ends

Also sourcing script2.sh directly does the correct thing (without exiting from the current shell session):
$ source script2.sh
script2


text:
Q: Double AND Where Clause with between Dates I currently have a query like this
WHERE Category = 'Freezing' OR Category ='Ooredoo FTTH fault'OR Category ='Ooredoo TT fault ' OR Category ='No Picture'

but i want use this date search query with the above code,
im able to use any 1  of this code but im unable to use both query, i have used "AND" or "OR" But its Not working,
ScheduleDate BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'  ```

A: a or b or c and d is ambiguous. You need to use parenthesis to make it explicit how to group the ands and ors. If you want category to match ANY of the options AND the schedule is between certain dates. (a or b or c) and d.
where (
    Category = 'Freezing' or
    Category = 'Ooredoo FTTH fault' or
    Category = 'Ooredoo TT fault ' or
    Category = 'No Picture'
  )
  and ScheduleDate BETWEEN ? AND ?

(Note: Do not use string concatenation to put values into queries, especially not straight from user input. It's a security hole and can cause errors. Use bind parameters.)
(Note: You have an extra space in one of your options.)
You can also use in to make the query simpler.
where
  Category in (
    'Freezing', 'Ooredoo FTTH fault', 'Ooredoo TT fault', 'No Picture'
  )
  and ScheduleDate BETWEEN ? AND ?


text: Q: How to create an installer out of an installer in Java EnvironMent i must created an exe with another Exe. While the first Exe has some restrictions, in the second exe which follows that restrictions. i use Innosetup and Launch4j for creating the first exe and i don't know how to develop an exe while i am execute another exe, is it possible in java environment.


text:
Q: JFugue: play list of music strings using loop I am trying to play a list of music strings using a for loop.
While the first music string is played correctly along with the base, the second and the subsequent do not play simultaneously.
Am i missing something here?
/**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        List<String> musicStringList = new ArrayList<>();

        musicStringList.add("G5i Ri G5i Ri G5i Ri G5i Ri G5i Ri G5i Ri G5i Ri G5i Ri");
        musicStringList.add("D5i Ri D5i Ri D5i Ri D5i Ri D5i Ri D5i Ri D5i Ri D5i Ri");
        musicStringList.add("E5i Ri E5i Ri E5i Ri E5i Ri E5i Ri E5i Ri E5i Ri E5i Ri");

        Player player = new Player();
        String base = "Cmajw Gmajw";
        for (int i = 0; i < musicStringList.size(); i++) {
            List<Pattern> patterns = new ArrayList<>();
            String voice = musicStringList.get(i);
            Pattern p0 = new Pattern(voice);
            p0.setInstrument("Flute");
            Pattern p1 = new Pattern(base);
            p1.setInstrument("Piano");
            patterns.add(p0);
            patterns.add(p1);
            for (int j = 0; j < patterns.size(); j++) {
                patterns.get(j).setVoice(j);
            }
            Pattern[] patternsArr = patterns.toArray(new Pattern[0]);
            player.play(patternsArr);
        }
    }


text:
Q: How to disable Remmina Remote Desktop automatic shortcuts? I noticed that Remmina Remote Desktop comes installed by default in 12.04.  This is great because I have used it in the past and really enjoy it.  Anyways, there is a little problem.  When I am doing RDP connection to my Windows 7 machine, it seems that windows shortcuts are enabled by default, without pressing ctrl or alt or the windows button.  Every time I type the letter "f", the search window pops up in the windows environment, and the text "f" is never entered into the email.  As you could see, writing an email or editing other text is almost impossible like this.
Has anybody had any experience with this?  Know how to fix it?

A: I had the same problem. My solution was to use Windows-Key on my keyboard to deactivate the shortcuts. With Windows-Key + F it seems to can be activated again. Try it.
Additional: The Num-block (NumPad) is working/active only if the Num-Button/Key is deactivated.
I hope it helps.
Regards
Alexej


text:
Q: GRUB disappears after changing description of Windows Boot Manager I installed Elementary OS, and everything worked nicely. I got GRUB when booting the computer, I could boot Windows and Elementary OS. The only problem was that Windows Boot Manager showed up twice in the EFI boot menu. One of them was GRUB, and the other was just Windows. I probably should have just left it alone, but I went into Windows and typed in bcdedit /set {bootmgr} description GRUB
This ruined everything. This actually got rid of the Windows Boot Manager entry in EFI (the one that was secretly GRUB) and left the one that was just Windows. Now I can't get into Linux again.
Most of the tutorials online are about getting GRUB back after installing Windows, or aren't for EFI. For this reason, I'm reluctant to follow those tutorials. They say to reinstall grub to MBR, even though I originally installed it to the EFI partition. That doesn't seem right to me.
EDIT: I got more information on the problem. I reinstalled GRUB, using a common method I found online. I then used efibootmgr, and it appears that when I renamed Windows Boot Manager to GRUB, the new entry was actually created. There is also an entry named ubuntu. However, neither of these entries is in the boot order. I can't change the boot order to add them in though. The command works, but the change does not get saved.

A: I see you found a solution; however, I'd like to point out at least part of the reason for the problem, since that may help you (or others) avoid similar problems in the future....
In the initial dual-boot configuration you describe (Windows/ElementaryOS), you have two boot managers:

*

*The motherboard's (EFI's) built-in boot manager -- This boot manager relies on entries stored in NVRAM, which point to EFI boot programs. The NVRAM entries can be added, deleted, and otherwise modified via programs like efibootmgr in Linux, bcdedit in Windows, and EasyUEFI in Windows. Typically, a computer boots to its default EFI boot program automatically and without pausing to show you a menu at boot time; to get a menu, you must hit a system-specific key soon after you power on the computer or reboot it. Common options for this key include Esc, Enter, and a function key (typically F8 or above).

*GRUB -- After you install ElementaryOS, GRUB should become the default boot program specified by the EFI's built-in boot manager. GRUB is itself a boot manager, though, and in a dual-boot configuration, it should show a boot menu when it runs. This boot menu is constructed through an on-disk configuration file, which is stored at /boot/grub/grub.cfg in ElementaryOS. (Another file, /boot/efi/EFI/ubuntu/grub.cfg, may also be involved.)

(Note: A boot manager presents a menu or some other way for a user to select which OS to boot. A boot manager typically hands off to a boot loader, which loads an OS kernel into memory and hands over control to the kernel. Some programs, including GRUB, are both boot managers and boot loaders; but others, like the EFI boot manager or the Linux EFI stub loader, are one or the other but not both. Linux users are often sloppy about distinguishing between these two types of programs because GRUB does both jobs.)
In any event, when you ran bcdedit in Windows, you adjusted the EFI's boot manager, but this had no effect on the GRUB configuration. Thus, you ended up bypassing GRUB, which of course is not what you'd intended. To modify GRUB's menu, you need to edit its configuration file, but that's a more awkward process than you might expect, since grub.cfg is actually constructed by scripts so that it can be customized for your particular system. The GRUB Customizer tool presents a relatively friendly GUI front-end to GRUB customization, but I'm not an expert on its use. It's also possible to use other boot managers and boot loaders in Linux, bypassing GRUB entirely.
Another issue that's likely relevant is Secure Boot. ElementaryOS is based on Ubuntu, which uses a program called Shim for Secure Boot Support. The Shim binary (shimx64.efi) is signed by Microsoft and is therefore trusted by most EFIs. Shim's main purpose is to expand the number of Secure Boot keys that the firmware will accept and to launch GRUB (grubx64.efi), which in turn is signed with another key (Canonical's, in the case of Ubuntu, and presumably also therefore ElementaryOS, although I've not checked this).
Given the nature of your solution, I suspect you had at least two entries for ElementaryOS in your EFI's NVRAM boot listing, one of which pointed to Shim and the other of which pointed to GRUB. I'm guessing that the one that pointed directly to GRUB came earlier in your boot order, but was ignored by the firmware because it failed the firmware's unmodified Secure Boot test. When you told the firmware to trust GRUB, though, it began passing the test and so GRUB would launch. It might have been set up some other way initially, but your mistake with bcdedit in Windows wiped out or changed the order of the entry that booted via Shim. Your re-installation of GRUB also likely mucked with things a bit.
If you want to understand this even better, I recommend you read one or more of the following:

*

*Adam Williamson's blog entry on how EFI works -- This page describes the theory behind EFI-mode booting.

*A question and answers on the differences between BIOS and EFI booting on Superuser.com -- This provides the basics of the preceding, but is more concise.

*My page on EFI boot loaders for Linux -- This page describes EFI boot loader choices for Linux systems. There are two sub-pages on Secure Boot.

Even the sum total of these pages won't tell you precisely what happened on your system, but you may be able to better diagnose it by examining your sudo efibootmgr -v output, and to fix similar problems should they occur in the future.

A: I found the solution on my own. Apparently, I had to mark grubx64.efi as trusted in the UEFI settings. This is really strange though since I had Secure Boot off the whole time. Anyway, this added a new entry for the EFI bootloader, and this entry does indeed load GRUB, as it should.


text:
Q: Lattice points in a circle I've started reading about Gauss circle problem.
As I've read H.steinhaus(one of the great polish mathematicians of the history) has proved : for every positive integer "n" there exists a circle of area "n" which contains exactly "n" lattice points (point with integer coordinates).
I'm looking for his proof and some other articles about main problem(function which counts lattice point in a circle).


text:
Q: How to secure Android App that pulls data from OAuth protected resource My company is building a RESTful API that will return moderately sensitive information (i.e. financial information, but not account numbers).  I have control over the RESTful API code/server and also am building the Android app.  I've setup the API to use OAuth 2 with authorization code grant flow (with client ID and secret), and I auto-approve users without them having to approve the client since we own both client and provider.  We use CAS for SSO and I am using this for the Authorization server as part of the OAuth 2 process when the user logs in to retrieve the token.
I am contemplating various ways to secure the data on the Android app.  I've concluded that storing the client id and secret on the device is definitely not going to happen, but am thinking that storing the auth token might work, since it is only risk to the individual user (and really only if they happen to have a rooted phone).
Here are two options I have thought of.  They both require me to have a sort of proxy server that is CAS protected, does the dance with the API server, and returns the auth token.  This gets rid of the need for storing the client id and secret in the app code.
Here are what I've come up with:
1) Require the user to enter their password to access data each time they startup the App.  This is definitely the most foolproof method.  If this were done, I'd probably want to save the userID for convenience, but in that case couldn't use the CAS login (since it's web-based). I might be able to use a headless browser on the backend to log the user into CAS and retrieve the token based on what they enter in the Android form, but this seems hacky. Saving the userID is similar to what the Chase app does (if you happen to use this one) - it saves the userID but not your password between sessions.
2) Store the auth token on the Android device. This is a little less secure, but almost foolproof. When the user starts the app for the first time, open the webpage to the CAS login of the proxy server that returns the token (similar to https://developers.google.com/accounts/docs/MobileApps).  After the user logs in and the token is returned to the app, encrypt it and store it private to the application.  Also, use ProGuard to obfuscate the code, making the encryption algorithm more difficult to reverse engineer.  I could also work in a token refresh, but I think this would be more of a false sense of security.
3) Don't use CAS but come up with another way to get an auth token for the service.
Any advice of how others have implemented similar scenarios (if it's been done)?
Thanks.

A: Well the reason why standards like OAuth are developed is that not everyone has to rethink the same attack vectors again and again. So most often it is your best choice to stick to something already available instead of baking your own thing.
The first problem with clients that are not capable of secretly storing data is that the user's data could be accessed by some attacker. As it is technically not possible to prevent this (code obfuscation won't help you against an expert attacker), the access token in OAuth 2 typically expires after short time and doesn't give an attacker full access (bounded by scope). Certainly you shouldn't store any refresh token on such a device.
The second problem is client impersonation. An attacker could steal your client secret and access your API in his own (maybe malicious) app. The user would still have to login there himself. The OAuth draft there requires the server to do everything it can to prevent this, but it is really hard.

The authorization server MUST authenticate the client whenever possible. If the authorization server cannot authenticate the client due to the client's nature, the authorization server MUST require the registration of any redirection URI used for receiving authorization responses, and SHOULD utilize other means to protect resource owners from such potentially malicious clients. For example, the authorization server can engage the resource owner to assist in identifying the client and its origin.

I think Google are the first to try another approach to authenticate a client on such devices, by checking the signature of the application, but they are not yet ready for prime time. If you want more insight into that approach, see my answer here.
For now, your best bet is to stay on the OAuth way, i.e. having the access token, client ID and client secrect (when using the authorization code grant flow) on the device, and configure your server to do additional checks. If you feel more secure obfuscating these, just do it, but always think of it as if these values were publicly available.


text:
Q: Strange Queue Behavior I have a queue in Java which is exhibiting strange behavior. If I call q.size(), After elements are pushed into the queue, only the first half of the items are popped out of the same queue. However, all of the items are popped if I store the value returned by q.size() before popping any items off of q. Why is that? The official documentation says:

public int size()
Returns the number of elements in this list.

Here is the code I am using. I used three different compilers: JDK 6.0_31, JDK 7.0_7, and Eclipse Compiler 0.A48. The results are the same.
import java.util.*;

public class StrangeQueueTest{
   public static void main(String[] args){
      Queue<String> q = new LinkedList<String>();
      String[] testData = {"1: one", "2: two", "3: three", "4: four", "5: five",
         "6: six", "7: seven", "8: eight", "9: nine", "10: ten", "11: eleven",
         "12: twelve", "13: thirteen", "14: fourteen", "15: fifteen",
         "16: sixteen", "17: seventeen", "18: eighteen", "19: nineteen",
         "20: twenty"};

      //Push items into the queue
      for(int x = 0; x < testData.length; x++)
         q.add(testData[x]);

      //Pop items out of the queue, calling size() at every iteration
      for(int x = 0; x < q.size(); x++)
         System.out.println(q.poll());

      //Pop items out of the queue, calling size() once
      /*int count = q.size();
      for(int x = 0; x < count; x++)
         System.out.println(q.poll());*/
   }
}

Why doesn't the size() method work consitently? Am I doing something wrong? If so, what?

A: You only get half the elements because you are counting from both ends and you stop when you reach the middle. Put another way: Every time you poll(), you reduce size() by one. At the same time, you are counting how many you have removed. The problem is that you have coded your loop to stop when the number you have removed is at least as large as the remaining size.
Instead of this:
for(int x = 0; x < q.size(); x++)
     System.out.println(q.poll());

use this:
while (q.size() > 0)
     System.out.println(q.poll());

A: (This is really an extended comment. I agree with the prior answers.)
Almost always, when it seems an API method is not following its specification, the problem is really in the test program. The next question is how the original questioner could have found what was going on, without just seeing the problem.
The first step in debug is to get information. The behavior of x and q.size() in the loop seem possibly relevant, so I modified the loop to:
  for (int x = 0; x < q.size(); x++) {
    System.out.println("x=" + x + ", q.size()=" + q.size());
    System.out.println(q.poll());
  }

and ran the program. The output was:
    x=0, q.size()=20
    1: one
    x=1, q.size()=19
    2: two
    x=2, q.size()=18
    3: three
    x=3, q.size()=17
    4: four
    x=4, q.size()=16
    5: five
    x=5, q.size()=15
    6: six
    x=6, q.size()=14
    7: seven
    x=7, q.size()=13
    8: eight
    x=8, q.size()=12
    9: nine
    x=9, q.size()=11
    10: ten

This output makes it obvious that each iteration of the loop both increases x and decreases the queue size, causing x stop being less than the size half way through.


text:
Q: Dumping entity in Spring Boot I am using Spring Boot with Kotlin, and want to dump an entity to the browser.
Entities.kt:
@Entity
class Person(
    var name: String,
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null
)

@Entity
class Cat(
    var name: String,
    @ManyToOne var ownedBy: Person,
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null
)

HtmlController.kt:
@Controller
class HtmlController(private val repository: CatRepository) {

    @GetMapping("/")
    fun index(model: Model): String {
        model["cats"] = repository.findAll()
        return "index"
    }
}

In my index template I am able to loop through the cats with {#cats}{/cats}, but I want to dump the whole lot out (e.g. to see what relationships are available). Is that possible? I tried modifying the controller above to return respository.findAll().toString() but that gives me the error:

There was an unexpected error (type=Not Found, status=404).

A: When returning a String from a Controller, Spring MVC will assume that you are pointing to a view-file. So it will look for a file in some configured folder, where the file name is the string-representation of a list of Cats. This, of course, does not exist, and you get a 404.
The simplest way of doing this would be to create a "REST-style" endpoint, and return the data as a fitting data format, for instance json. My example is with Java, but you could transform to Kotlin:
@RestController
public class CatRestController {

    @Autowired
    private CatRepository repository;

    @RequestMapping(path = "/cats", method = RequestMethod.GET)
    public List<Cat> getAllCats() {
        return repository.findAll();
    }
}

Spring Boot should automatically convert the list to json. The method might work if moved to your existing Spring MVC controller, but I haven't tested. I have an example from a regular Spring MVC project (not Spring Boot), and the method signature looks something like this:
@RequestMapping("/cats.json")
public @ResponseBody List<Cat> getCats() {


text:
Q: On any of my Heroku apps, several `heroku pg:` commands fail immediately with "Cannot read property 'includes' of undefined." (When I asked this previously, it was incorrectly flagged as a duplicate of this one. They are not related.)
On any of my Heroku apps, several heroku pg: commands fail immediately with Cannot read property 'includes' of undefined.
For example:
$ heroku pg:push mydb DATABASE_URL -a $myapp
heroku-cli: Pushing mydb ---> postgresql-vertical-12345
 case
------

(1 row)

 ▸    Cannot read property 'includes' of undefined

$ heroku pg:ps -a $myapp
 ?column?
----------
(0 rows)

 ▸    Cannot read property 'includes' of undefined

This started within maybe the past two weeks. I have created/destroyed many apps, always with the same result. My goal is just to be able to push my local data. This error message doesn't exactly give me much in the way of next steps.
Is this a bug, or am I doing something wrong (in which case, how do I fix it)?

A: I have the same issue here and have created a support ticket, they responded by linking me to your github heroku/cli ticket.
I now see they have updated the docs on how to push a local db and recommend using s3 https://devcenter.heroku.com/articles/heroku-postgres-import-export#import:
Generate a signed URL using the aws console:
aws s3 presign s3://your-bucket-address/your-object
Use the raw file URL in the pg:backups restore command:
heroku pg:backups:restore '<SIGNED URL>' DATABASE_URL
I haven't tried it yet but might be a workaround

A: just had the same issue.. Updating the CLI fixed it for me. Just need to run heroku update ..


text:
Q: WCF and using WEBGET to test service in browser Hi I am very new to using WCF (half a day old) and I have created a service which I can see via localhost
http://localhost:[port]/Service1.svc? - no 404!
However, before I want to connect to this service via an application, I want to see if the service does actually return what is meant to. (Just making sure the database connection is OK etc)
I have this on my IService (unfortunately it is in VB.Net, but I do know C#..)
<OperationContract>
<WebGet(UriTemplate:="/method/{parameter}")>
Function getData(ByVal parameter As Integer) As String

And this of course fires (or should) the method getData in the service1.svc class.
So firing up the webservice, I tried to do this...

http://localhost:61094/Service1.svc?method/1

and

http://localhost:61094/Service1.svc/method/1

However nothing. (doesnt debug on the code either)
Looking around, It could be do with my web config file which I haven't touched.
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

What is it that I am missing?
Thanks

A: You could try setting up an explicit service definition:
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
        <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="WebBehavior">
                    <webHttp/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <services>
            <service name="WebApplication1.Service1">
                <endpoint address="" binding="webHttpBinding" contract="WebApplication1.IService" behaviorConfiguration="WebBehavior" />
            </service>
        </services>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
    </system.webServer>
</configuration>

and then have a contract:
Imports System.ServiceModel
Imports System.ServiceModel.Web

<ServiceContract()>
Public Interface IService
    <OperationContract>
    <WebGet(UriTemplate:="/method/{parameter}")>
    Function getData(ByVal parameter As String) As String
End Interface

and an implementation:
Public Class Service1
    Implements IService

    Public Function getData(ByVal parameter As String) As String Implements IService.getData
        Return "Foo bar"
    End Function
End Class

Now navigating to /Service1.svc/method/123 will invoke the proper method.


text:
Q: Show a by ng-repeat select option (AngularJS) I'm trying to make a select list with two or three options, which depends on the first selected option in a ng-repeat. When the customer selects in the first option "Dome Camera" there should be only list two options in the second ng-repeat based on the listed mounting items (in this case: roof, wall and pole).
Can somebody help me with this?

    <select class="form-control" name="type-camera">
      <option ng-repeat="camera in cameraTypes">{{camera.name}}</option>
    </select>

    <select class="form-control" name="type-camera">
      <option ng-repeat="mounting in ?????">{{mounting}}</option>
    </select>

The $scope.cameraTyps looks like:
"0": {
      "name": "Dome Camera",
      "price": 2975.67,
      "install": 4,
      "mounting": {
        "name": "roof",
        "name": "wall",
        "name": "pole"
      }
    },
    "1": {
      "name": "WV-SF135E",
      "price": 327.70,
      "install": 1.5,
      "mounting": {
        "name": "roof",
        "name": "wall"
      },
      "lens": "fixed"
    }

A: This should help you https://stackoverflow.com/a/22017098/1703519
Basically you add an ng-change function to the select box, and from there you can change the option list that the second select list is looking at dynamically.
Look at the fiddle from that answer to see a similar example (not exactly your scenario but close)

A: So if I understand you correctly, you want to make the list of the second ng-repeat dependent on the selection of the selected option of the first list? That can easily be achieved by using ng-model with ng-change

    <select class="form-control" name="type-camera" ng-model="selectedCamera" ng-change="onChangeCamera();">
      <option ng-repeat="camera in cameraTypes">{{camera.name}}</option>
    </select>

    <select class="form-control" name="type-camera">
      <option ng-repeat="mounting in mountingList">{{mounting}}</option>
    </select>

In your controller:
$scope.onChangeCamera = function() {
  if($scope.selectedCamera.name === 'Dome Camera') {
    //For example
    $scope.mountingList = ['Roof', 'Wall', 'Pole'];
  }
}

A: First of all, your data structure is incorrect, I think your mounting object in fact is an array, so I changed it.
Point 1: I extremely recommend you to use ngOptions instead of ngRepeat. ngOptions was made exactly for <select> tag.
Point 2: You don't need to use ngChange directive or $watch as some people suggested, you just need to set the ngModel, then Angular can do the rest.
See it in action:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.cameraTypes = [
       {
          "name":"Dome Camera",
          "price":2975.67,
          "install":4,
          "mounting":[
             {
                "name":"roof"
             },
             {
                "name":"wall"
             },
             {
                "name":"pole"
             }
          ]
       },
       {
          "name":"WV-SF135E",
          "price":327.70,
          "install":1.5,
          "mounting":[
             {
                "name":"roof"
             },
             {
                "name":"wall"
             }
          ],
          "lens":"fixed"
       }
    ];
  });
<!DOCTYPE html>

        <select class="form-control" name="camera-type" ng-options="camera.name for camera in cameraTypes" ng-model="camera">
          <option value="">Select a camera</option>
        </select>

        <select class="form-control" name="mounting-type" ng-options="m.name for m in camera.mounting" ng-model="mounting">
          <option value="">Select a mounting</option>
        </select>


text:
Q: Case when no record then error (postgresql) Struggling with a simple problem and find no solution.
https://ideone.com/Hisu8H (sqlfiddle mini) Should be two rows, but only one OK appears.
If there is a record there should be an OK result. If no records there should be ERROR result.
SELECT
CASE WHEN (SELECT count(*) from code)=0 THEN 'ERROR' else 'OK' end
FROM code
WHERE "CODE_ID"='EXISTS'

The problem is that if the CODE_ID exists, there will be a line OK but if the record is missing there will be no line fetched at all.
In a simple query this works. But not as a condition!
SELECT COALESCE(count(*), 0) FROM code
WHERE "CODE_ID"='ERROR'

Thanks in advance for any clue!

A: If there is no row that matches the condition then nothing is returned and you can't count it.
To return information about values that are used in a condition but do not exist in the database you typically use an outer join on the list of values:
select t.id,
       code.code_id
from (
  values ('error'), ('test')
) as t (id)
  left join code on code.code_id = t.id;

This essentially a where code_id in ('error', 'test') query that also returns those values from the in list that do not exist in the table.
This can then be used to identify the missing values:
select t.id,
       case when code.code_id is null then 'Error' else 'OK' end as status
from (
  values ('error'), ('test')
) as t (id)
  left join code on code.code_id = t.id;


text:
Q: wholeTextFiles Method is failing with ExitCode 52 java.lang.OutOfMemoryError I have HDFS directory with 13.2 GB and 4 files in it. I am trying to read all files using wholeTextFile method in spark, But i have some issues
This is my code.
val path = "/tmp/cnt/warehouse/"
val whole = sc.wholeTextFiles("path",32)
val data = whole.map(r => (r._1,r._2.split("\r\n")))
val x = file.flatMap(r => r._1)
x.take(1000).foreach(println)

Below is the spark Submit.
spark2-submit \
--class SparkTest \
--master yarn \
--deploy-mode cluster \
--num-executors 32 \
--executor-memory 15G \
--driver-memory 25G \
--conf spark.yarn.maxAppAttempts=1 \
--conf spark.port.maxRetries=100 \
--conf spark.kryoserializer.buffer.max=1g \
--conf spark.yarn.queue=xyz \
SparkTest-1.0-SNAPSHOT.jar

*

*even though i give min partitions 32, it is storing in 4 partitions only.

*My spark submit is correct or not?

Error Below
Job aborted due to stage failure: Task 0 in stage 32.0 failed 4 times, most recent failure: Lost task 0.3 in stage 32.0 (TID 113, , executor 37): ExecutorLostFailure (executor 37 exited caused by one of the running tasks) Reason: Container from a bad node: container_e599_1560551438641_35180_01_000057 on host: . Exit status: 52. Diagnostics: Exception from container-launch.
Container id: container_e599_1560551438641_35180_01_000057
Exit code: 52
Stack trace: ExitCodeException exitCode=52:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:604)
    at org.apache.hadoop.util.Shell.run(Shell.java:507)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:789)
    at org.apache.hadoop.yarn.server.nodemanager.LinuxContainerExecutor.__launchContainer__(LinuxContainerExecutor.java:399)
    at org.apache.hadoop.yarn.server.nodemanager.LinuxContainerExecutor.launchContainer(LinuxContainerExecutor.java)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Container exited with a non-zero exit code 52
.
Driver stacktrace:

A:

*

*Even though i give min partitions 32, it is storing in 4 partitions
  only.

You can refer below link
Spark Creates Less Partitions Then minPartitions Argument on WholeTextFiles

*My spark submit is correct or not?

Syntax is correct but value you have passed is more than it needed. I mean you are giving 32 * 15 = 480 GB to Executors + 25 GB to driver just to process  13 GB data?
Giving more executors and more memory does not give efficient result. Sometime it cause overhead and also failure due to lack of resources
Error is also showing issue with resources you are using.
For processing only 13 GB data you should use like below configurations (not exactly, you have to calculate):
Executors # 6
Core #5
Executor-Memory 5 GB
Driver Memory 2 GB
For more details & calculation you can refer below link:
How to tune spark executor number, cores and executor memory?

Note: Driver does not require more memory than Executor so Driver
  memory should be less or equal to Executor memory in most of cases.


text:
Q: the server tag is not well formed. do u know? Please can anyone tell me why this happened?
<asp:TemplateField HeaderText="Receta">
    <ItemTemplate>
        <asp:Image ID="Receta1" runat="server" ImageUrl='<%# "Handler1.ashx?PacientId=" + Eval("PacientId") %>' Height="200px" Width="200px"
    </ItemTemplate>
</asp:TemplateField>

A: Your asp:Image is missing the ending /> to it.  That would definitely cause the error.


text:
Q: .Net - why does the contents of my ContextMenu appear on my UserControl? I have the following problem. When I create a control using a ContextMenu in .NET, the control somehow gets the second two lines of the ContextMenu and displays it.

The UserControls code is here:
public partial class Icon : UserControl
{
    private static int IconCount = 0;

    public struct IconPrefs
    {
        public string title;
        public string image;
    }

    public Icon(IconPrefs prefs)
    {
        InitializeComponent();
        SuspendLayout();
        IconPrefs icon = prefs;
        SetupIcon(icon);
        ResumeLayout();
        Refresh();
    }

    private void SetupIcon(IconPrefs icon)
    {
        IconCount++;

        PBIcon.Image = Image.FromFile(icon.image);
        PBIcon.SizeMode = PictureBoxSizeMode.StretchImage;
        ForeColor = Color.Black;
        LblIconTitle.Text = icon.title;

        Tag = icon;
    }
}

And this is how it is used:
private void addNewApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
        prefs.title = "Computer";
        prefs.image = @"GUIImages/Default/System/Computer.ico";

        Controls.Icon icon = new Controls.Icon(prefs);
        TFLP.Controls.Add(icon);
}

Any ideas how to get the control to work as expected?


text:
Q: How to compute the chi-y genus for a non-Kahler manifold? I am a physicist and first-time poster so I will do my best to make this question clear. Apologies in advance if it's trivial.
I am trying to compute the chi-y genus of the "Goldstein-Prokushkin manifold" formed from a certain torus fibration over a K3 surface. (http://arxiv.org/pdf/hep-th/0212307v2.pdf). In particular, the total space is non-Kahler with known Betti numbers and SU(3) structure group.
Formally, it looks like I will need to compute the dimensions of $H^p(X, \bigwedge^q E)$ where $E$ is the bundle over the total space X. The Hirzebruch-Riemann-Roch theorem relates this quantity to $\int_X ch(\bigwedge^q E)td(X)$ for each q.
However, in practice I have never computed these quantities and have struggled to find a sample computation. My question then is a.) if I need to use HRR to compute the chi-y genus, can someone provide some technical guidance or a reference to proceed? and b.) Is there perhaps an alternative way to compute these quantities using what's known about the manifold that is more transparent than HRR? (In the paper they construct a Gysin sequence relating cohomology classes of the total space to cohomology classes of the base K3 but I'm totally unfamiliar with Gysin sequences and moreover they were computing $H^p(X, \mathbb{R})$ rather than $H^p(X, \bigwedge^q E)$).
Thanks for your help!


text:
Q: Hide Navigation Bar SwiftUI for MacOS 11.1 Is there a way to completely hide the Navigation bar on the MacOS version of SwiftUI?  I know there's navigationBarHidden(true) but that only works on iOS from what I've seen.
So I'm trying to have something like a title screen when the app boots so the user has to press enter and it goes to different screen.
struct TitleScreen: View {
    var body: some View {

        ZStack {
            Color.customColor
                .ignoresSafeArea(.all)

            NavigationView {
                 NavigationLink(destination: MainMenu()) {
                     /*nothing*/
                }.keyboardShortcut(KeyEquivalent.return, modifiers: .init())
            }

            VStack {
                Text("Press Enter!")
            }
        }
    }
}

struct MainMenu: View {
    var body: some View {
        Text("Main Menu")

        Image("placeholder")
    }
}

I'm trying to have the Navigation bar that appears due to NavigationView not be there.
Also it would be nice if the original View in TitleScreen went away in some way but I can worry about that later.

A: Ok so it turns out that wasn't even my problem, and this is really a duplicate question of this: macOS SwiftUI Navigation for a Single View.


text:
Q: Can I use my iPod classic to store photos for my Canon 5D MkII? I have an 80GB iPod classic. I am going on a trip and I have only the iPod, my iPhone, and my iPad. I want to use the iPod to store photos.
Is this possible?

A: Yes.
You need the discontinued "iPod" camera connector. (not to be confused with the iOS iPad camera connector)

*

*http://support.apple.com/kb/TA38187
They are for sale on Amazon (and of course at local thrift shops and electronics shops worldwide).
http://www.amazon.com/Apple-Camera-Connector-iPod-White/dp/B000KIRGF4


text:
Q: Comparing two text files and counting number of occurrences I'm trying to write a blog post about the dangers of having a common access point name.
So I did some wardriving to get a list of access point names, and I downloaded a list of the 1000 most common access point names (which there exists rainbow tables for) from Renderlab.
But how can I compare those two text files, to see how many of my collected access point names that are open to attacks from rainbow tables?
The text files are build like this:
collected.txt:
linksys
internet
hotspot

Most common access point names are called
SSID.txt:
default
NETGEAR
Wireless
WLAN
Belkin54g

So the script should sort the lines, compare them and show how many times the lines from collected.txt are found in SSID.txt ..
Does that make any sense? Any help would be grateful :)

A: If you don't mind using python script:
file1=open('collected.txt', 'r')            # open file 1 for reading
with open('SSID.txt', 'r') as content_file: # ready file 2
    SSID = content_file.read()

found={}                                    # summary of found names
for line in file1:
    if line in SSID:
        if line not in found:
            found[line]=1
        else:
            found[line]+=1
for i in found:
    print found[i], i                       # print out list and no. of occurencies

...it can be run in the dir containing these files - collected.txt and SSID.txt - it will return a list looking like this:
5 NETGEAR
3 default
(...)

Script reads file 1 line-by line and compares it to the whole file 2. It can be easily modified to take file names from command prompt.

A: First, take a look on a simple tutorial about sdiff command, like How do I Compare two files under Linux or UNIX. Also, Notepad++ support this.

A: To find the number of times each line in file A appears in file B, you can do:
awk 'FNR==NR{a[$0]=1; next} $0 in a { count[$0]++ }
    END { for( i in a ) print i, count[i] }' A B

If you want the output sorted, pipe the output to sort, but there's no need to sort just to find the counts.  Note that the $0 in a clause can be omitted at the cost of consuming more memory, which may be a problem if file B is very large.


text:
Q: In R, looking for a more detailed str() showing full names or a tree I want to change parts of a ggplot2 object made by a function and returned as a result, to remove the Y-axis label. No, the function does not allow that to be specified in the first place so I want to change it after the fact.
str(theObject) ## shows the nested structure with parts shortened to ".." and I want to be able to type something like:

theObject$A$B$C$myLabel <- ""

So how can I either make an str -like listing with full paths like that or perhaps draw a tree structure showing the inner working of the object?
Yes, I can figure things out using names(theObject) and finding which branch leads to what I am looking for, then switching to that branch and repeating but it looks like there could be a better automated way to find a leaf node such as:
leaf_str(obj=theObject, leaf="myLabel")

might return zero or more lines like:
theObject$A$B$C$myLabel

theObject$A$X$Y$Z$myLabel

Or, the entire structure could be put out as a series of such lines.
I have searched and found nothing quite like this. I can see lots of uses especially in teaching what an object is. Yes, S4 objects might also use @ as well as $.

A: The
tree

function in the xfun package may be useful.
See here for more details
https://yihui.org/xfun/


text:
Q: Java Adding Large Data ro ArrayList I made a program which reads a text file which contains tweets. This text file is 16MB so it's really large. My program reads it line by line and adds words to an ArrayList. While doing this, I got an ArrayIndexOutOfBoundsException. I debugged my code to part where it throws exception. I noticed that, code keeps running after throwing exception and adds words to ArrayList.
java.lang.ArrayIndexOutOfBoundsException: 0
    at Test.main(Test.java:39)
java.lang.ArrayIndexOutOfBoundsException: 0
    at Test.main(Test.java:39)
java.lang.ArrayIndexOutOfBoundsException: 0
    at Test.main(Test.java:39)
java.lang.ArrayIndexOutOfBoundsException: 0
    at Test.main(Test.java:39)
#Jobs: 272
#Job: 269
#jobs: 225
#TweetMyJOBS: 223
#job: 155

That's how it looks on console. After multiple exceptions, my program runs and displays a result. Result is also wrong.For example, first one should be  #Jobs: 4251. Does anybody have any idea why would it throw exception then keeps running?
here is the code:
try
        {
            line = reader.readLine();
            // scan = new Scanner(textinput);
            while (line != null)
            {

                String[] splitted = line.split("#"); // Line splitted according to "#".

                for (int x = 1; x < splitted.length; x++)
                {
                String[] temp = splitted[x].split(" "); // String splitted with space and first word is hashtag.
                try
                {
                   //Line 39 is here.
                    hashtags.add(temp[0]); // hashtag added to ArrayList.

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

            }
            line = reader.readLine();
            linenum++;
        }

    } catch (FileNotFoundException e1)
    {
        e1.printStackTrace();
    }

A: 16MB is not big. Your code keeps running because you catch the exception and just display the stacktrace. The exception results from temp being a zero length array, most likely because splitted[x] was an empty String.
A good way to debug your code is to print (or log) values during the excution, especially when an exception is thrown.

A: ArrayIndexOutOfBounds exceptions are not caused by large amount of data. They are caused when you try to access an element that does not exist.
int[] apples = new int[5];
apples[7];

This would give me an ArrayIndexOutOfBoundsException because apples [7] does not exist.


text:
Q: CUPS and Foomatic fail with "Cannot allocate memory" on Arch Linux ARM I'm trying to print to my Brother MFC-7820N via network printing on a Pogoplug with Arch Linux ARM installed on it. I'm using the BRScript3 CUPS driver that came in the distribution. When I try to print at 300 dpi, the print job processes forever but never returns an error or prints. When I switch to 600 dpi, the printer prints an error message and the CUPS log says this:
W [26/Nov/2013:22:00:06 -0600] [cups-driverd] Unable to execute "/usr/lib/cups/driver/foomatic": Cannot allocate memory
W [26/Nov/2013:22:00:06 -0600] [cups-driverd] Unable to execute "/usr/lib/cups/driver/gutenprint.5.2": Cannot allocate memory

The print job status within the CUPS web interface is "Filter failed."
Given that my system is a little embedded device, I might suspect the system doesn't have enough RAM to do the job, but about half the system memory (at least 55MB and sometimes quite a bit more) is free. Is it really a RAM issue? Is there any way to get around this issue? I don't have a swap drive since I'm running the system off of a USB flash drive.
UPDATE: The output of free is:
[root@alarm ~]# free
             total       used       free     shared    buffers     cached
Mem:        121924      50736      71188          0       9704      23568
-/+ buffers/cache:      17464     104460
Swap:            0          0          0

I know it is a bad idea, but I tried adding a swap image on the USB flash drive. That prevented the aforementioned error from occurring, but the device simply froze up.


text:
Q: getWidth() and getHeight() for custom view give wrong values I've got a Custom View where I draw a grid onto a canvas. I want the grid to be drawn so that the outer edges of the grid coincide with the edges of the device screen. I use the getWidth() and getHeight() methods to determine the dimensions of my grid and then draw it, but the grid that appears always has cells drawn off-screen.
If I get the width and height of the display and use those for drawing instead then the width of my grid will be what I want, but the height is still off because some the height of the display is taken up by battery and wifi indicators, etc. Also, I don't want to use these values as I want to be able to embed my view in larger xml layouts.
Below is the code where I find my view width and height in my custom view:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
    cellWidth = w/nCols;
    cellHeight = h/nRows;
    //find view dimensions
    viewWidth = getWidth();     //this is just equal to w
    viewHeight = getHeight();   //this is just equal to h
    super.onSizeChanged(w,h,oldw,oldh);
}

and the onDraw of my custom view:
@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);

    canvas.drawRect(0,0,viewWidth,viewHeight, background);

    for(int i=0; i <= nRows; i++){
        canvas.drawLine(0,i*cellHeight, nCols*cellWidth,i*cellHeight,lines);
        canvas.drawLine(i*cellWidth, 0, i*cellWidth, nRows*cellHeight, lines);
    }
}

}
The approach I've followed is similar to this but has not worked.
How can I get the true values for the width and height of my view?
Thanks for reading!

A: I'm guessing you have already seen this?
Custom View Height and Width
Or perhaps this is a different problem.

A: I would do it by subtracting the height of the status bar.
Have you seen this post?
Author suggests:
Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight = rectangle.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;

or alternatively,
public int getStatusBarHeight()
{
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height","dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

A: When it comes to canvas there's several things that could be causing the issue, but just at first glance i can notice that you are trying to use the getWidth before the onSizeChanged has been passed to the superclass to do the proper calculations, in stead of calling super.onSizeChanged(w,h,oldw,oldh); at the end of the method, try by doing it like this:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
    super.onSizeChanged(w,h,oldw,oldh);
    cellWidth = w/nCols;
    cellHeight = h/nRows;
    //find view dimensions
    viewWidth = getWidth();     //this is just equal to w
    viewHeight = getHeight();   //this is just equal to h
}

This is what i saw at first glance, but truth is that when it comes to canvas you have to be very explicit on sizes by your self, and do not expect the parent to handle any size based on your draws...
Regards!


text:
Q: Update position of child object widgets in Kivy (Python not .kv) I have a parent widget that adds and positions custom widget objects, but when the window is resized they don't update their position...
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Color, Line, Ellipse, Rectangle
from kivy.metrics import dp
from kivy.uix.widget import Widget

class circleChild(Widget):
    def __init__(self, *args, **kwargs):
        self.pos = kwargs.get('_pos')
        self.size = kwargs.get('_size')
        super(circleChild, self).__init__()
        with self.canvas:
            Color(0.4, 0.6, 0.9, 1)  # ConrflowerBlue
            Ellipse(pos=self.pos, size=self.size, width=dp(2))

class RootWidget(BoxLayout):
    def __init__(self, *args, **kwargs):
        BoxLayout.__init__(self, *args, **kwargs)
        self.bind(pos=self.draw)
        self.bind(size=self.draw)
        self.layout1 = BoxLayout()
        self.layout2 = BoxLayout(opacity=0.8)
        self.add_widget(self.layout1)
        self.add_widget(self.layout2)
        self.childrenAdded = False

    def draw(self, *args):
        with self.canvas.before:
            Color(.8, .8, .8, 1)  # LightGrey
            self.bg = Rectangle(pos=self.pos, size=self.size)
        self.layout1.canvas.clear()
        with self.layout1.canvas:
            Color(0, 0, 0, 1)  # Black
            Line(
                points=[
                    self.center_x, self.center_y - 200, self.center_x,
                    self.center_y + 200
                ],
                width=dp(2))
            Line(
                points=[
                    self.center_x - 200, self.center_y, self.center_x + 200,
                    self.center_y
                ],
                width=dp(2))
        if not self.childrenAdded:
            self.addChildren()

    def addChildren(self, *args):
        circle1 = circleChild(
            _pos=[self.center_x + 100, self.center_y + 100], _size=[100, 100])
        circle2 = circleChild(
            _pos=[self.center_x + 100, self.center_y - 200], _size=[100, 100])
        circle3 = circleChild(
            _pos=[self.center_x - 200, self.center_y + 100], _size=[100, 100])
        circle4 = circleChild(
            _pos=[self.center_x - 200, self.center_y - 200], _size=[100, 100])
        self.layout2.add_widget(circle1)
        self.layout2.add_widget(circle2)
        self.layout2.add_widget(circle3)
        self.layout2.add_widget(circle4)
        self.childrenAdded = True

class PositionChildren(App):
    title = "PositionChildren"

    def build(self):
        return RootWidget()

if __name__ == "__main__":
    PositionChildren().run()

Results in:

The problem is when resizing the window, this happens :

How would reposition the childWidgets in python?

A: I see that you are complicating creating new properties like _pos or _size, instead you should only use the existing properties pos and size, on the other hand you are using the canvas at every moment, instead reusing the elements.
Considering the above, the simple solution is:
from kivy.app import App
from kivy.graphics import Color, Line, Ellipse, Rectangle
from kivy.metrics import dp
from kivy.uix.widget import Widget

class circleChild(Widget):
    def __init__(self, **kwargs):
        super(circleChild, self).__init__(**kwargs)
        self.draw()
        self.bind(pos=self.redraw, size=self.redraw)

    def draw(self):
        with self.canvas:
            Color(0.4, 0.6, 0.9, 1)  # ConrflowerBlue
            self.ellipse = Ellipse(width=dp(2))

    def redraw(self, *args):
        # reuse
        self.ellipse.pos = self.pos
        self.ellipse.size = self.size

class RootWidget(Widget):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.draw()
        self.bind(pos=self.redraw, size=self.redraw)

        self.circle1 = circleChild(size=[100, 100])
        self.circle2 = circleChild(size=[100, 100])
        self.circle3 = circleChild(size=[100, 100])
        self.circle4 = circleChild(size=[100, 100])
        for c in (self.circle1, self.circle2, self.circle3, self.circle4):
            self.add_widget(c)

    def draw(self):
        with self.canvas.before:
            Color(.8, .8, .8, 1)  # LightGrey
            self.bg = Rectangle(pos=self.pos, size=self.size)
            Color(0, 0, 0, 1)  # Black
            self.vline = Line(width=dp(2))
            self.hline = Line(width=dp(2))

    def redraw(self, *args):
        # reuse
        self.bg.pos = self.pos
        self.bg.size = self.size
        self.vline.points = [
            self.center_x,
            self.center_y - 200,
            self.center_x,
            self.center_y + 200
        ]
        self.hline.points=[
            self.center_x - 200,
            self.center_y,
            self.center_x + 200,
            self.center_y
        ]
        self.circle1.pos = [self.center_x + 100, self.center_y + 100]
        self.circle2.pos = [self.center_x + 100, self.center_y - 200]
        self.circle3.pos = [self.center_x - 200, self.center_y + 100]
        self.circle4.pos = [self.center_x - 200, self.center_y - 200]

class PositionChildren(App):
    title = "PositionChildren"

    def build(self):
        return RootWidget(size=(100, 100))

if __name__ == "__main__":
    PositionChildren().run()


text:
Q: Jet API connection problems So far, I am connecting to jet.com in postman, but when i attempt to connect via php, I do not get any errors or a response. The page is blank. So far this is the code that I have:
protected static $api_user_id = "****";
protected static $api_secret = "****";
protected static $merchant_id = "****";
protected static $api_prefix = "https://merchant-api.jet.com/api/";
class Jet
{
    public function getNewToken()
    {
    $ch = curl_init($this::$api_prefix.'/Token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //If necessary add your ssl pem: curl_setopt($ch, CURLOPT_CAINFO,'/ssl/cacert.pem');
    $request = json_encode(array(
        "user" => $this::$api_user_id,
        "pass" => $this::$api_secret
    ));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($request))
    );
    $data = curl_exec($ch);
    curl_close($ch);
    if($data = json_decode($data)){
        if($token = $data->id_token){
            //SAVE $token SOMEWHERE and save last time you got a token
            $this->setToken($token);
            $this->setTokenTs(date('r'));
            $this->save();
            echo $token;
            return true;
        }
    }
    return false;

    $return = curl_exec($ch);
    $err = curl_error($ch);

    curl_close($ch);

    if ($err)
    {
        echo "cURL Error #:" . $err;
    }
    else
    {
        echo $return;
    }
    }
}
$jetAPI = new Jet;
$jetAPI->getNewToken();

Im not sure what I am doing wrong. Any help would be greatly appreciated. Thanks.

A: I am using:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $obj);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: $app"));
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($curl);

The key here is the curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);


text:
Q: Laravel artisan error:processutils In Application.php line 104:
Class 'Illuminate\Support\ProcessUtils' not found

every time I excute artisan in my project this problem appears, what can I do?

A: Assuming you used ProcessUtils in your custom command (this is probably what you did) you should import it from valid namespace. Add:
use Symfony\Component\Process\ProcessUtils;

before line:
class ....

Now it seems you haven't imported it or you imported in from invalid namespace because there is no Illuminate\Support\ProcessUtils class but there is Symfony\Component\Process\ProcessUtils class.


text:
Q: Difference between request dispatcher forward and servlet chaining What is the difference between request dispatcher's forward method and the concept of servlet chaining?
Example
RequestDispatcher rd= req.getRequestDispatcher("pathToServlet");
rd.forward(req,resp);

What this does is forwards the request without involving the client(browser) interaction. But can we achieve the same using Servlet Chaining?. If we can then what is the difference?.

A: It's not different. "Servlet chaining" is just a term coined in dark J2EE 1.1/1.2 ages when servlet filters didn't exist. Indeed, it's basically the approach of using RequestDispatcher#forward() to forward from one to other servlet (and ensuring that the response isn't already committed as that would otherwise result in IllegalStateException).
Since J2EE 1.3 (Servlet 2.3, over a decade ago already!) servlet filters were introduced which made the process so much more clean and easy. Since then, "Servlet chaining" is frowned upon and usually marked as "bad design". These days, you'd ultimately like to end up with only one front controller servlet and several business models.

A: I think the concept of 'chaining', as it relates to configuring the server instead of using the forward() method, is that you can configure certain types of requests to activate a particular chain of servlets.
For instance, if a request is from within an Intranet you might want the users to see some internal advertising. So you could have all these requests go through as AddInternalBanner servlet first.
The forward() method is useful if a particular servlet decides it should pass the request along.


text:
Q: Check a string contain particular substring or not Check a string contain particular substring or not.
when a user register I want to check entered emailid domain match with my predefined emailid or not(eg @gmail.com ,@outlook.com etc).

A: Using regular expressions is probably the best way.
function validateEmail(email) {
    var re = /@gmail.com$/;
    return re.test(email);
}

A: You can use indexOf javascript method, or use regular expression:
var mail = "foo@gmail.com";
var domain = "foo";
if(mail.indexOf(domain) > -1) {
  console.log("domain valid");
} else {
  console.log("domain not valid");
}

So you can have your custom function:
/* global domain array */
var domains = new Array("gmail.com", "outlook.com", ...);

var checkDomain(mail) {
   for(var i = 0; i != domains.length; ++i) {
      if(mail.indexOf(domains[i]) > -1) {
         return true;
      }
   }
   return false;
}


text:
Q: SimpleDateFormat but with current or next year I'm trying to adjust my method and accept current year or next if the second part of date is next year.
My code:
    private static final String PERIOD = "24 Dec-2 Jan";
    private static DateRange _period = null;

    public static void main(final String[] args)
    {
        _period = DateRange.parse(PERIOD, new SimpleDateFormat("dd MMM", Locale.US));
    }

And the parse method:
    public static DateRange parse(final String dateRange, final DateFormat format)
    {
        final String[] date = dateRange.split("-");

        if (date.length == 2)
        {
            try
            {
                final Date startDate = format.parse(date[0]);
                final Date endDate = format.parse(date[1]);

                return new DateRange(startDate, endDate);
            }
            catch (final ParseException e)
            {
                _log.log(Level.WARNING, "Invalid Date Format.", e);
            }
        }

        return new DateRange(null, null);
    }

So after i execute the code i want to have _startDate to show 24 Dec 2020 and _endDate to show 4 JAN 2021 since is in next year
Edit: Current it print this:
Thu Dec 24 00:00:00 EET 1970
Fri Jan 02 00:00:00 EET 1970

While i need this
Thu Dec 24 00:00:00 EET 2020
Fri Jan 02 00:00:00 EET 2021

A: Updated to use Java 8 date APIs. You can find a pre-Java8 version in the revision history.
You can use Java 8 date APIs to parse a MonthDay (a partial date), set it to the current year (with LocalDate), and then adjust the years to move the date range to the earliest valid range in the future.
public static DateRange parse(final String dateRange, final DateTimeFormatter formatter) {
    final String[] dates = dateRange.split("-");
    if (dates.length == 2) {
        try {
            final LocalDate now = LocalDate.now();
            final int currentYear = now.getYear();
            int startYear = currentYear, endYear = currentYear;
            // Parse partial dates (MonthDay) and set the year to the current year.
            LocalDate startDate = MonthDay.parse(dates[0], formatter).atYear(currentYear);
            LocalDate endDate = MonthDay.parse(dates[1], formatter).atYear(currentYear);
            // Increment both years if the start is in the past.
            if (startDate.isBefore(now)) {
                startYear++;
                endYear++;
            }
            // Increment the end year if the end is before the start.
            if (endDate.isBefore(startDate)) {
                endYear++;
            }
            // Update dates with the years.
            startDate = startDate.withYear(startYear);
            endDate = endDate.withYear(endYear);
            return new DateRange(startDate, endDate);
        } catch (DateTimeParseException e) {
            _log.log(Level.WARNING, "Invalid Date Format.", e);
        }
    }
    return null;
}

public static void main(String[] args) {
    final String dateString = "24 Feb-2 Jan";
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM", Locale.US);
    final DateRange dateRange = parse(dateString, formatter);
    System.out.println(dateRange);
}

Note that the format is d MMM instead of dd MMM to support single digit days.

Alternatively, if you need to support date strings that include years, you can use a LocalDate solution, and add a default year in the formatter parameter.
public static void main(String[] args) {
    final String dateString = "24 Feb-2 Jan";
    final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("d MMM")
            .parseDefaulting(ChronoField.YEAR, Year.now().getValue())
            .toFormatter(Locale.US);
    final DateRange dateRange = parse(dateString, formatter);
    System.out.println(dateRange);
}

public static DateRange parse(final String dateRange, final DateTimeFormatter formatter) {
    final String[] dates = dateRange.split("-");
    if (dates.length == 2) {
        try {
            final LocalDate now = LocalDate.now();
            final int currentYear = now.getYear();
            int startYear = currentYear, endYear = currentYear;
            // Parse partial dates (MonthDay) and set the year to the current year.
            LocalDate startDate = LocalDate.parse(dates[0], formatter);
            LocalDate endDate = LocalDate.parse(dates[1], formatter);
            // Increment both years if the start is in the past.
            if (startDate.isBefore(now)) {
                startYear++;
                endYear++;
            }
            // Increment the end year if the end is before the start.
            if (endDate.isBefore(startDate)) {
                endYear++;
            }
            // Update dates with the years.
            startDate = startDate.withYear(startYear);
            endDate = endDate.withYear(endYear);
            return new DateRange(startDate, endDate);
        } catch (DateTimeParseException e) {
            _log.log(Level.WARNING, "Invalid Date Format.", e);
        }
    }
    return null;
}


text:
Q: Setting up second PS4 We have a family PS4 which I set up as the primary user with parental controls etc and my two kids have sub accounts.
My eldest has now bought himself his own PS4 for his room and I'm wondering how to get this set up for him. I still want parental controls and he will need to be able to link to our primary account to enable us to authorise funds when he wants to buy something.
How do I set up this new PS4 to enable him to use his current PSN account?

A: You should be able to sign-in to the new PS4 with your son's existing PSN details (which should have been created on the Family PS4). Signing with the existing details will retain the trophies and other data, but you will have to setup any console-specific parental controls again (like Play time limits and age restrictions). You will also sign-in as the main (master) account holder in order to setup the parental controls.


text:
Q: subquery into where doctrine 2? I have a little problem trying to implement a subquery within a where. Actually I have no idea who it might be. Agradesco that I can help beforehand.
This is my QueryBuilder
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb2 = $em->createQueryBuilder();

$qb->select('pp')
        ->add('from', 'ORM\Entity\PedidoProducto pp')
        ->innerJoin('pp.idPedido', 'pd')
        ->innerJoin('pp.idProducto', 'p')
        ->join('ORM\Entity\ProductoCompra', 'pc', 'WITH', 'pc.idProducto = p.id')
        ->where($qb->expr()->eq('pc.idCompra', $qb2->select('MAX(pc1.idCompra)')
                ->add('from', 'ORM\Entity\ProductoCompra pc1')
                ->where('pc1.idProducto = pc.idProducto')
                ->groupBy('pc1.idProducto')->getDQL()))
    ->groupBy('pc.idProducto');

And this is the query:
SELECT *
FROM pedido_producto pp
INNER JOIN pedido pd ON pp.id_pedido = pd.id
INNER JOIN producto p ON pp.id_producto = p.id
INNER JOIN producto_compra pc ON pc.id_producto = p.id
WHERE pc.id_compra = (
SELECT max(pc1.id_compra)
FROM producto_compra pc1
WHERE pc.id_producto = pc1.id_producto
GROUP BY pc1.id_producto) GROUP BY pc.id_producto

This is the error:
Doctrine\ORM\Query\QueryException

File:

    C:\xampp\htdocs\ventasV1\vendor\doctrine\orm\lib\Doctrine\ORM\Query\QueryException.php:52

Message:

    [Syntax Error] line 0, col 183: Error: Expected Literal, got 'SELECT'

I hope and I can help you solve it.
Thank you.


text:
Q: File ownership in 13.04 set to messagebus instead of syslog for /var/log files Forgive me if this has been asked and answered already, I did search and couldn't find anything.
On 12.10, /var/log files were written to. auth.log, syslog, and others. However, both fresh install and upgrades to 13.04 result in auth.log and other files being empty. Looking at the ownership, I see at least auth.log and a couple of others are now owned in 13.04 by messagebus:adm instead of syslog:adm as they were in 12.10 and earlier. Changing the file ownership to syslog:adm on auth.log results in it being written to again.
My question is, why are permissions being set this way in 13.04 and how do I go about reverting everything to what they should be? My concern is that I may be able to fix a few things, but I have no idea what else isn't getting written to as a result of this possible bug.

A: I managed to fix it with sudo find /var/log -type f -user messagebus -exec chown syslog:adm {} \;


text:
Q: SSL Certificate Binding Issue - One or more intermediate certificates in the certificate chain are missing I receive the following message after binding our SSL wildcard certificate to our TFS site.
One or more intermediate certificates in the certificate chain are missing.  To resolve this issue, make sure that all of the intermediate certificates are installed.
Does the certificate need to authenticate to the internet?
I've added this wildcard cert to other site binding and this is the first time I've seen this message.
How do I resolve this message?

A: I imported DigiCert High Assurance CA in Trusted Root on both TFS Build and Application server.


text:
Q: Can I install a 32-bit SQL Server 2005 alongside a 64-bit SQL Server 2008 installation? The place where I work at currently runs a 32-bit SQL Server 2005 installation on its server which we work with. In addition, the systems we are developing on have not yet been tested for 64 bit ODBC compatibility.
I also do independent projects from home which will require me to install 64-bit SQL Server instances on my laptop. I'm a little worried about the combinations so I need to know if it'll work.
I'll be installing SQL Server 2005 developer edition (32-bit) to my laptop. I expect this will work fine along with the installation of the service packs.
I'll then be installing SQL Server 2008 developer edition (64-bit) on to the same laptop.
Are there any gotchas that I need to look out for or prevent from happening?

A: Your client side 32bit  ODBC can connect fine to both 32bit and 64bit instances. The only issue would be if you have 32bit code (XP DLLs or esoteric 32bit linked server drivers) that loads into the SQL Server process, which is very unlikely to be the case. So it should be perfectly fine to continue to develop your 32bit app against a 64bit server.
But ultimately the answer is yes, you can mix and match any version and architecture side-by-side, as long as they are installed as different (named) instances. Problems usually arise if you deploy side-by-side the tools (Management Studio, Profiler etc), but that does not seem to be your case.


text:
Q: How do I stop Github's web editor from adding a newline to the end of file? I recently used Github's web editor to propose a change to a project. However, it added a newline to the end of the file, and that is against project's style rules (some sort of compatibility issue).
I've tried simply removing the newline, but after committing all I get is this:

No changes to show.
This commit has no content.

I've dug through github settings, but haven't found anything that might be related to newlines or end-of-files. I don't know anything about git command line, or any way to use github other than their web editor. I barely even understand how to clone a repository.
How do I fix this?

A:
How do I fix this?

Unless you work at GitHub, you can't. You have to use the git command line.
I am surprised they still haven't fixed this. It makes the web editor unusable for projects with blocking lint checks.


text:
Q: How to take a specif commit and move it to another branch and keep the changes I added a very large file and had to delete it from the commit.
When I did that something happened and it mixed up the commits, brought old commits to my branch. Now i had 5 months commits
So I need to take the commits I made on that branch (3 commits) and take it to a new branch.

(In the image we have dozens of commits, and the last 3, which are mine that I want to keep)
Is there any way I can do this without bringing these old commits? like a git stash?
obs: repo in github

A: I think git cherry-pick might be a good option if you know which commits you want on the new branch:
git checkout -b my-new-branch <sha of first commit you want>
git cherry-pick <sha of next commit on the new branch>
git cherry-pick <sha of next commit...>


text:
Q: The reason why Silverlight assembly is not binary compatible with "normal" .NET assemblies Silverlight assemblies are not binary compatible with "normal" .NET assemblies. How can it be, considering the fact that the same compiler is used to create both types of assemblies (even though mscorlib.dll is not referenced for Silverlight)?

A: Right, so, good question.
There's a lot of misconception in this area and it's important to separate fact from fiction.
Fiction: Silverlight assemblies are compiled by magical microsoft gnomes and that makes them incomptiable with the .Net desktop CLR.
Fact: The CLR has this beautifully articulated system called "Fusion".
Each assembly has an assembly manifest embedded as part of the DLL/EXE.
The assembly manifest contains a bunch of stuff (Names of Embbeded Resource, Type System information, etc) and also which other Assemblies are required for this assembly.
Fusion is the part of the CLR responsible for taking that Assembly Manifest dependency and finding the corresponding physical file.
Fusion for Silverlight Assemblies on the Desktop .Net CLR - just works. (assuming all dependencies are present)
Fusion on the Silverlight CLR for desktop assemblies - won't work.
Mainly because the .Net BCL (Base Class Library) DLLs just aren't there. As was mentioned, it's a different mscorlib.dll, agcorlib.dll, System.dll, System.Windows.dll, etc.
The reason those DLLs are different is primarily security. The normal BCLdoes all kind of nasty stuff with pointers, platform specific p/invokes, files, registry and what not. And we can't have that just running the browser.
So, summing up:
Silverlight Asemblies --> Runing on Desktop CLR == Works
Desktop Assemblies --> Running on the Silverlight CLR == Doesn't work
If you'd like a real world example of Silverlight assemblies running on the desktop CLR, check out my article from a year ago @ SILVERLIGHT DLLS ON THE DESKTOP CLR

A: The IL code is the same. However the core libraries are different so even the simplest operation in a library compiled for .NET won't work in Silverlight since the library will be referencing external libraries not present in Silverlight.

A: The aren't compatible, because Silverlight uses a light weight version of mscorlib.dll. However you can reuse your code written for "normal" .NET on Silverlight with some tricks.


text:
Q: Load the creative information with the adgroup not just the creative id I am trying to figure out if anyone has a better way to load facebook adgroups with the creative information. So far the only way I have been able to find is, load all the adgroups using the api point here: /act_{account_id}/adgroups
 I pass the fields 'creative' to get the id, then I have to load all the creatives and pull the data i want.
I can not seem to find a way to filter the creatives to only return the ones I want. Returns all the creatives that ever existed in the account. Seeing that some accounts have 25k+ creatives this is an issue.
The creative endpoint is: '/act_{account_id}/adcreatives/'
https://developers.facebook.com/docs/marketing-api/adcreative/v2.3
Ideally, it would be amazing if there was a way to just load the creative information directly from the adgroup listing.
I am just looking for a few fields in the adcreative url_tags and object_story_spec

A: You can use nested request for that. In your case the URL would look like this
/v2.3/<adgroup_id>?fields=creative{url_tags,object_story_spec}


text:
Q: Configurable Mongo database url and name in Spring Boot Application I am trying to configure mongodb properties through application-{environment-name}.properties for connecting to mongodb.
Here's my code for making connection to mongo:
@Configuration
@EnableAutoConfiguration
public class SpringMongoConfig {

    @Value("${db.connectionURL}")
    private String databaseURL;

    @Value("${db.name}")
    private String databaseName;

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        System.out.println("database url: " + databaseURL + " db name: " + databaseName);
        return new SimpleMongoDbFactory(new MongoClient(databaseURL), databaseName);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }
}

Here's my application-test.properties file:
db.connectionURL=localhost
db.name=rahab

I'm getting null values for databaseURL and databaseName. My idea is that the values are still not available during bean creation. But I don't have any idea to achieve this.

A: you can use PropertySource in the configuration to specify the location of the properties file which you have created. The example code is given below:
@Configuration
@EnableAutoConfiguration
@PropertySource("application-test.properties")
public class SpringMongoConfig {

@Value("${db.connectionURL}")
private String databaseURL;

@Value("${db.name}")
private String databaseName;

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    System.out.println("database url: " + databaseURL + " db name: " + databaseName);
    return new SimpleMongoDbFactory(new MongoClient(databaseURL), databaseName);
}

@Bean
public MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    return mongoTemplate;
}
}

Hope it helps to solve your issue.


text:
Q: IDisposable within Constructor Chain I have the following two constructors:
public Source(FileStream fileStream) {
    // Stuff
}

public Source(String fileName) : this(new FileStream(fileName, FileMode.Open)) {
    // Nothing, the other constructor does the work
}

The issue with the second constructor is rather obvious, a FileStream is being created and used, but not disposed. Because it's inside of a constructor chain, a using block is not possible. I can't move the new FileStream() into the body of the constructor because, while it would then be in a using block, the logic of the other constructor wouldn't be able to be called. I can't extract out that logic because it modifies readonly fields. I could duplicate the logic in each constructor, but that's obviously not a good solution.
I really would prefer to keep the syntactic sugar the second constructor provides. How can I best do this? Or is this just a bad idea?

A: I'm not really sure what's stopping you disposing of it in the constructor that takes the FileStream:
public Source(FileStream fileStream) {
    try
    {
        // Stuff
    }
    finally
    {
        fileStream.Dispose();
    }
}

public Source(String fileName) : this(new FileStream(fileName, FileMode.Open)) {
    // Nothing, the other constructor does the work
}

If it's because you want to keep the Stream alive for callers of the FileStream constructor, you can add a third private constructor:
public Source(FileStream fileStream): this(fileStream, disposeStream: false) {
    // Nothing, the other constructor does the work
}

public Source(String fileName) : this(new FileStream(fileName, FileMode.Open), disposeStream: true) {
    // Nothing, the other constructor does the work
}

private Source(FileStream fileStream, bool disposeStream) {
    try
    {
        // Stuff
    }
    finally
    {
        if (disposeStream)
        {
            fileStream.Dispose();
        }
    }
}

A: Take a look at StreamReader implementation, which has two types of ctors:
public StreamReader(Stream stream)
      : this(stream, true)
    {
    }

public StreamReader(string path)
      : this(path, true)
    {
    }

Internally they both call the same Init method with a parameter leaveOpen, which is set to true for the first ctor and to false for the second ctor and based on this parameter the Stream gets (or not) disposed.
So you can do something like this:
public class Source : IDisposable
{
    private readonly Stream _stream;
    private readonly bool _leaveOpen;

    private Source(Stream stream, bool leaveOpen)
    {
        _stream = stream;
        _leaveOpen = leaveOpen;
    }

    public Source(FileStream fileStream) : this(fileStream, true)
    {

    }

    public Source(string fileName) : this(new FileStream(fileName, FileMode.Open), false)
    {

    }

    public void Dispose()
    {
        if (!_leaveOpen)
        {
            _stream?.Dispose();
        }
    }
}


text:
Q: Session Expire in MVC I am facing a problem,
I have set session time out in web.config
<system.web>
<sessionState timeout="60" mode="InProc" />
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>

In my controller
public ActionResult CreateBrand()
{
Session.Timeout=60;
Purchase purchase = Session["purchaseItem"] as Purchase;
if (purchase!=null && purchase.Brand != null)
{
return View(purchase.Brand);
}
return View();
}

A: You never actually ask a question, so I'll take a stab at guessing what you're asking...
<sessionState timeout="60" mode="InProc" />

When mode="InProc", setting timeout="60" usually does not extend the session timeout beyond 20 minutes because the application pool will spin down (by default) after 20 minutes.
No application pool = no process = no session.
Either change your application pool settings or use a different session state provider.


text:
Q: How to use a UTF8 properties file with Vaadin Bean Validation I'm currently using Vaadin and an add-on named Vaadin Bean Validation for Java Bean Validation API 1.0 (JSR-303). The implementation of this API is hibernate-validator.
I have a custom property file with UTF8 as charset. But with this mechanism, special letters like "éèà" are always displayed wrong.
How can I fix this?

A: Properties files are as per specification read using ISO-8859-1.

... the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes ; only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.

So, any character which is not covered by the ISO-8859-1 range needs to be escaped in the Unicode escape sequences \uXXXX. You can use the JDK-supplied native2ascii tool to convert them. You can find it in JDK's /bin folder.
Here's an example assuming that foo_utf8.properties is the one which you saved using UTF-8 and that foo.properties is the one which you'd like to use in your application:
native2ascii –encoding UTF-8 foo_utf8.properties foo.properties

If you're using an IDE such as Eclipse, then you can just use the builtin properties file editor which should automatically be associated with .properties files. If you use this editor instead of the plain text editor, then it'll automatically escape the characters which are not covered by the ISO-8859-1 range.

A: Escape the UTF-8 character is the properties file.
e.g.:
foo.bar.max=Foo \u00E1 \u00E9 and \u00F6bar

will display as:
Foo á é and öbar

Here is a tool that can help you convert the characters: http://rishida.net/tools/conversion/