sed: Delete multiple lines from files between pattern, when found string

Question: I'm trying to delete lines between two pattern (Beginn: info / End: } ), where match a string.
Here my file:
# bla bla
# bla bla
# bla bla
# bla bla

nnssjnds nkjdnds "nsrnsnmks" ffsns {
  is on or off at 9:12:43 23/02/2015;
  is nass or trocken at 08:32:12 22/02/2015;
}

info text01text {
  beginn 30/04/2015 10:00:04;
  end    30/04/2015 19:00:04;
  check1 30/04/2015 11:30:04;
  check2 30/04/2015 13:00:04;
  check3 30/04/2015 16:00:04;
  Check4 30/04/2015 18:00:04;
  build top end;
  mix water 0102030456789;
  xim "43ndf392rfhf<DF>3}";
  test space = "ALLFINE";
  eman cpre "ann";
}
info text02text {
  beginn 30/04/2015 10:00:04;
  end    30/04/2015 19:00:04;
  check1 30/04/2015 11:30:04;
  check2 30/04/2015 13:00:04;
  check3 30/04/2015 16:00:04;
  Check4 30/04/2015 18:00:04;
  build top end;
  mix water 0202030456789;
  xim "43ndf392rfhf<DF>3";
  test space2 = "ALLFINE2";
  eman cpre2 "ann2";
}
info text03text {
  beginn 30/04/2015 10:00:04;
  end    30/04/2015 19:00:04;
  check1 30/04/2015 11:30:04;
  check2 30/04/2015 13:00:04;
  check3 30/04/2015 16:00:04;
  Check4 30/04/2015 18:00:04;
  build top end;
  mix water 0302030456789;
  xim "43ndf392rfhf<DF>3";
  test space3 = "ALLFINE3";
  eman cpre3 "ann3";
}

my sed script
:point
/^info/,/^}/ {
   /}/!{
      $!{
         N;
         bpoint
      }
   }
   /0202030456789/d;
}

My sed script worked correct with the string 0202030456789 and delete all lines from info text02text { to }.
Try it with the string 0102030456789 from text01text, then delete sed to } from line "  xim "43ndf392rfhf3}";" and the lines
test space = "ALLFINE";
eman cpre "ann";
}

don't delete.
How is it possible to delete all lines, where found the string?
Thanks!
Comment: replace `/}/!{` by `/^ *}/!{`
Answer: From your sample
try this:
:point
/^info/,/^}/ {
   /\n *}/!{
      $!{
         N;
         bpoint
      }
   }
   /0202030456789/d;
}

But I prefer:
/^info .*{/ {
  :a;
    N;
    /\n *}/!ba;
    /0202030456789/d;
}

This could by written (under bash):
mixToDel=0302030456789
sed < file '/^info .*{/{ :a;N;/\n *}/!ba;/'$mixToDel'/d;}'

Or maybe:
sed < file '/^info .*{/{ :a;N;$!{/\n *}/!ba};/'$mixToDel'/d;}'

to prevent missing } at end of file:
/^info .*{/{
  :a;
    N;
    $!{
        /\n *}/!ba
    };
    /'$mixToDel'/d;
}


Does playing with friends increase your ability to gain infernal rings faster?

Question: Assuming the probability of getting key is 25% (torment 1).
If playing single, we get:

4 tries per key
4 keys for machine
4 machines per organ
4 organs per ring

So a total of 256 attempts, for a single ring.
What about if we play with 4 of our friends? Does that increase our chances of getting those rings?
Comment: If only it was that simple... I usually have to do way more than 4 runs per key, and that was with 2 people in party. Also, keys are untradable, so I don't see how partying speeds it up.
Comment: @Chippies More dmg, faster kills. More people, more magic find.
Comment: @Assylum ah, I didn't think of it that way. More people don't necessarily make the kills faster though, because the HP scales up, but I see your point.
Comment: More people also increases the chance of finding keys and number of portals that can be opened.  If we go through and kill all the keywardens.  Lets say all of them drop a key for every party member.  With 1 player, that's 1 machine.  for 2 players, 2 machines. four players gives you four machines.  That means more portals in a game so more chance of getting an organ quicker.
Answer: With 4 players you get the keys a lot faster.

You need 1/4 as many runs because you get the same amount of keys and
can share portals.
You increase magic find.
You can split to find the keywardens and port to eachother.
You can kill the bosses on higher torment than on your own because of partybuffs+revive

Easiest way to do this is splitting up for act 1,2,4 at first then as soon as someone finds one you port to them until only act 3 is left and then everyone ports there and search the map.
Comment: I've never heard of a keywarden in act V? Is there really one, or is it a mistake?
Comment: Yes but by how much? My guess is it still take 64 play
Comment: 64 is a lot less than 256 though..


Creating a partial (or bounded) FileStream in C#

Question: I have a FileStream that consists of several files put into one file, and I have a list of the lengths of the files, in other words I can easely calculate the position and length of all the files. What I want to create is a Open-method that takes a fileindex and returns a stream containing only that file. Currently I've implemented this using a memory-stream, but that forces me to copy the whole (not the container, but the whole contained) file into memory, and I don't want to do that. So, what I would like to be able to do is create a class that implements stream and takes another stream, a offset and a length parameter and then is readable and seekable, only when you do Seek(0) you should get to the offset of the underlaying stream. So like an adapter-class, and I was wondering if this was possible, or even a good idea, or if anyone has any better ideas of how to solve this problem. I realize that if I do it the way I just described I need to make sure that access to the underlaying stream is synchronized, and that all of the partial streams open holds a private variable telling them where currently in the stream they are, but this should probably be dooable, right? has anyone done anything like this before? Or is there a simpel .NET-class I can just use? Any help would be appreciated.
Oh, and sorry for bad english, I forgot to install my browser in english, so spellchecker tells me everything is wrong.
Answer: If you're using .NET 4.0, you could use memory-mapped files. They do pretty much what you've described: you can map a "view" of a large file, specified by an offset and a length, into memory, and access just that part of the file using a Stream.
Otherwise, I think your approach sounds good. Just watch out for corner cases involving reading or writing beyond the boundaries of the intended file!


error: cannot access zzb class file for com.google.firebase.iid.zzb not found

Question: Getting error:

error: cannot access zzb
  class file for com.google.firebase.iid.zzb not found

after including AccountKit:
    compile 'com.facebook.android:account-kit-sdk:4.+'

Also onCreate &  onDestroy is not getting resolved.

    public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

     @Override
      public void onCreate() {
        super.onCreate();
    }

      @Override
      public void onDestroy() {
        super.onDestroy();
    }
    }

Firebase & play services: v11.4.0
Comment: I had this error when I added the new Places Implementation, any fix here ?
Answer: Firebase and play services libraries were older.
Upgraded them to v15.0.0 and accountkit to v4.32 resolved compile errors and build errors.

Update:
15.0.0 crashed at runtime when notification was received (fortunately app was in beta)
Stacktrace:
AbstractMethodError:firebase.iid.zzb.zzd(intent)

Solution-
Downgrading them to 11.8.0 worked.
(Accountkit v4.32)

Update: Also faced problem of not receiving push notification on Oreo 8.0

Solution- Notification not showing in Oreo


MotionLayout ignores padding

Question: I'm trying to animate margin, padding and alpha of a textview on swipe.
At the start, there is no padding of the textview, alpha is 1.
At the end, I want alpha to be 0, padding to be 100dp, 16dp dp margin on the sides, alpha to be 0.5
Everything works, except the padding is not changing.
Does MotionLayout support padding?
I'm using androidx.constraintlayout:constraintlayout:2.0.0-beta4.
adding more text since SO says that my post looks like is mostly code...
adding more text since SO says that my post looks like is mostly code...
adding more text since SO says that my post looks like is mostly code...
The layout xml:
    <androidx.constraintlayout.motion.widget.MotionLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layoutParent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/test">

    <TextView
        android:id="@+id/fakenavigationBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:text="hello world">
    </TextView>
</androidx.constraintlayout.motion.widget.MotionLayout>

The motion scene:
<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@id/fakenavigationBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alpha="1"
            android:padding="100dp"
            motion:layout_constraintTop_toTopOf="parent"
            motion:layout_constraintStart_toStartOf="parent">
        </Constraint>

    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:id="@id/fakenavigationBar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:alpha="0.5"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintEnd_toEndOf="parent"
            motion:layout_constraintBottom_toBottomOf="parent">
        </Constraint>

    </ConstraintSet>

    <Transition
        motion:constraintSetStart="@+id/start"
        motion:constraintSetEnd="@+id/end"
        motion:duration="2000"
        motion:motionInterpolator="linear">

        <OnSwipe
            motion:touchAnchorId="@+id/fakenavigationBar"
            motion:touchAnchorSide="top"
            motion:dragDirection="dragDown"/>
    </Transition>
</MotionScene>

Comment: maybe other people will more understand if you explain what you're trying to achieve or share the screenshot
Comment: I added more details to the question.
Comment: Is there anybody here? Like for real, anybody? What can I do to make people see this post and help me?
Answer: This is a limitation of MotionLayout
Padding is not a supported attribute ConstraintSet and as such  does not support it.
There are not even methods on View setPaddingTop so they cannot be treated as custom Attributes.
This is a gap in MotionLayout but there are issues with padding. Padding changes the views measured dimension which request layout as the dimension of the view changes.
This is expensive because the only way to resolve the animation is to resolve the starting and ending constraintset and rebuild the interpolation.
It is best if you redesign you layout to use margins as this is the control of the Layout.
Answer: I'll admit this isn't a very helpful answer but I've had the same problem with padding. Margins seem to work okay for MotionLayout but it does not appear to support padding. What I did to make mine work somewhat how I wanted was to add the padding in my MotionLayout file to whatever view I wanted. It respected the padding within that file but not within the Motion Scene Constraint Sets so it made it impossible to animate paddings in my situation. It would just keep the static padding that was set in the MotionLayout file which was enough for me to get by.
It does seem from this blog post that you could potentially animate between paddings if you set your Motion Scene transition to be between two distinct layouts as opposed to ConstraintSets.
I have asked a question to a few different resources about why MotionLayout doesn't support padding and will update my answer if I get anything useful but as far as I can tell, animating padding values isn't supported in MotionLayout.
Answer: It is possible, but it apparently comes at a large performance cost.
Add a MotionLayout.TransitionListener to your MotionLayout that calculates the correct padding value for a given progress value (0f-1f), and sets it to your view in onTransitionChange():
motionLayout.setTransitionListener(object : MotionLayout.TransitionListener {
    override fun onTransitionStarted(motionLayout: MotionLayout, startId: Int, endId: Int) { }

    override fun onTransitionChange(motionLayout: MotionLayout, startId: Int, endId: Int, progress: Float) {
        val paddingInPx = calculatePaddingPx(progress)
        myView.setPadding(paddingInPx, paddingInPx, paddingInPx, paddingInPx)
    }

    override fun onTransitionCompleted(motionLayout: MotionLayout, currentId: Int) { }

    override fun onTransitionTrigger(motionLayout: MotionLayout, triggerId: Int, positive: Boolean, progress: Float) { }
})

