text:
Q: Saving a process ID when detaching a command in Bash When I detach command:
$ command &

The result is a printout to STDOUT:
[1] < PID >

I would like to monitor this PID. However, I cannot write this output anywhere but STDOUT! How can I redirect this to a file or a variable?
I have tried:
$ command 1> ./temp.txt &

But this still finds its way to STDOUT!
Thanks in advance for the help!

A: $! should contain the PID of the last background process. Something like...
$ command &
$ echo $! > temp.txt

Should give you a file named temp.txt with the PID in it.
Or on one line...
$ command & echo $! > temp.txt


text:
Q: ModelBase, instance, iteration, and order_by There are several different issues here but they are conflated.
I know there is a difference between the class and the instance, but I can't seem to figure out how to access the latter instead of the former. In the Polls Tutorial 1, they do q=Question(question_text="What's up?") and then do various things with that. But that's easy. At that point, there is only 1 Question object. Surely I'm not supposed to make variables for every single row in my table, am I? There has to be a better way, but I can't find it. For example:
for a in Articles:
    print a.sections_set.order_by('id')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ModelBase' object is not iterable

And
for a in Articles():
    print a.sections_set.order_by('id')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'Articles' object is not iterable

I'm getting a LOT of type errors like this, not all of them having 'iterable'. I saw the Loop Like A Native video, so I tried:
def __iter__(self):
    for a in Articles:
        print a.sections_set.order_by('id')
__iter__(Articles)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 2, in __iter__
TypeError: 'ModelBase' object is not iterable

My ultimate use case here is simply to get the sections to display in order. Currently they show up under their respective article, which is correct*, but in reverse order, which I also can't seem to fix. I put
Sections.objects.order_by('id')

In my view
And I put
class meta:
    ordering = ['id']

on my Sections model. Nothing works.
(*) I also put
Articles.objects.order_by('id')

In the same view, and that almost worked. It did put the Articles in order, except Article VI comes between Article I and Article II. I went through them all, one at a time, and found that
Articles.objects.get(name='Article I')
<Articles: Article I>

A1 = Articles.objects.get(name='Article I')
A1.id
3

Articles.objects.get(name='Article II')
<Articles: Article II>

A2=Articles.objects.get(name='Article II')
A2.id
13

(I also don't get how Article II jumped all the way to id=13 since I put these in at the same time and in order.)
A6=Articles.objects.get(name='Article VI')
A6.id
17

Last time I checked, 13 was before 17. Does Python/Django have a problem with Roman numerals? If so, then why are all the rest of them now in the right order?
And here's the killer: my template has no issue at all with the iteration based on the same view code:
{% for a in A %}

{{ a.name }} {{ a.popular_name }}

    {% for section in a.sections_set.all %}

{{ section.name }} {{ section.popular_name }}

    {% endfor %}
{% endfor %}

This code works with no issues other than the ones I described above. But this code
{% for a in A %}

{{ a.name }} {{ a.popular_name }}

        {% for section in a.sections_set.order_by('id') %}

{{ section.name }} {{ section.popular_name }}

    {% endfor %}
{% endfor %}

throws a template syntax error:
Could not parse the remainder: '('id')' from 'a.sections_set.order_by('id')'

Finally, in polls tutorial 3, when they introduce render, they change the code with order_by in it without explanation, from
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]

to
def index(request):
    latest_question_list = Question.objects.all().order_by('-pub_date')[:5]

It would help me understand how to use it if they would a) be consistent and b) explain changes like this.

A: The second part of your question appears to fully answer the first part: to iterate through all the articles, you use the objects manager, ie Article.objects.all() to return them all, Article.objects.order_by('whatever') to modify the ordering, or Article.objects.filter(fieldname=whatever) to query on a certain field value.
For the second part, Django, of course, doesn't know anything at all about Roman numerals: the fact that some of them are in order is a coincidence. And you shouldn't rely on the primary key - id - for ordering, either: if you delete and recreate an item, you will get a higher id, since databases generally do not reuse ids. You should add a specific order field on your model, and order by that field.
Finally, the template language simply does not permit function calls with parameters, which is why you get that error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing two VectorDrawables fails in Kaspresso - Android I'm trying to use Kaspresso for tests and I'm checking whether a view has a certain drawable with the method:
withId<KImageView>(R.id.criticalErrorImage) {
    hasDrawable(R.drawable.error_graphic)
}

With PNG works really well, while comparing the image stored in the imageView and restored and the VectorDrawable fails.
The file where the check is made is this one.
In particular this part of code:
            var expectedDrawable: Drawable? = drawable ?: getResourceDrawable(resId)?.mutate()

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
                expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tintColorId?.let { tintColorId ->
                    val tintColor = getResourceColor(tintColorId)
                    expectedDrawable?.apply {
                        setTintList(ColorStateList.valueOf(tintColor))
                        setTintMode(PorterDuff.Mode.SRC_IN)
                    }
                }
            }

            if (expectedDrawable == null) {
                return false
            }

            val convertDrawable = (imageView as ImageView).drawable.mutate()
            val bitmap = toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()

            val otherBitmap = toBitmap?.invoke(expectedDrawable) ?: expectedDrawable.toBitmap()

The funny part is that it works if I'm setting the image through databinding, while it doesn't work if I set it in all other ways. Cannot understand why.
I've created a POC here: https://github.com/filnik/proof_of_concept
In particular, here is the test: https://github.com/filnik/proof_of_concept/blob/master/app/src/androidTest/java/com/neato/test/POCInstrumentationTest.kt
While here I dynamically set the image:
https://github.com/filnik/proof_of_concept/blob/master/app/src/main/java/com/neato/test/FirstFragment.kt

A: The issue was because actually the image is scaled. So the scaled image is different from the original one.
To avoid this issue I've used this "altered" KImageView:
package your_package

import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.DrawableCompat
import androidx.test.espresso.DataInteraction
import androidx.test.espresso.assertion.ViewAssertions
import com.agoda.kakao.common.assertions.BaseAssertions
import com.agoda.kakao.common.builders.ViewBuilder
import com.agoda.kakao.common.utilities.getResourceColor
import com.agoda.kakao.common.utilities.getResourceDrawable
import com.agoda.kakao.common.views.KBaseView
import com.agoda.kakao.image.KImageView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher

class KImageView2 : KBaseView<KImageView>, ImageViewAssertions2 {
    constructor(function: ViewBuilder.() -> Unit) : super(function)
    constructor(parent: Matcher<View>, function: ViewBuilder.() -> Unit) : super(parent, function)
    constructor(parent: DataInteraction, function: ViewBuilder.() -> Unit) : super(parent, function)
}

interface ImageViewAssertions2 : BaseAssertions {
    /**
     * Checks if the view displays given drawable
     *
     * @param resId Drawable resource to be matched
     * @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
     */
    fun hasDrawable(@DrawableRes resId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) {
        view.check(ViewAssertions.matches(DrawableMatcher2(resId = resId, toBitmap = toBitmap)))
    }
}

class DrawableMatcher2(
    @DrawableRes private val resId: Int = -1,
    @ColorRes private val tintColorId: Int? = null,
    private val toBitmap: ((drawable: Drawable) -> Bitmap)? = null
) : TypeSafeMatcher<View>(View::class.java) {

    override fun describeTo(desc: Description) {
        desc.appendText("with drawable id $resId or provided instance")
    }

    override fun matchesSafely(view: View?): Boolean {
        if (view !is ImageView) {
            return false
        }

        if (resId < 0) {
            return view.drawable == null
        }
        val bitmap = extractFromImageView(view)
        view.setImageResource(resId)
        val otherBitmap = extractFromImageView(view)

        return bitmap?.sameAs(otherBitmap) ?: false
    }

    private fun extractFromImageView(view: View?): Bitmap? {
        return view?.let { imageView ->
            var expectedDrawable: Drawable? = getResourceDrawable(resId)?.mutate()

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
                expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tintColorId?.let { tintColorId ->
                    val tintColor = getResourceColor(tintColorId)
                    expectedDrawable?.apply {
                        setTintList(ColorStateList.valueOf(tintColor))
                        setTintMode(PorterDuff.Mode.SRC_IN)
                    }
                }
            }

            if (expectedDrawable == null) {
                return null
            }

            val convertDrawable = (imageView as ImageView).drawable.mutate()
            toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()
        }
    }
}

internal fun Drawable.toBitmap(): Bitmap {
    if (this is BitmapDrawable && this.bitmap != null) {
        return this.bitmap
    }

    if (this is StateListDrawable && this.getCurrent() is BitmapDrawable) {
        val bitmapDrawable = this.getCurrent() as BitmapDrawable
        if (bitmapDrawable.bitmap != null) {
            return bitmapDrawable.bitmap
        }
    }

    val bitmap = if (this.intrinsicWidth <= 0 || this.intrinsicHeight <= 0) {
        Bitmap.createBitmap(
            1,
            1,
            Bitmap.Config.ARGB_8888
        ) // Single color bitmap will be created of 1x1 pixel
    } else {
        Bitmap.createBitmap(this.intrinsicWidth, this.intrinsicHeight, Bitmap.Config.ARGB_8888)
    }

    val canvas = Canvas(bitmap)
    this.setBounds(0, 0, canvas.width, canvas.height)
    this.draw(canvas)
    return bitmap
}

