text:
Q: Hibernating and booting into another OS: will my filesystems be corrupted? IMPORTANT
If you came here looking for an answer to this question, please read all the answers below. There are some testimonials from people who have lost data doing this. If you plan to do this regularly, I highly recommend that you test for yourself.

Original Question
Suppose I have Windows and Linux installed on the same computer. If I hibernate Windows, can I boot into Linux without corrupting the Windows filesystem when I resume Windows? What about the other way around? What if I hibernate one, boot into the other, and mount the hibernated filesystem read/write? Read-only? If this is unsafe, is there any way to detect the hibernated state of the other OS and prevent mounting its filesystem?
Basically, how far can I push this before it breaks, and how dangerous is it near the edge? I think I know the answers to some of the above questions, but for other ones, I have no idea, and for obvious reasons I have not tested this on my own computer. If someone has tested these, please enlighten the rest of us. I'm not necessarily looking for a specific answer to every question; I'll accept any response that answers a reasonable portion.

EDIT
Let me clarify that when I say "hibernate," I mean the process of writing the contents of RAM to the hard disk and completely powering down the computer. In this state, powering the computer back on brings you through the BIOS and bootloader again, and you could theoretically select another operating system on a multi-boot system. Anyway, on with the original question:

My Results
Ok, after everyone's assurances that this would work, I tested it for myself. I set up Ubuntu to remount all ntfs filesystems and external drives read-only before hibernating. There was no need for a similar Windows setup because Windows does not read Linux filesystems. Then, I tried alternately hibernating one operating system and resuming the other, back and forth a few times. I even tried mounting the Windows filesystem from Ubuntu read-write, and creating a few files. Windows didn't complain when I resumed. So, in conclusion, you can more or less freely hibernate in a dual-boot Windows/Linux scenario.
Note that I did not test a dual Linux/Linux co-hibernation situation. If you have two or more Linux installs and you hibernate one of them, you might be able to corrupt the filesystem by mounting it from another.

A: I regularly hibernate my Windows XP and boot over USB into Ubuntu.
Works flawlessly.
There is a difference between 'Standby' mode and 'Hibernate' mode.
The OS state is completely flushed to the disk and your hardware is powered off.
If you power up the machine and boot into some other OS, it has no impact on the hibernated OS.
You can keep as many OS'es hibernated as you want.
As an example,
You could have multiple Ubuntu installations (say, one per USB flash drive),
And, hibernate each, unplug the drive, and boot into another one.
There is no edge here because there is no stacking/chaining effect.
The hibernated USB sticks in this examples are all independent of each other
(across a power-cycled machine).
One small downside of a hibernated "C:\" drive and booting into another OS is,
you would not be able to mount the hibernated boot partition in the new OS.
The partition is locked with hibernation.
It will be corrupted if edited in that state.

A: I can confirm the loss of data issue with a shared NTFS partition.  I dual-boot between Lucid Lynx Ubuntu and Windows 7.  After hibernating Windows 7 and booting into Ubuntu, I proceeded to build three VirtualBox virtual machines (over the course of 7 days) and installed a variety of software packages into those machines.  Upon restarting into Windows 7, the files disappeared.  Gone.  ntfsundelete and foremost were not able to find them.
So, I ran a series of tests to see if this was in fact what caused the loss of data.  When shutting Windows 7 down, starting Ubuntu, writing some files, restarting back into Windows 7, the files are always retained.  When hibernating Windows 7, restarting in Ubuntu, writing some files, restarting into Windows 7, the new files are gone.
I don't know about CHANGES written to a file, whether they are retained or lost, but new files and folders added to a shared NTFS partition are most likely going to be lost in this situation.

A: There is nothing wrong with what you mentioned.  Even if you mounted the hibernated filesystem, the contents of the hibernation are saved to a large file on the disc - as long as you don't touch this file, or any important system files (obviously), then nothing will happen.
If you change the contents of a partition from another OS after you turn the system off, the original partition will still boot with no problems.  It's the same thing in hibernation.
Just be sure that when mounting/unmounting the partition, you don't damage any system files or drive header information (e.g. MBR, file journals) - although this point has nothing to do with hibernation, and more just a common warning we all need to know.

A: Just ran into an issue on a shared physical drive (FAT32) between Windows XP and Windows 7.  I hibernated Windows XP, booted into Windows 7 for a few days, then went back to XP.  Now I have a corrupt file system on the shared drive.  Disk Checker is running, and it looks pretty bad.  Mostly cross linked files though, but thousands of them.

A: This is kinda old, but being a critical issue, another testimonial is worth it.
I have an external NTFS USB hard drive that I'm using for data (no OS-related files) with 2 different PCs. I used to get constant data loss on it until I isolated the problem. One of the PCs is rather old and slow (Windows XP) so I was using hibernate for faster restart times, disconnecting the hard drive while in that state and writing data with the other PC (Windows 7). Data loss was not occurring every time but it was definitely caused by this scenario. Since I stopped doing it, it never happened again.

A: I ran into problems with hibernate and multi-booting.
Situation: Ubuntu and WinxP Multboot but the data partition visible for both OS.
I did some testing... back and forth...
So I was editing a Wordfile with Word... Saved the file and closed Word.
Hibernated... started Ubuntu... edited the same file with OpenOffice... hibernated.
Rebbooted to the hibernated WinXP. Word did NOT 'see' the changes... It simply loooked like another file...
I also did this testing the other way around...
Second time file was corrupted... I could not open the file or delete the file
Chkdsk 'solved' the problem but the file was lost...
In another test Ubuntu did not even see the edited file.
SO when using hibernation and the same partitions (does NOT need to be the partition where the OS boots from...) ist is very dangerous... Files can and will corrupt in my tests and I can repeat it...
BTW: In my tests I ALWAYS saved the file and closed the application (Word and OpenOffice) befre going into hibernate...!!
I thought mounting the partition was the culprit but now I think the problem must be something about file-caching or whatever...
Anyhow: Be careful with multi-OS-hibernation...!!
Regards, ArnoR

A: Don't do it (again!)
I hibernated my Vista/NTFS and booted up Lucid, worked 3 days on the shared ntfs partition, and started having files and directories disappearing or locked with nasty error messages (within lucid). When I booted back to windows it was a true mess, desktop gone havoc etc..  Hopefully chkdsk was able to fix most of it and I fished out from found.000 about 98% of what I had before.
So it's definitely not a good thing to do.
I sort of remember that this was not possible before: 'hibernated' ntfs partitions were not mountable in linux for some (apparently good) reason. I'd like to come back to this old behavior

A: I had the following highly destructive experience with dual-booting Windows (Vista) and Ubuntu (9, 10, 11). I am not a technical user, though I have long experience using and configuring Windows and DOS. I installed Ubuntu via a live CD on a Win Vista machine. This proceded flawlessly and I had the dual boot up and running in no time. Seeing as there were no warnings attached to the Ubuntu installation, I (naively) assumed that I could hibernate (saving to disk, not suspending) both systems and switch freely between them. This had the following results:
1) I made the mistake of editing a text-file in Ubuntu that I had forgotten was open in Windows. Afterwards the file was inaccessible to either operating system. It could not even be deleted. Chkdsk finally deleted it, but my data were lost.
2) I also tried two other file operations from Ubuntu directly into the Win partition: Generating a pdf-file from OpenOffice, and creating a directory/folder on the Win desktop. Both were inaccessible from Windows (though they could be seen in Win explorer). Luckily they could be deleted from Ubuntu, though chkdsk had to be run afterward to delte then completely from Windows.
3) A large OpenOffice Writer file (saved as *.doc), which was edited first in one, then in the other operating system several times (it was not open in the other system when I edited it), suddenly ballooned in size from about 2 MB to 7 MB, making it nearly impossible to load and save. When I saved the file as an *.odt document its size was greatly reduced but save/load times were no faster. When I unzipped the file, its "contents" section turned out to be more than 22 MB. When I accessed this with a text editor, it turned out that every single word and space in the document was separately formatted in and out of the same style! I finally resolved the problem by comparing the giant version with an earlier version of the same file, using the old version as the basis for the comparison, and then accepting all changes and saving.
4) At this point I upgraded from Ubuntu 10 to Ubuntu 11 and discovered that the 11 system used the new Unity interface exclusively, which was completely unacceptable for my purposes. When I figured out how to install Gnome on Ubuntu 11, it turned out Gnome 3 was far inferior to Gnome 2. I therefore decided to uninstall Ubuntu completely and make a fresh installation of Karmic Koala, which uses Gnome 2 without any trace of the new Unity system. This turned out to be complicated, but after finding the exact same instructions repeated in several manuals online, I proceded. Everything went fine until I ran EasyBCD 2.1.2 (from windows), which would allow me to reboot directly to Windows after Ubuntu's Grub booter had been removed. On rebooting, I found that my MBR was fatally damaged and the machine did not recognize any bootable hard drives. I needed to pay a technician to restore the MBR.
5) Now I could boot to Vista again and I was getting ready to reinstall Ubuntu, when I discovered that a number of files started disappearing from my system at random. Obviously the file system was still corrupted. Only a complete reinstall of Windows solved the problem, and I am now considering very carefully what I should do to avoid similar problems in the future, before installing Karmic Koala. I hope my problems are related to the hibernation issue, but to be sure, I am considering creating a separate "transfer" NTFS partition, where I can put files from one operating system before accessing them from the other. Impractical, but it ought to be safe. I hope.

A: I always hibernate Windows before booting in anything else, Windows is just too slow to start from scratch. But it is dangerous to write to the partition of hibernated OS, because some of the FS tables are still in memory (well, in hibernation file but not in the FS), applications still have handles to some files and generally file system state is kind of unstable.
But you can mount that partition read-only, this way it will stay exactly the same as before hibernation and Windows won't notice a thing.
As for a suggestion about mounting it normally and just stay away from system files, it is not a good idea. Relocation of a file content might happen, MFT might be changed, access time attributes will be changed, all those things might seriously corrupt a file system. It is not so dangerous with FAT but it is really really dangerous with NTFS, as it is far more complicated and have far more state in the memory.