Within your MotionScene, add:
<Transition motion:layoutDuringTransition="honorRequest"/>
See also: https://github.com/androidx/constraintlayout/issues/7#issuecomment-721447209
Edit 1: although I was able to change padding with this technique, I eventually decided against using it because the performance impact was very noticeable on older devices.
Edit 2: There is also a issue related to scrolling animations, if you do a fling, then the TransitionListener callbacks are not guaranteed to be called, so the transition will reach it's start/end state without having updated the padding.

MotionLayout ignores padding


Errors when performing fsck on encrypted partition in recovery mode

Question: I'm booting in recovery mode
Unmount crypto partition.
umount /dev/mapper/sda6_crypt and i make fsck -c /dev/mapper/sda6_crypt
fsck output:
fsck.LVM"_member: not found
    fsck: Error 2 while executing fsck.LVM2_member for /dev/mapper/sda6_crypt

In crypto volume there are two crypto partitions:

swap
home

I make:
fsck -c /dev/mapper/cifrado-home

fsck.ext2: Superblock invalid, trying backup blocks...
fsck.ext2: Bad magic number in super-block while trying to open /dev/mapper/cifrado/home

I make: fsck -c /dev/sda6
fsck: fsck.crypto_LUKS: not found
fsck: Error 2 while executing fsck.crypto_LUKS for /dev/sda6

Comment: It's useful if you actually ask a question...  :)
Answer: Boot the Ubuntu Desktop CD or go to recovery mode,
Install lvm2 and cryptsetup,

sudo apt-get install lvm2 cryptsetup

load the cyrptsetup module :

sudo modprobe dm-crypt

Decrypt your file system,

sudo cryptsetup luksOpen /dev/hda5
  crypt1

Get the live CD to recognize (activate) your LVM :

sudo vgscan --mknodes sudo vgchange
  -ay

Run fsck,

fsck /dev/mapper/

Answer was found here.


Value of a series in $\tan$

Question:
Question: The value of: $$(1+\tan 1^o)(1+\tan 2^o)(1+\tan 3^o)...(1+\tan 44^o)$$ is:
A) 2
B) A multiple of 22
C) A multiple of 4
D) Not an integer

I'm not sure how I would solve this question. However, by intuition, I would say that the number wouldn't be an integer. As all the terms in the bracket are between 1 and 2, their product shouldn't give an integral value. Am I right?
Comment: See http://math.stackexchange.com/questions/304461/x-1-tan-1-circ1-tan-2-circ1-tan-3-circ-ldots1-tan?rq=1
Comment: $\frac 32$ and $\frac 43$ are between $1$ and $2$ too -- do you contend their product is not an integer?
Comment: Hint: $(1 + \tan(a^\circ))(1+\tan((45-a)^\circ) = 2$
Comment: @HenningMakholm Aha.... Don't know how I missed that. Thanks anyways I have checked the similar questions :)
Answer: Note I found something interesting $(1+tan(1degree))(1+tan(44degree))\approx 2$ this can easily be proved by simplifying $(1+tan(a))(1+tan(45-a))$

Value of a series in $\tan$


How do I beat the desert temple third room?

Question: It's big and empty and I can't get up to the top, what should I do? I can't jump high enough, anti-gravity doesn't seem to do anything either.
My first tactic was to use the octopus summoning crown to create a pile of octopi that I could climb up, but when I teleported to the back of the room they followed me back, trapping me in the entrance.
Comment: [Octopi work](http://i.imgur.com/iCTNMEq.png)
Answer: Use the staff of summoning, the tribal people will stack to the right. Keep teleporting back and jumping on top of the heap to build up the pile.
Answer: This is how I did it.  Just keep jumping.  If one lands directly on your head, summon wall of demons and teleport back if necessary.  Keep jumping!  ;)
Comment: I tried using octopi first, but their staggered piling caused me to quickly get trapped in the tunnel to the left. The tribesmen are nice, rectangular blocks, so they don't trap you until the second row reaches the left wall.
Answer: Equip A tribal summoning spear and Boots of introspection (keeps you grounded so there's no need to use teleport). You will also need Pogo stick and A desert bird feather.
Wait until at least 6 tribal warriors are summoned and jump on the closest one. Continue building layers until you reach the top.
You can use Black demons spell destroying all tribal warriors if tribal warrior blocks your way just before you reached the chest.
Comment: I couldn't get it to work with the boots of introspection - he'se always either too far from the chest, or keeps jumping on top of the damn thing!
Comment: You could also try Shrinking spell, this should trigger chest to open if I remember correctly.
Answer: Here's how it works using Obsidian Wall. Took quite a lot of time, but was worth it :)
Use teleport to switch back and you can use the spear to break through the wall (to get it lower) since using bare hands is painfully slow. It takes about 5 minutes to build this up.
Requirements: pogo stick, Anti Graviti Potion X1, obsidian wall spell
Comment: This is amazing, bravo
Answer: An easier way with the clones.
Comment: This is good, but requires a lot of cloning potions which probably take longer to make than it would to use spearmen!
Answer: Finally I obtained the Pogo Stick, and the cloning method is now working :)
Build a pyramyd of yourself(ves) and jump :)
Comment: You already posted this yesterday.  There's no need to repost, just edit your existing one.
Answer: You can also use Obsidian Wall, but it's kind of slow.  Put a wall somewhere in the middle of the room, then shoot fireballs at it until it's short enough to jump up on. Then put a new wall after the first one, rinse and repeat.
The advantage of this approach is that you don't have to waste chocolate bars on the spear or the crown.
Note: you should unequip your weapon before, otherwise you will destroy the wall you're standing on.


convert binary string to integer array in c#

Question: I want to convert binary value into integer array in c#.
For example consider binary value : 111 , it's integer equivalent is 7 (right most digit equals to integer 1, middle binary digit is equivalent to integer 2 and left most digit is 4, so 1+2+4 = 7).
how do I get each integer digit (i.e. 1, 2 ,4) in form of an array (or list) using c# ?
Comment: Why would you not just want the integer, and extract bits from that as required?
Comment: Can you rephrase your question.. ? Do you simply want the binary places? Or do you want the value 7 from the binary representation .. ? Provide some pseudo-code or something so we can see what you're after.
Comment: possible duplicate of [Convert binary string into integer](http://stackoverflow.com/questions/9149728/convert-binary-string-into-integer)
Answer: Like this:
string binaryString = "111";
var integerValue = Convert.ToInt64(binaryString,2);

integerValue will be 7 now.
Update, thanks to the comments:
If you want to store each value then you need to go through the string step by step in a for loop and bit-shift (<< operator) to get to your desired outcome.
[Test]
public void BinaryStringToValues()
{
    const string binaryString = "111";
    var values = new List<int>();
    for (var i = 0; i < binaryString.Length; i++)
    {
        if (binaryString[binaryString.Length - i - 1] == '0')
        {
            continue;
        }
        values.Add(1 << i);
    }

    Assert.AreEqual(1, values[0]);
    Assert.AreEqual(2, values[1]);
    Assert.AreEqual(4, values[2]);
}

The test will pass.
Comment: While this answers converting from binary .. I don't know how it relates to "how do I get each integer digit (i.e. 1, 2 ,4)".. or what that even means.
Comment: Probably because only a teacher would dream up an exercise as silly as this one... or you've simply been trolled.  Either way, have a +1
Comment: Why do I have the feeling I am doing somebodies homework? :)
Comment: If you like, you can use `1 << i` instead of `(int)Math.Pow(2, i)`.
Comment: @JeppeStigNielsen :)), now I have the feeling I am back in university! Thx, looks much cooler this way! :) long time I used bit shifting
Answer: string bin = "1011";

var str = String.Join(",", bin.Reverse().Select((c, i) => (c - '0') * (1 << i)));

str will be 1,2,0,8. if you want the result as a list
var list = bin.Reverse().Select((c, i) => (c - '0') * (1 << i)).ToList();

Comment: @JeppeStigNielsen How about `((BigInteger)1 << i)` to make it unlimited(!) ?
Comment: @LB If you still want long, use `1L << i`. Or maybe `ulong`, use `1ul`. This will give strange results if string length exceeds 31, or 63, or 64 (`1ul`), so you might want to check for that.
Comment: @L.B Yeah, that is great.
Answer: It's not entirely clear what you want, but let's assume that from this string:
"1011011"

you want to get this array:
64, 16, 8, 2, 1

then you can use this code (LINQPad program):
void Main()
{
    string input = "1011011";

    int[] values = input
        .Select((value, idx) => value == '1'
                ? (1 << (input.Length - idx - 1))
                : 0)
        .Where(value => value > 0)
        .ToArray();

    values.Dump();
}

Output:

This will:

For each character that is '1'
Calculate the position, from the right, where the rightmost position is position 0
Then it will calculate 1 << x (x is that position), which will return 1 for the rightmost position, 2 for the one left of it, 4 for the one left of 2, 8 for the next, 16, 32, 64, and so on.
The array at this point would be [64, 0, 16, 8, 0, 2, 1] so we'll remove the zeroes
Comment: Thanks everyone, your feedbacks are very helpful..


Portable Indoor Airconditioner not cooling -- let's discuss possible reasons (and solutions)

Question: I have a portable indoor airconditioner (LG LP1311BXR 13,000 BTU).
I bought it refurbished from Walmart 2 years ago. It worked beautifully until recently.
Symptoms:

The fan, compressor seem to be working.
It cools ever so slightly, but not strongly (i.e. the air coming out is slightly cooler than room temperature.
It is vented fine, no blockage in the exhaust system.

What are the potential causes?

I'm thinking it's low on refrigerant / freon. Can you think of anything else?

What are the possible solutions?

Call a repair-person, obviously. But I bought it for only $250. Is it worth it to call someone who's likely to charge me a lot of money to fix it?
Would it be possible to add refrigerant myself? Is this something I should take on? (I'm reasonably handy.)
Comment: It may be worth checking the space where the unconditioned air enters the unit. Depending on the particulate in the air, these cooling fins can become dirty and clogged. I have a portable unit that I have to clean somewhat regularly to keep them cooling effectively. Dust Bunnies > Cooling Fins
Comment: I don't know that it could be blocked by dirt and detritus to completely STOP cooling, but I know that I drop my output temp by 5-10F when I clean my unit (after I've let it get FAR too dirty). If nothing else, it's an easy, no cost way to go, and one more thing you'd rule out.
Comment: My room is indeed quite dusty. However, this is *indoors*! Are you saying that despite it being indoors, the fins can get so dirty that the cooling can stop? That's insane! Also, the air coming out the front *is* a little cool (though not enough). Is that a clue that it might be the fins?
Answer: If it's not an obvious mechanical failure, it could be (a) a problem with the controls or (b) a refrigerant leak.
Symptoms of control problems would be the compressor not turning on or not staying on. You should be able to hear it turn on/off distinct from the fan; if you aren't hearing that, then it may be repairable by replacement of a thermostat or the unit's control board.
A refrigerant leak would be likely if the compressor and fans are running fine, but it's not cooling. One sign of this would be constant running of the compressor. In a partial leak, you may find that a section of the coil is freezing over. Maybe you saw that last year?
If it's a refrigerant problem, the system could potentially be recharged. This is not a DIY job as the refrigerant chemicals are environmentally and personally dangerous, and require special equipment to recharge. You could try calling some appliance repair shops to see if they would do this repair.


Android how to combine two parse queries using 'OR'

Question: I am looking to combine two parse queries into one which satisfies an 'OR' condition. How do I achieve this? The docs say that I need a list of parse queries but I am not very sure how to do that ?
Here is my code :
ParseQuery<ParseUser> numberQuery = ParseUser.getQuery();
        numberQuery.whereNotEqualTo("objectId", currentUser.getObjectId());
        numberQuery.whereContainedIn("phoneNumber", values);
        ParseQuery<ParseUser> emailQuery = ParseUser.getQuery();
        emailQuery.whereNotEqualTo("objectId", currentUser.getObjectId());
        numberQuery.whereContainedIn("email", values);
        ParseQuery<ParseUser> superQuery = ParseUser.getQuery();
        superQuery.or

How do I complete this query and get the 'OR' of the two in superquery ?
Thanks
Answer: Okay I figured it out myself. To create a list you use
    List<ParseQuery<ParseUser>> queries = new ArrayList<ParseQuery<ParseUser>>();

and then
queries.add(q1);
queries.add(q2);

and so on.
And then you use
ParseQuery<ParseUser> superQuery = ParseUser.getQuery();
        ParseQuery.or(queries);

to get the final combined query.


problems with ices

Question: I am trying to compile ices but I get this error when I execute make
make: *** No targets specified and no makefile found.  Stop.

Can anyone help me to fix it?

@Martin: Thanks for your interest, when I ran ./configure I got this error:
configure: error: C++ preprocessor "/lib/cpp" fails sanity check

I have a file called Makefile.in and other file called Makefile.am
Comment: Is there a file called Makefile?  Were there any errors when you ran ./configure?
Answer: TL;DR You need a C++ compiler and run ./configure before make

Install a C++ compiler
sudo apt-get install g++

Follow these steps
cd
sudo apt-get install libmp3lame-dev libxml2-dev libshout-dev libvorbis-dev
wget http://downloads.us.xiph.org/releases/ices/ices-0.4.tar.gz
tar xf ices-0.4.tar.gz
cd ices-0.4
./configure --prefix=/usr/local --with-pic --with-lame
make
sudo make install

Comment: So what.  You need g++ as well.  Did you try following these instructions?
Comment: @AB: I have the **gcc compiler** installed
Comment: @MartinThornton: Thanks so much guys¡¡¡¡ I only **needed to install g++** (newbie error:D)........Thanks again A.B:)

problems with ices


sorting program using pointers

Question: I have a program that:

given a sequence of numbers,
sorts even numbers in ascending order, and
sort odd numbers in descending order, and
adds the sorted even numbers to an array followed by the sorted odd numbers.

Example:
<code>Input: 1, 2, 3, 4, 5, 6
Expected output: 2, 4, 6, 5, 3, 1
Actual output: 1578032, 0, 3, 6, 6487408, 0
</code>
here is my code:
<code>#include < stdio.h >

int main() {
    input();
}
int input() {
    int n;
    printf("Enter The Number Of Elements You Want To Enter : ");
    scanf("%d", & n);
    int * ptr, i, ev = 0, od = 0;
    ptr = (int * ) calloc(n, sizeof(int));
    for (i = 0; i < n; i++) {
        printf("Enter Number : ");
        scanf("%d", (ptr + i));
        if ( * (ptr + i) % 2 == 0) {
            ev++;
        } else {
            od++;
        }
    }

    sorteven( & ptr, ev, od, n);
}
int sorteven(int * ptr, int ev, int od, int n) {
    int i, j = 0, swap = 0, * ptreven;
    ptreven = (int * ) calloc(ev, sizeof(int));
    for (i = 0; i < n; i++) {
        if ( * (ptr + i) % 2 == 0) { *
            (ptreven + j) = * (ptr + i);
            j++;
        }
    }
    for (i = 0; i < ev - 1; i++) {
        for (j = 0; j < ev - i - 1; j++) {
            if ( * (ptreven + j) > * (ptreven + j + 1)) {
                swap = * (ptreven + j); *
                (ptreven + j) = * (ptreven + j + 1); *
                (ptreven + j + 1) = swap;
            }
        }
    }
    sortodd( & ptr, ev, od, n, & ptreven);
}
int sortodd(int * ptr, int ev, int od, int n, int ptreven) {
    int i, k = 0, swap = 0, * ptrodd, j;
    ptrodd = (int * ) calloc(od, sizeof(int));
    for (i = 0; i < n; i++) {
        if ( * (ptr + i) % 2 != 0) { *
            (ptrodd + k) = * (ptr + i);
            k++;
        }
    }
    for (i = 0; i < od - 1; i++) {
        for (j = 0; j < od - i - 1; j++) {
            if ( * (ptrodd + j) < * (ptrodd + j + 1)) {
                swap = * (ptrodd + j); *
                (ptrodd + j) = * (ptrodd + j + 1); *
                (ptrodd + j + 1) = swap;
            }
        }
    }
    merge( & ptr, ev, od, n, & ptreven, & ptrodd);
}
int merge(int * ptr, int ev, int od, int n, int * ptreven, int * ptrodd) {
    int * ptrmerge, i, j;
    ptrmerge = (int * ) calloc(n, sizeof(int));
    for (i = 0; i < ev; i++) { *
        (ptrmerge + i) = * (ptreven + i);
    }
    for (i = ev, j = 0; i < n; i++, j++) { *
        (ptrmerge + i) = * (ptrodd + j);
    }
    display( & ptrmerge, n);
}
int display(int * ptrmerge, int n) {
    int i;
    printf("OUTPUT : ");
    for (i = 0; i < n; i++) {
        printf(" %d ", * (ptrmerge + i));
    }
}
</code>
Comment: `sortodd(&ptr, ev, od, n, &ptreven);
}
int sortodd(int *ptr, int ev, int od, int n, int ptreven)` :  The type of `ptr` and `ptreven` are different.  `merge(&ptr, ev, od, n, &ptreven, &ptrodd);
}
int merge(int *ptr, int ev, int od, int n, int *ptreven, int *ptrodd)` : ditto. and so on.
Comment: your program has multiple logical and programmatical issues. e.g. (ptr+i), ptr is pointer to integer, i is an integer, how do you wanna do that operation. plus, it is not bad to check the warning at compile level, they give you good information. Yo repeated this operation a lot in your code. first fix simple mistakes then put the corrected code here to find the logical problem to it. I think your problem is not understanding how pointer works
Comment: The point of this being given to you as homework is so you learn how to use tools like the compiler to help you write your code. Read the advice given to you by @Eisa and follow it. Once you have code that compiles without warnings then ask for human help. Or ask for human help to fix specific compiler errors and/or warnings. If that approach is distasteful to you then you should stop attending your programming class now because that's what programming is and you need to get used to it or stop doing it.
Comment: @BLUEPIXY can you please correct the code?
Comment: @SyedHussain you can use `qsort` for this, it would make your code alot shorter.
Answer: like this
<code>#include <stdio.h>
#include <stdlib.h>

void input(void);

int main(void){
    input();
}

void sorteven(int *ptr, int n);
void sortodd(int *ptr, int n);
void display(int *ptt, int n);

void input(void){
    int n;
    printf("Enter The Number Of Elements You Want To Enter : ");fflush(stdout);
    scanf("%d", &n);

    int *ptr, i, ev = 0, od = 0;
    if((ptr = calloc(n, sizeof(int)))==NULL){
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < n; i++){
        int v;
        printf("Enter Number : ");fflush(stdout);
        scanf("%d", &v);

        if(v % 2 == 0){
            ptr[ev++] = v;
        } else {
            ptr[n - ++od] = v;
        }
    }

    sorteven(ptr, ev);
    sortodd(ptr + ev, od);
    display(ptr, n);
    free(ptr);
}

void sorteven(int *ptr, int n){
//sort to ascending order
    int i, j, temp;

    for (i = 0; i < n - 1; i++){
        for (j = 0; j < n - i - 1; j++){
            if(ptr[j] > ptr[j + 1]){
                int temp = ptr[j];
                ptr[j] = ptr[j + 1];
                ptr[j + 1] = temp;
            }
        }
    }
}

void sortodd(int *ptr, int n){
//sort to descending order
    int i, j, temp;

    for (i = 0; i < n - 1; i++){
        for (j = 0; j < n - i - 1; j++){
            if(ptr[j] < ptr[j + 1]){
                int temp = ptr[j];
                ptr[j] = ptr[j + 1];
                ptr[j + 1] = temp;
            }
        }
    }
}

void display(int *ptr, int n){
    int i;

    printf("\nOUTPUT : ");
    for (i = 0; i < n; i++){
        if(i)
            putchar(' ');
        printf("%d", ptr[i]);
    }
    putchar('\n');
}
</code>

sorting program using pointers


Why does my Xbox keep signing me out of Xbox live

Question: When ever I am playing Xbox it randomly signs me into Xbox live then later will sign me out of Xbox live and I don't know how to fix this little issue. If anyone knows the answer it would be much appreciated if you could help me out.
Comment: Are you talking about the Xbox 360? Are you perhaps connected via WiFi?
Comment: if your profile exists on another xbox somewhere, like a friend's house, make sure it's not signing in over there by mistake. Home Sharing can also produce this behavior when games do not share between consoles correctly
Answer: if it is an xbox 360 it is usually a problem with your modem/network.
Restart your modem, if that doesn't work simply turn it off and play offline.
Answer: Try the following steps:

Do the Xbox live test (You can find it at the Network Settings);
Re-download your profile;
If your profile data is on a external drive, move it to the internal console HDD;
If your console is not updated, accept any updates you have waiting.

If none of these steps fix your problem, try contacting Microsoft, your hardware may be faulty.


Circuit to make Nest thermostat think there are separate heating and cooling systems