Not the cleanest solution possible, but it works. If anyone can provide a better solution would be great :-)


text:
Q: Filter list based on another query result with JMESPath Having an object such as the one below:
{
  "pick": "a",
  "elements": [
    {"id": "a", "label": "First"},
    {"id": "b", "label": "Second"}
  ]
}

how can I retrieve the item in the elements list where id is equal to the value of pick?
I was trying something like:
elements[?id == pick]

But, apparently, the expression at the right of the comparator is evaluated relative to the object being tested against my filter expression.
How can I achieve what I want? If this is not possible out of the box, do you have any suggestion of where I should start extending JMESPath? Thank you!

A: Unfortunately, JMESPath does not allow to reference the parent element.
To circumvent this limitation, in this simple case, you can:

*

*read the pick attribute in the first query,

*create the second query using the value just read,

*read the wanted content in the second query.

Actually, thanks to f-strings, two last steps can be performed in
a single instruction, so the code can be:
pck = jmespath.search('pick', dct)
jmespath.search(f'elements[?id == `{pck}`]', dct)

where dct is the source JSON object.
A more complex case
If you have a more complex case (e.g. many such elements, with different pick
values in each case), you should use another tool.
One quite interesting option is to make use of Pandas package.
Assume that your source dictionary contains:
dct = {
  "x1": {
    "pick": "a",
    "elements": [
      {"id": "a",    "label": "First_a"},
      {"id": "b",    "label": "Second_a"},
      {"id": "c",    "label": "Third_a"}
    ]
  },
  "x2": {
    "pick": "b",
    "elements": [
      {"id": "a",    "label": "First_b"},
      {"id": "b",    "label": "Second_b"},
      {"id": "c",    "label": "Third_b"}
    ]
  }
}

The first thing to do is to convert dct into a Pandas DataFrame:
import pandas as pd
df = pd.DataFrame.from_dict(dct, orient='index')

The result (printed in a "shortened" form) is:
   pick                                           elements
x1    a  [{'id': 'a', 'label': 'First_a'}, {'id': 'b', ...
x2    b  [{'id': 'a', 'label': 'First_b'}, {'id': 'b', ...

Description (if you have no experience in Pandas):

*

*x1, x2, ... - the index column - values taken from first level keys
in dct.

*pick - column with (no surprise) pick elements,

*elements - column with elements (for now each cell contains the
whole list).

This shape is not very much useful, so let's explode elements column:
df = df.explode('elements')

Now df contains:
   pick                          elements
x1    a   {'id': 'a', 'label': 'First_a'}
x1    a  {'id': 'b', 'label': 'Second_a'}
x1    a   {'id': 'c', 'label': 'Third_a'}
x2    b   {'id': 'a', 'label': 'First_b'}
x2    b  {'id': 'b', 'label': 'Second_b'}
x2    b   {'id': 'c', 'label': 'Third_b'}

This shape is closer to what we need: Each source row has been broken into
a couple of rows, each with separate item from the initial list.
There is one more thing to do, i.e. create a column containing id values,
to be later compared with pick column. To do it run:
df['id'] = df.elements.apply(lambda dct: dct['id'])

Now df contains:
   pick                          elements id
x1    a   {'id': 'a', 'label': 'First_a'}  a
x1    a  {'id': 'b', 'label': 'Second_a'}  b
x1    a   {'id': 'c', 'label': 'Third_a'}  c
x2    b   {'id': 'a', 'label': 'First_b'}  a
x2    b  {'id': 'b', 'label': 'Second_b'}  b
x2    b   {'id': 'c', 'label': 'Third_b'}  c

And to get the final result you should:

*

*select rows with pick column == id,

*take only elements column (together with key column, but this detail
Pandas gives you just out of the box).

The code to do it is:
df.query('pick == id').elements

giving:
x1     {'id': 'a', 'label': 'First_a'}
x2    {'id': 'b', 'label': 'Second_b'}

In the Pandas parlance it is a Series (let's say a list with each element
"labelled" with an index.
Now you can covert it to a dictionary or whatever you wish.


text:
Q: Convert hex to double with a given floating-point format in java I have a String representing a HEX value of a 64bit integer "0000000000EA6484". I need to transform it to the double value "0.9155962467" using Java. The instructions I 've been given is to format a 12.52 FP value of type int64_t (8 Bytes).
I found with some googling that the int64_t datatype in C++ is a signed integer. I have also found this post which seem to be relevant but confused me a bit.
Finally I have tried the following java code to see if I get the expected result but I get in both cases "7.5894195E-317". I am sure that either I have not understood how to solve the problem so I would appreciate some help, or that the expected output is wrong.
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) {
String hexString = "0000000000EA6484";//0.9155962467

    long longValue = Long.parseLong(hexString, 16);
    longValue = Long.parseUnsignedLong(hexString, 16);
    System.out.println(longValue);

    double doubleValue = Double.longBitsToDouble(longValue);
    System.out.println(doubleValue);

    byte[] bytes = hexStringToByteArray(hexString);
    doubleValue = ByteBuffer.wrap(bytes).getDouble();
    System.out.println(doubleValue);
}
public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}
}

A: As shown, 0000000000EA6484 represents 0.9155962467193603515625 in a Q40.24 format, not a floating-point format. This is a fixed-point format with 40 integer bits (including a sign bit) and 24 fraction bits. To convert it from the integer represented by those bits in a 64-bit integer format to the value represented by the same bits in the Q12.52 format, divide it by 224: EA648416 = 1536115610, 15361156 / 224 = 0.9155962467193603515625. In Java, dividing the integer value by 16777216 (224) should suffice.
It appears whomever told you this was a 12.52 FP format was wrong. Even if there is some endian issue, or any other byte reordering, that would not explain the shifted position of the bits with respect to a 12.52 format, since it differs by a sub-byte fraction (52 bits − 24 bits = 28 bits, which is 3½ bytes).


text:
Q: jQuery's .bind() vs. .on() I found two great articles talking about the new function .on(): jquery4u.com, elijahmanor.com.
Is there any way where the .bind() still is better to use than .on()?
For example, I have a sample code that look like this:
$("#container").click( function( e ) {} )

You can note that I just have one item retrieved by the selector and in my case, the <div> named #container already exists when my page was loaded; not added dynamically. It's important to mention that I use the latest version of jQuery: 1.7.2.
For that sample, should .on() be used instead of .bind() even if I don't use the other features provided by the .on() function?

A: If you look in the source code for $.fn.bind you will find that it's just an rewrite function for on:
function (types, data, fn) {
    return this.on(types, null, data, fn);
}

http://james.padolsey.com/jquery/#v=1.7.2&fn=$.fn.bind

A: From the jQuery documentation:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

A: These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });

However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });

The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on() function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).

A: As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.
jQuery API documentation for .bind()

A: Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.
However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