A: Booting Windows over an hibernated Linux is not a good idea. I just lost 20 GiB of data in a shared NTFS partition...
I hibernated Ubuntu Lucid one day, and the next I fired up my computer.  Some update messed up the saved option in Grub, so instead of booting Ubuntu again as it should, it started Windows 7.  When I came back with my coffee, I just went on using it without recalling Ubuntu was in bear mode.  I probably accessed music, Firefox profile, documents, downloads and games from the shared partition.
The next time I switched to Ubuntu, I saw the "waking up from hibernation" message.  Dang.  But I expected it to fail at waking, and soft reboot instead, as happened the previous time I "tried" this (in my Karmic times).  But no, it woke up alright.  Cool.  Or not.  I quickly realized a directory in the root of the shared partition was now empty.  I think the only programs accessing the shared partition on resuming were Quod Libet (music player) and Transmission (bittorrent client).
I went back to Windows, where I couldn't even open the directory.  Trying to "dir" it in shell produced "file not found".  Corrupted.  Still, the partition's free space had not increased, so my 20 GiB where probably still there, safe from being overwritten.  Maybe.
But how to get to them?
A little research provided little help, and made my hopes even more bleak.
I ran Scandisk ("Check for Errors") without auto repair, since I don't wanted to risk it fixing things by further destroying my data.  The result was not very informative: "Errors found.  Run with auto repair."  Unknown to me, seemingly it also marked the partition to be automatically checked on next boot.  I powered off and went away, and came back with EasyRecovery later.
The computer started with me not paying attention, as usual, and when I looked, chkdsk was already spewing errors in full swing, which it did for some ten minutes.  Oh well, here goes nothing.
Fortunately I did lit a candle for Santa Tecla recently, and after Windows started, my data was back, all of it as far as I can tell, though some files ended up in found.000.
So yes, this had a happy ending.  You'll forgive the dramatic suspense, but that's to drive a point across: backup your data!  And (in my case) keep the backup up to date!  And of course, be extra careful with hibernation and shared partitions...

A: DANGER! I can also confirm this is a dire issue for both FAT32 and NTFS volumes & only when Windows (I have windows 7) is hibernated. I think this is tied to caching and have considered setting the drive up for quick removal. That may fix it, but I haven't tried it yet because I really only want to set one partition up this way which Windows does not seem to support. Even my OSX ntfs driver supports per partition cache control, but not windows. Also, my OSX ntfs driver seems to recognize that the drive should not be mounted. Seems to be tied to this issue. Hope that helps.

A: Here is my experience. I am using a dual boot system with Windows and Kubuntu (11.04). Most of my files are on a Windows NTFS partition and I use primarily it from Linux. It's mounted using FUSE.
This is what happened:

*

*Hibernated Windows

*On the next boot, booted to Linux and used it for couple of weeks - without booting to Windows

*Booted back to Windows (because an online test only worked in Internet Explorer and nothing else, somehow ie4linux wasn't sufficient)

When Windows resumed, I noticed that all the files created in those two weeks were missing. I rebooted back to Linux to verify only to find files missing there too. I am guessing Windows restored the NTFS filesystem to the state when it was hibernated and restored it back to that point in time.
I tried tools like ntfsundelete and testdisk. Those missing files are not listed. Also, Linux mounts that drive in RW mode even when Windows had hibernated and not shutdown. I guess Linux warns or just mounts the drive in read-only mode, but that didn't happen here.

A: I can also confirm that share some non-system partition between two different O/S in hibernate state makes file system corruption and loose of data.
Scenario:
I have 3 partitions NTFS:
1. Windows XP
2. Windows 7
3. Data
( I have to still use XP for old apps which don't work well in compatbility mode).
Example:
Boot from partition 1 (XP) and run Thunderbird which store files on 3. Then hibernate (OS dump RAM to hibernate file and shutdown PC).
Boot from partition 2 (7) and run Thunderbird which store files on 3. Here the problem begins with access files etc. sometimes with or without chkdsk.
Back to boot from partition 1 and files fixed by OS_2_7 are again corrupted, even worst some open files before hibernation (ex. Firefox) are corrupted now.
So yes. Hibernate two O/S no matter they use system/non-system partition will make data corruption. Why ? I suppose the root cause is file LOCK and MFT. After wake up from hibernation O/S doesn't refresh MFT so still suppose to find files in old sectors, so any file which changed his size/place will be corrupted.

A: I used to do exactly this. I never mounted the system drive of the hibernating machine to avoid accidents, and each OS have their own separate swap partition. However I had a dedicated data partition, which I would use to transfer data between the two hibernating OS. I even put my Firefox and Thunderbird profile there, so I don't need to keep two separate profiles. Just make sure to close the Firefox on one machine before hibernating it.
I don't recall ever having any issues with the setup, and I used it for quite a long time as well.

A: I just don't think this is possible.
When you hibernate, the computer is 'locked in' (for lack of a better term) to that OS. You aren't hibernating the OS, you are hibernating the whole computer. When to resume from hibernation, you don't go through the BIOS and the POST time again.


text:
Q: react: how to get data from redux store in a rendered component? In my redux store, I have products and cartItems. when I render every single product I also give a button called addToCart on every product. so when I clicked the button, that item is added on the cartItems array (store)
now every cart item has a quantity property. so that if add to cart button is called again, I increment the quantity.
what I want is the value of the quantity of that cartItem in my rendered product component. so that I can conditionally give the add to cart button's text content like that:
${cartItem.quantity} on bag
this is my product component:
const Product = ({
  id,
  title,
  brand,
  price,
  image_url,
  addCartItem
}) => {
  const [isClicked, setIsClicked] = useState(false);

  const handleAddToCart = (id) => {
    setIsClicked(true);
    addCartItem(id);
  };

  return (

      {/* <Link to={`/product/${id}`}> */}

        {title}
        {brand}

      {/* </Link> */}

        ${price}
        <button onClick={() => handleAddToCart(id)}>
          {isClicked ? `${I need quantity here} in Bag` : 'Add to Cart'}
        </button>

  );
};

A: You said you have a reducer named cartItems[] and in which you store product{} after user clicks add to cart button. Okay, simple logic. Now what you want is a property named quantity that is in every product of cartItems[]. You can get that property using redux's useSelector hook(since you're using hooks).
const { quantity } = useSelector(store => store.cartItems.find(item => item.id === id));

What we are doing here is that we are getting the target product from the cartItems array
using the id that's getting passed in as argument and then accessing the quantity from that product. This will be very bad for performance if the products[] list is large and the cartItems[] is large as well. Try to use an object to store the cartItems{} and access it like
const quantity = useSelector(store => store.cartItems[id].quantity);

This approach is very performant since there's no loop, it's O(1).
Hope this answers your question.

A: I hope you connected properly the reducer to the global store using combinereducer,  if you connected then you can use like this -
import the useSelector from the react-redux, since you are using react hooks,
import { useSelector} from 'react-redux';

and simply call useSelector inside the function like this to get the data
  const taskDetails = useSelector((state) => (state.taskDetails.entities));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to put 3 numbers which sum to 0 in a list My list named myList is not getting updated.
I'm defining it inside a function and I'm using it inside that function
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        myList = []
        a = []
        for i in range(len(nums)):
           # print("---i",nums[i])
        #    print(a[0])
            for j in range(i+1,len(nums)):
             #   print("----j",nums[j])
                for k in range(i+2,len(nums)):
                #    print("-----k",nums[k])
                    if nums[i]+nums[j]+nums[k] == 0:
                        print("m into it now for i",nums[i],"j",nums[j],"k",nums[k])
                        print("oooo",myList)
                        a.append(nums[i])
                        a.append(nums[j])
                        a.append(nums[k])
                  #      print(myList)
                        myList.append(a)
                        print("....",myList)
                        print("---",a)
                        a.clear()
        print(myList)

Getting output as:
[[], [], [], []]

A: Python treat everything as object.
When you have a list like:
my_list = [1,2,3]

Here my_list is a reference to the the list [1,2,3] stored in memory.
Now if you pass my_list to any other function or use it in any other object like you have append the a in myList, so here basically python use this as reference to the original list. And now myList has stored the reference of a inside it.
That's why when you clear the contents of a, it also affects the content of myList.
You don't have to clear the content of list a. Just re-initialize it every time  in for loop like this.
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        myList = []
        for i in range(len(nums)):
           # print("---i",nums[i])
           # print(a[0])
            for j in range(i+1,len(nums)):
             # print("----j",nums[j])
                for k in range(i+2,len(nums)):
                    # print("-----k",nums[k])
                    if nums[i]+nums[j]+nums[k] == 0:
                        print("m into it now for i",nums[i],"j",nums[j],"k",nums[k])
                        print("oooo",myList)
                        a = []
                        a.append(nums[i])
                        a.append(nums[j])
                        a.append(nums[k])
                        # print(myList)
                        myList.append(a)
                        print("....",myList)
                        print("---",a)
        print(myList)

UPDATE:
As Artog mentioned in comments
You can easily see this in action by running print(list(map(hex,map(id, myList)))) at the end of the function instead. This will show that the memory address is the same for all entries with the original code, but different with the new.


text:
Q: What is a cleaner way to alternate colors in a foreach loop in PHP and when would processing speed really be a factor? Although this works, speed and cleanliness matter.
if (file_exists($fileToCheck)) {
    $contents = file_get_contents($fileToCheck);
    $lines = array_reverse(explode("\n", trim($contents)));
    $line ="";
    $c = 0;
    foreach($lines as $row) {
        if ($c == 0) { $line .= "".$row."
"; $c = +2; }
        if ($c == 1) { $line .= "".$row."
"; $c = +2; }
        if ($c == 2) { $c = 1; }
        if ($c == 3) { $c = 0; }
    }
} else { $line = "Huzzah! No errors today!"; }

Thanks.

A: You want to use the modulus/modulo operator.
So, if you wanted to make all even numbers red, and the others blue, you would do this:
foreach($lines as $row) {
    if ($c % 2 == 0) {
        $line .= "".$row."
";
    } else {
        $line .= "".$row."
";
    }
    $c++;
}

You could simplify this further:
foreach($lines as $row) {
    $colour = ($c % 2 == 0) ? 'red' : 'blue';
    $line .= "".$row."
";
    $c++;
}

https://www.php.net/manual/en/language.operators.arithmetic.php

A: Something like this? Same idea just less code
if (file_exists($fileToCheck)) {
$contents = file_get_contents($fileToCheck);
$lines = array_reverse(explode("\n", trim($contents)));
$line = "";
$c = 0;
foreach ($lines as $row) {
    $color = 'red';
    if ($c == 1) {
        $color = 'blue';
        $c = 0;
    } else {
        $c++;
    }
    $line .= "" . $row . "
";
}
} else {
    $line = "Huzzah! No errors today!";
}


text:
Q: Spring Data MongoDB: How to work with LocalDateTime field type in BulkOperations? Spring Boot already have Jsr310Converters, but there is a problem with BulkOperations.
Here is a model:
@Document
@Data
@NoArgsConstructor
public class Data2 {

    @Id
    private String id;
    private LocalDateTime createdAt;
    private int value;

}

It works fine with MongoRepository and MongoTemplate. This code works fine:
Data2 data2 = new Data2();
data2.setValue(1);
data2.setCreatedAt(LocalDateTime.now());
data2Repository.save(data2);

mongoTemplate.updateFirst(
                new Query(where("_id").is(data2.getId())),
                new Update().set("createdAt", LocalDateTime.now().minusHours(1)).set("value", 2),
                Data2.class);

But it fails with BulkOperations:
BulkOperations bulks = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Data2.class);
bulks.updateOne(new Query(), new Update().set("createdAt", LocalDateTime.now().minusHours(1)).set("value", 3));
bulks.execute();

Here is a stacktrace:
Caused by: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.time.LocalDateTime.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46) ~[bson-3.2.2.jar:na]
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63) ~[bson-3.2.2.jar:na]
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37) ~[bson-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:210) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.encodeMap(DBObjectCodec.java:220) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:196) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:128) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:61) ~[mongodb-driver-3.2.2.jar:na]
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63) ~[bson-3.2.2.jar:na]
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29) ~[bson-3.2.2.jar:na]
    at com.mongodb.connection.UpdateCommandMessage.writeTheWrites(UpdateCommandMessage.java:84) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.UpdateCommandMessage.writeTheWrites(UpdateCommandMessage.java:42) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.BaseWriteCommandMessage.encodeMessageBodyWithMetadata(BaseWriteCommandMessage.java:129) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.RequestMessage.encodeWithMetadata(RequestMessage.java:160) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.WriteCommandProtocol.sendMessage(WriteCommandProtocol.java:212) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.WriteCommandProtocol.execute(WriteCommandProtocol.java:101) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.UpdateCommandProtocol.execute(UpdateCommandProtocol.java:64) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.UpdateCommandProtocol.execute(UpdateCommandProtocol.java:37) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:159) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:286) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.connection.DefaultServerConnection.updateCommand(DefaultServerConnection.java:140) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation$Run$3.executeWriteCommandProtocol(MixedBulkWriteOperation.java:480) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation$Run$RunExecutor.execute(MixedBulkWriteOperation.java:646) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation$Run.execute(MixedBulkWriteOperation.java:399) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:179) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation$1.call(MixedBulkWriteOperation.java:168) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:230) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:168) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:74) ~[mongodb-driver-core-3.2.2.jar:na]
    at com.mongodb.Mongo.execute(Mongo.java:781) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.Mongo$2.execute(Mongo.java:764) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:2195) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:2188) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.BulkWriteOperation.execute(BulkWriteOperation.java:121) ~[mongodb-driver-3.2.2.jar:na]
    at org.springframework.data.mongodb.core.DefaultBulkOperations.execute(DefaultBulkOperations.java:266) ~[spring-data-mongodb-1.9.3.RELEASE.jar:na]
    at scratch4.service.DataService.test2(DataService.java:71) ~[classes/:na]