Question: I have a Nest thermostat that I am trying to wire in a simple but unique configuration.  My apartment uses fan coil units for heating and cooling.  The building changes over from hot to cold water for the summer months and back to hot water for the winter months.  The old thermostat jumped the Y1 and W1 terminals.  When the building changes over for the winter months, the mode on the thermostat is switched manually so the display shows the heating set points, but the same fan that blows air over the cold coils in the summer will now blow air over the warm coils for heating.
Unlike the old thermostat, the Nest does not allow the Y1 and W1 terminals to be jumped.  It is programmed to see separate circuits on those terminals that turn on cooling and heating systems, respectively.  I want to create a circuit that, when the Nest closes the circuit between the R and Y1 terminal, the fan turns on but the W1 terminal does not have a current.  When the Nest closes the circuit between the R terminal and W1, the same fan turns on but Y1 does not have a current.  After reading about diodes, I thought that I might be able to use two diodes to make the circuit perform as I described above, but then I became (more) confused when reading about using diodes on AC circuits.  Can the circuit be built similar to my picture with the diodes below with a resistor to stop the diode from burning up or am I totally on the wrong track.
Comment: Diodes won't work with an AC circuit.  The *simplest* solution might be to put a small manual winter/summer switch in there...  not necessarily the most convenient, but the simplest...
Comment: @Trevor - what happened to your responses?
Comment: @Fredster This thing wont let me edit the schematics in this forum, so I deleted it. Did you check with the Nest folks if their stat is smart enough to handle your situation anyway? They seem to have quite the support system set up. If not the summer/winter switch mentioned above is probably a better bet for you anyway.
Comment: If you are able to use the TS with `Y1` `W1` jumpered, look into Heat+Cool mode which doesn't require a summer/winter switchover:  https://nest.com/support/article/What-is-Heat-Cool-mode
Answer: Original Answer Deleted: Can not support over on this forum.
You really have a couple of conflicting requirements here.
1. The NEST Wire Detection
Since the NEST is "smart" enough to figure out what wires are connected to it via some method and algorithm in the controller, which no doubt is proprietary, and since said testing happens only when it powers up, you can't just use a simple summer/winter switch.
Without knowing exactly how that works it is foolhardy to try to design a solid state circuit to augment the thermostat to monitor both lines and turn on your fan when either comes on.
Though I am fairly sure there will be a way to fool the thermostat into thinking there are two contactors attached.
2. Space
The "add two AC relays" approach will fix the issue, but suffers from the fact that 24V AC relays are rather large and you are adding a contact life issue into the equation. As such, unless your house or apartment wiring has an extra line that is not being used so you can hook up the relays inside, or close to, the heater/cooler unit, this is an "ugly" approach.
Recommendations
You really need to do some experimenting.
First: Despite what they are telling you, I'd be trying a jumper between the W and Y terminals. They obviously don't want to recommend that connection, but I don't see why it should not work. The isolation between two relays is not that great in the first place.
With your fan wire connected to one terminal, jumper the other with a small resistor say 10R. If it works and the resistor does not get really hot with no demand from the thermostat, you are golden. If the resistor gets hot, remove it immediately! If the NEST pops up an error code, or simply does not switch the line, then you know for sure it's a no-go.
Second: Failing the above, then you need to figure out how to fool the thing into thinking there is a wire connected. I would start out hooking up a fairly large resistor, perhaps 100K, between the Y pin and the C pin. If it does not fool it, try smaller resistors down to about 1K - 2 Watt. If you still can't fool it you will need a more "relay like" dummy load with inductance.
If you can`t jumper it and you can't fool it, you are stuck with the two relay solution or finding a different TSTAT.
If you CAN fool it, then you have two new choices.

Hook the fool-it resistor or circuit to both the W and Y pins so it powers up thinking both are connected, then use a summer/winter switch to connect the appropriate one to your fan as need be. Since the resistors will be in there always, the bigger the resistor you can use to fool it, the better.
Have someone design you a solid state circuit that incorporates the fooling device, monitors the W & Y outputs, and turns on the fan when appropriate.
Comment: Trevor, thanks for providing a solution to my problem.  i'm going to build the circuit.  If the Nest provides power to both the Y1 and W1 terminals simultaneously, I assume the fan would just turn on?  Can I find a solid-state 24V AC relay in a small size?  I ultimately want to be able to put the circuit in a box used for a typical light switch.
Comment: @Fredster that's te issue.. I could not find small ones, but I did not look long.
Comment: looks like your second solution can be built in a small footprint! If I understand this (at least partially), if Y is closed, the current flows through R2, into the diode bridge and starts the fan. The higher ohm R1 ensures current flows through R2.  If W is closed, the transistor M1 closes and connects the circuit to the diode bridge which again starts the fan.  Is that close to a proper explanation?  Why is C2 needed?
Comment: @Fredster the bridge and M1 form an AC switch since the current always goes the same way through the MOSFET. D5 and D6 form a half wave rectifier along with C2 that sets up a simple DC power supply that turns on the gate of M1 through R1. D7 keeps the gate voltage at a max of 12V. R2 is there to discharge C2 when the Y and W switches open, which in turn, turns off M1.
Comment: @Trevor - In my diagram, the thermostat closes R with Y1 or R with W1 depending on mode (Air Conditioning or Heating).  In your circuit, I don't see the analogue between my diagram and the connection at the bottom of the 'diamond' (the bridge). I'm missing something.
Comment: @Fredster ya I may have been confusing myself how the Y and W outputs were worked. Closing this answer now it's over here anyway. Not appropriate for this forum, and I cant edit the schematics anymore over here.
Comment: If you're switching at the 'stat, the relays can be as small as Nest will accept as a load.  You are only switching a 24V pilot voltage. In which case your earlier schematic had it right.
Comment: @Harper true, but finding a sub-miniature 24V AC relay is not easy.
Comment: @Trevor my first thought was "Mouser, relays, filter 24VAC, done" but looking at some of those tiny relays I'm not sure they'd draw enough for Nest to detect them.  That is a question for Nest.  If their current minimums are sensible enough this gets a lot easier.
Comment: @Harper ya it really depends on how they do it. They may just detect the ac through them when they are off. But I'm pretty sure they will not tell anyone if they ask.
Comment: My latest thinking is those 29mm sized relays (350 ohm coil) will in fact work.  A common question is how to power the Nest without a C-wire (it leaks power through the contactor without picking it up).  They say if it does pick it up, parallel the contactor coil with a 220 ohm resistor.  That tells me it can power itself through ~150-200 ohms, so it certainly ought to be able to detect 350.
Comment: @Harper yes indeed.The OP has gone quiet since he decided to try jumpering the outputs. Maybe this is a non-question.
Comment: @Trevor it's not wasted effort. The question of making a Nest/Ecobee control "weird thing *X* which is not a stock furnace/AC" comes up weekly here.
Answer: When dealing with the Nest and other smart 'stats, the trick is that you need to put things on their outputs which will vaguely emulate a relay.  That's because they electronically "sense" whether something is attached to Y and W.
If it senses nothing attached to a wire at configuration time, it will assume that feature is not there.
A switch that selects the line that is active is incompatible with that.  Same is true of any scheme coming to a diode.  Now, you could emulate a relay coil with a big resistor between W and C, and Y and C... at the expense of wasting some power and making heat in a potentially inopportune place.
The Y and W lines are meant to go to the coil of a contactor.  The contactor interrupts mains power to the fan.  The fan does not run on 24V.
Rectifiers method
In this scenario, you have two bridge rectifiers, then onto the fan relay coil.  This gives the relay bouncing ball DC from either W or Y, without them interfering with each other.  The relay coil doesn't care. It is laminated for AC, so eddy currents shouldn't be a problem.
The idea is the rectifier will be transparent to the Nest.  It will see the coil load it expects to see (without any inductive kick).  It doesn't know it is seeing the same coil on both wires.

rectifier 1's AC side goes to W and C.
rectifier 2's AC side goes to Y and C.
Both rectifiers' DC sides are paralleled and go to the fan contactor coil.

The contactor operates the fan, of course.  Super important: the two wires from the rectifier output to the fan must be separate, they cannot be made common with R or C, or you will dead short the rectifiers.
Two contactors method
Simpler would be what Trevor describes in his since deleted answer.  I saved this schematic out of his answer.  Except where it says 'fan', that is actually the two sides of the fan contactor. Paralleling AC won't hurt here since only one will be on at a time, still they should be right next to each other.
Comment: @Trevor, it took me a while to get to my apt, but I was finally able to jump Y1 & W1 as you suggested.  After installing the jumper, the Nest-E identified the wiring change and sees both a cooling and heating system.  It looks like it works.  The only thing I ws unable to do was run the Nest test for the A/C because its too cold here and the Nest won't cycle the compressor at current outdoor temperatures.  Thanks again for all of your help and insight!
Comment: @Trevor, I will not be able to test the simple jumper because I'm not at my apt and won't be for a while. It will be the first thing I do after I open the door.  Nest can fix this in software, just offer the option to the homeowner/installer.  With their new home security product just coming out, I doubt they will put as much effort into this as they once did.
Comment: my diagram did not have the fan relay in the picture.  I oversimplified.  This was my first post on stack exchange and I'm confused about what happened to Trevor's diagrams (removed?).  Trevor's  second picture was a little different than the way the nest works.  I envisioned a circuit that closed the circuit with Y1 if in air cond. mode or closed the circuit to W1 if heating mode was operational.  I can't find relays small enough to fit where I need them, so his second schematic with the bridge seemed like a better answer.  I think I may still not be articulating where I'm confused.
Comment: I;m not sure the polarity is right on those relay coils though. I think I got that backwards. common on the relays should go to the R side if Y and W are sinks.. But I'm not convinced of that either.
Comment: @Trevor, in the solid state schematic you posted, the Y or W is a switch, but the Nest closes the circuit by connecting the R (from my drawing) with Y or W.  A wire comes from Y to diode and W to diode.  Then runs through circuit, but where is the single output to the fan relay to turn on the fan?
Comment: @Fredster ok that's where you confused me. YOur drawing shows the plus side is the C.
Comment: @Trevor, I am in the 'little knowledge...' camp.  C is common on the thermostat.  I thought the R/C provided power for the 'stat which I did not make clear in diagram.  Apologize for imprecision.  I think the circuit would have 2 inputs (Y and W, one of which Nest will close depending on heating or cooling) and 1 output.  When R/Y is closed, fan turns on, W shows no current and vice-versa for W.
Comment: @Fredster the other issue with the solid state circuit is the Nest may not recognize it. To be honest I am not convinced you can not jumper Y & W. Their literature seems to be talking about the R terminals not using jumpers. You really need to check with them. This may be a non-issue.
Comment: @Trevor, R isn't jumped with nest (which may be done with other thermostats between R and Rc).  Y and W can't be jumped either, Nest expects separate wires to run AC  and heat.  I am pretty sure that if I can build a circuit as I described above, Nest will think its got AC and heat wired properly so it will let me set up the Nest for heating and cooling.  With only one wire (lets say W) it will only think I have a heating system when in fact the fan is used for heating and cooling.
Comment: @Fredster did you ask them that?
Comment: @Trevor, yes.  Spent a lot of time on phone with them.  My configuration has 3 wires (R/C/W) not the usual 4 or 5 because my building provides hot/cold water through fan coil and the same fan is used for heating and cooling.  I'm trying to fool the Nest into thinking its got a separate fan for cooling and heating even though there is one fan.  They understand my issue but don't support it.
Comment: @Trevor, I misread your comment about jumping Y and W.  Must have been late.  i have not tried that and should have tested it before posting.
Comment: @Fredster do you still have the receipt ;) See my updated answer.
Comment: @Fredster how many wires exist in your thermostat cable between the thermostat and fan blower/transformer?  If you only have 3, that will make things "a bit tight"...
Comment: @Trevor, I am going to follow the suggestions in your answer. What does the 10R resistor on the jumper between Y and W do?  When the Nest closes R and Y, won't it see the load that is on the other end of the terminal (W) that its jumped to without the resistor?  If it works and the resistor doesn't get warm, should I leave it in the jumper?
Comment: @Harper, there are only wires coming into the box.
Comment: @fredster you left the important number off.  Do all the wires go back to the heater and is the transformer located there?
Comment: @Fredster if the resistor fools it into thinking there are two wires not one, and it operates as expected. You can just short the two together and hook up your fan to one or the other. With them tied together like that it may detect the signal on the other pin when it does not expect it and go into a fault mode, or it may just not notice work. That's why you need to experiment.
Comment: @Harper, there are 3 wires that come into the box for the stat.  The electronics are by the fan coil unit.
Comment: @Fredster it sounds like the Nest was "designed defensively" specifically to allow you to do that.  The things they think of!
Answer: I'm in a similar situation- a second apartment with a "two-pipe" heating/cooling system where I want to control the system's 120V fan motor using a Nest E thermostat. I also want to be able to remotely monitor the apartment's temperature using my smart phone, which the Nest will give me.
I'll be using a simple solution that I've bench tested and it worked as planned. The bench test included all the components in my schematic below with the exception of the fan motor. I was easily able to switch between the "heating only mode" to the "cooling only mode" and the Nest E thermostat responded correctly to operate the simulated fan motor on and off.
My next step will be to install these components into the live system (later in December). I'll confirm back afterwards on how it all worked out.
So here's the setup:

Relay/Transformer- Since the Nest requires low voltage (24VAC) to operate, I'm using a relay/transformer to bridge the Nest thermostat over to the 120V fan motor. I selected an Aube RC840T-120 relay/transformer. (Thanks Anthony Ngu.) The RC840T-120's transformer feeds the Nest with low voltage power (using the C and R wires). The Nest returns a control signal back to the RC840T-120's relay coil to turn the fan motor on and off (using either the W1 or the Y1 wires, depending on the position of the SPDT switch.)
SPDT Switch- Rather than trying to "trick" the Nest into believing there was both a heating system and a cooling system simultaneously available, I used a SPDT throw switch to select when the system is operating in the "heating only mode" or in the "cooling only mode". The Nest did not have trouble sensing when the system's heating or cooling features were available for use.
Comment: When the Nest E is originally configured if it doesn't 'see' a connection on 'Y1' or 'W1' (assuming other wires are set up properly), it will not configure for heating and cooling - whichever wire is not attached.  What I don't understand about your solution is how the Nest E sees the Y1 and W1 connections when its in setup mode so that heating and cooling functions are available during normal use.  I have not yet tested @Trevor's idea of just jumping Y1 and W1 (since I haven't been to the apartment in several months)


How is a map initialised in memory

Question: I just tarted to write solidity and i have some questions that i could not find the answer to.
When you declare a map like this:
struct UserAccount{
    string name;
    uint id;
}

mapping (address => UserAccount) public accounts;

How will that be initialised? or with what?
For example, accessing
accounts[0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc]

will return an instance of an UserAccount? If yes, that means that the map creates an instance of UserAccount for every possible address? Doesn't that consume very much memory? If not, then how comes you can do this:
accounts[_address].name = _name;

?
And the second question:
I keep reference in my contract of an address that is the owner, the address that created the contract:
address public owner;
constructor() public {
    owner = msg.sender;
}

After i call this function:
uint userCount=0;
mapping (address => UserAccount) public accounts;

function createAccount(string _name, uint _id, address _address) onlyOwner() public {
    UserAccount user;
    user.name = _name;
    user.id = _id;
    accounts[_address] = user;
    userCount += 1;
    // accounts[_address].name = _name;
    // accounts[_address].id = _id;
    // userCount += 1;
    emit UserCreated(_address, _id, _name);
}

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

the owner address changes. The commented lines from createAccount function are the way to do it, i know, but i want to understand why it does not work.
To clarify my problem i will also post a js test.
beforeEach(async () => {
    voting = await Voting.new({from: owner});
});

it("Should delete poll, as owner", async () =>{
    var name = "Sandu";
    console.log("LOCAL OWNER= " + owner);
    console.log("OWNER BEFORE CREATE ACCOUNT FROM SOL= " + await voting.owner());
    await voting.createAccount(name, 1, firstUser,{from:owner});
    console.log("OWNER AFTER CREATE ACCOUNT FROM SOL= " + await voting.owner());
    var pollName = "First Poll";
    var endDateS="2018-08-11T10:20:30Z";
    var endDate=new Date(endDateS)
    await voting.createPoll(pollName, 1, endDate.getTime()/1000,{from:firstUser});

    try{
        await voting.deletePollById(1,{from: owner});
    }catch(err){
        console.log(err.message);
    }

    assert.notEqual(pollName, await voting.getPollById(1));
});

The test above prints this:
LOCAL OWNER= 0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc //Owner that o have in my js file local, first address from the ganache accounts.
OWNER BEFORE CREATE ACCOUNT FROM SOL= 0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc  //The owner account from my contract before calling the function
OWNER AFTER CREATE ACCOUNT FROM SOL= 0x000000000000000000000000000000000000000a   //The owner account from my contract after calling the function

I can't understand why the value from owner changes as i don't touch that in my function.
If anyone can help it would be much appreciated. Again, i know the right way to do it but i am posting this out of the desire to understand what i am doing not to get the job done.
Answer: Please do not post multiple questions in a single post as it will result in the question being closed as too broad.
For your first question, all variables have an initial default value. From the Solidity docs:

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type's default value.

No storage is used for zero values.
For your second question, you're overwriting the state variable because you're using a storage variable where you should be using a memory variable. See the answer provided here: what are state variables in solidity?

How is a map initialised in memory


submenu items in menu are beneath page elements

Question: At the top of this page is a jquery menu.  When putting the cursor over 'stuff for him' the submenu item is lost behind the #headliner div.  It also is lost behind the black footer.  I have tried another menu (Telerik RadMenu) and the same problem occurs.  I need another set of eyes to give me some insight on what's happening.  Html / CSS Code below.
Menu CSS:
ul#menu {
background: #940;
color: #fff;
margin: 0;
padding: 0.3em 0em;

}

ul#menu li {
display: inline;
margin: 0.1em 1em;
position: relative;
}

ul#menu h2, ul#menu h3 {
font-size: 100%;
font-weight: normal;
display: inline;
}

ul#menu li a {
color: #fff;
text-decoration: none;
padding: 0 0.4em;
}

ul#menu li a:hover {
text-decoration: underline;
}

ul#menu li.mega a {
background: transparent url(../images/icons/arrow.gif) center right no-repeat;
padding: 0 1.2em;
}

ul#menu li.mega a:hover {
text-decoration: underline;
}

ul#menu div {
display: none;
}

ul#menu li.mega div {
border: 1px solid #dda;
width: 18em;
position: absolute;
top: 1.6em;
left: 0em;
padding: 1.3em;
background: #ffc;
color: #930;

}

ul#menu li.hovering div {
display: block;

}

ul#menu li.mega div a {
color: #300;
padding: 0;
background-image: none;
text-decoration: underline;
}

ul#menu li div a.more {
color: #390;
font-weight: bold;
}

ul#menu div h3 {
color: #f70;
font-weight: bold;
font-size: 1.1em;
}
ul#menu div p {
margin: 0 0 0.8em 0;
padding: 0;
}

demo.css
html, body, form
{

    margin: 0px;
    padding:0px;
    height: 100%;

}

body {

    background: url("../images/common/2010_logo_bg_02.gif") repeat;
    font: 12px Arial,Helvetica,FreeSans,"Liberation Sans","Nimbus Sans L",sans-serif;

}

#wrapper
{

    height: auto !important;
    height: 100%;
    min-height: 100%;
    position: relative;
    width:1000px;
    margin: 0 auto -435px;
    background-color:#ebebeb;

}

.push {
height: 435px;
}

#topsection
{
   width:1000px;

}

#commandbar div
{

    color: #333333;
}

#main
{

   background-color: #ebebeb;

}

#bottom
{

    position:relative;
    margin: 0 auto;
    height: 435px;
    width: 1000px;

}
#footer {

    background: #000;
    color: #fff;
    font-size: 12px;

}

#footer ul.yellow li a {
    color: #f5eb26;
     font-size: 14px;
     font-weight:bold;
}

#footer ul.yellow li a:hover {

     text-decoration:underline;
}

#footer ul.blue li a {
    color:  #66ccff;
     font-size: 14px;
     font-weight:bold;
}

#footer ul.blue li a:hover {

     text-decoration:underline;
}

#footer ul.white li a {
    color:  #ffffff;
     font-size: 12px;

}

#footer ul.white li a:hover {

     text-decoration:underline;
}

#footer .box-footer-1 div.more,
#footer .box-footer-2 div.more,
#footer .box-footer-3 div.more,
#footer .box-footer-4 div.more {
    text-align: right;
}

#footer .box-footer-1 div.more a,
#footer .box-footer-2 div.more a,
#footer .box-footer-3 div.more a,
#footer .box-footer-4 div.more a {
    color: #ffff00;
    text-decoration: none;
}

#footer .box-footer-1 {

    float:left;
    width: 390px;
    _width: 400px;
    height: 389px;
    padding: 20px 10px 0px 0px;
    border-right: 1px solid #666;
    margin-left:15px;
}

#footer .box-footer-1 img {
    margin-bottom: 10px
}

#footer .box-footer-2 {
    float:left;
    width: 194px;
    height: 389px;
    padding: 20px 10px 0px 10px;
    border-right: 1px solid #666;

}

#footer .box-footer-2 ul {
    margin: 0px;
    padding: 0px;
}

#footer .box-footer-2 ul li {
    margin: 10px 0px 0px 10px;
    list-style: none;
}

#footer .box-footer-3 {
    float:left;
    width: 140px;
    height: 389px;
    padding: 20px 10px 0px 10px;
    border-right: 1px solid #666;
}

#footer .box-footer-3 ul {
    margin: 10px;
    padding: 10px;
}

#footer .box-footer-4 {
    float:left;
    width: 129px;
    padding: 20px 10px 0px 10px;
    height: 389px;
}

#footer .box-footer-4 ul {
    margin: 0px;
    padding: 0px;
}

#footer .box-footer-4 ul li {
    margin: 10px 0px 0px 20px;
    list-style: none;
}

#footer h1 {
    margin: 0px 0px 10px 0px;
    padding: 0px;
    font-size: 20px;
}

#footer h2.blue {
    color: #66ccff;
}

#footer h2 {
    margin-top: 10px;
    padding: 0px;
    font-size: 14px;
    color: #f5eb26;
}

#copyright
{

    background: #ccc;
    color: #000;
    height:25px;
}

#copyright a
{
    font-size: 10px;
    text-decoration:none;
}

h1
{
    font-size:16px;
}

.clear {
    clear: both;
}

.left
{
    float:left;
}

.right {
    float: right;

}

.outer_canvas
{
    background-color:#ffffff;
    padding-left:10px;
    padding-bottom:30px;
    border: 1px solid silver;

}

.inner_canvas
{
     background-color:#f4f3f3;
     margin-left:0px;
     margin-top:15px;
     margin-right:20px;
     padding:15px 15px 20px 20px;
     border: 1px solid #e5e5e5;

}

.margin
{
    margin:10px;
}
.margintop
{
    margin-top:5px;
}

.marginbottom
{
    margin-bottom:15px;
}

.marginleft
{
    margin-left:10px;
}

.marginright
{
    margin-right:10px;
}
.textbox
{
    border: 1px solid silver;
    height: 20px;
    padding-top: 5px;
    padding-left: 5px;
}

.padding
{
    padding:15px;
}

.surround
{
    padding: 10px 0px 10px 0px;
}

.small
{
    font-size:10px;
}

.italic
{
    font-style:italic;
}

.bold
{
    font-weight:bold;
}

.big
{
    font-size:20px;
}

.underline
{
    text-decoration:underline;
}

.error
{
    color: Red;
    font-weight:bold;
}

.blue
{
    color:Blue;
}

.light_blue
{
       color: #005ABE;
}

.lightblue_shading, h2.lightblue_shading
{
       color: #005ABE;
       margin:3px;
}

.white
{
    color:#ffffff;
}

.grey
{
  color:#cccccc;
}

.hide
{
    display:none;
}

.break-word {
  word-wrap: break-word;
}

.success_border
{
    border:2px dashed green;
}

.error_border
{
    border:2px solid red;

}

.mappoints
{
    padding:0;
    margin:0;
}

.mappoints li
{
    list-style-type:none;
}

/* --------- Headliner --------- */

#headliner
{
    height: 38px;
    position:relative;
    width: 1000px;
    margin: 0 auto;
    background-image: url('../images/common/headliner_bg.jpg');
}

#headliner h1
{
    margin:0px;padding:0px;
}

#left_container
{
    float:left;
    margin-top:5px;
    background-color:#ffffff;
}

#right_container
{
    float:left;
    margin-top:5px;
}

The master page
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Demo.master.cs" Inherits="MasterPages_Demo" %>
<%@ MasterType TypeName="BaseMasterPage" %>
<%@ Register Src="~/MasterPages/Controls/Headliner.ascx" TagName="Headliner" TagPrefix="uc1" %>
<%@ Register Src="~/MasterPages/Controls/MegaTemplateMenu.ascx" TagName="MegaTemplateMenu"
    TagPrefix="uc2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager2" runat="server" />
    <link id="Link1" runat="server" href="~/css/demo.css" rel="stylesheet" type="text/css" />
    <link id="Link2" runat="server" href="~/css/megamenu.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>

        <uc2:MegaTemplateMenu ID="MegaTemplateMenu1" runat="server" />
        <uc1:Headliner ID="Headliner1" runat="server" />

                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                </asp:ContentPlaceHolder>

Rules

Volunteer Opportunities

                    Personnel

BC & Yukon

Ontario

Alberta

Saskatchewan

Manitoba / Nunavut

Quebec

Maritimes

NFLD & Labrador

                    National Office

                    Map / Driving Directions

                    Feedback

                    <asp:TextBox ID="txtEmailFeedback" runat="server" Width="180px" CssClass="small italic"
                        ForeColor="#333333">enter your email address</asp:TextBox>

                    <asp:TextBox ID="txtFeedback" runat="server" TextMode="MultiLine" Rows="5" Width="180px"></asp:TextBox>

                    <asp:Button ID="btnFeedback" runat="server" Text="Submit" Width="75px" />

                    Sign up for our newsletter:

                    <asp:TextBox ID="txtEmailNewsletter" runat="server" Width="180px" CssClass="small italic"
                        ForeColor="#333333">enter your email address</asp:TextBox>

                    <asp:Button ID="btnNewsletterSignUp" runat="server" Text="Sign Up" Width="75px" />

                        <asp:Label ID="lblCopyright" runat="server"></asp:Label>

                    <asp:HyperLink ID="linkPrivacy" runat="server" NavigateUrl="~/privacy-policy.aspx">Privacy Policy</asp:HyperLink>
                    |
                    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/terms-of-use.aspx">Terms of use</asp:HyperLink>

    </form>

Answer: If I remove position:relative from #bottom and #headliner - the submenu opens over the #headliner and #bottom divs.


What is the benefit of splitting aggregator and parent projects?

Question: I've read that it's supposedly a good idea to split an aggregator project (the one with all the module declarations) from the parent/dependency project (the one with all the shared or common dependencies). So that the parent project is not the one you use to do a full build.
Why is that?
Comment: could you post the link to where you read this?
Comment: I can't seem to find it again. It was in just JIRA issue as I recall, where developers of that project were getting their parent project (which also has modules declared) split, so that one project only has the modules, and the parent project only has the dependencies. The reason given there was something about making it easier for multi-module configuration or something. Sorry I can't be more specific - I was just wondering about it.
Answer: In a large environment you may want to have parents that define common behaviour for classes of projects (e.g. a servlet parent, a portlet parent, a war parent etc). Because there is no multiple inheritance in Maven, you either have to have a gigantic parent POM with all this content in and some complicated profile conventions, or several parents, one for each type of project.
Similar projects are not necessarily built together (in fact usually not). To build your projects for a single release you therefore want an aggregator that defines the relevant modules to be built.
There is a section of the Maven book that describes the distinction between aggregation and inheritance. This may help your understanding.
Answer: Aggregator projects generally package up all dependent projects somehow (e.g. as a J2EE EAR or WAR archive, or as a distribution ZIP), which requires all dependent projects to be built first.
However, a parent POM must be built before it's children projects.
If the parent project is also the aggregator, then you have a circular dependency:
Aggregator depends on children dependencies, which depend on the Aggregator parent.
In our build system we solve this by having a parent POM file that is also the reactorizes it's children. One of the children is an aggregator, which depends on the other children and creates the distribution artifact. Maven dependency resolution allows us to build the top-level pom, which reactorizes all children in the correct order, with the aggregator project last.
Comment: It is perfectly valid for an aggregator to declare a module , this is *not* the same as introducing a dependency and does not introduce a cycle. Several projects do exactly this (e.g. http://subversion.jfrog.org/artifactory/public/trunk/pom.xml). You would only introduce a cycle by the aggregator/parent declaring dependencies on the children.


SSAO artefacts on iPhone (OpenGL ES)

Question: I've never written shaders before, and now I'm trying to implement SSAO with SceneKit on OS X and iOS. I'm trying different SSAO shaders that I find, e.g. from Three.js, this one, and this one.
On OS X they all work as they should, but on iPhone all of them giving me the same artefacts (images show SSAO pass only). The lines move when I move the camera. So it must be because of some differences of OpenGL ES. Anyone knows what's wrong?

Answer: Resolved by adding precision highp sampler2D to my shaders.
About default precision settings on ES - https://www.khronos.org/files/opengles_shading_language.pdf page 36.
Comment: Out of curiosity, what was the precision before? Low or Medium?
Comment: I found a document saying it's low for samplers and high for float/int by default on ES. Oh, ints depend on shader type I've added link to my answer.
Comment: OK. Was just wondering if you'd tried mediump as there could be performance (and power) benefits.
Comment: mediump doesn't help in my case, and also I don't notice any significant performance difference either.

SSAO artefacts on iPhone (OpenGL ES)


Printing the count of each file in a folder using AWK

Question: I have a folder with more than 100 .gz files. I need to get the output as:
file name : Count

Eg:
abc.gz : 123456

cde.gz : 123456
test.gz : 456896
Comment: The count of what?
Comment: Do you mean the size?
Comment: Count of equal files? Equal file types?  Update your original post with correct info.
Comment: Please edit your question so that it contains the required information. It sounds like you mean the _line count_, or the number of lines in each file (although it's questionable what use this would be for a `.gz` file).
Comment: I have a folder with more than 100 .gz files. I need to get the output as:

    file name : Count

Sample Output
--------------------
abc.gz : 123456
cde.gz : 123456
fgh.gz : 25365
qwe.gz : 5623
Comment: I was using wc -l filename for getting the count of each file. Wans trying to get it in a single command for all the files in the folder
Comment: Is it the line count you like?
Answer: To count the lines of each file in the current directory you can do
wc -l *

The above will generate a warning for any subdirectories present. To avoid these warnings, you can use the find command like:
find . -maxdepth 1 -type f -exec wc -l {} +

Of course the above will count the number of lines in the files as they are. If the files are compressed, and you need the number of lines of the uncompressed files that they contain, you can use the following script:
#!/bin/bash
for i in *.tar.gz
do
  echo "$i: $(zcat -- "$i" | wc -l)"
done

Comment: That is true. Added a script that can work with `.tar.gz` files
Comment: note that if it is `gz` files you probably need to do `zcat file | wc -l`.
Comment: Below query works perfectly :  Thanks much
for i in *.tar.gz
do
  echo "$i: $(zcat -- "$i" | wc -l)"
done


Extending continuous function of space to continues function on one-point compactification

Question: I came across an interesting problem.
Let $A$ be locally compact and  $B$ be its one-point compactification. I WTS that a continuous function $g : A \rightarrow \mathbb{R}$ can be extended to a continuous function $\bar{g}: B \rightarrow \mathbb{R}$ iff there is some constant $c$ such that $g − c$ vanishes.
We say that $g$ vanishes if for any $\epsilon >0$, there is some compact $C\subset A$ such that $|g(m)|<\epsilon$ for any $m\in A \setminus C$.
I honestly have no clue how to prove this, but I'm curious to see how this is true, as it's not the criterion I'd expect for extending a continuous function. How does the proof of this go?
Answer: Let $g:A\to\mathbb{R}$ and $*$ be the unique point added to $A$, i.e. $B=A\cup\{*\}$.

"$\Rightarrow$" Let $g':B\to\mathbb{R}$ be the extension of $g$. Put $c:=g'(*)$. We will show that $g-c$ vanishes.
So pick $\epsilon > 0$ and define
$$U=\{b\in B\ |\ |g'(b)-c| < \epsilon\}$$
So $U=f^{-1}(-\infty, \epsilon)$ for $f(b)=|g'(b)-c|$. Since $g'$ is continous then so is $f$ and thus $U$ is open in $B$.
Therefore $C:=B\backslash U$ is compact (being a closed subset of a compact space). Note that $*\not\in C$ since $*\in U$ because $|g'(*)-c|=0<\epsilon$. Thus $C=A\cap C$ and therefore $A\cap C$ is a compact subset of $A$ that satisfies desired properties. This completes the proof. $\Box$

"$\Leftarrow$" Let $c\in\mathbb{R}$ be such that $g-c$ vanishes. Define
$$g':B\to\mathbb{R}$$
$$g'(x)=\begin{cases}
g(x) & \mbox{ if } x\in A \\
c & \mbox{ if } x= *
\end{cases}$$
Obviously $g'$ extends $g$. All that is left is to prove that $g'$ is continous. Can you complete the proof?
So it is enough to prove that if $c\in(a,b)$ for some $a,b\in\mathbb{R}$ then $g'^{-1}(a,b)$ is open in $B$. Let $x\in g'^{-1}(a,b)$. If $x\neq *$ then there exists an open neighbourhood $U$ of $x$ in $A$ (and thus in $B$) such that $g'(U)=g(U)\subseteq (a,b)$ (by continuity of $g$). Therefore the only thing that we actually have to prove is the existence of a neighbourhood $U$ of $*$ such that $g'(U)\subseteq (a,b)$.
Take $\epsilon := \min\big(|b-c|, |a-c|\big) > 0$. Since $g-c$ vanishes then there exists a compact subset $C\subset A$ such that
$$g(A\backslash C)\subseteq (c-\epsilon, c+\epsilon)\subseteq (a,b)$$
By the definition of the one point compactification $U:=A\backslash C\cup\{*\}$ is open in $B$ and since $g'(*)=c$ then $g'(U)\subseteq (a,b)$ which completest the proof. $\Box$
Comment: @CuriousKid7 Continuity of $g'$ implies that $U$ is open in $B$ (since $U$ is a preimage of $(-\infty, \epsilon)$ via composition of continous functions). We know that $C\cap A$ is compact because $C\cap A = C$ (which is compact) and that is because $*\not\in C$.
Comment: The only thing to check is that the preimage of a neighborhood of $\ast$ is open. This preimage will contain $c$. I'm not sure though what to do.
Comment: @CuriousKid7 Is it clear now?
Comment: Yes, that makes sense immediately. Thanks!
Comment: Where do we use the fact that $g'$ is continuous in the first part? Also, how do we know $C\cap A$ is compact?


How to run a predicate on ObjectInstance property of DataTrigger

Question: I have a list saved in the ObjectInstance of the ObjectDataProvider class. When calling my datatrigger i would like to run a predicate on the list and return a value true/false so i can hide/show text.
Ideally i would like to call a property "Noresults" that would return true/false so i can toggle text in the view.
<DataTrigger Binding="{Binding Path=ObjectDataProvider.NoResults, Mode=OneWay,Source={StaticResource DongleContentsProvider}, BindsDirectlyToSource=True}" Value="true">
    <Setter TargetName="NoResults" Property="Visibility" Value="Visible" />
</DataTrigger>

Answer: Add a Binding.Converter which does run any logic and returns a respective bool.


What is this panel with two 30A breakers for?

Question: I recently newly moved into an apartment in the west Bay Area, in California. Because I have an electric car & want to use L1 (120V 12A) charging, I took a look at the breaker panel to see what circuits were present. Here's what I saw:

I'm no electrician, but my understanding was that 30A breakers aren't allowed on 15/20A receptacles (my apartment has 15A receptacles). Is that correct, why are these breakers 30A, and will this pose any dangers especially if I use it for heavy loads like EV charging?
The apartment was constructed in the 1950s to the best of my knowledge.
Edit: Yeah, the apartment is definitely underpowered by modern standards. It was built all-gas (gas stove, gas oven, gas heating) but did get a normal window AC retrofitted at some later date.
Edit 2: Ok, you all asked for it. Here's a photo of the whole electrical box. As you can tell, it's a fourplex with a separate attached room for washer/dryer hookups.

I have not been able to find another panel beyond this one - I've looked in all interior rooms.
Comment: It looks like these breakers are (a) in use as a disconnect for the entire service, (b) way undersized for most service (typically at least 60A and this is just 30A) (c) normally should be a double-breaker not two single breakers. And that is all in addition to your need for 15A or 20A breakers to protect your apartment circuits. **Look for another panel somewhere with more breakers.** It might even be an old fuse box rather than breakers. But based on this limited information, I'd be seriously concerned about whether you have the capacity to add *any* EV charging.
Comment: You should not attempt to open the long bottom metal box. That is the utility's junction box, the wires inside are totally unfused and always live (unless the utility disconnects the building's feed from the local transformer). It should open after loosening the screws (and maybe some force to break the rust free) but you absolutely should not touch it.
Comment: @ThreePhaseEel, I think the question is "what's the box _below_ the meter?". It appears that the meter is below the box in the first pic (looking at the 2 ground wires & the remnant of paper stapled to the wood that are common to both pics), but there is another box below the meter in the 2nd pic.
Comment: @manassehkatz-Moving2Codidact  YEAH AGREED , look for another panel someplace. Something is off here.
Comment: The meter appears to be rated for 15A if I'm reading correctly. Yikes.
Comment: Well, a 30A/240V or even 30A/120V service to an *all-gas* apartment is possible.  I have one.  But you have a second problem: you need to figure out the other loads to see if EV charging is even *possible* and if so, how much. We might be able to wangle 2880W (240V/"15A" actual 12A) out of this deal.
Comment: Just posted some more pics that should answer questions about meter placement. The long bottom metal box seems to be unopenable, as does the yellow one (no idea what's in there). I'm as puzzled as you all are.
Comment: Also: Firestarter Pacific for the laundry room! Classy!
Comment: Thanks for the help, guys! Looked around but I couldn't find another breaker panel (checked every room, closet, and walked around outside). My only guess is maybe the roof or crawlspace? But that seems unlikely. I'll do a more extensive search tomorrow.
Comment: @KevinLiu what's the box above the meter, or is that the breaker box in the first photo?
Comment: @FreeMan normal utility practice ("hot sequence") would put the breaker box below the meter for an overhead service (which I'm kinda presuming it is, given the age of the meter base)
Comment: I'm afraid to even speculate about this equipment.
Comment: @KevinLiu do other buildings in the vicinity have overhead or underground power? Is there a service mast and triplex cable running off to a power pole from your building?
Comment: @ThreePhaseEel thanks for that tip. Also, there _is_ another box below the meter, just not what I was expecting. Probably something you'd have been familiar with.
Comment: Now I'm curious about the rating on the house meter and all those circuit breakers for the laundry.  If that's another 15A single phase unit I would just slowly walk away from this whole thing and buy some extra fire insurance.
Answer: This apartment building needs some serious professional help
Because this is an apartment, what you can touch on your own is very limited, and certainly doesn't extend to what appears to be issues with improperly retrofitted/overfused service equipment, nor to the Fire Protection Eliminated "house panel" serving the shared circuits.  (Certainly, 15A receptacles on a 30A circuit would be a Code violation when the building was built!)
You'll need to have the landlord get an electrician in to sort everything out, which may very well involve having to cut power to the entire building, given that the incoming cable from the utility appears to be entering the utility's trough from an unknown point inside the building, not a proper service mast or stub-up.
Comment: @RobertChapin -- this is a Rule of Six setup with separate service disconnect enclosures, so *that* part is fine (even with the Rule of 6 changes in the 2020 NEC)
Comment: The OP should bear in mind that if the landlord is the cheapskate he appears to be, his hand could be forced by calling in the local building inspector. _However_, that has consequences, including the possibilities of raised rent or lease termination.
Comment: Were buildings not required to have a main disconnect back then?  Or do you imagine it's located somewhere else?


WebClient/HttpRequest Navigating To Page After Login

Question: I want to login to a website using a webclient or httpwebrequest, after i'm logged in i want to navigate to a page in the site.
so i know how to post data and to login, my problem is with the navigation after the login,
it redirect me to the login page, i know it has to do with the cookies, but i dont understand what i'm doing worng... here is my code -> it is taken from another answear on stackoverfllow... (http://stackoverflow.com/questions/8425593/c-sharp-httpwebrequest-post-login-to-facebook)
<code>        string getUrl = "somesite.com";
        CookieCollection cookies = new CookieCollection();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(cookies);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        cookies = response.Cookies;

        string getUrl2 = "somepage.login.com";
        string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");

        HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
        getRequest.CookieContainer = new CookieContainer();
        getRequest.CookieContainer.Add(cookies);

        getRequest.Method = WebRequestMethods.Http.Post;
        getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
        getRequest.AllowWriteStreamBuffering = true;
        getRequest.ProtocolVersion = HttpVersion.Version11;
        getRequest.AllowAutoRedirect = true;
        getRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] byteArray = Encoding.ASCII.GetBytes(postData);
        getRequest.ContentLength = byteArray.Length;
        Stream newStream = getRequest.GetRequestStream();
        newStream.Write(byteArray, 0, byteArray.Length);
        newStream.Close();

        HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            string sourceCode = sr.ReadToEnd();
        }
        //untill here it works fine i'm logged in....

        HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
        getRequest2.CookieContainer = new CookieContainer();
        getRequest2.CookieContainer.Add(cookies);
        HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();
        cookies = getResponse2.Cookies;

        using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
        {
            string sourceCode = sr.ReadToEnd();
        }
        //here it rediects me to login page
</code>
any suggestions> what i'm doing wrong
Answer: Do not instantiate CookieContainer for each request. You need one CookieContainer over all requests. Try this:
<code>    CookieContainer cc = new CookieContainer();

    string getUrl = "somesite.com";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
    request.CookieContainer = cc;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    string getUrl2 = "somepage.login.com";
    string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");

    HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
    getRequest.CookieContainer = cc;

    getRequest.Method = WebRequestMethods.Http.Post;
    getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
    getRequest.AllowWriteStreamBuffering = true;
    getRequest.ProtocolVersion = HttpVersion.Version11;
    getRequest.AllowAutoRedirect = true;
    getRequest.ContentType = "application/x-www-form-urlencoded";

    byte[] byteArray = Encoding.ASCII.GetBytes(postData);
    getRequest.ContentLength = byteArray.Length;
    Stream newStream = getRequest.GetRequestStream();
    newStream.Write(byteArray, 0, byteArray.Length);
    newStream.Close();

    HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
    using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
    {
        string sourceCode = sr.ReadToEnd();
    }
    //untill here it works fine i'm logged in....

    HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
    getRequest2.CookieContainer = cc;
    HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();

    using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
    {
        string sourceCode = sr.ReadToEnd();
    }
    //here it rediects me to login page
</code>
Comment: Are you sure you are logged in successfully?


Couldn't segue to another view controller from textField

Question: I want to have the pretty simple transition from the home view where the user enters the text in the textfield, then have its segue go to the next view controller. I did implement the function textFieldShouldReturn(textField: UITextField) -> Bool which tries to perform the segue, but didn't get the desired result.
Here's the part of the code
class LogInVC: UIViewController {
    @IBOutlet weak var logInLabel: UILabel!
    @IBOutlet weak var logInField: UITextField!

    override func viewDidLoad() {
        NSLog("LogIn view loaded, setting delegate")

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(_ animated: Bool) {
        NSLog("viewWillAppear: Performing possible queued updates")
        textFieldShouldReturn(textField: logInField)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let autoCheckInVC = segue.destination as?
            AutocheckInVC else {
            preconditionFailure("Wrong destination type: \(segue.destination)")
        }

        guard logInField.text != nil else {
            preconditionFailure("Text property should not be nil")
        }

    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.performSegue(withIdentifier: "AutoCheckInVC", sender: self)
        return true
    }
}

Any quick help for debugging this would be so greatly appreciated. I have tried quite much time fixing this, but I haven't found the way out!!!
Comment: What´s not working, the segue or passing the data from your textField to the next textField?
Comment: the segue is not operating like I wanted to be! I'm not trying to save the passing data from the textField or something equivalently
Comment: Also, I don't know why there why the line **        textFieldShouldReturn(textField: logInField)
** complains about "result of call to this method is unused".
Comment: is `prepare(for segue: sender: )` getting called? You would also better call `super.viewDidAppear()`. Also, you have to make `LoginVC` conform to `UITextFieldDelegate` and in `viewDidLoad` set `logInField.delegate = self`. Otherwise the function won't be called on your textField return action
Answer: You have a few errors in your code:

To be able to call textFieldShouldReturn you need to inherit from UITextFieldDelegate and set the delegate of your textField, logInField.delegate = self
Don´t call textFieldShouldReturn from viewDidAppear
Use the latest syntax for the method textFieldShouldReturn
You got the warning result of call to this method is unused because it was never called since you never had the delegates

Try this code instead of yours:
class LogInVC: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var logInLabel: UILabel!
    @IBOutlet weak var logInField: UITextField!

    override func viewDidLoad() {
        NSLog("LogIn view loaded, setting delegate")

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        logInField.delegate = self
    }

    override func viewDidAppear(_ animated: Bool) {
        NSLog("viewWillAppear: Performing possible queued updates")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let autoCheckInVC = segue.destination as?
            ViewController else {
                preconditionFailure("Wrong destination type: \(segue.destination)")
        }

        guard logInField.text != nil else {
            preconditionFailure("Text property should not be nil")
        }

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.performSegue(withIdentifier: "AutoCheckInVC", sender: self)
        return true
    }
}

Comment: Thank you for the great explanation and for pointing out the importance of requiring to import the delegate. Also, I don't think I need the function `prepare(for segue: UIStoryboardSegue, sender: Any?)  `, since the segue is already performed inside the function `textFieldShouldReturn`.
Comment: @Goldie np glad to help you. Good luck with your project.
Comment: actually, I'm doing the whole test again for this one, then encountering this problem: this segue actually transition `LogInVC` to 'AutoCheckInVC` twice than it's supposed to be do it once for all. I inspect that there's something wrong inside this func `textFieldShouldReturn()`, especially when calling `self.performSegue(withIdentifier: "AutoCheckInVC", sender: self)`. Any suggestion for the fix since it's crucial?