A: The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.
The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an
event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"
The .delegate is superior to .on because of the argument's order:
$(elem).delegate( ".selector", {
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
});

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.
With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:
$(elem).on({
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there
are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.


text:
Q: RESTfulness of SOA with Single Entry Point I have a service-oriented architecture with a single gateway for all client requests.  I like this because the gateway is tidy, hides all "internal" services, and acts as a dispatcher and homemade load balancer.
Because of my design, however, the client only ever knows about "one" resource.  And must send up messages that have requested operations and their parameters defined in JSON.
{
    "operation" : "Login",
    "parameters" :
    {
         "username" : "John",
         "password" : "1234"
    }
}

Should I be sad because my architecture is not RESTful?  Am I not leveraging HTTP like REST prescribes?  Please critique.

A: I don't know if "sad" is the right word, but one of the arguments in favor of REST, especially as implemented in using HTTP "properly" is that it provides to you, for free, the following (taken from Fielding's dissertation):

*

*Client-Server interaction, separating UI from data storage

*Stateless Server, improving reliability and scalability

*Client Cache, reducing some network traffic

*Uniform Interface, decoupling implementations from the services they provide

*Layered System, where each component is only concerned with those just below or just above it

*Representation Orientation, where you think in terms of resources

*HATEOAS, where your application essentially navigates links

*A constrained interface, with a small number of verbs (e.g. GET, PUT, POST, DELETE, and only about 3 others)

When you go with SOAP or another RPC solution, instead of REST, you are in theory giving up some but not all of these characteristics.  You may be giving up client cacheability and you are thinking procedurally, and you probably can't use all the safety and idempotency conditions that RESTafarians exploit to a tee.
RESTful services have become very popular and not by accident.  But does that mean you have to build RESTful services or that non-RESTful services are inherently much worse?  I don't think so.  I've done a couple RESTful SOAs for two different companies and while I prefer to SOAP (which seems bulky these days) and to home-grown APIs like yours (which, even if elegant, aren't standard), I don't diss other approaches and dismiss them as inferior.
If you are going to go with your own API, and return only 200s and 404s, and do everything with GET, then yes your API is conceptually simple and perhaps it will work fine for you.  But if you need a variety of media types, and you have persistent storage requirements containing collections that are often appended to, deleted from, created and updated, then learning modern RESTful API design will at least open up new ways of thinking for you.
Bottom line is don't feel sad nor feel like you have to go to REST because everyone else is doing it.  But the advantages are real and REST is not just hype.

A: Nope. Basically you have a home brewed SOAP style RPC using JSON instead of XML.
You might ask whether it's worth reinventing that with JSON rather than using a SOAP stack, but if you're talking to JavaScript, it might simply be easier to to use than SOAP, plus there's no burden of conforming with the SOAP standards/tool sets.
Other than that, seems fine to me.


text:
Q: Apache shows It Works instead wordpress start page I know nothing about Apache and those things... I need to make a web page, so I tried to install wordpress and it didn't work well
When I try to access localhost having wordpress installed, Apache shows me just the "It Works" page...
I don't know where to search, nor which file modify...
I'll put the whole info you need but be patient please... I'm less than a newbie
I have phpmyadmin, mysql, apache, wordpress (I'm making the page right now in wordpress) but when clicking in the home from wordpress it shows the It works page
Thank you so much...
I'll put just the apache2.conf file
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about  Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#    work with the default configuration.

# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# The directory where shm and other runtime files will be stored.
#

DefaultRuntimeDir ${APACHE_RUN_DIR}

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more     than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited   amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP    addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a    <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular  modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and  /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>

<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the    AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>

#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they  use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

A: I am not techie, so here is my newbie solution. I had two index.php files in my wordpress root, so I removed the one that existed before my wordpress installation, restarted apache2 and mysql, cleared cache in Chrome, and the problem was gone.

A: Fast solution
Maybe you rather neet to look for host files in
/etc/apache2/sites-available
/etc/apache2/sites-available/000-default.conf
Usually, it says that in default the root directory of a website is
/var/www/html
I think. You need to double check if you put your website's files there.
Another solution
Or maybe you need to make another virtual host for your site. Which is useful when you have a few domain names. To separate your sites.
Make a host file:
For example, make a host file example.com.conf (use your site name instead of example.com)
make a file
/etc/apache2/sites-available/example.com.conf
put there:
<VirtualHost *:80>
          ServerAdmin your@mail.com
          ServerName example.com
          ServerAlias www.example.com
          DocumentRoot /var/www/example.com/public_html

          ErrorLog /var/www/example.com/logs/error.log
          CustomLog /var/www/example.com/logs/acess.log combined
</VirtualHost>

Make a directory for your website:
mkdir /var/www/example.com/
mkdir /var/www/example.com/public_html

Now /var/www/example.com/public_html is a root directory of your web site
Then you need activate virtual new host and restart apache server
run commands:
a2ensite example.com
service apache2 restart

or (use sudo command in case you login not as root, which is always better):
sudo a2ensite example.com
sudo service apache2 restart

Copy your website files to /var/www/example.com/public_html/
Don't forget to give correct rights for files
for this уou can run:
chown -R www-data:www-data "/var/www/"
chmod u=rwx,g=rw,o= -R "/var/www/"
find "/var/www/" -type d -exec chmod g+x {} \;

(but be sure apache works from user www-data, in another case you need use another username instead of www-data)


text:
Q: Can I take $n(\epsilon)$ to be this value?
Prove that $\displaylines{\lim_{n\rightarrow \infty}\frac{3n+2}{2n+7}=\frac{3}{2}}$.

Let $\epsilon > 0$. Then
$\begin{aligned} \left | \frac{3n+2}{2n+7}-\frac{3}{2} \right |=\left | \frac{6n+4-6n-21}{2(2n+7)} \right |=\left | \frac{-17}{2(2n+7)}\right |=\left | \frac{-17}{2(2n+7)}\right |=\frac{17}{4n+14}&<\frac{17}{4n}<\epsilon\\ &\Rightarrow n>\frac{17}{4\epsilon} \end{aligned}$.
Take $n(\epsilon)=\left \lceil \frac{17}{4\epsilon} \right \rceil\in \mathbb{N}$. Is this correct or not?


text:
Q: How does JavaScript's lexical environment maintain variables declarations within nested block scopes? I've read a couple of more comprehensive articles on the execution context and now I am sort of confused and messed up in the head.
To keep the question as brief as possible avoiding long citations I better try to illustrate my mental model through an example focusing on details I can't get, so that you could correct me and point at the mistakes.
Here is an example:
var tomato = 'global tomato';

{
  let tomato = 'block tomato';
  console.log(tomato); // 'block tomato'
}

console.log(tomato); // 'global tomato'

So far, everything is clear. When JS engine created an execution context (global one in our case) var tomato declaration from the first line was placed into a Variable Environment while let tomato within a block scope went into a Lexical Environment. That explains how we ended up with 2 different tomatoes.
Now, let's add another tomato, like here:
var tomato = 'global tomato';

{
  let tomato = 'block tomato';

  {
    console.log(tomato); // ReferenceError: Cannot access 'tomato' before initialization
    let tomato = 'nested block tomato';
  }

  console.log(tomato); // won't reach here
}

console.log(tomato); // won't reach here

ReferenceError is no surprise. Indeed, we tried to access a variable before it's been initialized which is known as Temporal Dead Zone. And that nicely indicates that JS had already created another variable tomato within the most nested block. Also JS had been aware of this tomato being uninitialized at the moment we referenced it. Otherwise, it would have grabbed tomato from the outer scope which is equal to 'block tomato' without throwing any error. So let's fix the error and swap the lines, like this:
var tomato = 'global tomato';

{
  let tomato = 'block tomato';

  {
    let tomato = 'nested block tomato';
    console.log(tomato); // 'nested block tomato'
  }

  console.log(tomato); // 'block tomato' - still 'block tomato'. Nothing has been overwritten.
}

console.log(tomato); // 'global tomato'

What I wonder is how JavaScript manages this most nested block. Because by the time that execution reaches the line:

let tomato = 'nested block tomato';

the Lexical Environment of the execution context already contains the variable tomato which was initialized in the outer scope with the value of 'block tomato'. Assuming JS doesn't create a new execution context (with Lexical and Variable environments respectively) just for the blocks of code (that's only the case for function invocations and global script, right?) and obviously, it doesn't override variables in existing Lexical Environment with the ones having the same name but coming from the nested block scopes. As the last piece of code shows, where a brand new, independent variable was created to hold a value 'nested block tomato'.
Then the question is where exactly is this variable stored? I mean there is only one Lexical Environment for an execution context but we might create a numerous nested scopes declaring variables inside. I'm struggling to visualize where these variables would be stored and how this whole thing fit together.

A:
Assuming JS doesn't create a new execution context (with Lexical and Variable environments respectively) just for the blocks of code (that's only the case for function invocations and global script, right?)

That's an incorrect assumption.
See the specification:

A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.

The block statement creates a new lexical environment.

A: In ECMAScript, lexical scopes can be nested.

I mean there is only one Lexical Environment for an execution context but we might create a numerous nested scopes declaring variables inside.

No, there is one Lexical Environment for … well … each Lexical Environment. ("Scope" is just a different term for "Environment" after all.)
The specification does not force the implementor to implement this in any specific way. A typical way could be to have linked list of environments.


text:
Q: Counter Variable not incrementing React I have 6 cubes displayed on the page and there is a counter.
When you click on a cube, its background changes to red and the counter increases by one, but the counter does not want to increase. I always have it 1. But if you remove the setcub([...cubikinapole]) line, then the counter starts working as it should, but now the background does not change. What to do?
import "./styles.css";
import {useState} from 'react'
export default function App() {
  let [cubikinapole, setcub] = useState([
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png", style: 'none'},
    {id:2,title:2, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png" , style: 'none'},
    {id:3,title:3, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png" , style: 'none'},
    {id:4,title:4, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png" , style: 'none'},
    {id:5,title:5, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png" , style: 'none'},
    {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png" , style: 'none'},
  ])
  let [count,se] = useState(0)
  function  a(el) {
    se(count++)
    el.style = 'active'
    setcub([...cubikinapole])
    console.log(count)
  }
  return (

                          {cubikinapole.length !== 0 ?
                    cubikinapole.map((el)=>

a(el)}>

                    )
                    : console.log() }

  );
}

CSS
.active{
  background-color: red;
}

A: You can try this code. count++ increases its value after the setCount function is executed, so you should use count+1 to pass the increased value to the function. And you'd better use useEffect to monitor the count value.
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
  let [cubikinapole, setCub] = useState([
    {
      id: 1,
      title: 1,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/1.png",
      style: "none"
    },
    {
      id: 2,
      title: 2,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/2.png",
      style: "none"
    },
    {
      id: 3,
      title: 3,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/3.png",
      style: "none"
    },
    {
      id: 4,
      title: 4,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/4.png",
      style: "none"
    },
    {
      id: 5,
      title: 5,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/5.png",
      style: "none"
    },
    {
      id: 6,
      title: 6,
      img: "https://www.zonkpro.ru/zonk/assets/dice/mini/6.png",
      style: "none"
    }
  ]);

  let [count, setCount] = useState(0);

  useEffect(() => {
    console.log(count);
  }, [count]);

  function a(el) {
    setCount((prev) => prev + 1);
    el.style = "active";
    setCub([...cubikinapole]);
  }
  return (

      {cubikinapole.length !== 0
        ? cubikinapole.map((el) => (

 a(el)}>

          ))
        : console.log()}

  );
}

Live demo: https://codesandbox.io/s/amazing-haze-0zdb26?file=/src/App.js:0-1369

A: you're never supposed to change the value of a useState by the value itself, only by the setter - what you're doing where you're writing se(count++) is giving the old value of the count to se and then directly changing count by count++,
so it looks like a race condition, you can fix it by just changing it to se(count+1) and your code will run as it should

A: There are a few issues. Note: I've changed the names of some variable for clarity.

*

*You can't set your counter like that. Ideally you want to take the previous state, and then update and return that. So setCount(count++) becomes setCount(prev => prev += 1).

*ids should be unique. If you want to uniquely identify an element you can use a data attribute, and then pick up that value in the handler.

*With the id in hand in your handler you should find the object in state that where the object id matches the id of the element you clicked on, and then update that. To do that make a copy of the state first, update the object, and then set the state using the changed copy.

*It's not really clear whether it was the background of the cube you wanted to change, or the image itself so I've just left your code as-is. For the actual image to change would be slightly more difficult.

const { useState } = React;

// For clarity I'm passing in the image
// config to the component, and then setting the
// cube state with it
function Example({ config }) {

  // Initialise the states
  const [ cubes, setCubes ] = useState(config);
  const [ count, setCount ] = useState(0);

  // When an element is clicked take the
  // id from its data set. Make a copy of the state
  // and then find the index of the object that has a
  // matching id. Then update that object with the new
  // style, and set both the cube and count states
  function handleClick(e) {
    const { id } = e.currentTarget.dataset;
    const copy = [...cubes];
    const index = copy.findIndex(cube => cube.id === Number(id));
    if (index >= 0) copy[index].style = 'active';
    setCubes(copy);
    setCount(prev => prev += 1);
  }

  // I've added a count element here.
  // `map` over state adding the data attribute
  // to the div element.
  return (

Count: {count}

      {config.map(obj => {
        const { id, style, img } = obj;
        return (

        );
      })}

  );

}

const config=[{id:1,title:1,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png",style:"none"},{id:2,title:2,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png",style:"none"},{id:3,title:3,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png",style:"none"},{id:4,title:4,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png",style:"none"},{id:5,title:5,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png",style:"none"},{id:6,title:6,img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png",style:"none"}];

ReactDOM.render(
  <Example config={config} />,
  document.getElementById('react')
);
.active { background-color: red; }


text:
Q: performing search over list created by directive I am very new to AngularJs, Somehow I am now able to create a directive which can be used for binding data from controller to html.Now I want to create a functionality like a search over the list which is shown on AngularJs.
This list contains different objects.
I have created the Plunker here
HTML
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

    <diuv>
      <input type="text" placeholder="search"/>
      <input type="button" value="Search" />

Controller
   angular.module('app', []);

    angular.module('app').controller('movieDesc', function($scope) {

      $scope.movies = [{
        name: 'abc',
        desc: 'this is desc text for the movie',
        pic: 'http://png.clipart.me/graphics/thumbs/134/abstract-geometric-background-triangle-and-square-black_134053397.jpg'
      }, {
        name: 'def',
        desc: 'this is desc text for the movie def',
        pic: 'http://png.clipart.me/graphics/thumbs/201/abstract-modern-banner-background-of-geometric-shapes-abstract-geometric-form_201768245.jpg'
      }, {
        name: 'ghi',
        desc: 'this is desc text for the movie ghi',
        pic: 'http://www.cianellistudios.com/images/abstract-art/abstract-art-infinite-150.jpg'
      }]

      $scope.saveData = function(data) {
        console.log(data);
      }

    });

My Directive
angular.module('app').directive('movies', function() {
  return {
    templateUrl: "movieCard.html",
    restrict: "EA",
    scope: {
      movies: '=',
      save: '&'
    },
    link: function(scope, element, attrs) {
       console.log("link function called");
      element.addClass('moviesBox');
      var clickedFn = function() {
        alert("clicked");
      };
      console.log("console", element[0].querySelector('.btnSelect'));
      var $this = element[0].querySelector('.btnSelect');
      $($this).click(function() {
        alert(scope.movies.desc)
      })
    }
  }
})

movieCard.html

    Name: {{movies.name}}

    Description: {{movies.desc}}

    <input type="text" ng-model="movies.someText">

    <input class="btnSelect" type="button" value="Desc" ng-click="clickedFn()">

    <input class="btnSelect" type="button" value="Save Data" ng-click="save({movie: movies})">

There is a search button in HTML, so on that I want to perform that search option, where I can type and get that list only which I search

A: You can achive this with 2 options.
1. Use smth like this.
<input type="button" value="Search" data-ng-click=filter(key) data-ng-model="key" />

$scope.filter = function(key){
$scope.filteredMovies = $scope.movies.filter(function filterByName(movie){
   return movie.name.indexOf(key) !==-1;
 });
};

When you click, this code will filter you list and only filtered itmes will be presente on filteredMovies .

*Same behavior you can achive using angular filter from there:
https://docs.angularjs.org/api/ng/filter/filter

Usage
  In HTML Template Binding
  {{ filter_expression | filter : expression : comparator}}
  In JavaScript
  $filter('filter')(array, expression, comparator)

angular.module('app').filter('superFilter', function(){
return function(list, key){
if (!key) {
return list;

}
return list.filter(function filterByName(movie) {
return movie.name.indexOf(key) !== -1;
});
}

});

But be care with filter :)


text:
Q: how to add current login user to welcome.java i Have this Login Page so i need the cuurent login user to get display in welcome.java
please and i need the curent user to be display in welcome .java file
public class Login extends Activity implements OnClickListener{

    private EditText user, pass;
    private Button mSubmit, mRegister;
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL =webservice/login.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // Look up the AdView as a resource and load a request.
        AdView ad = (AdView) findViewById(R.id.ad);
        ad.loadAd(new AdRequest());

        // setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        // setup buttons
        mSubmit = (Button) findViewById(R.id.login);
        mRegister = (Button) findViewById(R.id.register);

        // register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    // save user data
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(Login.this);
                    Editor edit = sp.edit();
                    edit.putString("username", username);
                    edit.commit();

                    Intent i = new Intent(Login.this, ReadComments.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

A: Not sure what you exactly mean. Do you want to display the last successful user to the login prompt?
It looks like it is saved in the shared preferences with the key "user". (See code following the "json success tag" comment).
// setup input fields
user = (EditText) findViewById(R.id.username);

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sp.getString("user", "");
user.setText(userName);

pass = (EditText) findViewById(R.id.password);


text:
Q: RSA Enabled Simple Java Chat - Not PKCS#1 block type 2 or Zero padding I created a simple java chat application . Below is the follow
Run ChatClient.java - Dialog box is shown where user enters username. Then private key and public key are generated and stored in C:/username/publickey,C:/username/privatekey.
Above step repeats when we run ChatClient.java again.
Then user1 sends message to User2 in encrypted form using User2 public key (Which is working fine)(after encryption , message is stored in text file) then User2 clicks decrypt button which decrypts the text (reads the encrypted text from file) using User 2 private key then display in textarea.
When I trying to decrypt I am getting "Not PKCS#1 block type 2 or Zero padding" exception
public static byte[] encrypt(String text, PublicKey key) throws {
    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance(ALGORITHM);
    // encrypt the plain text using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(text.getBytes("UTF8"));
    return org.apache.commons.codec.binary.Base64.encodeBase64(cipherText);
}

public static String decrypt(String text, PrivateKey key) throws  {
    byte[] dectyptedText = null;

      // get an RSA cipher object and print the provider
      final Cipher cipher = Cipher.getInstance(ALGORITHM);

      // decrypt the text using the private key
     cipher.init(Cipher.DECRYPT_MODE, key);
     byte[] byteCipherText =org.apache.commons.codec.binary.Base64.decodeBase64(text):
     byte[] cipherData = cipher.doFinal(byteCipherText);
     return new String(dectyptedText);
}

private void btnDecryptActionPerformed(ActionEvent evt) throws  {
    String name11 = this.getTitle();
    String test90 = null;
    String PRIVATE_KEY_FILE = "C:/keys/"+name11+"/private.key";
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader("cipher.txt"));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        while(in.ready())
        {
            String stest= in.readLine();
            test90 = stest;

        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    ObjectInputStream inputStream = null;
    try {
    inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    PrivateKey privateKey = null;
    try {
        privateKey = (PrivateKey) inputStream.readObject();
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
    inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        PrivateKey privatekey = (PrivateKey) inputStream.readObject();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String plainText;

//  byte[] test100 = test90.getBytes();
//  out.println(test100);
    plainText = decrypt(test90, privateKey); (Getting Error Here)
    decryptText.append(plainText);
}

A: The highlighted code below means test90 only contains the last line in the cipher.txt file. Does cipher.txt contain 1 line only? If you want to read in everything, you need to concatenate each line as you read it in.
while(in.ready())
{
    String stest= in.readLine();
    test90 = stest;
}

It is also a good idea to System.out the variable test90 in the decrypt method to be sure that you're getting the expected base64 data to be decrypted.


text:
Q: Resolve a domain name to CNAME alias locally using dnsmasq I'd like to resolve a domain name somedomain.com to a CNAME (AWS load balancer, e.g. some-balancer-1213231237.ap-southeast-2.elb.amazonaws.com), but only locally.
What I mean to achieve is that whenever I try to visit somedomain.com, I want to be served by the above mentioned load-balancer - this should only be limited to my own computer.
It's not possible to achieve this by editing /etc/hosts as in there only A records (IP addresses) can be mapped. I read somewhere that dnsmasq would be the most robust solution to achieve this. However, the documentation is very unclear about how this can be achieve. I'd appreciate your advice and perhaps a piece of config with an example. Thanks!

A: You can add the following to your configuration file in dnsmasq:
cname=somedomain.com,some-balancer-1213231237.ap-southeast-2.elb.amazonaws.com

as specified in the man page:
--cname=<cname>,[<cname>,]<target>[,<TTL>]

Return a CNAME record which indicates that <cname> is really <target>. There are significant limitations on the target; it must be a DNS name which is known to dnsmasq from /etc/hosts (or additional hosts files), from DHCP, from --interface-name or from another --cname. If the target does not satisfy this criteria, the whole cname is ignored. The cname must be unique, but it is permissible to have more than one cname pointing to the same target. Indeed it's possible to declare multiple cnames to a target in a single line, like so: --cname=cname1,cname2,target
If the time-to-live is given, it overrides the default, which is zero or the value of --local-ttl. The value is a positive integer and gives the time-to-live in seconds.

As the man page specifies, you will have to define the target in your /etc/hosts file though:
203.0.113.80   some-balancer-1213231237.ap-southeast-2.elb.amazonaws.com

So I'm not sure this would be very useful to you.

A: You have to keep in mind, that the to be resolved hostname has to be added to the /etc/hosts file too !
E.g.: the right part in the hosts file:
10.1.1.1 ip1.example.com

dnsmasq.conf entry:
cname=cname.example.com,ip1.example.com
Test:
ping  cname.example.com
PING ip1.example.com (10.1.1.1) 56(84) bytes of data.
64 bytes from ip1.example.com (10.1.1.1): icmp_seq=1 ttl=64 time=0.063 ms

That's all it takes ;-)


text:
Q: How to wait JsDialog response? I'm trying to use the JQuery dialog and actually I've no problem in this. Now I want replace my alert confirmation with a JQuery Dialog Confirmation, the problem's that when I show the JQuery Dialog the code continue to work and doesn't wait the JQuery Dialog response. What I'm trying so is create a mode to wait the JQuery dialog result and after it continue the code execution.

Function fired after button press
function start(title, message, messageButtons)
{
  //messageButtons => contains the buttons with the function see bottom

    if(confirm)
    {
        jQuery("body").append(
        "
" +
        "
" + message + "
" +
        "
"
        );

        jQuery("#message_box").dialog({
            autoOpen: false,
            modal: true,
            resize: "auto",
            width: 400,
            height: "auto",
            resizable: false,
            buttons: messageButtons,
            closeOnEscape: true
            });
    }
    else
    {
        console.log("No response");
    }
}

Message buttons structure:
  var messageButtons = {};
  messageButtons['OK'] = function()
  {
       confirm = true;
  };

  messageButtons[EALang['cancel']] = function()
  {
       confirm = false;
       $('#message_box').dialog('close');
  };

The JQuery Dialog is displayed correctly but in the browser console I get No response before the user select an answer from the JQuery Dialog. So the main problem is stop the js code after the JQuery Dialog appear, wait the user selection, and later continue the code above. How you can see I valorize the confirm variable in the button function, this function are called when the user press the appropriate button and this working fine.

A: You should try to use a callback to execute whatever code you want at a certain point in js.Dialog, it seems to be quite good with callbacks, here is some info about that: http://code.kolmio.com/jsdialog/Docs/Callbacks.html
Also, a way of saving a piece of code to be executed later is to set a time out: http://www.w3schools.com/jsref/met_win_settimeout.asp


text:
Q: Sybase sysobjects - what's the equivalent table in DB2? I have a simple sql in Sybase,
select user_name(uid), type, name
  from sysobjects

I'm wondering that what is the equivalent sql in DB2?

A: I don't think there is a single view that shows all objects.
For tables that would be SYSCAT.TABLES
All available views are listed in the manual: Catalog Views


text:
Q: Swift 3 unresolved identifier CGColorGetComponents How can I refactor this code in Swift 3?:
    extension UIColor {
        var hexString: String {
            // Produces "Use of unresolved identifier 'CGColorGetComponents'"
            let components = CGColorGetComponents(self.cgColor)
            ....
        }
    }

A: var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
self.getRed(&r, green: &g, blue: &b:, alpha: &a)
...


text:
Q: Signed APK cannot be installed on a device Cannot install signed release APK on my phone and cannot upload it on Play Store.
I created a signed release APK with V1 and V2 JAR signatures check boxes checked. When I try to put the APK on my phone and install it gives:

App Not Installed

I double checked and I don't have the app installed with the same package name; I removed it for all users.
After no luck, I thought of uploading it to Play Store using Test Draft, but
as soon as I upload the same signed release APK, it gives me the error:

No JAR Signature.

I'm using Android Studio Version 3.3 and I'm dealing with a Play Store Jar Signature error (double checked V1 and V2 checkboxes and both are checked).
Play Store error:

Generating release APK with Android 3.3 (latest as of now) produces same error on APK installation and during the Play Store upload.
Generating signed release APK with my other system which have Android version 3.1 works fine (APK installation and Play Store upload without any errors).
It may be a fix, but still the source of the error is not found.

A: It looks like your APK is not signed. You can verify this locally by running the following command:
jarsigner -verify app.apk

If the app is signed (with v1 signing), it should output jar verified.
Are you sure that you are uploading the APK that is signed and not an old build or an intermediate artifact?

A: Try using third Party Software for Signing. That fixed it for me I was having the same issue and nothing else helped. FYI you can still use the key you generated in Android Studio.

A: You have to Check many factors on this issue.

*

*add this line in your manifest.  'android:testOnly="false"'

*add this line in your build.gradle app 'multiDexEnabled true'

After this all you have to open setting in your mobile allow from unknown source and also allow from source like from files or whatsapp from where you want to install this application.
check image for more understandings
enter image description here


text:
Q: Android - A class object that belong to MainActivity not match with the sub-activity when startActivity is done First of all, I'm new to the Android environment, so excuse me if I say something without sense.
Current Situation
I'm doing an application that have two activities:
MainActivity and GraphActivity.
Also I have a class BLEConnection that I want it to know both activities.
The MainActivity have only one button.
onClick() of the button:

GraphActivity graph_activity = new GraphActivity();
BLEConnection radino_right = new BLEConnection(mainThread, graph_activity);
btnConnect.setText("Connecting");

The class BLEConnection has a BluetoothGattCallback() object, and when it detects onConnectionStateChange() it calls a thread running in MainActivity.
If the Bluetooth device is connected, the String connect_status = "Connected", then this thread creates an Intent and do the startActivity().
Thread running in MainActivity:

Thread mainThread = new Thread(new Runnable() {
    @Override
    public void run() {
        if(connect_status.equals("Connected")){
            Intent nextScreen = new Intent(getApplicationContext(), ((Object) graph_activity).getClass());
            //startActivityForResult() instead of startActivity() because I want to finish() it from the MainActivity if the connection with the device is closed.
            startActivityForResult(nextScreen,1);
        }
        else{
            if(nextScreen != null){
                finishActivity(1);
            }
        }
    }
});

Troubleshoting
The troubleshooting that I am having is that I noticed that the object graph_activity that belong to MainActivity and that I passed to BLEConnection does not match with the real GraphActivity that is launched with the startActivity() method.
Does anyone know how can I solve this?
I think that if I do a "new" when I create the activity object, it generates a new thread GraphActivity, and when I call startActivity() it generates another thread of the same class, but not linked with the previously object that I created before.
I don't know how to solve that.

A: Ok, I think you should refactor a bit. It is true, you create 2 different instances of graphactivity. you don't need the first one.
You could use a singleton with listeners like this:
1 Make BLEConnection a Singleton:
public class BLEConnection {
    private static BLEConnection singletonInstance = new BLEConnection();

    private BLEConnection() {} //constructor cannot be called from outside

    public static BLEConnection getInstance() {
        return singletonInstance;
    }

    (... your Stuff here)
}

Now BLEConnection will stay in Memory and you always get the same Instance if you call
BLEConnection bleconnection = BLEConnection.getInstance();

from anywhere in your app.
2 Create a listener interface:
public interface BLEConnectionListener {
    void statusUpdated(String newStatus);
    //you can write more functions here. Every activity from step 3 has to implement them
}

3 Make your Activities implement the interface:
public class MainActivity implements BLEConnectionListener {
    public void statusUpdated(String newStatus) {
        //do your thread thing here if you want to...
    }
}

public class GraphActivity implements BLEConnectionListener {
    public void statusUpdated(String newStatus) {
        //do graph stuff here
    }
}

4 Inform BLEConnection about the interfaces:
MainActivity & GraphActivity in onResume / onPause:
public void onResume() {
    // bla
    BLEConnection bleConnection = BLEConnection.getInstance();
    bleConnection.addListener(this);
}

public void onPause() {
    // bla
    BLEConnection bleConnection = BLEConnection.getInstance();
    bleConnection.removeListener(this);
}

Update BLEConnection
public class BLEConnection {

    private ArrayList<BLEConnectionListener> listeners = new ArrayList<BLEConnectionListener>();

    public void addListener(BLEConnectionListener listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void removeListener(BLEConnectionListener listener) {
        if (listeners.contains(listener)) {
            listeners.remove(listener);
        }
    }

    public void forwardStatusUpdate(String statusString) {
        for (BLEConnectionListener listener: listeners) {
            listener.statusUpdated(statusString);
        }
    }
}

I hope this is understandable. In BLEConnection, you can now call
forwardStatusUpdate("Connected");

to inform all the listeners (= active activities) about the status.


text:
Q: How to tell if a web page has loaded with in a WebBrowser Control I am trying to write a program that will tell my grandmother whether the internet is live or not. I know, I know, She just doesn't get it. So I want to create a program to load google.com or something and all I want the program to do is tell her whether the site was found or not. Is there a way to do this with the WebBrowser control?
I would really appreciate any help!
Thanks,
Cecil

A: You should use the Ping class.
Call Ping.Send("google.com") and check whether Status is Success.


text:
Q: sweetModal.js bug if height is too big I'm using SweetModal.js and if the height of the modal is more that the screen height there is no way to scroll to the top of the modal. You can check it on the business owner registration form ( at the right side ) http://om.hello21group.ru/ just add a few places to increase the height of the modal
Is there any way to fix it?

A: .sweet-modal-overlay {
    overflow: scroll !important;
}

.sweet-modal-box{
    max-height: unset !important;
    height: unset !important;
}

It allows you to scroll text on the sweetModal.

A: In your css, you have given
.sweet-modal{
  top:50%;  /* . -- issue -- */
}

It is causing the issue. Pls change its value to some other value such as
top:80%; may solve your problem


text:
Q: Boost equivalent of std::getline for boost::static_string I am changing my datatypes from std::string to boost::static_string, as I realized that when I write on file, I get 8 seconds with Boost against 25 seconds with the STL.
I was using std::getline for parsing the input, but that is obviously not compatible with boost::static_string. Which is the Boost equivalent of std::getline that works with boost::static_string specifically?

A:
I was using std::getline for parsing the input, but that is obviously not compatible with boost::static_string

You'd probably phrase it in terms of istream::read (which takes char*, size_t).

for parsing the input

In this case, why don't you share the input so we can solve the XY problem? The code being performance critical YET using iostreams for parsing seems like a very stark contradiction to me.

*

*50% chance that you can just keep using std::getline with std::string (and convert to static_string) because the parsing is not on any performance critical path

*50% chance that the real perf bottleneck is in the parsing, and I'd love to show you alternatives (using Boost)


text:
Q: Learn How To Develop GUI Applications I'm learning Objective-C and already know many other languages, but every time that i try to develop GUI applications i stuck, because i didn't understand and mental visualize the application running and those coordinates of the buttons and the other objects always let me confused, but where i can learn how to do good GUI applications using only my codes(without any type of IDE)? Thanks.

A: I suggest you start "thinking" about the application before actually developing it. How to navigate and access its functionalites from the end user's perspective, by doing wireframes / mockups. Use tools such as balsamiq mockup for that (here are many other similar tools).
In the end, what you really want to do is look at the usability, and develop an approach to development that puts the end-user in the center of the creative process. There are some excellent free resources out there. My favourites are: http://www.uxmatters.com/ and this book and blog Designing Web Interfaces

A: I suggest starting small and working your way up. Start off writing a simple Unit converter application with a GUI. Then maybe try something bigger like a minimal text editor (Open, edit the text, and save back out), and go from there.
Also, if you have a certain kind of application you really like, use it as an example and try to think how its developer made it. The great thing about Cocoa apps on the Mac is you can usually open up the actual interface files the application uses (right-click the Application bundle and select "Show Contents", navigate in there until you find .xib or .nib files, which usually can be opened by Interface Builder). Poke around in those to get an idea of how the apps work.
Finally, when you start building your applications (big or small) I highly suggest doing paper mockups. While using a tool on a computer is great, a blank sheet of paper has much less to get in your way. It's essentially your imagination and the paper. Start with a big rectangle (your Window) and draw in the interface. You'll get a feel of how things relate spatially. Don't focus too much on making the mockups pretty or detailed, but do focus on flow of the application and how you'd want it to be used.


text:
Q: Is there a way to combine loading jQuery and Google Analytics? I currently have the following:
<script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script>
<script>
  //<![CDATA[
    google.load('jquery', '1.6');
  //]]>
</script>

<script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', '...']);
        _gaq.push(['_trackPageview']);

        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
</script>

Seems like two very different ways to load js. Is there some way I can combine these so the load is most efficient?

A: For this call you need to load google jsapi first.
google.load('jquery', '1.6');

If you just want the jquery loaded asyncronously parallel to other script file calls, use the following :
var jq = document.createElement("script");
jq.src = "/path/to/jquery.js"; jq.type="text/javascript"; jq.async=true;
document.getElementsByTagName("head")[0].appendChild(jq);


text:
Q: Project input error i want to use the developed listView,
i downloaded the jar file of the swipeList project from here:
https://github.com/47deg/android-swipelistview/downloads
named:
swipelistview-1.0-SNAPSHOT.jar
and i import this jar file into my project in eclipse
however when i create an xml , like the example in your website:
<com.fortysevendeg.android.swipelistview.SwipeListView
            xmlns:swipe="http://schemas.android.com/apk/res-auto"
            android:id="@+id/android:list"
            android:listSelector="#00000000"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            swipe:swipeFrontView="@+id/relative"
            swipe:swipeBackView="@+id/layoutUpdate"
            swipe:swipeActionLeft="reveal"
            swipe:swipeActionRight="reveal"
            swipe:swipeMode="both"
            swipe:swipeCloseAllItemsWhenMoveList="false"
            swipe:swipeOpenOnLongPress="false"
            swipe:swipeAnimationTime="2"
            swipe:swipeOffsetLeft="5"
            swipe:swipeOffsetRight="5"
            />

i get an error message in this line:

can someone tell me where am i wrong please?
thanks alot


text:
Q: iOS when finished recording, turn off red status bar for AV Audio Recorder My app both records with and asks permission to use, background recording. I enjoy the red status bar while recording despite the fact that no one else seems to. My problem is turning it off...
This is the code I use when I am finished with the recording process:
- (void)stopRecording {
    [self.recorder pause];
    [self.recorder stop];
    self.recorder = nil;

    [self.audioSession setActive:NO error:nil];
    self.audioSession = nil;
}

I want this red bar to be gone once the recording is done (or at least shortly thereafter) to let the user know it has finished. Obviously it refuses and a quick Google search will show that a number of other people have had similar problems. Can anyone tell me what the solution is because I have at least 2 apps I have found that respond properly to stopping a recording and shutting it off at an appropriate time.

A: Turns out I was missing just a few lines of code... here they are:
- (void)stopRecording {
    [self.recorder pause];
    [self.recorder stop];
    self.recorder = nil;

    [self.audioSession setActive:NO error:nil];
    [self.audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    self.audioSession = nil;
}


text:
Q: Android Material Design View State changes vs Elevation I'm trying to implement Material Design in my apps but I can't understand what is the difference to implement a shadow with StateListAnimator or assign an elevation to the views.
Below is the links about what im talking about:
StateListAnimator
Elevation
What I'm seeing is that both can do the same thing, so why did they implement both in v5.0?

A: StateListAnimator allows you to animate View properties including elevation. The default Button implementation uses StateListAnimator to handle elevation and translationZ changes in response to disabled and pressed state changes.
So instead of setting the elevation attribute, the default Button style uses the stateListAnimator attribute.
Here is a sample of what the XML for that looks like:
res/animator/button_state_list_anim_material.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:state_enabled="true">
        <set>
            <objectAnimator android:propertyName="translationZ"
                            android:duration="@integer/button_pressed_animation_duration"
                            android:valueTo="@dimen/button_pressed_z_material"
                            android:valueType="floatType"/>
            <objectAnimator android:propertyName="elevation"
                            android:duration="0"
                            android:valueTo="@dimen/button_elevation_material"
                            android:valueType="floatType"/>
        </set>
    </item>
    ...


text:
Q: .NET GC of unreferenced objects with static members So I'm curious, will GC - and especially finalization - occur on an instance x in .NET when:

*

*x is not referenced by anything

*x has a static DbConnection property

*y is an instance of the same class as x

*y is still referenced by something

It strikes me that in this event, x could be declared dead by external references - but executing finalization on it may cause the DbConnection to be disposed while y still needs and holds a reference to it.
So which is it, in the scenario I described, is x collected? Does it get finalized? Or do all instances of it's type need to orphan in the heap before any one of them is collected? Will finalization happen across each instance?
I would think so, is the general rule to be followed just: Never touch a static or otherwise shared object in your finalizers?

A: Yes, the x instance would be eligible for GC.  The DbConnection, since it is static, is completely unrelated to the instances in this case, and not relevant for determining whether the object is eligible for GC.  It will not get collected as long as the static property holds a reference.

Never touch a static or otherwise shared object in your finalizers?

This is typically a good call.  In general, you should never write finalizers for your managed types, unless they're wrapping unmanaged resources, at which point the type should do nothing but manage that resource (ideally).  Even then, using SafeHandle is often a better approach when possible.


text:
Q: Terminate Colab session completely from notebook cell I want to completely kill the session of my Colab after a particular cell is run.
I have tried the solution in the following thread. Although it disconnects the session, the session is reconnected in a few seconds.
How to terminate current colab session from notebook cell
I want the session to only reconnect when a cell is run by the user or the user presses the reconnect button.


text:
Q: I want to test a simple singleton case and it has a linkage error I want to test a simple singleton case,  write a class C below:
class C {
    static C * ptr_c;
    C(){}
public:
    static C* getInstance()
    {
        if (ptr_c == nullptr)
            ptr_c = new C();
        return ptr_c;
    }
    void show()
    {
        std::cout << "this is class C" << std::endl;
    }
};

with test code:
int main()
{

    C* ptrc = C::getInstance();
    ptrc->show();
}

but it ouput  link error:
Undefined symbols for architecture arm64:
"C::ptr_c", referenced from:
C::getInstance() in test-1db68d.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


text:
Q: How to divide array into groups by an item in it in Ruby Say I have an array:
array = [{"account_id"=>"01", "ad"=>"1"},
{"account_id"=>"05", "ad"=>"2"},
{"account_id"=>"05", "ad"=>"3"},
{"account_id"=>"01", "ad"=>"2"},
{"account_id"=>"10", "ad"=>"3"},
{"account_id"=>"04", "ad"=>"4"}]

How can I divide it into groups divided by account_id like
l1 = [{"account_id"=>"01", "ad"=>"1"},{"account_id"=>"01", "ad"=>"2"}]
l2 = [{"account_id"=>"05", "ad"=>"2"},{"account_id"=>"05", "ad"=>"3"}]
....

and then return the lists together.
How can I do this? Is there any exist APIs? Furthermore, I'm thinking of using data structure like a list of lists (like List<List<Map<String, String>>> in Java? Sorry I'm new to Ruby), but let me know if there's better way to present. Thanks

A: array = [{"account_id"=>"01", "ad"=>"1"},
         {"account_id"=>"05", "ad"=>"2"},
         {"account_id"=>"05", "ad"=>"3"},
         {"account_id"=>"01", "ad"=>"2"},
         {"account_id"=>"10", "ad"=>"3"},
         {"account_id"=>"04", "ad"=>"4"}]

p array.group_by { |h| h['account_id']}

REsult
{"01"=>[{"account_id"=>"01", "ad"=>"1"}, {"account_id"=>"01", "ad"=>"2"}], "05"=>[{"account_id"=>"05", "ad"=>"2"}, {"account_id"=>"05", "ad"=>"3"}], "10"=>[{"account_id"=>"10", "ad"=>"3"}], "04"=>[{"account_id"=>"04", "ad"=>"4"}]}

Or you may the result as follows
array.group_by { |h| h['account_id']}.values.each do |value|
  p value
end

Result
[{"account_id"=>"01", "ad"=>"1"}, {"account_id"=>"01", "ad"=>"2"}]
[{"account_id"=>"05", "ad"=>"2"}, {"account_id"=>"05", "ad"=>"3"}]
[{"account_id"=>"10", "ad"=>"3"}]
[{"account_id"=>"04", "ad"=>"4"}]


text:
Q: Chrome 26 "Inspect Element" copy-paste issue For some reason, i'm not able to paste css code to the "inspect element" window..
Lets say I want to test "font-weight:bold; color: red" and paste it to the element.style, which results with:

As you can see, only the "font-weight" was pasted.
This is really annoying as I was used to just paste the code as is...
Especially if i'm trying a couple of styles from a tutorial or a solution to a problem I found here.
Is it only me? Anything I can do to fix it?

A: The bug is known and will be fixed in the next release :
https://groups.google.com/forum/?fromgroups=#!topic/google-chrome-developer-tools/RC3i6GW2h28

A: You could always edit the style in-line for testing:
Right click tag.  Click 'add attribute'.  Type style=" ctrl+ v "
Not sure if there's a more elegant solution.  element.style just adds a style="" attribute anyway.


text:
Q: Select2 closes immediately after data loaded Im trying to load data to select2 with ajax post method on click. But after data loads the selectbox closes. I have to open it again to see data. I need it to be stay opened. Here my code.
$('#newLawyer').select2();
$('#newLawyer').one('select2:opening', function() {
    $.ajax({
        method: 'POST',
        url: API_URL + 'getMemberList',
        async: true
    }).done(function (data) {
        console.log(data)
        result = $.map(data.data, function (obj) {
            return {
                text: obj.name,
                id: obj.id
            };
        });
        $("#newLawyer").select2({
            placeholder: "Bir seçim yapınız",
            data: result,
            cache: true
        });
    })
})

A: Try this
$('#newLawyer').select2({
  minimumInputLength : 0,
  ajax: {
    url: API_URL + 'getMemberList',
    method: 'POST',
    async: true,
    dataType: 'json'
    processResults: function (data) {
      // Transforms the top-level key of the response object from 'items' to 'results'
      const results = [];
      data.data.map(obj=> {
        if( /* any search condition put here */ ) {
          results.push({text: obj.name, id: obj.id})
        }
      });

      return { results };
    }
  }
});


text:
Q: BACPAC import hangs on processing table I am trying to import a database from Azure to local with the Import Data-tier application of a BACPAC. This has worked well for backups of this database up until this month. Now the import hangs on:
"Processing Table '[dbo].[Tablename]' In Progress"
The table it hangs on, is the largest sized table (storage size) in the database.
Any input to a possible solution would be greatly appreciated.


text:
Q: Trigger onClick event with URL I would like to be able to navigate to a page and open up content in one of three content containers in an accordion js structure.
Here is the html:

REEL

                    content

ABOUT

                content

CONTACT

                content

And here is my javascript:
// JavaScript Document

var ContentHeight = 200;
var TimeToSlide = 250.0;

var openAccordion = '';

function runAccordion(index)
{
  var nID = "Accordion" + index + "Content";
  if(openAccordion == nID)
    nID = '';

  setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'"
      + openAccordion + "','" + nID + "')", 33);

  openAccordion = nID;
}

function animate(lastTick, timeLeft, closingId, openingId)
{
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;

  var opening = (openingId == '') ? null : document.getElementById(openingId);
  var closing = (closingId == '') ? null : document.getElementById(closingId);

  if(timeLeft <= elapsedTicks)
  {
    if(opening != null)
      opening.style.height = ContentHeight + 'px';

    if(closing != null)
    {
      closing.style.display = 'none';
      closing.style.height = '0px';
    }
    return;
  }

  timeLeft -= elapsedTicks;
  var newClosedHeight = Math.round((timeLeft/TimeToSlide) * ContentHeight);

  if(opening != null)
  {
    if(opening.style.display != 'block')
      opening.style.display = 'block';
    opening.style.height = (ContentHeight - newClosedHeight) + 'px';
  }

  if(closing != null)
    closing.style.height = newClosedHeight + 'px';

  setTimeout("animate(" + curTick + "," + timeLeft + ",'"
      + closingId + "','" + openingId + "')", 33);
}

I'd love to be able to put a #reel in the URL string and be able to navigate to, and open Accordion1Content.

A: You can use JQuery's pageready function, along with URL parsing to trigger a click event:
Say your URL looks like: http://mysite.com/?page=reel
$(function() {
    var url = window.location.href;
    var page = url.match(/page=([^\?]+)/)[1];
    if (page=="reel") { runAccordion(1); }
});

You could add cases for the other page names as well.


text:
Q: Close overlay on click or escape key I have created an overlay which covers the entire page, I am looking for a way to either click on the body to close the overlay and/or using the escape key:

Search

function toggleDiv(divId) {
    $("#"+divId).fadeToggle();
}

A: escape:
$(document).keyup(function(e) {
  if (e.keyCode == 27) { <DO YOUR WORK HERE> }   // esc
});

How to detect escape key press with JavaScript or jQuery?
Click outside overlay:
$('html').click(function() {
    //Hide the menus if visible
});

$('#menucontainer').click(function(event){
    event.stopPropagation();
});

How do I detect a click outside an element?


text:
Q: Find a basis and the dimension of this vectorspace. $U=\left \{ (x_1,...,x_n)\in\mathbb{R}^n:\sum^n_{k=1}x_k =0 \right \}$
My thoughts:
(1) I think that $\text{dim(U)}=n-1$, but I'm not sure how to show that.
(2) The basis needs to be a set of independent vectors in U and every element of U is a linear combination of that set.
So using (1) and (2) I've come to the suspicion, that $(1,-1,0,...,0), (0,1,-1,0,...,0), ... ,(0,...,1,-1)$ would form a basis. Which is yet to be proven, but I have no idea how (probably showing its span is U and all vectors are independant, still though).
Thanks for any help.

A: The defining equation can be written
$$
x_1=-x_2-x_3-\dots-x_n
$$
You get $n-1$ solution vectors by giving each free variable the value $1$ (and $0$ to the others); for $n=4$ they would be
$$
\begin{bmatrix}
-1\\
1\\
0\\
0
\end{bmatrix}\,,\quad
\begin{bmatrix}
-1\\
0\\
1\\
0
\end{bmatrix}\,,\quad
\begin{bmatrix}
-1\\
0\\
0\\
1
\end{bmatrix},
$$
The same procedure works for general homogeneous linear systems and always gives a set of $p$ vectors, where $p$ is the number of free variables.
These vectors are surely linearly independent. You can see it by considering the linear mapping
$$f\colon \mathbb{R}^n\to\mathbb{R}^p$$
obtained by 'removing the rows corresponding to nonfree variables'. What you get is certainly the canonical basis of $\mathbb{R}^p$ because of how the vectors have been built.
A general result, which can be easily proved is the following.

If $f\colon V\to W$ is a linear map and $\{v_1,v_2,\dots,v_p\}$ is a set of vectors in $V$ such that $\{f(v_1),f(v_2),\dots,f(v_p)\}$ is linearly independent, then also $\{v_1,v_2,\dots,v_p\}$ is linearly independent.

Therefore the $n-1$ vectors above are linearly independent. The rank-nullity theorem will then end the computation.

A: $\sum_{n=0}^{n} x_k = 0$ implies that the whole space is determined by  $n-1$ vectors. Mathematically $x_n = \sum_{n=0}^{n-1} x_k$. That is one vector is determined by linear combinations of $n-1$ vectors.

A: Hint: Consider the map $f:V \rightarrow \mathbb{K}$ such that $f: \sum\lambda_iv_i \mapsto \sum\lambda_i $. Why rank superior bound is 1? Why is it 1 at least? Now remember $\operatorname{dim}(V)=\operatorname{dim}(\operatorname{Ker})+\operatorname{dim}(\operatorname{Im})$. Who is the Ker?.
Obs: $U = (1, \dots, 1)^{\perp}$


text:
Q: Best approch for creating ePub reader similar to iBook or Stanza application I am planning to develop a ePub reader for iOS devices. I don't want to use webView for this. In this application, I want features like iBook or stanza app. I want to know, which approch is used in developing Stanza app.

A: Books in ePub format are HTML with some meta-data. Different generators create differently formatted HTML. The work needed to implement a parser capable of displaying all ePub is a mammoth task! If you do not want to use a web view then your project is doomed from the start.
Stanza, Apple's iBooks, my own ePub reader for iPad, and any other ePub reader I know of all use a standard Web view as the basis. On top of that you need allot of CSS and Javascript to tweak all mutations of ePubs there is.

A: Your approach should be to learn how to parse the ePub data and bundle that with an app that displays the content as well as handles all the other features.  Probably want to look at Core Text.

A: Actually you do can write an ePub reader without an WebView, but you need to render everything on your own. You can find some open source epub reader for reference.

A: Download Sample project from here http://ideveloperworld.blogspot.in/2011/02/epub-reader.html


text:
Q: React countdown timer using new Date() I tried coding a countdown timer as follows.
Every second the getTime() function is called. In this function, I have a variable named finishhours and a variable named currentHours. Finishhours is equal to the time that the countdown timer should be zero. CurrentHours is equal to the current time.
To make calculations easier I format both variables in hours. For example, 10:45:32 will become 10 + 45/60 + 32/3600 = 10,76.
From there I can calculate the remaining hours, minutes and seconds and assign these values to variables: rHour, rMin and rSec. These 3 variables are then used to display the remaining time on the screen.
The problem I am facing is that the function getTime() gets called multiple times every second. And the number of times it gets called increases exponentially. For example, after one second elapses the function is called 2 times, one second later the function is called 8 times, then 32 times, and so on.
This is my code:
import React, { useState } from 'react';
import '../Timer.css';

const startDate = new Date();
const Timer = ({ end }) => {
  const[rHour, setRHour] = useState(2); //countdown 2 hours.
  const[rMin, setRMin] = useState(0);
  const[rSec, setRSec] = useState(0);

  function getTime(){
    const finishHours = startDate.getHours() + 2 + startDate.getMinutes() / 60 + startDate.getSeconds() / 3600;
    const currentHours =  new Date().getHours() + new Date().getMinutes() / 60 + new Date().getSeconds() / 3600;
    const remainingHours = finishHours - currentHours;

    const remainingHour = Math.floor(remainingHours);
    const remainingMinute = Math.floor((remainingHours - remainingHour) * 60);
    const remainingSecond = Math.floor(((remainingHours - remainingHour) * 60 - remainingMinute)*60)

    setRHour(remainingHour);
    setRMin(remainingMinute);
    setRSec(remainingSecond);
    console.log("count")
  }

  setInterval(function(){
    getTime()
  }, 1000);

  return(

        {("0" + rHour).slice(-2)}
        :
        {("0" + rMin).slice(-2)}
        :
        {("0" + rSec).slice(-2)}

        Uur

        Min

        Sec

  );
};

export {Timer};

Is there a way I can prevent this?
Thank you in advance.

A: Basically every render you are doing is creating a new setInterval, you only want a single setInterval when the component is mounted.
For things like this you want to use useEffect, useEffect also has a callback method you can use to clean up the setInterval when the component is unmounted.
So using this information.
try>
  useEffect(() => {
    const i = setInterval(getTime, 1000);
    return () => clearInterval(i);
  }, [end]);  //dependency, if end changes remount

A: You should set the interval in a useEffect. As on each setstate the component is being re-rendered and setting the interval again.
useEffect(()=>{
 setInterval(()=>{
    getTime()
  }, 1000);
},[]);

A: Try this code : UseEffect will set this interval once even Timer function call multiple time. then after setInterval will call again and again.
import React, { useState } from 'react';
import '../Timer.css';

const startDate = new Date();
const Timer = ({ end }) => {
  const[rHour, setRHour] = useState(2); //countdown 2 hours.
  const[rMin, setRMin] = useState(0);
  const[rSec, setRSec] = useState(0);

  function getTime(){
    const finishHours = startDate.getHours() + 2 + startDate.getMinutes() / 60 + startDate.getSeconds() / 3600;
    const currentHours =  new Date().getHours() + new Date().getMinutes() / 60 + new Date().getSeconds() / 3600;
    const remainingHours = finishHours - currentHours;

    const remainingHour = Math.floor(remainingHours);
    const remainingMinute = Math.floor((remainingHours - remainingHour) * 60);
    const remainingSecond = Math.floor(((remainingHours - remainingHour) * 60 - remainingMinute)*60)

    setRHour(remainingHour);
    setRMin(remainingMinute);
    setRSec(remainingSecond);
    console.log("count")
  }

  useEffect(()=>{
    setInterval(function(){
      getTime()
    }, 1000);
  }, []);

  return(

        {("0" + rHour).slice(-2)}
        :
        {("0" + rMin).slice(-2)}
        :
        {("0" + rSec).slice(-2)}

        Uur

        Min

        Sec

  );
};

export {Timer};