Spring Boot version: 1.4.1.RELEASE

A: I think the issue is that there is no converter registered for java.time.LocalDateTime.
The way I got around it is to first convert it to a DBObject and then create an update object from it:
Update.update(key, template.getConverter().convertToMongoType(value));

Not sure if this will work for your case though.


text:
Q: Oracle performance on a table I have table with 100 million rows.  I have to use BETWEEN operator and query is very slow.  Have to get all rows that are either in range for amount and price or all with that city and state.
I have 2 indexes one on t.name and another on t.city & t.state.
Performance of this query is very slow.  How can I improve this query.
SELECT t.trader_id, t.name, t.city, t.state
  FROM trader t
  WHERE t.name = 'john test' AND
        is_valid = 1 AND
        ((t.amount BETWEEN (-2500.0000 , 2800.000) AND
          t.price between (25.00000 , 58.000000)) OR
        (t.city='city' AND
         t.state='state'))

The has non-unique Indexes present on

*

*t.name

*t.city, t.state

For (name and is_valid) there are about 78000 rows.  For (price and amount) there are about 331809 rows. For (city and state) there are about 13500 rows.

A: You haven't provided much hard information such as explain plans, presence of indexes or data distribution.  Which reduces any answer to a guess.
However, your question is probably titled wrongly.  The BETWEEN operator is unlikely to be the main cause of the poor performance.  You have an OR clause which specifies two completely different sets of criteria.  So the database can't use any index on AMOUNT, PRICE, CITY or STATE.  That throws the burden onto the remaining criteria.  Unless you have a compound index on (NAME, IS_VALID) and that combination returns a very small percent of rows you're looking at a full table scan.  A full table scan of 100 million rows will take some time to execute.
What you can do about it really depends on the details I specified in my opening sentence.  Guessing at solutions on top of a guessed diagnosis is just a waste of everybody's time.  Provide some details and then we can discuss it further.


text:
Q: phpmyadmin me solicita password XAMPP Hola que tal he instalado XAMPP en mi linux y el servicio de MYSQL esta encendido pero al tratar de usar phpmyadmin este me tira varios errores, adjunto imagen de evidencia. Se que me solicita password pero es la primera vez que instalo XAMPP desconozco que esta pasando.
PD cambie de puerto mysql de 3306 a 3307 y en el archivo config.inc.php configure de 'localhost' a '127.0.0.1' recomendaciones que vi en internet porque el servicio de MYSql no encendia hasta después de hacer esto.

A: Al revisar el post puedo indicarte que revises el archivo "config.inc.php" y verifiques en algún apartado que diga :
-'user': root

-'password': "La contraseña que debería ser."

$cfg['Servers'][$i]['user']= 'root'

$cfg['Servers'][$i]['password']= ' ' <<<---- Así debería aparecer si no pusiste contraseña a la hora de instalar, si posee una contraseña diferente deberia de aparecer en ese apartado.

Mas si no te sirve de mucho mi ayuda, te dejo el link:
Solucion 1

A: A menos de que hayas definido una contraseña PHPMyAdmin no la pide, en caso de que te la pida y hayas instalado por primera vez solo da en entrar sin poner nada, por default la contraseña de PHPMyAdmin de XAMPP es "" y por lo que veo estas intentando poner "NO" como contraseña.


text:
Q: Ruby on Rails display imdb star rating I have a ruby on rails application that on the index.html.erb page loops around each film to display title, image, director, etc. What I would like to do is display the film's imdb rating as well. Is there a way I can do this?
index.html.erb:
<% @films.each do |film| %>
        <% if film.release_date < Date.today %>

            <%= image_tag film.image_url,:size => "900x200" %>

<%= film.title %>

                        Continues Friday 16th January - Thursday 5th February

                        <%= link_to 'Show', film_path(film) %>   <%= link_to 'Edit', edit_film_path(film) %>

<% end %>

A: This gem should be all that you need for grabbing the data from IMDB.
In addition, you can get the style for the ratings using ratyrate.


text:
Q: WebViewClient onPageStarted never gets triggered browsing SPA I'm opening in a WebView a SPA written in angularjs which uses hashbang urls. (e.g. http://www.myapp.com/#!/page1) I can only see onPageFinished getting triggered and never onPageStarted.
Is there any issue with navigating hashbang urls in a single page application?


text:
Q: Excel,CSV,PDF and Copy is not working in Datatable Tools i downloaded DataTables-1.9.4 and trying to run it, but Excel,CSV,PDF and Copy is not working only print option is working,I followed all steps given in document. please share the code which running with all files saving.

A: You should run this in localhost,For me also this problem occurred, I tried to run it in Apache 2.2  in that also no use. then I applied it with Django+Apache2.2 it is working fine.

A: Unlike print button table tools works on Flash.
Make sure you have flash player installed.
Also the file copy_csv_xls_pdf.swf is present in your project folders and mentioned in right path like the example at http://datatables.net/extras/tabletools/
Check in console whether you have any errors.


text:
Q: Android Studio crash at startup Just installed Android Studio (on the 9th Feb 2015) and I can't get past the startup as it crashes providing the following error - any ideas?:
Version of Android Studio (available in the about box):v1.0
OS version: Windows 7 (64-bit)
Java JRE/JDK version: JDK v1.8.0
Internal error.
java.lang.RuntimeException: java.lang.NullPointerException
    at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:159)
    at com.intellij.idea.MainImpl$1$1$1.run(MainImpl.java:46)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at Java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)        at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)

A: One options is to reinstall the Android Studio and imported settings from previous instance. So the project locations will not lost and can update the Android Studio too.