Create file for download without saving on server with C#

Question: Here my code.
Can I do that without physical saving on the server?
Thank you!!
StringBuilder text = new StringBuilder();
string sFileName = "file.txt";

using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("docs\\" + sFileName), false, Encoding.ASCII))
{
    SW.WriteLine("test");
    SW.Close();
}

System.IO.FileStream fs = null;
fs = System.IO.File.Open(Server.MapPath("docs\\" + sFileName), System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + sFileName);
Response.ContentType = "text/plain";
Response.BinaryWrite(btFile);
Response.End();

Comment: Would writing to a MemoryStream instead of a filesteam work?
Comment: You have a sample for me? Thanks!
Answer: var result = new HttpResponseMessage(HttpStatusCode.OK)
             {
                 Content = new ByteArrayContent(content)
             };

//a text file is actually an octet-stream (pdf, etc)
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
//we used attachment to force download
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                           {
                                               FileName = "tets.txt"
                                           };

Where content is byte[] containing data You want put in file
Comment: Thank you. but "HttpResponseMessage " is class of .Net4.5 and I using 3.5... :(
Comment: @inon, You can use Response class,from .net 3.5. Just instead of setting Content use Response.BinaryWrite(content)


How can I disable the Palpatine 'Where've You Been?!' screen?

Question: When I launch the Tiny Death Star game, it always shows Palpatine in a chair, saying how much I have made while not playing the game.

How can I disable this screen so it immediately shows my Tiny Death Star first?
Answer: Although you can't disable the screen, you can skip it quickly. The continue button doesn't appear for a second or two, but even before it appears you can tap that spot on the screen to immediately dismiss it.
Comment: COOL! Didn't notice that. Thank you so much!
Comment: This deserves the green checkmark! The other answer doesn't provide a solution (not that I don't like the other answer, this one is just more helpful).
Answer: In my opinion, you can't.
I know it's annoying and frankly the whole animation is way too long without the option to skip it... But I've been looking all over the game myself and didn't find any disable option.
The game came out like 5 days ago, so we can hope that Nimblebit includes this issue in one of their updates. There's stil a lot of bugs, so I'm expecting an update very soon :-)