text:
Q: EditText background change color automatically when select an email When I start my app, the email field is ok, but when I touch it, and a dropdown with some emails appear, when I select one of them, the background color of the email field suddenly change. I can't figure out why it's happening
The editText field before, with the dropdown, and after the problem appears
Here's the xml of the editText
<EditText
    android:id="@+id/editTextEmail"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="8dp"
    android:layout_weight="1"
    android:ems="10"
    android:hint="@string/emailHint"
    android:inputType="textEmailAddress"
    style="@style/loginField"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout4" />

And the @style/loginField
<style name="loginField">
    <item name="android:textColor">@color/gray400</item>
    <item name="android:textColorHint">@color/gray400</item>
    <item name="backgroundTint">@color/gray400</item>
    <item name="android:paddingTop">25dp</item>
</style>

Maybe I used something wrong or I'm missing something. Hope someone can help

A: That color change indicates that the field was autofill-ed.
You can override this color if you want to.
<style name="AppTheme" parent="...">
    <item name="android:autofilledHighlight">#cccccc</item>
</style>

and then change your application to use this new theme


text:
Q: Compose maps using key and value in Kotlin I have two maps and I want to merge using some rules
val a = mapOf(1 to 101, 2 to 102, 3 to 103)
val b = mapOf(101 to "a", 102 to "b", 103 to "c")

is there a way to merge using values for a and key for b
val result = mapOf(1 to "A", 2 to "b", 3 to "c")

A: Since the values of a and the keys of b will always match, you can do this with a single mapValues
val result = a.mapValues { (_, v) -> b.getValue(v) }

getValue can be safely used here since the key v always exist in b as a consequence of our assumption.
In general, if b may not have all the values of a as keys, you can do:
val result = a.entries.mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()

This removes the key from the result, if the key's corresponding value in a doesn't exist as a key in b. You can also use this as an alternative if you don't like the !! in the first solution.
mapNotNull and toMap loops through the entries one time each. If that is a problem for you, use asSequence:
a.asSequence().mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()

A: Since you're sure each value from map a is present in map b, this should be as simple as using mapValues and using the value of that key in map b
a.mapValues { entry ->
    b[entry.value]
}

Due to having to edit and redo my answer, @Sweeper beat me to it and provided a more in-depth answer.


text:
Q: Is this comma usage correct? When we hear about eating disorders, such as binge eating, anorexia, or bulimia, I usually don't know about it.

A: The commas are fine, but the sentence itself needs a little editing. Try

When we hear about eating disorders, such as binge eating, anorexia, or bulimia, we often do not understand much about them.


text:
Q: Shebang (#!) not working in Python Script I have 2 versions of Python 2.7 and 3.7 in Windows. Everything was working fine before I reinstalled them, but now it just defaults to 2.7 even though I have the script to run 3.7
I tried these different options:
#!/usr/bin/python3
#!/usr/bin/env python3
#!python3

Environment variables I tried
PATH = D:\python3\python (same directory as 'where python' command)
PY_PYTHON = 3

Also, if I just install the 3.7 version by itself, Python does not recognize the.py file formats by default (unrecognized file icons), that is until I install 2.7.
So if I just have 3.7 installed, I cant open the .py files directly from the command line without using the 'py -3' executable. Perhaps the solution to why it defaults to 2.7 can be explained by this? I just dont know how to fix it.


text:
Q: ASP .NET + Docker on linux throws system.io.filenotfoundexception: could not find file I have an error in my .NET Web Api project when I run it with Docker on linux. This is just a very small email service that I want to host . The file that throws the error is the html email template file, so its a .html file.
My service works in debug mode on windwos and also in docker running on windows, however when I run it on my webserver and try to send an email it throws

system.io.filenotfoundexception: could not find file

the relative path should be in docker:
/app/Templates/email-template.html
I already search in the internet for a solution but did not found it for myself.
What I tried so far are:
a)
Changing the path in the EmailService.cs file
//1st try
Directory.GetCurrentDirectory() + "/Templates/email-template.html"

//2nd try
@"Templates/email-template.html"

//3rd try
@"templates/email-template.html"

//4th try
@"email-template.html"

In the docker file I tried to copy the files to the workdir file because I read that maybe they did not got copied during the docker build
I tried those copy stuffs in the docker files
#1
COPY MailService.WebApi/Templates/email-template.html /app/templates/
#2
COPY MailService.WebApi/Templates/email-template.html .
#3
COPY ["MailService.WebApi/Templates/email-template.html", "MailService.WebApi/"]

I really don't understand why its not working on linux since it is percefly running on windows (both debug mode and docker).


text:
Q: how to pass custom design image to Shopify cart Basically I have a customizer where user can customize their product and after customization I am able to capture that design as image but I don't know to pass that image to cart show that image as product image.
For the purpose I take a product that has no image, I do this just for the purpose to show my custom image instead of the product image.
Anyone have idea please help.
Here is my working link

Bottle Customizer
  (store password: thazia)

A: If you have a way to save the image and upload it to Shopify files then you can pass the image URL to a custom hidden field with some kind of property.
So for example:
<input type="hidden" name="properties[custom-image]" value="IMAGE URL HERE" />

Then in the cart template you will have to loop the line_item properties until you find this custom-image property and use that one instead of the line_item.image object.
This will be true if you have a way to save the image in a way that you can link to it afterwards.


text:
Q: Best way to log to Graylog2 from PL/SQL What is the preferred way to log to a Graylog2 Server from PL/SQL code?
I couldn't find any PL/SQL Logging API/Package that supports Graylog2.

A: The easiest approach would probably be using UTL_HTTP to make calls to the HTTP API of Graylog.  You could also look into making calls to syslog via something like Log4PLSQL and the forwarding them over using rsyslog.


text:
Q: Unity DI - C# Dependency Injection how to use with a repository class constructor ? It's only intended for controllers? i wanna know if it's possible to inject dependency for a class constructor as it is injected for controllers, i have the following cenario as an example:
An AccountController which depends on an AccountRepository like bellow:
public AccountController(IAccountRepository repository)

The dependency is injected perfectly using Unity DI, which have the following configuration:
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager(), accountInjectionConstructor);
        container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
        container.RegisterType<IdentityDbContext<ApplicationUser>, ApplicationDbContext>(new HierarchicalLifetimeManager());

The problem is that i have a class AuthorizationServiceProvider which also needs the AccountRepository... In this case, how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?
Provider = new SimpleAuthorizationServerProvider>(),

This provider is set inside the Startup class and called before the Unity DI config initializes...
Here the visual studio complains that there's no argument given that corresponds to the class constructor, but if i provide a new AccountRepository i'd have to provide all it's dependencies as well, (ApplicationDbContext context, UserManager userManager) which are already provided for the Unity DI when creating the controllers....

Could somebody help me please?
Thanks in advance...

A:
how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?

You can't. This is actually the core of what we're trying to achieve with Dependency Injection. Your application code should let go of the control over its dependencies. This means that your application code should not create an AuthorizationServiceProvider. Rather, it should let a third-party provide this dependency. Typically, this means you require the dependency be supplied using Constructor Injection.
Letting application code create these dependencies itself causes problems, typically referred to as the Control Freak anti-pattern or Dependency Inversion Principle violation. It causes strong coupling, which can hinder maintainability.
When working with Dependency Injection, this third-party is called the Composition Root. The Composition Root is:

a (preferably) unique location in an application where modules are composed together.

With DI, only the Composition Root will create graphs of objects. You are using Unity, which is a DI Container. The DI Container acts as the Composer, which is part of your Composition Root.
Instead of using a DI Container, you can build the object graphs by hand, which means you will have to create a complete tree of dependencies at once. This practice is called Pure DI. Still, the Composition Root is the location where those object graphs are created; with or without a DI Container.
Your view of DI might be troubled by the use of the standard Identity template that Visual Studio provides. From a design and DI perspective, however, this template is horrifying.
Either way, all these stated concepts, patterns and anti-patterns are described quite thoroughly in the book Dependency Injection in .NET by Mark Seemann.


text:
Q: Mule ESB 3.6 User Authenticatication I'm implementing a web application with mule + raml + counchDB. It is working very well. But now I have to develop a authentication feature. To validate not only api clients, but users of this client. The goal is reach the same behavior of a normal Web application. The user call url, a login page is loaded ,user inputs username and password and is authenticated. After that for each request I have to validate user login and the url parameters to be sure he has rights to access information.
But I'm lost in how is the best way to do it or even if it is possible with mule. I've read about HTTP Basic Authentication, that I thing fits in what I need. But I could not realize if allows me to authenticate muof user and manager it to performe right validations.
Thanks for attention,
   Valter Gomes

A: The enterprise edition of mule has an oauth 2 module that you can plug in your mule application. Please see http://www.mulesoft.org/documentation/display/current/Mule+STS+OAuth+2.0a+Example+Application
There is no equivalent on the open source side, that I know of.


text:
Q: EF Foreign Key constraint I'm still studying Entity Framework and tried to create a model including the foreign keys.
But when I tried to migrate the code, I got this error

Introducing FOREIGN KEY constraint 'FK_dbo.QuestionResults_dbo.QuestionsTables_QuetionsTableId' on table 'QuestionResults' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints

These are my model classes:
public class MainDetails
{
    [Key]
    public int Id { get; set; }
    public string Language { get; set; }

    [Required]
    public string CustomerName { get; set; }

    [Required]
    public string ContactNumber { get; set; }
    public string EmailAddress { get; set; }

    [DisplayName("Service Type")]
    [ForeignKey("QuestionsTable")]
    public int ServiceTypeId { get; set; }
    public virtual QuestionsTable QuestionsTable { get; set; }

    [Required]
    public string VehicleNumber { get; set; }

    [Required]
    public string ServiceLocation { get; set; }
    public string Suggestion { get; set; }
    public bool Status { get; set; } = true;

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Created Date")]
    public DateTime CreatedDate { get; set; } = DateTime.Now;

    public virtual QuestionResults QuestionResults { get; set; }

    public virtual IList<QuestionResults> QuestionResultsMainlist { get; set; }
    public virtual IList<QuestionsTable> QuestionsTables { get; set; }
}

public class QuestionsTable
{
    [Key]
    public int Id { get; set; }
    public string ServiceType { get; set; }
    public string Question { get; set; }
    public virtual IList<MainDetails> MainDetailsServiceType { get; set; }
    public QuestionsTable()
    {
        MainDetailsServiceType = new List<MainDetails>();
    }
}

public class QuestionResults
{
    [Key]
    public int Id { get; set; }

    [DisplayName("MainDetail ID")]
    [ForeignKey("MainDetails")]
    public int MainDetailsId { get; set; }
    public virtual MainDetails MainDetails { get; set; }

    [DisplayName("MainDetail ID")]
    [ForeignKey("QuestionsTable")]
    public int QuetionsTableId { get; set; }
    public virtual QuestionsTable QuestionsTable { get; set; }

    [Required]
    public string CustoAnswer { get; set; }
}

This is the table structure I wanted to create:

A: To resolve this you can use the EF Model Builder
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<QuestionsTable>()
        .HasRequired(a => a.MainDetails)
        .WithOptionalDependent()
        .WillCascadeOnDelete(false); //This is the important row
}

You'll have to play around with the type of relationship you would like along with whether you specify explicitly the foreign key. If you haven't seen this model builder before have a read here: https://learn.microsoft.com/en-us/ef/core/modeling/

Upon breaking your scenario down I noticed some "oddities". I reduced the noise in the domain model to from your example to this
public class MainDetails
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("QuestionsTable")]
    public int ServiceTypeId { get; set; }

    public virtual QuestionsTable QuestionsTable { get; set; }

    public virtual QuestionResults QuestionResults { get; set; }

    public virtual IList<QuestionResults> QuestionResultsMainlist { get; set; }

    public virtual IList<QuestionsTable> QuestionsTables { get; set; }
}

public class QuestionsTable
{
    [Key]
    public int Id { get; set; }
    public string ServiceType { get; set; }
    public string Question { get; set; }
    public virtual IList<MainDetails> MainDetailsServiceType { get; set; }
}

public class QuestionResults
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("MainDetails")]
    public int MainDetailsId { get; set; }
    public virtual MainDetails MainDetails { get; set; }

    [ForeignKey("QuestionsTable")]
    public int QuetionsTableId { get; set; }
    public virtual QuestionsTable QuestionsTable { get; set; }
}

I few things I noted.

*

*MainDetails contains both One-To-Many (QuestionTable) and Many-To-Many (IList) relationships? I'm unsure on your intention

*QuestionsResults contains singular relationships to both entities which aren't replicated in the QuestionTable class? that's fine if it's intentional

*ServiceType is a string in QuestionsTable but you are expecting an int as the foreign key in MainDetails?


text:
Q: Does not preserve excel connection setting in excel manager in SSIS I have created SSIS package which will generate excel file from sql table.
But when I try to execute 2nd time that same package after deleting that file (try to generate new file again) i'm getting following error
Error at Data Flow Task [Excel Destination [329]]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E37.

Error at Data Flow Task [Excel Destination [329]]: Opening a rowset for "Excel_Destination" failed. Check that the object exists in the database.

Error at Data Flow Task [SSIS.Pipeline]: "component "Excel Destination" (329)" failed validation and returned validation status "VS_ISBROKEN".

Error at Data Flow Task [SSIS.Pipeline]: One or more component failed validation.

Error at Data Flow Task: There were errors during task validation.

A: To fix this issue.
In the Excel connection manager properties you have to set the "DelayValidation" property to TRUE.

A: To fix this issue. In the Excel connection manager properties you have to set the "DelayValidation" property to TRUE.

i think change  "DelayValidation" on Dataflow Properties.


text:
Q: How to Superscript some Text in a TextBox/TextBlock Control in windows phone 8? I'm working on windows phone 8 app, and m stuck here, guys i want to show some text as a superscript either in TextBox or in TextBlock where-ever possible. suggest me how can i obtained it. Thanks

A: Why don't you use a stackpanel wrapping a couple of textblocks instead?  Then adjust the margines on the stuff you want super and subscripted.
        <StackPanel Orientation="Vertical">
        <TextBlock Text="H2O3" FontSize="40" Margin="0,10"/>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="H" FontSize="40" />
            <TextBlock Text="2" FontSize="40" Margin="0,-20,0,0"/>
            <TextBlock Text="O" FontSize="40"/>
            <TextBlock Text="3" FontSize="40" Margin="0,10,0,-10"/>
        </StackPanel>
    </StackPanel>

A: There's an alternative but it's only available in WP8: Typography.Variants.
I personally prefer this approach as it aligns more with WPF but there are cases where you have to do baseline manipulation or in this instance, margin wrangling. If WPF is any indication, it also requires a font that supports variants which are generally open type/true type only. See Superscript / subscript in hyperlink in WPF for a better explanation.


text:
Q: Excel and SPSS return opposite coefficients I am getting familiar with SPSS, specifically the Automatic Linear Modeling functionality. I first ran SPSS, using Best Subset method which gives me the result of "best" variables. Being uncertain, I run again in Excel with the  same data. Much to my surprise, the coefficients of one variable are not the same: they are the opposite of each other, having identical attributes. I am ok with the different intercepts but opposite coefficients imply very different stories about the data.
What is the meaning of this? What did I do wrong? What model should be used? Does this mean I have to check again everytime SPSS return a model from best subset functionality?

This is the transformation summary.
Role    (Summer_transformed)    Predictor
Actions Taken   (Summer_transformed)    Change measurement level from continuous to ordinal
Role    (Month_transformed) Predictor
Actions Taken   (CK_transformed)    Trim outliers
Actions Taken   (Month_transformed) Trim outliers
Role    (CK_transformed)    Predictor

A: It seems that SPSS uses summer_transformed=1 as the reference group, while Excel uses summer_transformed=0. You can see that the difference in intercepts is also equal to the difference between these groups, so once you correct the reference, you should get exactly the same results.
Two side comments: 1) I wouldn't use values in the billions when learning a method, just to see the results easier; 2) I always recommend R instead of SPSS as your second analysis tool, if you want to understand the methods and are not afraid to get hands dirty with some coding.