OnKeyPress event on itemtpl in sencha touch

Question: I am new to sencha.The onkeypress event of a text box not seems to be firing when it used in itemtpl.This is my code:
 itemTpl: new Ext.XTemplate('<tpl>

<input  type="text" onkeypress="{[this.myFunction()]}"

<tpl>',
 {
   myFunction: function(itemKey)
{
console.log('myFunction');
 }
}

The console logs 'myFunction' when the list is loading.When a key is pressed the key press event is not firing.My expectation to trigger my function on pressing the key from keyboard.Please help..I have been looking for a solution long time.
Comment: It's not firing because `this` in `{[this.myFunction()]}` in its context refers to the global object and not to `itemTpl`.
Comment: Thanks for your reply.Actually I need to pass a store value from itemtpl to the function.For that i asked this question.When i wrote the function in the controller the value getting is undefined.
Here is the code

onkeypress='myFunction(values.itemkey)'
Comment: Go with the anser from kevhender and pass a argument to the function.
Answer: Lorenz is right, this does not refer to the itemTpl when the text field is modified.  Change the handler to call a global function, perhaps something in a controller:
onkeypress="MyApp.app.getController(\'MyController\').myFunction()"

MyController.js:
Ext.define('MyApp.controller.MyController', {
    extend: 'Ext.app.Controller',
    //other config here

    myFunction: function() {
         //do something here
    }
});

Update (based on your comments elsewhere):
To pass arguments, just use the normal notation for a store value in an XTemplate.  Also make sure to surround the argument with quotes, if it is not a number/boolean:
itemTpl: new Ext.XTemplate(
    '<tpl>

',
        '',
            '
',
                '<input  type="text" onkeypress="MyApp.app.getController(\'MyController\').myFunction(\'{myStoreValue}\')">',
            '
',
        '	',
    '

<tpl>'
)

Answer: change your Ext.XTemplate code like that:
itemTpl: new Ext.XTemplate("<tpl>

<input  type='text' onkeypress='myFunction(this)'

<tpl>")

that Function define in index.html:

Comment: Thanks for your reply.Actually I need to pass a store value from itemtpl to the function.For that i asked this question.When i wrote the function in the controller the value getting is undefined.
Here is the code

onkeypress='myFunction(values.itemkey)'
Answer: itemTpl: new Ext.XTemplate('<tpl>

<input  style="color:green;display:block;width:50px;text-align:center;" type="text" pattern="\d*" id="{ItemKey}" onkeyup="myapp.app.getController(\'myappController\').TextboxKeyUp(this)" onfocus="myapp.app.getController(\'myappController\').TextFocus(this)" >

<tpl>',


Show that if $f''(0)$ exists and $f(0)=f'(0)=0$, then $\sum f(\frac1n)$ converges

Question: I need help with this problem:
Let $f$ be a continous function over an interval that contains $0$. Let $a_n = f(\frac 1 n)$ (for n large enough).

Show that if $f''(0)$ exists and $f(0)=f'(0)=0$, then $\sum_{n=1}^\infty \ a_n$ converges.

I've already shown  that if $\sum_{n=1}^\infty \ a_n$ converges, then $f(0)=0$ and that if $f'(0)$ exists and $\sum_{n=1}^\infty \ a_n$ converges, then $f'(0)=0$.
How do I show this one?
Answer: We can use comparison test based on the following fact
$$
\lim_{x\to 0} \frac{f(x)}{x^2}=\lim_{x\to 0}\frac{f'(x)}{2x}=\frac{f''(0)}{2}
$$ where L'Hopital's rule is used in the first equation. Thus for all sufficiently large $n\ge N$,
$$
n^2|a_n| = n^2\left|f\left(\frac1n\right)\right|\le |f''(0)|
$$ hence
$$
\sum_{n\ge 1}|a_n| \le \sum_{n=1}^{N-1} |a_n|+\sum_{n\ge N} \frac{|f''(0)|}{n^2}<\infty.
$$ The series converges absolutely, which implies that the series converges.
Comment: Why did you compare it to $x^2$?
Comment: @davidllerenav It is a natural choice in view of the Taylor-Mclaurin expansion $f(x) = f(0)+f'(0)x +\frac{f''(0)}2 x^2 +\cdots \cong \frac{f''(0)}2 x^2$. Also, $2$ is the first exponent $r\in \Bbb N$ such that $\sum_{n\ge 1} \frac1{n^r}<\infty$. (Thus we find that $\sum_{n\ge 1}f(1/n)\cong \sum_{n\ge 1} \frac{f'(0)}{n}$ does not converge if $f'(0)\ne 0$.)
Comment: Ok, I think I got it. Can't I also do it by the limit comparison? Because I already proved that if $f'(0)$ exists and $\sum_{n=1}^\infty \ a_n$ converges then $f'(0)=0$. I did it by using the derivative definition and supposing that $f'(0)$ isn't 0, ending up with $\lim_n\to\infty nf(\frac 1 n)=t$. Then by the limit comparison test, I reached a contradiction, thus $f'(0)=0$. Can't I do it that way instead?
Comment: @davidllerenav Yes, you can also do it by limit comparison test. Indeed, what I wrote in my answer can be viewed as a logic behind applying limit comparison test.
Comment: So if I just write the same thing but with $f''(0)$ and show that $f''(0)=0$, then $\sum_{n=1}^\infty \ a_n$ must converge?
Comment: @davidllerenav Yes, it's right.
Comment: Thanks, I thought that I still needed to prove that the series converges. Since I only know that the derivatives at 0 are 0 and that $\lim_{n\to\infty} a_n = 0$ and that means that it either converges or diverges. But I don't have to, right?
Answer: By Taylor's Formula with remainder $|f(x)| \leq  cx^{2}$ for some constant $C$ for $x$ in a neighborhoodod $0$. Hence $\sum f(\frac 1 n)$ is dominated by a constant times $\sum \frac 1 {n^{2}}$.
Comment: Why is the remainder $cx^2$? Is there another way of doing it?
Comment: $\frac {f'(x)|} {|x|}=\frac {|f'(x)-f'(0)|} {|x|}  \to f''(0)$. From this it follows that $|f'(x)| <(1+|f''(0)|) |x|$ if $|x|$ is sufficiently small. Now $|f(x))=|f(x)-f(0)|=|x||f'\zeta)|$ for some $\zeta$ between $0$ and $x$. Is it clear now that $|f(x)| \leq Mx^{2}$ for some $M$, for $|x|$ is sufficiently small?
Answer: As $f''(0)$ exists, $f'(0)$ is can be linearly approximated:
$$ f'(h) = m\cdot h+ r(h)$$
With some function $r$ with $\frac {r(h)} h\to 0$ for $h\to 0 $. Therefore we can find an interval $U:=[-a,a]$ so that $ r(h) \le m\cdot h$, and by that:
$$x\in U\implies f'(x) \le 2 m\cdot x
$$
From this follows $f(x) \le mx^2$ per integration for $x\in U$, and thus the sum converges
(as for some $N$ the tail of the sum, $\sum_{i=N}^\infty f(1/i)$, is completely in $U$ for all $i$ it assumes, and we know that $\sum_{i=0}^\infty \frac 1 {x^2}$ converges).