text:
Q: Can multilevel locks cause deadlocks in multithread programs? I have a program with writers and readers and their access right is controlled by a monitor.
So, this was supposed to starve, but I got a deadlock. I was wondering why and then I remembered that I put another lock, which I think was unnecessary inside my read method inside readers to protect my global variable from inconsistencies. I thought it wouldn't cause any deadlock, because I could run the threads 10000 time without any deadlock occurring, but when I had to do my lab demo, it deadlocked at the 10010th thread I think. I don't understand why it would do that though. Also, I didn't expect it to starve, but apparently it was supposed to.
My question is: are those multilevel locks responsible for the deadlock? If not, what's causing this?!
    import java.io.*;
    import java.io.IOException;
    import java.util.*;

    public class Writer extends Thread{

    private int number;

    public Writer(int number)
    {
        this.number = number;
    }

    public int getNumber()
    {
        return number;
    }

        public static void Write(String filename){

        try {

            String content = RandomString();

            File f = new File(filename);

            if (!f.exists())
            {
                f.createNewFile();
            }

            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Task1out.txt", true)));
            out.println(content);
            out.close();

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

    public static String RandomString(){

        String chars = new String("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        int n = chars.length();

        String randomString = new String();
        Random r = new Random();

            for (int i=0; i<100; i++)
            {
                randomString = randomString + chars.charAt(r.nextInt(n));
            }

        System.out.println("RandomString() generated: " + randomString);

        return randomString;

    }

    public void run(){

        try{

        //FileControl fc = new FileControl();

            int number = this.getNumber();

            for(int i = 0; i <1000; i++) //CHANGE IT TO 1000
            {
                main.fc.WriterEntry(number);

                //write file random characters (must append)

                Write("Task1out.txt");

                main.fc.WriterExit(number);

            }
        } catch(InterruptedException e)
        {
            System.out.println("Interrupted Exception caught");
        }

    }

}

This is the writer class.
    import java.io.BufferedWriter;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.*;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

public class Reader extends Thread{

    private int number;

    public Reader(int number)
    {
        this.number = number;
    }

    public int getNumber()
    {
        return number;
    }

        public static synchronized void Read(String filename)throws InterruptedException{

        BufferedReader br = null;

            main.lock.lock(); //lock
        try{

        try {

            String line;
            char[] chars = new char[100];
            int readIndex2 = 0;
            int addToIndex = 0;

            br = new BufferedReader(new FileReader(filename));

            int initialReadIndex = main.getIndex();

            System.out.println("initial read index: " + initialReadIndex);

            while ((line = br.readLine()) != null && readIndex2 < initialReadIndex+100 && addToIndex < 100) {

                for(int i = 0; i< 100; i++)
                {
                    if (initialReadIndex == readIndex2 || initialReadIndex < readIndex2)
                    {

                        if(line.length() > addToIndex)
                        {

                        chars[i] = line.charAt(i);
                        addToIndex++;
                        }

                    }
                    else
                    {
                        readIndex2++;
                    }
                }
                System.out.println(chars);
            }

            if(line == null)
            {
                System.out.println("nothing to read");
            }

            main.incrementIndex(addToIndex);

            System.out.println("current read index: " + (initialReadIndex + addToIndex));

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("buffered reader exception");
        } finally {

            try {

                if (br != null)
                    {

                    br.close();
                    }
            } catch (IOException ex) {
                ex.printStackTrace();
                System.out.println("exception during closing");
            }
        }
        }finally{
            main.lock.unlock(); //lock

        }

        }

    public void run(){

        try{

        //FileControl fc = new FileControl();

        int number = this.getNumber();

            for(int i = 0; i <1000; i++) //CHANGE IT TO 1000
            {
                main.fc.ReaderEntry(number);

                //read file

                Read("Task1out.txt");

                main.fc.ReaderExit(number);
            }
        } catch(InterruptedException e)
        {
            System.out.println("Interrupted Exception caught");
        }

    }

        }

This is the reader class.
 import java.io.BufferedWriter;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class main{

    public static FileControl fc = new FileControl();

    final static Lock lock = new ReentrantLock();

    public static int readIndex;

    public static void incrementIndex(int increment) {

                readIndex = readIndex + increment;

    }

    public static int getIndex()
    {
        return readIndex;
    }

    public static void main(String[] args) throws InterruptedException {

            Writer [] writer = new Writer[10];
            Reader [] reader = new Reader[10];

            for(int i = 0; i < 10; i++)
            {
                reader[i] = new Reader(i);
                writer[i] = new Writer(i);
                //creating readers and writers

            }

            for(int i = 0; i < 10; i++)
            {
                //anonymous threads
                //(new Thread(new Writer())).start();
                //(new Thread(new Reader())).start();

                reader[i].start();
                writer[i].start();

            }

            for(int i = 0; i < 10; i++)
            {
                try{
                    reader[i].join();
                    writer[i].join();
                } catch(InterruptedException e){
                    e.printStackTrace();
                }

            }

        }

}

This is the main class.
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class FileControl {
    final Lock lock = new ReentrantLock();
    final Condition writers = lock.newCondition();
    final Condition readers = lock.newCondition();
    int activereaders = 0;
    int waitingwriters = 0;
    boolean writing = false;

    public void WriterEntry(int number)throws InterruptedException{
        lock.lock();
        try{
                if(writing == true || activereaders > 0){
                    waitingwriters++;
                    System.out.println("Writer thread " + number + " : waiting to write");
                    writers.await();
                    waitingwriters--;
                }
                System.out.println("Writer thread " + number + " : ready to write");

                writing = true;
           }
        finally{
            lock.unlock();
        }

    }

    public void WriterExit(int number)throws InterruptedException{
        lock.lock();
        try{
            System.out.println("Writer thread " + number + " : finished to write");

            System.out.println("writers " + waitingwriters + "readers " + activereaders); //test

            if(waitingwriters > 0)
                writers.signal();
            else{
                writing = false;
                readers.signal();
            }
        }
        finally{
            lock.unlock();
        }

    }

    public void ReaderEntry(int number)throws InterruptedException{
        lock.lock();
        try{

            if(writing == true || waitingwriters > 0){ //remove activereaders > 0
                System.out.println("Reader thread " + number + " : waiting to read");
                readers.await();
                activereaders++;
            }

            System.out.println("Reader thread " + number + " : ready to read");
        }
        finally{
            lock.unlock();
        }

    }

    public void ReaderExit(int number)throws InterruptedException{
        lock.lock();
        try{

        activereaders--;

        System.out.println("Reader thread " + number + " : finished to read");

        System.out.println("writers " + waitingwriters + "readers " + activereaders); //test

            if(activereaders == 0)
            {
                if(waitingwriters > 0)
                {
                    writers.signal();
                }
                else
                {
                    readers.signal();
                }
            }
        }
        finally{
            lock.unlock();
        }

    }

}

This is the monitor.
pseudocode for the monitor

A: Whenever you have multiple locks A, B and C you can have deadlock if you don't guarantee that your code attempts to acquire said locks in the same order.
final Lock A = new ReentrantLock();
final Lock B = new ReentrantLock();
final Lock C = new ReentrantLock();

A,B,C or C,B,A, or A,C,B - it does not matter so long as the order is consistent.
A problem arises when you have one code path try for: A,B,C
And another trying for C,B,A.
As you can probably guess since A and C are both being held, one of the two will get B and then both will deadlock. (Aka you have a cycle in the resource locking graph)
Formally speaking deadlock can arise only if all of the following conditions hold:

*

*No Preemption: The system will not free resources after allocation;
they can only be released by the holding process.

*Circular Wait: Discussed above.

*Mutual Exclusion: Only one process can use a resource at any given time.

*Resource Holding: A process is currently holding at least one resource and requesting/waiting for additional resources which are held by another process.

The best solution is to make sure the order is consistent or lock at a higher (single) level. Another option is to use a locking library that will timeout while attempting to lock (or use conditions and write your own wrapper that does this). But that approach is not for the faint of heart. Some implementation of this will wait a random amount of time and try again, but this can be highly inefficient as the number of locks increases.
Resources:

*

*Here is a practical article on analyzing deadlock in Java that you
might be interested in:
http://www.journaldev.com/1058/java-deadlock-example-and-how-to-analyze-deadlock-situation

*You can also use open source tools like JCarder to find deadlock:
http://www.jcarder.org/ which for programs with large dumps can be
easier then trying to grok dump files.

P.S. I didn't actually read much of your code since its poorly formatted and and is not a minimal example (ie. too verbose for our purposes here). But this advice should answer you question from a theoretical standpoint.

A: It's certainly possible. It's also possible for you to check at runtime!
The first step is to get the thread dump. Here are three methods:

*

*If you open up the process in VisualVM, and go to the "threads" tab, it'll tell you if it detects this sort of a deadlock. You can then do a thread dump (there's a button right there), which will tell you what each thread is doing, as well as any locks it owns and any which locks (if any) it's trying to acquire.

*On Linux or Mac, you can get the stack by issuing kill -3 <pid>, where <pid> is your java process' id. It'll dump that same thread dump to stderr. The bottom of that thread dump will also contain a summary of deadlocks it detects. I don't know how to do this on Windows.

*You can also invoke jstack <pid>, which will print the thread dump to stdout (the jstack's stdout, not the original java process').

I wrote up a sample program that deadlocks and ran it (see my gist). The relevant section of the thread dump is:
Found one Java-level deadlock:
=============================
"Thread-2":
  waiting for ownable synchronizer 7f42b0f38, (a java.util.concurrent.locks.ReentrantLock$NonfairSync),
  which is held by "Thread-1"
"Thread-1":
  waiting for ownable synchronizer 7f42ba170, (a java.util.concurrent.locks.ReentrantLock$NonfairSync),
  which is held by "Thread-2"

And the relevant thread states are:
"Thread-2" prio=5 tid=7fc01c911000 nid=0x113d18000 waiting on condition [113d17000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <7f30c3528> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:156)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:811)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:842)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1178)
    at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:186)
    at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)
    at Locky$Boomer.run(Locky.java:22)
    at java.lang.Thread.run(Thread.java:680)

   Locked ownable synchronizers:
    - <7f30c3558> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

"Thread-1" prio=5 tid=7fc01d06c800 nid=0x113c15000 waiting on condition [113c14000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <7f30c3558> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:156)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:811)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:842)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1178)
    at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:186)
    at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)
    at Locky$Boomer.run(Locky.java:22)
    at java.lang.Thread.run(Thread.java:680)

   Locked ownable synchronizers:
    - <7f30c3528> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

This will not work on all deadlocks. For instance, deadlocks due to waiting on external resources won't get caught. But it'll catch Lock-based deadlocks, as well as synchronized-based ones.


text:
Q: Using MultipleView controller in Container view I am building an iOS app which have its many different views and difficult also.
I have a tab bar with 4 pages that are as under

*

*Account

*Main Page

*Wallet

*My Lists

when User will tap on List (4th num option), my app needs to show a Header with segmented control (or any top bar like control not decided yet) I want to move Multiple ViewController here . let say top bar has 5 buttons as under

*

*Home list

*Relative list

*Friends list

*office list

*clients list

For these different list I have made different View controller. that I want to move in the My List (which is Main view controller and will be deal as a Master view controller and will contain above mentioned 5 buttons) In this Master view controller when I click Home list or Friends list button it will move related View controller just below this top bar (button list)
For more clarification see the picture below. And just let me know How can I do this. . How can I make specific area to be taken by child View controller.

A: Well I think you are a little confuse in using Container view using IB or by programmatically. when You use in IB , you have to simple create a related class for it. Just like You create View Controller by dragging from Object library  and associate it with coca touch UIViewController class.
I will suggest to watch this tutorial. its quiet simple and easy to understand.
but the answer of your question is:
Take a UIView just below the top bar as you said in question. You can make it full width and full height however you like. Then create its out let. just like below and use this as
@IBOutlet var viewMain: UIView!

and just move your Child view controller with this
viewMain.addSubview(childViewController)

You are done

A: If SegmentControl views have same design then you do not need separate ViewControllers for each.
If Each list has totally different UI then there are many ways to do this.
1- Use scrollview,its content width will be Screenwidth * number of views.
Just add all the views in scrollView.
For Example you want to add to two views Here is the code
    self.scrollView.contentSize = CGSize(width: UIScreen.main.bounds.size.width * 2, height: self.scrollView.frame.height)
    let vc1 = your view controller
    vc1.view.frame =  CGRect(x: 0, y: 1, width: scrollView.frame.size.width , height: scrollView.frame.size.height)

    let vc2 = your second viewcontroller
    vc2.view.frame =  CGRect(x: UIScreen.main.bounds.size.width, y: 1, width: scrollView.frame.size.width  , height: scrollView.frame.size.height)

    scrollView.addSubview(vc2.view)
    scrollView.addSubview(vc1.view)

Now if you want to change visible view
scrollView.scrollRectToVisible(CGRect(x: UIScreen.main.bounds.size.width * CGFloat(//Position of your view 1 or 2), y: 0.0, width: UIScreen.main.bounds.size.width, height: scrollView.frame.size.height), animated: true)

2- Use Containers
3- There are very good open source libraries(pods) available as well.One one them is CarbonKit
https://github.com/ermalkaleci/CarbonKit


text:
Q: How to add items with image into NSMenu? I want to implement similar to this NSMenu into my app which I have shown into the screenshot. I want to add an item with an image like this. Also, I want to assign a title to the group of NSMenuItems.
How can I set an image(icon of the file) to an item of NSMenu? And how can I set the title for the group of NSMenuItems?
The code I have tried is as below:
NSMenu *statusMenu;

NSMenuItem *itm=[[NSMenuItem alloc]initWithTitle:[foldermenuarray objectAtIndex:j] action:@selector(cleanNowPressed:) keyEquivalent:@""];
[itm setImage:[NSImage imageNamed:@"whiteMenu.png"]];
[statusMenu addItem:itm];

I have shown arrows for showing things which are required for my app.
The exact view that I want to achieve is shown in the screenshot.

A: The easiest way to do it is using xib editor. Select a Menu item from xib->Select 4th tab called "Show the attributes inspector"->Enter you image name->Done!
NOTE: Make sure your custom image is perfect size for your menu item.


text:
Q: Counting the execution of terminating conditions in Fibonacci series Following pseudo-code, which computes the n-th Fibonacci number:
int fibonacci(int n)
{
    if (n == 0){
        print(0)
        return 0
    }
    if (n == 1)
    {
        print(1)
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2)
}

If one calls fibonacci(3), then the following will happen:

*

*fibonacci(3) calls fibonacci(2) and fibonacci(1) (the first call).

*fibonacci(2) calls fibonacci(1) (the second call) and fibonacci(0).

*The second call of fibonacci(1) prints 1 and returns 1.

*fibonacci(0) prints 0 and returns 0.

*fibonacci(2) gets the results of fibonacci(1) and fibonacci(0) and returns 1.

*The first call of fibonacci(1) prints 1 and returns 1.

*fibonacci(3) gets the results of fibonacci(2) and fibonacci(1) and returns 2.

In total, 1 will be printed twice and 0 will be printed once.
Objective is to know how many times 0 and 1 will be printed for a given integer N.
INPUT
The first line contains an integer T, denoting the number of test cases.
The next T lines contain an integer N.
OUTPUT
For each test case, print one line of output which contains 2 integers separated by a space. The first integer is the number of times 0 is printed. The second integer is the number of times 1 is printed.
CONSTRAINTS
1 <= T <= 50
0 <= N <= 40

SAMPLE INPUT
2

0

3

SMAPLE OUTPUT
1 0

1 2

Code
public class Fibonacci {

    /**
     * @param args
     */
static int zero =0,one = 0;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] input = readInput();
    for(int i =0; i < input.length;++i) {
        System.out.println(getOutput(input[i]));
    }
}
public static int[] readInput() {
    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
    String temp;
    int[] input = null;
    try {
        temp =bufferReader.readLine();
        int counter = Integer.parseInt(temp);
        input = new int[counter];
        for(int i =0 ; i < counter ;++i)    {
            input[i] =Integer.parseInt(bufferReader.readLine());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return input;
}
public static String getOutput(int number)  {
    //System.out.println(fibonacci(number));
    return zero+" "+one;
}
public static int fibonacci(int n) {
    if (n == 0) {
        //System.out.println(0);
        ++zero;
        return 0;
    }
    if (n == 1) {
        //System.out.println(1);
        ++one;
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

This works fine for 1st test case but fails for subsequent test cases.

A: I think you need to reset the values of zero and one before calling getOutput.
    for(int i =0; i < input.length;++i) {
        zero = 0;
        one = 0;
        System.out.println(getOutput(input[i]));
    }


text:
Q: Append two new lines before additional text using sed I've hit a bit of a stumper (for me). I'm attempting to insert two newline characters into the RHEL5 /etc/sysconfig/iptables file during our server build process (using kickstart post-installation scripts).
The specific sed command is:
${SED} -i "/-i lo/ a\
\n\n#Trusted Traffic\n-A INPUT -s 10.153.156.0/25,10.153.174.160/27 -d ${MGTIP} -m state --state NEW -j ACCEPT\n\n#Remote Access\n-A INPUT -s 10.120.80.0/21,10.152.80.0/21,10.153.193.0/24,172.18.1.0/24,${MGTNET}/${NUMBITS} -d ${MGTIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n#Backups\n-A INPUT -s 10.153.147.192/26 -d ${BKPIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n" ${IPTABLES}

This is actually part of a larger script. ${SED}and ${IPTABLES} are already set to the necessary values.
All of the newlines work with the exception of the first two. Or, more accurately, the second of the first two. Even the last two newlines after ACCEPT work. What happens with the first two newlines is that the first works, creating a newline after matching the iptables entry which contains -i lo. The second, however, simply inserts a literal 'n' prior to the #Trusted Traffic text.
It ends up looking like
(snip)
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
n#Trusted Traffic
-A INPUT (snip)

I've tried various methods of ensuring the second newline is inserted. I've used two blank lines instead of \n\n. I've used two newline characters on separate lines, I've used \\n\\n. Everything I've tried so far results in the same outcome: A literal 'n' being inserted instead of a second newline.
Does sed simply not work with two newline characters at the beginning of appended text? Is there a way to make this work that I'm simply ignorant of?

A: Interesting, I would have thought that one of your attempted solutions would work, but I am seeing the same behavior.  Here is one potential solution:
${SED} -i -e "s/-i lo.*/\0\n\n/" -e "// a\
#Trusted Traffic\n-A INPUT -s 10.153.156.0/25,10.153.174.160/27 -d ${MGTIP} -m state --state NEW -j ACCEPT\n\n#Remote Access\n-A INPUT -s 10.120.80.0/21,10.152.80.0/21,10.153.193.0/24,172.18.1.0/24,${MGTNET}/${NUMBITS} -d ${MGTIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n#Backups\n-A INPUT -s 10.153.147.192/26 -d ${BKPIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n" ${IPTABLES}

This works by first appending the two newlines to the end of the previous line, and then doing the append.

A: I don't see why it's not working either, but you can do this also with the substitute option instead of append:
${SED} -i "s%-i lo.*%&\n\n#Trusted Traffic\n-A INPUT -s 10.153.156.0/25,10.153.174.160/27 -d ${MGTIP} -m state --state NEW -j ACCEPT\n\n#Remote Access\n-A INPUT -s 10.120.80.0/21,10.152.80.0/21,10.153.193.0/24,172.18.1.0/24,${MGTNET}/${NUMBITS} -d ${MGTIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n#Backups\n-A INPUT -s 10.153.147.192/26 -d ${BKPIP} -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n\n%" ${IPTABLES}

A: Not sure about portability, but try:
${SED} '/-i lo/ a\
\
\
'"#Trusted Traffic\\
-A INPUT -s 10.153.156...
"

This technique works on BSD sed.  You can maintain double quotes throughout with:
${SED} "/-i lo/ a\\
\\
\\
#Trusted Traffic\\
-A INPUT -s 10.153.156...
"

In either case, there must be no whitespace between the backslash and the end of the line.


text:
Q: Conditionally import locals for improving performance on components Trying to import one language from many other languages in relative path to hinder unnecessary load on page refresh and get better Lighthouse results.
When Vue18i is like this, it loads these 2 languages.
locales: [
        {
          code: 'en',
          iso: 'en-GB',
          name: 'English',
          // file: 'en.json',
          file: 'en.js'
        },
        {
          code: 'tr',
          iso: 'tr-TR',
          name: 'Türkçe',
          file: 'tr.js',
          // isCatchallLocale: true
        },
      ],

I want it to load one language, and 1 page has a category component with over 200 arrays. Demand to load just one languages category translations conditionally.
For example, the below solution is not good considiring each language arrays and category translations.
<i18n>
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}
</i18n>

<template>
  <p>{{ $t('hello') }}</p>
</template>

When Categorizer.vue component opens, when config.baseapi is http://localhost:3000/en/p/add. it should load encategory translations to i18n.
import en from '~/locales/encategory.json'

If it is http://localhost:3000/tr/p/add, should load Turkish translation.
import tr from '~/locales/trcategory.json'

A: have found a simple way. Couldn't find references because there are many for CommonJS but not for ES6 JavaScript. This is for pure JavaScript optimized, thus for Nuxt. You don't want to load 50 languages for a, let's say a Turkish user:
    let productcolortr;
    let productcoloren;
    const sleep = (ms) => new Promise((f) => setTimeout(f, ms));
    if ($locale == 'en') {
            await sleep(4000); // simulate network delay
            productcoloren = (await import('../../../locales/productcoloren')).default;
            addMessages('en', productcoloren);
        } else {
            await sleep(4000); // simulate network delay
            productcolortr = (await import('../../../locales/productcolortr')).default;
            addMessages('tr', productcolortr);
        }

This is for new generation Sveltekit implication. It waits before DOM loads and implements the if condition. $lan is store variable, much better here than Nuxt:
{#if $lan == "en"}
    {#await import('../../locales/en.js') then c}
    {$lan = "en"}
    {/await}
    {:else}
    {#await import('../../locales/tr.js') then c}
    {$lan = "tr"}

    {/await}
{/if}


text:
Q: Angular 2+ ngOnInit() not being called if router navigates to current route( with new query params) from itself In my home.component.ts, my ngOnInit method is:
ngOnInit() {
    console.log("ngoninitcalled");
    this.activatedRoute.queryParams.subscribe((params:Params) => {
        let refresh = params['refresh'];
        if(refresh){
            // do something refreshing
        }
    }
}

And here is my customFunction
customFunction(email: string, username:string) {
    // do something custom
    this.router.navigate([''],{queryParams: {refresh:true}});
}

The '' route redirects to home.component.ts or HomeComponent(snippet of whose are above).
On checking console logs, I see that when HomeComponent is called with refresh param from other components(via this.router.navigate([''], {queryParams: {refresh:true}}), ngOnInit() is called. But if its called from HomeComponent itself(as in above code), ngOnInit() is not called.
So is it the expected behavior and can I safely call this.ngOnInit() after the router.navigate in my custom function to invoke ngOnInit() manually(assuming ngOnInit will never be called if HomeComponent is redirected to from itself)?

A: It is expected behavior that the ngOnInit is not called when navigating to the same component with different parameters.
But you should not call ngOnInit manually.
The subscription will get notified each time the parameters change. So code within the subscribe method will execute each time. You don't need to call ngOnInit.
Try it by moving your console.log within the subscribe.


text:
Q: Is there a way to disable/enable touchscreen programmatically without rebooting or signing out in Windows 10? I have perhaps a silly question, but I am curious to find out if, you can code a program, for instance in c++, which would disable or enable touch screen without rebooting or signing out, in addition I just want to disable touchscreen and be still able to use pen on tablet. (on windows 10).
I know you can enable or disable touch screen by Device manager, but that is not what I am looking for. Also I know that you can tweak registries to disable/enable the touchscreen, but it only takes effect if one reboots or signs out.
I would just want to know if there is a way to do this. Is there any function for this in .net framework or win32?
Thank you for any answer.

A: If you want to quickly enable and disable the touch screen, DevCon.exe is a good option.

DevCon (DevCon.exe) is a command line tool that can display detailed
  information about devices on computers running Windows. You can also
  use DevCon to enable, disable, install, configure, and remove devices.

You can use DevCon to create shortcut that can be quickly enabled and disabled.
DevCon Enable:
devcon [/r] enable {* | ID [ID ...] | =class [ID [ID ...]]}

DevCon Disable:
devcon [/r] disable {* | ID [ID ...] | =class [ID [ID ...]]}

Get the hardware ID, for example,  HID\VID_####&PID_####&COL##
Then create a Batch File
set "touchscreenid=ID_HERE"
devcon status "%touchscreenid%" | findstr "running"
if %errorlevel% == 0 (
    devcon disable "%touchscreenid%"
) else (
    devcon enable "%touchscreenid%"
)

Finally, change the properties of the file to make it a shortcut.
For details, you can refer warrenj203's answer.
Hope to help you.


text:
Q: Why to use @LocalBean and an interface at the same time on an EJB class? As I can understand, @Localbean on an EJB is used when one doesn't want to define any interface for the EJB. Then I saw many websites, including IBM1, that show something like this:
@Stateless
 @Local(LocalA.class)
 @Remote(RemoteA.class)
 @LocalBean
 public class MeineEJB {
     public void localA() {}
     public void remoteA() {}}

If it is a no-interface EJB, then what is the useage of @Local(LocalA.class) in this code? (I assume that it is an interface.)
And also, I don't understand @LocaBean and @Remote at the same time. @LocalBean says it is a local bean, but we defined it as a remote as well. Then why the annotation title is @LocalBean at the first place?
Thanks for reading folks.

A: You're just being confused about why @Local & @LocalBean are annotated on the  same MeinjeEJB class. And not specifically on their differences.
The no-interface (@LocalBean) is nothing but a variation  of the local view that exposes all public business methods of the bean class locally without the use of a separate business interface.
In EJB it's possible to expose an interface as a Local(i.e clients are running in the same JVM - Servlet, JSF, another EJB) interface, Remote (i.e clients are RMI, other forms of RPC, etc) interface, or No-interface view (implements no interface). I.e :
@Stateless
@Local(LocalA.class) @Remote(RemoteA.class)
@LocalBean
public class MeineEJB {
public void localA() {}
 public void remoteA() {}}

If the bean exposes at least one interface (local or remote) it will automatically loses the no-interface view. So we
needs to explicitly specify that it exposes a no-interface view by using the @LocalBean annotation on the bean
Note : Don't confuse  @Local & @LocalBean on the MeinjeEJB class. We need @LocalBean because MeineEJB will be invoked locally (i.e. cannot be invoke remotely) by clients (JSF, Servet, etc.). What will be invoked remotely is the RemoteA.class by the MeineEJB itself.


text:
Q: Domain Controller / DNS Issue - Creating Network of Virtual Machines for Development First off I am a developer, and I a moving into the realm of distributed computing.
I need to create a development environment which consists of:

*

*Many HPC Server 2008 nodes

*Domain Controller.

... all as virtual machines.
I followed this guide to creating a domain controller: d3planet.com/rtfb/2009/11/09/build-a-windows-server-2008-r2-domain-controller/
When I try to connect to the Domain like so via the Computer Name/Domain Change window (twitpic.com/qru6d/full) ,
I recieve the error: Error Message Window
The Error Reads:

"
  Note: This information is intended for
  a network administrator.  If you are
  not your network's administrator,
  notify the administrator that you
  received this information, which has
  been recorded in the file
  C:\Windows\debug\dcdiag.txt. The
  following error occurred when DNS was
  queried for the service location (SRV)
  resource record used to locate an
  Active Directory Domain Controller for
  domain 17B.CO.UK: The error was: "DNS
  name does not exist." (error code
  0x0000232B RCODE_NAME_ERROR) The query
  was for the SRV record for
  _ldap._tcp.dc._msdcs.17B.CO.UK Common causes of this error include the
  following:
  - The DNS SRV records required to locate a AD DC for the domain are not
  registered in DNS. These records are
  registered with a DNS server
  automatically when a AD DC is added to
  a domain. They are updated by the AD
  DC at set intervals. This computer is
  configured to use DNS servers with the
  following IP addresses:
  192.168.1.1
  - One or more of the following zones do not include delegation to its child
  zone: 17B.CO.UK CO.UK UK . (the root
  zone) For information about correcting
  this problem, click Help. "

The part which is interesting is:

This computer is
  configured to use DNS servers with the
  following IP addresses:
  192.168.1.1

That is the IP of the router, not the virtual machine with the domain controller & DNS.
This seems to be a common issue to newb domain admins such as myself.
(Remember, this is a network of virtual machines which are all able to see/ping each other)
Any help would be greatly appreciated and I can support more info as required, thanks.
P.S. Excuse the insertion of direct links & lack of images, side effect of my account having no rep as yet.  I will tidy up quesiton when I get the rep to do so.
Update:
Virtual Machine (VM) as a Domain Controller to create a domain which other virtual machines to join.
VMware Workstation with each VM using a Birdged Connection (connecting directly to network).  Each machine can ping the other machines.
Answer:
I have blogged about the exact steps taken to solve this problem here: blog.holsee.com/2009/11/windows-hpc-server-2008-development-environment/

A: are you running one of your AD controllers as a DNS server? If so, then you need to point your DNS requests to that server and not the 192.168.1.1 (which you said is your router). You can then configure your internal DNS server to forward requests that it's not authoritative for to an outside responder (or your router).

A: By virtual network do you mean you're creating a VM with a domain controller for testing? If so (I assume you're using VMware here), but when you create a VM you have to assign it a network based on the virtual networks you've created on the ESX host.


text:
Q: repaint() not working anymore I am currently learning java and am trying to draw on a JFrame via a JPanel...
Problem is, my render code was functioning, but I have changed stuff slighly, now the repaint() method wont refresh the JPanel anymore...
I have System.out.println() calls in every method, but my console just looks like this:

render
  render
  render
  render

, when I call the render() method. It was working before....
Anyways, here is my code.
package Graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Surface extends JPanel {

    JFrame frame;
    RandomFrame rf;

    public Surface(JFrame frame) {
        this.frame = frame;
        rf = new RandomFrame(frame.getWidth(), frame.getHeight());
    }

private void draw(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    g2d.setPaint(Color.blue);

    int w = getWidth();
    int h = getHeight();

    g2d.drawImage(rf.getRandom(w, h), null, 0, 0);
    System.out.println("draw");
}

@Override
public void paintComponent(Graphics g) {
    System.out.println("paintComponent");
    super.paintComponents(g);
    draw(g);
}

public void render() {
    System.out.println("render");
    repaint();
}

}

, whereas RandomFrame returns a BufferedImage with randomized data.

A: Inside your Surface constructor where you take frame, make sure your SurfacePanel is added to the frame. For instance
public Surface(JFrame frame) {
        this.frame = frame;
        frame.setContentPane(this); // add this line
        rf = new RandomFrame(frame.getWidth(), frame.getHeight());
    }


text:
Q: Not enough space in System Reserved partition (for shadow copy) when trying to create System Image I do know that system image is a legacy way to create Windows 10 backups, and I only use it as added helper method.
I freshly installed my Windows 10 19041 Workstation and in the setup I created a 300G partition on a 1T unpartitioned SATA SDD. Windows 10 setup created an additional 50M(!) System Reserved partition automatically, the size was its chosen size. I did know this habit of Windows setup, thought all OK so far.
Now I am trying to create a System Image, and got the error message. The message has right, below 500M the minimum req for shadow copy is 50M, so in my 50M partition, where 31M is reserved obviously there are no free 50M space. (then why it picked the 50M size during setup?) In my prev Windows 10 install the size of System Partition was 131M... also automatically created...)
Question
If I would like to have the System Image creation possibility, what are my options?
a) Can I somehow resize this System Reserved partitions (I suppose only with 3rd party tool, because the Windows System Partition has to be moved) If there is a trusted tool, (I means security, not data safety) I would give it a shoot)
b) In case it is not recommended, I am willing to reinstall my Windows 10, but it is possible to somehow let Windows 10 during the setup create bigger System Reserved partition supposing there are 300G unpartitioned space?

A: Concluded to use the completely free Macrium Reflect 7 (free edition)
Fully functional, even can do incremental images, created WinRE Restore disk, which boots with the very similar GUI. Works like charm.
When restoring it if flexible regarding the partition sizes, can shrink btw. (of course if there was free space on the source partition).


text:
Q: How to pass a php array of string values to a javascript variable I need to use php arrays in my javascript code. The arrays are defined in PHP in the same file as the javascript.
I have tried the following two ways:
var array_name = new Array('<?php echo implode("','", $php_array);?>');

and
var array_name = <?php echo json_encode($php_array);?>;

This works great if my php arrays are integers. However, when I try to do either when the array is a list of strings, then it does not work.
Any suggestions on what other options I have?
Any help appreciated.

A: put that json string into quotes (single quotes!)
var array_name = '<?php echo json_encode($php_array);?>';

enjooy