text:
Q: ElasticSearch 0.90.2 StreamCorruptedException on asking port 9300 I've just unpacked elasticsearch-0.90.2.zip on Windows XP, and started bin/elasticsearch.bat.
I've set JAVA_HOME to C:\Program Files\Java\jre7, as it was a problem at first run.
I'm trying to connect it from Google Chrome 27.0.1453.116.
According to elasticsearch.yml, "ElasticSearch, by default, binds itself to the 0.0.0.0 address", but 0.0.0.0:9200 responds 108 (net::ERR_ADDRESS_INVALID).
localhost:9200 or 127.0.0.1:9200 responds correctly: { "ok" : true, etc.
localhost:9300 responds 324 (net::ERR_EMPTY_RESPONSE), and displays StreamCorruptedException in the console window:
[2013-07-25 10:42:30,419][WARN ][transport.netty          ] [Happy Birthday] exc
eption caught on transport layer [[id: 0x478ae9b7, /127.0.0.1:1627 => /127.0.0.1
:9300]], closing connection
java.io.StreamCorruptedException: invalid internal transport message format
        at org.elasticsearch.transport.netty.SizeHeaderFrameDecoder.decode(SizeH
eaderFrameDecoder.java:27)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.callD
ecode(FrameDecoder.java:425)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.messa
geReceived(FrameDecoder.java:303)
        at org.elasticsearch.common.netty.channel.SimpleChannelUpstreamHandler.h
andleUpstream(SimpleChannelUpstreamHandler.java:70)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline$Default
ChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
        at org.elasticsearch.common.netty.OpenChannelsHandler.handleUpstream(Ope
nChannelsHandler.java:74)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:559)
        at org.elasticsearch.common.netty.channel.Channels.fireMessageReceived(C
hannels.java:268)
        at org.elasticsearch.common.netty.channel.Channels.fireMessageReceived(C
hannels.java:255)
        at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.read(NioW
orker.java:88)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.p
rocess(AbstractNioWorker.java:109)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector
.run(AbstractNioSelector.java:312)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.r
un(AbstractNioWorker.java:90)
        at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.run(NioWo
rker.java:178)
        at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(Thread
RenamingRunnable.java:108)
        at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.ru
n(DeadLockProofWorker.java:42)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
[2013-07-25 10:42:30,435][WARN ][transport.netty          ] [Happy Birthday] exc
eption caught on transport layer [[id: 0x478ae9b7, /127.0.0.1:1627 :> /127.0.0.1
:9300]], closing connection
java.io.StreamCorruptedException: invalid internal transport message format
        at org.elasticsearch.transport.netty.SizeHeaderFrameDecoder.decode(SizeH
eaderFrameDecoder.java:27)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.callD
ecode(FrameDecoder.java:425)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.clean
up(FrameDecoder.java:482)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.chann
elDisconnected(FrameDecoder.java:365)
        at org.elasticsearch.common.netty.channel.SimpleChannelUpstreamHandler.h
andleUpstream(SimpleChannelUpstreamHandler.java:102)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline$Default
ChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
        at org.elasticsearch.common.netty.OpenChannelsHandler.handleUpstream(Ope
nChannelsHandler.java:74)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:559)
        at org.elasticsearch.common.netty.channel.Channels.fireChannelDisconnect
ed(Channels.java:396)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.c
lose(AbstractNioWorker.java:361)
        at org.elasticsearch.common.netty.channel.socket.nio.NioServerSocketPipe
lineSink.handleAcceptedSocket(NioServerSocketPipelineSink.java:81)
        at org.elasticsearch.common.netty.channel.socket.nio.NioServerSocketPipe
lineSink.eventSunk(NioServerSocketPipelineSink.java:36)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendDow
nstream(DefaultChannelPipeline.java:574)
        at org.elasticsearch.common.netty.channel.Channels.close(Channels.java:8
12)
        at org.elasticsearch.common.netty.channel.AbstractChannel.close(Abstract
Channel.java:197)
        at org.elasticsearch.transport.netty.NettyTransport.exceptionCaught(Nett
yTransport.java:505)
        at org.elasticsearch.transport.netty.MessageChannelHandler.exceptionCaug
ht(MessageChannelHandler.java:224)
        at org.elasticsearch.common.netty.channel.SimpleChannelUpstreamHandler.h
andleUpstream(SimpleChannelUpstreamHandler.java:112)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline$Default
ChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
        at org.elasticsearch.common.netty.handler.codec.frame.FrameDecoder.excep
tionCaught(FrameDecoder.java:377)
        at org.elasticsearch.common.netty.channel.SimpleChannelUpstreamHandler.h
andleUpstream(SimpleChannelUpstreamHandler.java:112)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline$Default
ChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
        at org.elasticsearch.common.netty.OpenChannelsHandler.handleUpstream(Ope
nChannelsHandler.java:74)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:559)
        at org.elasticsearch.common.netty.channel.Channels.fireExceptionCaught(C
hannels.java:525)
        at org.elasticsearch.common.netty.channel.AbstractChannelSink.exceptionC
aught(AbstractChannelSink.java:48)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.notifyH
andlerException(DefaultChannelPipeline.java:658)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:566)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline$Default
ChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
        at org.elasticsearch.common.netty.OpenChannelsHandler.handleUpstream(Ope
nChannelsHandler.java:74)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:564)
        at org.elasticsearch.common.netty.channel.DefaultChannelPipeline.sendUps
tream(DefaultChannelPipeline.java:559)
        at org.elasticsearch.common.netty.channel.Channels.fireMessageReceived(C
hannels.java:268)
        at org.elasticsearch.common.netty.channel.Channels.fireMessageReceived(C
hannels.java:255)
        at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.read(NioW
orker.java:88)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.p
rocess(AbstractNioWorker.java:109)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector
.run(AbstractNioSelector.java:312)
        at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioWorker.r
un(AbstractNioWorker.java:90)
        at org.elasticsearch.common.netty.channel.socket.nio.NioWorker.run(NioWo
rker.java:178)
        at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(Thread
RenamingRunnable.java:108)
        at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.ru
n(DeadLockProofWorker.java:42)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

I've read about similar situations, but now there is no other node running, no networking, nothing uses the port, it is my first standalone ElasticSearch engine on the local machine with default configuration.
I can't imagine what should there be on port 1627 - perhaps it is the clue.
What do I wrong - or any solution?

A: Nothing is corrupted. The 9300 port is used for inter-node communication and uses an internal binary protocol, thus you can't use it from the browser. In order to use the 9300 port you have to use the Java API, either Node client or Transport client, which both understand the internal binary protocol.
From the browser you should only use the 9200 port, which is the one that exposes the REST API.

A: I have met the same problem. As I discovered issue is inside configs(/etc/elasticsearch/elasticsearch.yml by default). There is a tricky parameter http.enabled which was set to false by default. For fix you just need to set it to true:

   http.port: 9200
   http.enabled: true

I hope it will help.


text:
Q: Remote batch Powershell video adaptor querying I'm trying to write a powershell script to report the video cards used by all machines in a given range of the domain (GUM1 to GUM150).
I've actually successfully made the machines report their video cards via remote powershell, but there are two problems;

*

*The machines are not queried (or reported?) in the order they are defined in the txt list.

*The hostname is not reported back, which means I have a jumbled list of results and no corresponding machine name.
Here's what I've got so far;
$comp = get-content c:\users\myusername\pcs.txt

Where pcs.txt is a list of the machines by hostname, each name on a new line.
Then;
get-wmiobject -class CIM_VideoController caption -namespace root/cimv2 -computername $comp | sort-object -property machinename | format-table machinename, caption > gpus.txt

The reference book I'm using stated that using get-wmiobject automatically includes the machinename (i.e. the hostname) in the results of the object that returns. But I can't seem to make it appear in the list beside the GPU names (caption) it returns, it just returns a table with the GPU names and a blank column for machinename.
I've seen a lot of examples of querying details of a videocard, but they all return an extensive set of details about the card in a long list, per machine, whereas I want ONLY the hostname and video card name returned in a table all together for easy copy/paste into a spreadsheet.
I'm not sure CIM_VideoController is the best WMI object for this but none of the others I've seen return both GPU and hostname with the results object.
Any ideas?

A: welcome to SO. There are a few things wrong with your script that you should take care of.

*

*You are calling calling one WMI query on a list of servers. You name the variable $comp, but it holds an array of comps, and the -computername parameter does not accept a list of computernames. You can fix this by using a foreach loop.

*You are attempting to access a property of a WMI class that does not exist. Use the documentation to find what are the actual properties you need http://msdn.microsoft.com/en-us/library/aa388668(v=vs.85).aspx (machinename is not a property)

*Once you implement the first point there is no need to try to sort the object, your loop will go through the text file, query the computer, and append the results in the order specified in your pcs.txt
This one liner will take care of all of that:
get-content c:\users\myusername\pcs.txt | % { get-wmiobject -class CIM_VideoController -namespace root/cimv2 -computername $_ | format-table SystemName, caption >> gpus.txt}
This gets the array of pcs from the text file, pipes each one into the wmi query (% is a foreach loop, and $_ is the object in the pipe, in this case each line of pcs.txt), and then appends the results of each individual query onto gpus.txt, > just overwrites each time. If you wish to overwrite the file each time you run, then you should collect all the output first in variable, and then output once the loop is finished. The below scripts does that, and also provides a more readable solution (just less fancy)
$table = @()
$comps = get-content c:\users\myusername\pcs.txt
foreach($comp in $comps) {
    $table += get-wmiobject -class CIM_VideoController -namespace root/cimv2 -computername $comp  | format-table SystemName, caption
}
$table > gpus.txt

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tuple objectt is not callable trying to run the below code and receiving the 'tuple' object is not callable error. Any help would be appreciated!
drug_list = sum_df.index.tolist()
count = (study.groupby(["Drug Regimen"]) ["Age_months"].count()).tolist()
#list
#count

x_axis = np.arange(len(count))
x_axis = drug_list
plt.figure(figsize=(10,3))
plt.bar(x_axis, count, color="b", alpha = 0.5, align="center")
plt.title ("Drug Regimen Timepoints")
plt.xlabel("Drug Regimen")
plt.ylabel("Total Count")

TypeError: 'tuple' object is not callable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4864/2917130576.py in <module>
      8 x_axis = drug_list
      9 plt.figure(figsize=(10,3))
---> 10 plt.bar(x_axis, count, color="b", alpha = 0.5, align="center")
     11 plt.title ("Drug Regimen Timepoints")
     12 plt.xlabel("Drug Regimen")

TypeError: 'tuple' object is not callable


text:
Q: Changing color of menu on text hover I want to change the color of the menu on text hover. But not when the menu text is hovered but another heading. I have a heading "Not a restaurant, but here for them." and when the user hovers the word "restaurant" the menu text color should change to white and the word "restaurant" to red and the rest of the heading to white. The second part (that "restaurant" changes to red and the rest of the heading to white) already works. But how can I make it that also the color of the menu changes?

.headingRestaurant:hover {
  color: red;
}

.headingRestaurant {
  cursor: pointer;
}

.textb {
  pointer-events: none;
}

.headingRestaurant {
  pointer-events: initial;
}

.textb:hover {
  color: white;
}

      Home

      About

  Not a restaurant,

 but here for them.

A: Since CSS can only interact with things inside or below the current element, the easiest solution would be to use Javascript to handle the hover for you.
You can use the function addEventListener to add both a mouseover and a mouseout event on your restaurant text to add/remove a hover class to whichever element you want to hover.

var nav = document.querySelector('nav');
var headingRestaurant = document.querySelector('.headingRestaurant');

headingRestaurant.addEventListener('mouseover', function() {
    nav.classList.add('hover');
});

headingRestaurant.addEventListener('mouseout', function() {
    nav.classList.remove('hover');
});
.headingRestaurant:hover {
    color: red;
}

.headingRestaurant {
    cursor: pointer;
}

.textb {
    pointer-events: none;
}

.headingRestaurant {
    pointer-events: initial;
}

.textb:hover {
    color: white;
}

nav.hover,
nav.hover a {
    color: red;
}

            Home

            About

    Not a restaurant,

    but here for them.

If you'd like to use html and css only, you'd have to reverse the html flow so that the element you want to change is coded below the element you're hovering over.
In this case I've moved the nav and h1 to a container div and swapped them around so that the h1 is coded above the nav. The display order is then fixed by using both the properties display: flex and flex-direction: column-reverse. The hover in this method uses the css selector ~ which matches an selector that is preceded by another selector. In the case of .textb:hover ~ nav it would select any nav element that is preceded by a .textb which is hovered over. Since the part after the ~ is still a selector, you could also change a specific menu item.

.headingRestaurant {
    cursor: pointer;
    pointer-events: initial;
}

.textb {
    pointer-events: none;
}

.textb:hover {
    color: white;
}

.textb:hover .headingRestaurant {
    color: red;
}

.textb:hover ~ nav,
.textb:hover ~ nav a {
    color: red;
}

.textb:hover ~ nav a.about {
    color: purple;
}

.reversed {
    display: flex;
    flex-direction: column-reverse;
}

      Not a restaurant,

      but here for them.

              Home

              About

A: :has is definitely the way to go here but there are some clever cookies out there who might come up with something innovative. Note that this isn't fully supported yet.

/* This is just making things pretty */

nav ul li {
  display: inline-block;
  padding: 0.5rem 1rem;
  margin: 0;
  border: 1px dotted red;
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

nav ul li a {
  text-decoration: none;
  color: inherit;
}

/* This is the functional stuff */

.headingRestaurant:hover {
  color: red;
}

.headingRestaurant {
  cursor: pointer;
}

.textb {
  pointer-events: none;
}

.headingRestaurant {
  pointer-events: initial;
}

.textb:hover {
  color: white;
}

/* This colours the menu on hover */

body:has(.headingRestaurant:hover) nav {
  background-color: lightblue;
}

      Home

      About

  Not a restaurant,

 but here for them.

A: Replace target with whatever class/id you are using to identify your menu element and it will control the styling when hovering on the .headingRestaurant element.

.headingRestaurant:hover target {

}


text:
Q: Pass variable from shell script into inline ruby command? I want to be able to declare a variable in a shell script and use it in a ruby inline command.  Something like this:
foo=kroe761
bar=$(ruby -e 'puts $foo')
echo My name is $bar

$ My name is kroe761.

But, what I get is My name is. How can I get shell variables into my ruby script?

A: Your program does not work because the parameter expansion in the command line does not happen in the strings enclosed in apostrophes.
The Ruby code you run is exactly puts $foo and, because its name starts with $, for the Ruby code $foo is an uninitialized global variable. The Ruby program outputs an empty line but the newline is trimmed by $() and the final value stored in the shell variable bar is an empty string.
If you try ruby -e "puts $foo" (because the parameters are expanded between double quotes) you'll find out that it also does not produce what you want but, even more, it throws an error. The Ruby code it executes is puts kroe761 and it throws because kroe761 is an unknown local variable or method name.
Building the Ruby program in the command line this way is not the right way to do it (and doing it right it's not as easy as it seems).
I suggest you to pass the value of $foo as an argument to the script in the command line and use the global variable ARGV in the Ruby code to retrieve it.
foo=kroe761
bar=$(ruby -e 'puts ARGV[0]' "$foo")
echo "My name is $bar"

It is very important to put $foo between quotes, otherwise, if it contains spaces, it is not passed to ruby as one argument but the shell splits it by spaces into multiple arguments.
Check it online.


text:
Q: Join attributes by location in QGIS 3 I wonder if there is a better way to join attributes based on location.
I have a vector layer with polygons representing lines.
Layer A is the layer where I want to take the correct attributes and Layer B is the layer with the merged/dissolved polygons.
They're split into multi parts and I merged/dissolved them based on 'type' attribute (see image tables).
After merging/dissolving the polygons I want to re-assign the attributes back, based on the location.
I've tried the tool join attributes by location selecting 'contains' and 'one to one' join. The result displayed here is correct but with other features it looks like that it's taking the attributes of the adjacent polygon (which has different type attribute) instead of the
the polygon that falls in the same area and same attribute type.
So I have to check them manually which is a lot of time consuming if you have hundreds of features.

I have also tried using PostGIS, which I'm new, using the following spatial query:
SELECT table_A
FROM
table_A,
table_B
WHERE
st_contains(table_B.geom, table_A.geom);
Using this I get only a few features joined. What am I missing here?
Is there any other way to do this without spending too much time checking the features manually? Using python inside or outside QGIS or Arcmap?


text:
Q: How do I store more than 15,000 Japanese characters in a column? I want to store more than 15,000 characters of Japanese text in a SQL Server 2008 database. We have a front end tool that will display this text.

A: In this case only NVARCHAR(MAX) should be used. It's able to store up to 2^31-1 bytes of Unicode data (about 2 GB).


text:
Q: How to Use JSON With AJAX? I've defined a PHP callback function to handle the communication between server-side and client-side:
function json_render_modal_body() {

    check_ajax_referer( THEME_PREFIX . '-modals', 'nonce' );

    $response = array( 'text' => 'no' );
    $modal_id = null;

    if ( isset( $_GET['modal_id'] ) && ! $modal_id = filter_var( $_GET['modal_id'], FILTER_SANITIZE_STRING ) ) {
        wp_send_json_error( $response );
    }

    if ( ! $form = render_form( $modal_id ) ) {
        wp_send_json_error( $response );
    }

    $response['text'] = 'yes';

    wp_send_json_success( $response );

}

I've told WordPress about this function, to handle the communication process:
add_action( 'wp_ajax_json_render_modal_body', __NAMESPACE__ . '\json_render_modal_body' );
add_action( 'wp_ajax_nopriv_json_render_modal_body', __NAMESPACE__ . '\json_render_modal_body' );

I've registered/enqueued/localized my JS script to handle the AJAX request.
This is what I've localized:
wp_localize_script(
    THEME_PREFIX . '-modals',
    'mbe_theme_modal',
    array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( THEME_PREFIX . '-modals' )
    )
);

This is what my JS script looks like:
var modal_id = jQuery( e.relatedTarget ).attr( "data-target" ).replace( "#", "" );

jQuery.get(
    mbe_theme_modal.ajax_url,
    {
        action: "json_render_modal_body",
        modal_id: modal_id,
        nonce: mbe_theme_modal.nonce
    },
    function ( data ) {

        console.log( data );

    },
    'json'
);

Any idea why I keep getting a 0 in my AJAX response?
I've also tried removing the nonce stuff from my code, and accessing the direct URL (domain.com/wp-admin/admin-ajax.php?action=json_render_modal_body&modal_id=some-modal-id, however, I still continue to get a 0.
I've even tried keeping the PHP function super simple with nothing but a simple text response, and still continue to get a 0.

A: Usually, you can use the global variable ajaxurl instead of any path using admin-ajax.php.
More importantly, the PHP function should echo the response before calling wp_die(). Because you haven't called wp_die(), AJAX is probably waiting for more from PHP.
Hope this helps.
P.S. What is that 'json' string doing where the AJAX fail() function should be?


text:
Q: Prove that for any prime $p$, the set $\mathbb{Z}_p$ with the addition mod $p$ and multiplication mod $p$, and congruence mod $p$, is a field So this is all that we are given:

*

*F is closed under addition and multiplication, i.e. $\forall a, b \in F,$ we have $a + b$ and $a × b$ are also both in F.

*commutitivity: $a + b = b + a$ and $a × b = b × a$

*associativity: $a + (b + c) = (a + b) + c$ and $a × (b × c) = (a × b) × c$

*unique neutral element property: there are neutral elements 0 and 1 for addition and multiplication.

*Unique inverse element for each given element: and element a of F has unique additive inverse and
a unique multiplicative inverse.

*distributivity of multiplication over addition: $a × (b + c) = a × b + a × c$.

How do we prove that for a given number $n>1$ and defining $\mathbb{Z}_p= \{0, 1, 2, . . . , n − 1\}$, for any prime $p$, the set $\mathbb{Z}_p$ with
the addition mod p and multiplication mod p, and congruence mod p, is a field.
I'd really appreciate it if someone could help me with this proof.

A: (1). The additive and multiplicative identities are (obviously) $0$ and $1$ and are (obviously) unique. And $0\not \equiv 1\pmod p$. (That is necessary to say, because in a field the additive and multiplicative identities are not allowed to be equal).
(2).  Additive inverses:
(2A). Existence: If $0< x<p$ then $0<p-x<p$ with $x+(p-x)\equiv 0.$ And $0+0\equiv 0.$
(2B). Uniqueness: If $x+y\equiv x+y'\equiv 0$ then $y-y'\equiv 0.$ but if $0\leq y<p$ and $0\leq y'<p$ then $|y-y'|<p.$ And if $p$ divides $|y-y'|$ with $0\leq |y-y'|<p$ then $y-y'=0 .$
(3). Multiplicative inverses:
(3A). Existence: For $1\leq x<p$ let $M=\min \{z:0<z\land \exists y\;(xy\equiv z \pmod p\}.$
First, by considering the case $y=1$ we have $M\leq x<p.$
Second, we will show that if $xy\equiv k$ with $2\leq k<p$ then there exists $y'$ and $k'$ with $0< k'<k$ and $xy'\equiv k'.$ From this we will conclude that if $2\leq k<p$ then $k\ne M.$
Thirdly, from the first and second parts  above, we will have  $M=1$, so $xy\equiv 1$ for some $y$.
To prove the second part: Suppose $xy\equiv k$ with $2\leq k<p.$ Let $m=\max \{m'>0: m'k<p\}.$ Then $mk<p\leq (m+1)k.$ But $p$ is prime  and $m+1>1<k$ so we cannot have $(m+1)k=p.$ So $mk<p<(m+1)k.$
Let $y'=(m+1)y$ and $k'=(m+1)k-p.$ We have $0<k'<k'-mk=k.$ Now $$xy'=xy(m+1)\equiv k(m+1)\equiv k(m+1)-p=k'.$$
(3B). Uniqueness of  multiplicative inverse:  $$xy\equiv xy'\equiv 1\implies$$ $$\implies y\equiv y(1)\equiv y(xy')\equiv (yx)y'\equiv (1)y'\equiv y'.$$


text:
Q: How to add Image Asset as a Background in Flutter? I have a vector that I want to be part of the background of my screen but I don't know how will I implement it. I tried inserting image.asset in the children but it is being placed above my elements in the screen. Pease help. This is my existing code right now:
import 'package:ehatid_driver_app/signup.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'Welcome/components/body.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({
    Key? key,
  }) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {

  //text controller
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  Future signIn() async {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: _emailController.text.trim(),
        password: _passwordController.text.trim(),
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFFFFCEA),
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset("assets/images/illus14.png",
                    width: 250
                ),
                Text(
                  "Sign in to your account",
                  style: TextStyle(fontFamily: 'Montserrat', fontSize: 28, letterSpacing: -2, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 10),
                Text(
                  "Welcome Back! Ready for your next ride?", textAlign: TextAlign.center,
                  style: TextStyle(fontFamily: 'Montserrat', fontSize: 13, color: Color(0xff272727), letterSpacing: -0.5, fontWeight: FontWeight.w500),
                ),
                SizedBox(height: 30),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                            color: Color(0xffeeeeee),
                            blurRadius: 10,
                            offset: Offset(0,4)
                        ),
                      ],
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.only(left: 20),
                      child: TextField(
                        controller: _emailController,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: "Email",
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height:10),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: TextField(
                        controller: _passwordController,
                        obscureText: true,
                        decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                            borderRadius: BorderRadius.circular(15),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Color(0xFFFED90F),),
                            borderRadius: BorderRadius.circular(15),
                          ),
                          hintText: "Password",
                          fillColor: Colors.white,
                          filled: true,
                        ),
                      ),
                    ),
                SizedBox(height: 20),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: GestureDetector(
                    onTap: signIn,
                    child: Container(
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Color(0xFFFED90F),
                          borderRadius: BorderRadius.circular(50),
                      ),
                      child: Center(
                        child: Text(
                          "Sign in",
                          style: TextStyle(
                              color: Colors.white, fontFamily: 'Montserrat', fontSize: 16
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("Don't have an account yet?", style: TextStyle(
                        color: Color(0xFF494949), fontFamily: 'Montserrat', fontSize: 16, letterSpacing: -0.5, fontWeight: FontWeight.w500
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.pushReplacement(context, MaterialPageRoute(
                          builder: (_) => SignUpPage(),
                        ),
                        );
                      },
                      child: Text("Register", style: TextStyle(fontFamily: 'Montserrat', fontSize: 16,
                        letterSpacing: -0.5, fontWeight: FontWeight.w600,
                        decoration: TextDecoration.underline, color:Color(0xFFFEDF3F),
                      ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

This the output of the above code:

However, this is what I wanted it to look like. That yellow vector is an image, btw.


text:
Q: Can I tell a nodeJs server to generate just the dynamic HTML (while nginx sends the static data) and then automatically send to client? I have mostly dealt with Apache and php and am starting to play around with nginx and node.  I am really liking it.  I started with an Express server that handles sending all the website files and HTML rendering (Handlebars).
But that seemed a little sluggish and I looked at the benchmarks and it seems that node isn't the best for sending HTML on the fly.  I know having just static files saved to your nginx server is considered the fastest way to get user's their page requests.
I know you can set up a proxy in nginx to go to your node server. But my question is can you mix nginx and a nodejs server to get the best of both worlds?  So a user asks for a page from nginx. Nginx sends back all the static files for the website. Right as it sends those files can it tell the node server to create the dynamic content for the page that was requested as HTML then send it off to the user asap. I feel like doing this would cause for a faster page load time (maybe I'm naive and it won't make a difference).
The other question is how would the receiving of that dynamic HTML go? Can I set up like just the receiving part of a GET request for the data in javascript so when the page loads it GETs ready and waits for the dynamic HTML so it can grab it and put it in the correct places.  Otherwise I feel like if I have the node server send HTML to the client it will just take that as a new page and trash the previously loaded nginx static data it just received and load just the dynamic data.
Let me know what you think.

A: There are tons of ways to accomplish this, it all depends on how you want to construct your server.
Personally, I like to write client-side javascript which makes http requests to my server for content. That content is then processed and rendered in the web page. This is called AJAX. jQuery has methods that make writing AJAX requests quite simple. You can read up on it here.
Generally speaking, it is much more difficult for the server to send the client resources that they didn't ask for than it is for the client to make a request for the resource. The former would require a socket to stay open, listening for messages from the server. This isn't a bad solution, in fact this is the better solution for when your client and server should be in constant communication. However, in the scenario you are describing, it makes more sense for the client to request resources.


text:
Q: Can a Polyhedron have infinite vertex or edge set ? - and what is the exact definition of a solid. I've been reading about Polyhedrons through the following article.
http://en.wikipedia.org/wiki/Polyhedron
My question is:
Can a Polyhedron have infinite vertex or edge set ? If not, what does imply that this isn't possible ?
Also, what is the exact definition of a solid ?


text:
Q: Why is a document being created when I submit a search I'm building a search feature to add to one of my Notes apps.  It's very simple at the moment.  Got a search xpage and a search results xpage.  Oddly, when I submit the search, the correct search results comes up but an empty document is created in the database.
On the submit button, I set it to 'no update' (thinking that might cause this).  Didn't make a difference.
The 'on click' event simply opens the search results xpage.  I'm tossing up some session scoped variables for the search, then there's just a view on the search results page with the filtered list of docs.  Just not sure where the doc creation is coming from.
thanks
clem

A: opps!  Looks like I had added a document data source to the search xpage.  After removing that, no new doc was created.
Clem

A: A button of type "Submit" will submit the form and therefore save all datasources on the page. I would recommend avoiding that button type. If you want to specifically save, you can call datasourceName.save() or use the simple action.


text:
Q: Run-time error '9' when copying worksheet to another workbook I've been trying to write a macro to copy "Sheet1" from one workbook into another, but I keep getting a run-time error '9': Subscript out of range.
Sub CopySheetToOtherWbk()

Dim CopyFromBook As Workbook
Dim CopyToWbk As Workbook
Dim ShToCopy As Worksheet

Set CopyFromBook = Workbooks("AllBugs.xlsx")
Set ShToCopy = CopyFromBook.Worksheets("Sheet1")
Set CopyToWbk = Workbooks("YourFriendlyNeighborhoodTemplateWorksheet.xlsx")

ShToCopy.Copy After:=CopyToWbk.Sheets(CopyToWbk.Sheets.Count)

End Sub

The highlighted line is "Set CopyFromBook = Workbooks("AllBugs.xlsx")". Not sure what I'm doing wrong here. Relatively new to VBA. Any help is appreciated.

A: The Workbooks collection refers to all currently open workbooks. If the workbook isn't open you will need to do this first.
Set CopyFromBook = Workbooks.Open("C:\Some Location\AllBugs.xlsx")


text:
Q: logging multithreading deadlock in python I run 10 processes with 10 threads per each, and they constantly and quite often write to 10 log file (one per process) using logging.info() & logging.debug() during 30 seconds.
Once, usually after 10 seconds, there happens a deadlock. Processes stops processing (all of them).
gdp python [pid] with py-bt & info threads shows that it stuck here:
  Id   Target Id                                 Frame
* 1    Thread 0x7ff50f020740 (LWP 1622) "python" 0x00007ff50e8276d6 in futex_abstimed_wait_cancelable (private=0, abstime=0x0, expected=0, futex_word=0x564f17c8aa80)
    at ../sysdeps/unix/sysv/linux/futex-internal.h:205
  2    Thread 0x7ff509636700 (LWP 1624) "python" 0x00007ff50eb57bb7 in epoll_wait (epfd=8, events=0x7ff5096351d0, maxevents=256, timeout=-1) at ../sysdeps/unix/sysv/linux/epoll_wait.c:30
  3    Thread 0x7ff508e35700 (LWP 1625) "python" 0x00007ff50eb57bb7 in epoll_wait (epfd=12, events=0x7ff508e341d0, maxevents=256, timeout=-1) at ../sysdeps/unix/sysv/linux/epoll_wait.c:30
  4    Thread 0x7ff503fff700 (LWP 1667) "python" 0x00007ff50e8276d6 in futex_abstimed_wait_cancelable (private=0, abstime=0x0, expected=0, futex_word=0x564f17c8aa80)
    at ../sysdeps/unix/sysv/linux/futex-internal.h:205
...[threads 5-6 like 4]...
  7    Thread 0x7ff5027fc700 (LWP 1690) "python" 0x00007ff50eb46187 in __GI___libc_write (fd=2, buf=0x7ff50967bc24, nbytes=85) at ../sysdeps/unix/sysv/linux/write.c:27
...[threads 8-13 like 4]...

Stack of thread 7:
Traceback (most recent call first):
  File "/usr/lib/python2.7/logging/__init__.py", line 889, in emit
    stream.write(fs % msg)
...[skipped useless lines]...

And this code (I guess the code of logging __init__ function):
 884                                #the codecs module, but fail when writing to a
 885                                #terminal even when the codepage is set to cp1251.
 886                                #An extra encoding step seems to be needed.
 887                                stream.write((ufs % msg).encode(stream.encoding))
 888                        else:
>889                            stream.write(fs % msg)
 890                    except UnicodeError:
 891                        stream.write(fs % msg.encode("UTF-8"))
 892                self.flush()
 893            except (KeyboardInterrupt, SystemExit):
 894                raise

Stack of the rest threads is similar -- waiting for GIL:
Traceback (most recent call first):
  Waiting for the GIL
  File "/usr/lib/python2.7/threading.py", line 174, in acquire
    rc = self.__block.acquire(blocking)
  File "/usr/lib/python2.7/logging/__init__.py", line 715, in acquire
    self.lock.acquire()
...[skipped useless lines]...

Its written that package logging is multithreaded without additional locks. So why does package logging may deadlock? Does it open too many file descriptors or limit anything else?
That's how I initialize it (if it is important):
def get_logger(log_level, file_name='', log_name=''):
    if len(log_name) != 0:
        logger = logging.getLogger(log_name)
    else:
        logger = logging.getLogger()
    logger.setLevel(logger_state[log_level])
    formatter = logging.Formatter('%(asctime)s [%(levelname)s][%(name)s:%(funcName)s():%(lineno)s] - %(message)s')

    # file handler
    if len(file_name) != 0:
        fh = logging.FileHandler(file_name)
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

    # console handler
    console_out = logging.StreamHandler()
    console_out.setLevel(logging.DEBUG)
    console_out.setFormatter(formatter)
    logger.addHandler(console_out)
    return logger

A: Problem was because I've been writing output to console & to file, but all those processes were initialized with redirection to pipe, which was never listened.
            p = Popen(proc_params,
                      stdout=PIPE,
                      stderr=STDOUT,
                      close_fds=ON_POSIX,
                      bufsize=1
                      )

So it seems pipes in this case have it's buffer size limit, and after filling it deadlocks.
Here the explanation: https://docs.python.org/2/library/subprocess.html
Note

Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume. Use Popen with the communicate() method when you need pipes.

It's done for functions which I don't use, but it seems valid for Popen run, if then you don't read out the pipes.


text:
Q: Can two feature classes share geometry and have different attributes with ArcGIS Desktop? Is there a way for two feature class (say parent and child) to share same geometry shape but have their own set of attributes?
Features created or updated on parent feature class transfer its geometry shape to child feature class but not any of its attributes.
Both of feature class will be in same GDB and its storage type is SDE.ST_Geometry.
ArcGIS 10.3, Oracle RDBMS: 12.1.0.2


text:
Q: What is rwfs filesystem? I did a df on my embedded device and saw that the one of the filesystems mentioned was rwfs. What is rwfs ?
df
Filesystem           1k-blocks      Used Available Use% Mounted on
rwfs                     32768       312     32456   1% /var

A: Google helps here... rwfs filesystem
http://code.google.com/p/leviathanv/wiki/RWFS
To quote...

RWFS is a filesystem specifically designed to hold large amounts of data(500 Million EB). It accomplishes this by add further dividing disks into large blocks called blocksections. Their size is determined by the block size used

A: It's a tmpfs instance, as the output of mount will have told you.


text:
Q: I would like to create a pin-code dialogue, like the one you can switch on to dial on the iPhone I am new to coding and would like to set this up in my app. How or where do you start this process... In you AppDelegate file? Please provide me a jump start. I'm invoking this process from the UIButtonTypeInfoDark on the NavgationBar/TabBar Controller from the MainWindow. I am basically trying to set up a 4 digit pin to protect the users privacy within the app. I would like to create a pin-code dialogue, like the one you can switch on to dial on the iPhone.

A: you can use a text field, and set its keyboard type to "number pad"


text:
Q: Multivalued Dependencies For a Relational Schema
Teaching(Course,Books,Lecturer)
Hows Course →→ Books and Course →→ Lecturer multivalued dependencies?
For a particuar Course we cannot be sure about the book name! As many books are possible! So hows it a FD in first case?

A: These are not functional dependencies but multivalued dependencies (they are usually denoted with a double-headed arrow). Course -->---> Books means that once the course has been fixed all lecturers should use all books, i.e., whenever (L1,B1) and (L2,B2) correspond to a certain course, so should (L2,B1) and (L1,B2).
Course -->---> Books trivially implies Course -->---> Lecturer since both of them refer to the same pair of books and lecturers. In general, whenever X -->--> Y it also holds that X -->--> R-Y where R is the set of all attributes.


text:
Q: POST request via urllib/urllib2? Before you say anything, I've looked around SO and the solutions didn't work. I need to make a post request to a login script in Python. The URL looks like http://example.com/index.php?act=login, then it accepts username and password via POST. Could anyone help me with this?
I've tried:
import urllib, urllib2, cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )

login_data = urllib.urlencode({'username' : '[redacted]',
                               'password' : '[redacted]'
                               })

resp = opener.open('http://[redacted].org/index.php?act=login', login_data)
print resp.read()
resp.close()

and a little bit modified:
import urllib, urllib2, cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )

login_data = urllib.urlencode({'act' : 'login',
                               'username' : '[redacted]',
                               'password' : '[redacted]'
                               })

resp = opener.open('http://[redacted].org/index.php', login_data)
print resp.read()
resp.close()

A: You will probably need to look at the HTML source to find out what the login form action URL is. Sometimes it is the same as the page URL itself, but it's probably different. But since you haven't shown actual URLs, we can't help you there.
The <form> element might look something like:
<form method="POST" action="/do_login">

In that case, you would use /do_login in your POST url.


text:
Q: adding object to class I'm trying to add an object to a vector, but it's not working.
Code:
class GameClass{
public:
        void makeNewPlayer(int isItBad){
            if (isItBad==0){
                goodPlayers.push_back(PlayerClass());
            }
        }
private:
        vector<PlayerClass> badPlayers;
        vector<PlayerClass> goodPlayers;
};

class PlayerClass{
public:
    PlayerClass(int badStatus){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }

   void setMyLocation(int x, int y){
    myLocation[0]=x;
    myLocation[1]=y;
    }
    void getMyLocation(int *targetLoc){
    targetLoc[0]=myLocation[0];
    targetLoc[1]=myLocation[1];
    }
private:
    int myLocation[2];
    int isBad=1;
};

Error

no matching function for call to 'PlayerClass::PlayerClass()'|

From this line:
     goodPlayers.push_back(PlayerClass());

edit:
how can i make it default constructor???

A: You get that error because you do not have a default constructor.. You have a custom constructor hence the default constructor is not automatically supplied.
So you need to pass a value for badstatus something like:
goodPlayers.push_back(PlayerClass(4));

You can make default by making the badstatus as default argument, example:
PlayerClass(int badStatus=4){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }

Now even if you don't supply the argument of 4, it will work fine.. Give the badstatus a default value.
Suggestion: Always ensure that the default constructor is there for the class. Even if you forgot to pass in the argument, you can still instantiate the object from the class.
In your case, instead of setting int isBad=1; change to int isBad; and add the "=1" to
PlayerClass(int badStatus=1){
        myLocation[0]=rand()%(N-2)+1;
        myLocation[1]=rand()%(N-2)+1;
        isBad=badStatus;
    }


text:
Q: Why does potion level 128 give some potions weird effects? In Minecraft, some potion effects seem to get weird effects if you use level 128.
This seems to happen with:

*

*Haste, some block will be insta-mined, some blocks are unable to be mined. The hand-swing animation is also very slow.

*Mining Fatigue, while you can't mine anything like with level 127, the hand-swing animation is gone.

*Jump boost, you are unable to jump.

*Regeneration, it seems much slower then level 127.

*Wither, it seems much slower then level 127.

*Levitation, it seems to increase gravity. As soon as you jump or fall, you are much faster on the ground then normal.

Why does potion level 128 give some potions weird effects and why doesn't it happen with all potions?

A: Each potion effect is handled differently, but the important thing to note is storage size.
Internally the amplifier is stored as an integer (minimum of -2,147,483,648, maximum of 2,147,483,647), but when writing the amplifier to NBT it gets saved as a byte (minimum of -128, maximum of 127). If the value provided is outside of that range, it will be forced back into that range.
As such, when attempting to set the amplifier via NBT (e.g. with /give or /summon), you are restricted to that range and trying to exceed 127 will cause it to overflow to negative values (128 becomes -128). You cannot achieve an amplifier of 128 with NBT.
But the /effect command doesn't go through NBT to assign an effect. It directly sets the amplifier (which is stored as an integer) and is allowed to exceed the maximum. However, if the entity is saved to NBT, the effect is saved which will cause the value to overflow appropriately, potentially changing what the effect does due to the negative value.

When attempting to use /effect to apply a higher amplifier than 127 on a player, the client is sent an amplifier typecasted to byte via the SPacketEntityEffect packet, which reduces the amplifier into the byte range. The client and server are fighting over what the value is meant to be.
For example, with the following:
/effect @p minecraft:levitation 1 255

The server says "255" (since it's saved internally as an integer) but the client is saying "0" (since it's sent via packet as a byte). The result is the client seeing itself not moving. Some issues come as a result, such as taking damage will cause the player to shoot high into the air in an attempt to resync.
This is what causes oddities with players, but this doesn't work the same way with non-player entities. Their amplifier is internally stored as an integer and no packets are interfering, allowing the server full control. If the entity is saved to NBT, such as by chunk unloading, the effect will then overflow into byte range:
/effect @e[type=Creeper,c=1] minecraft:levitation 1 255


text:
Q: Setting UISearchBar's search field background image changes the padding When I set a search field background image on a UIImage, the padding between the magnifying glass and placeholder text in the search bar when selected changes.
With the default background:

With a custom background:

This change is caused by these two lines:
UIImage *colorImage = [UIImage imageWithColor:[UIColor grayColor] size:CGSizeMake(28, 28)];
[self setSearchFieldBackgroundImage:[colorImage imageWithRoundedCorners:5] forState:UIControlStateNormal];

imageWithRoundedCorners: is a category method that simply draws the image onto a CALayer with a corner radius and then creates a UIImage from the graphics context.
Why is this and how can I avoid this? I tried passing an explicitly resizable image, but that had no effect.

A: Its odd that it resets it, however you can use something like this to set it to your liking after setting the background image. searchTextPositionAdjustment is a property on UISearchBar and works perfectly. 8.0 seems to be the default, but you could set it to whatever you like.
[self.searchBar setSearchFieldBackgroundImage:[self imageWithColor:[UIColor grayColor] andSize:CGSizeMake(28.0, 28.0)] forState:UIControlStateNormal];
[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(8.0, 0.0)];

A: For all those now using Swift, you can use the following code (works in Swift 2)
let searchBarBackground = UIImage.roundedImage(UIImage.imageWithColor(UIColor.whiteColor(), size: CGSize(width: 28, height: 28)),cornerRadius: 2)
searchBar.setSearchFieldBackgroundImage(searchBarBackground, forState: .Normal)
searchBar.searchTextPositionAdjustment = UIOffsetMake(8.0, 0.0)

Use this with an extension to UIImage:
extension UIImage {
     class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    class func roundedImage(image: UIImage, cornerRadius: Int) -> UIImage {
        let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: image.size)
        UIGraphicsBeginImageContextWithOptions(image.size, false, 1)
        UIBezierPath(
            roundedRect: rect,
            cornerRadius: CGFloat(cornerRadius)
        ).addClip()
        image.drawInRect(rect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

To give something looking like this:

A: Updated solution for Swift 4
searchTextPositionAdjustment = UIOffset(horizontal: 8.0, vertical: 0.0)


text:
Q: VS2013.4 CTP2 TypeScript version? What version of TypeScript comes with VS2013.4 CTP2? And is there some way I can find out without having to install the update?

A: I should still be 1.0.x (probably 1.0.3) as the 1.1 release isn't yet available (and is a major compiler rewrite that will give performance gains).
Of course, if someone has already downloaded it, they will be able to confirm this or supply a corrected answer.


text:
Q: Align the column with minus in in bmatrix I am struggling with aligning the bmatrix with the minus symbol - it should look like in the picture
\begin{equation}
\begin{bmatrix}
  X_1 \\
  X_2 \\
\end{bmatrix}
= - \frac{1}{\xi_{11}\,\xi_{22} - \xi_{21}\,\xi_{12}}
\begin{bmatrix}
   \,\xi_{11} & \phantom{-}\xi_{12} \\
   \phantom{-}\xi_{21} & \,\xi_{22} \\
\end{bmatrix}
\begin{bmatrix}
  \xi_{10} \\
  \xi_{20} \\
\end{bmatrix}
\end{equation}

A: You mean like this? bmatrix has a starred version from mathtools package which accepts alignment options, here we chose [r]. Another solution is to use an array with [rr] alignments and manually add the brackets.
\documentclass[12pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}

\begin{equation}
\begin{bmatrix}
  X_1 \\
  X_2 \\
\end{bmatrix}
= - \frac{1}{\xi_{11}\,\xi_{22} - \xi_{21}\,\xi_{12}}
\begin{bmatrix*}[r]
    \xi_{11} & -\xi_{12} \\
   -\xi_{21} &  \xi_{22} \\
\end{bmatrix*}
\begin{bmatrix}
  \xi_{10} \\
  \xi_{20} \\
\end{bmatrix}
\end{equation}

\end{document}

A: There is also another choice to align your matrix with the minus symbol -, using spalign package with the option [r] (right). \spaligndelims{[}{]}\spalignmat[r]{....;....} is as a subsostitute of bmatrix in this case.

\documentclass[a4paper,12pt]{article}
\usepackage{spalign}
\begin{document}
\[\spaligndelims{[}{]}\spalignmat[r]{X_1; X_2}=-\frac{1}{\xi_{11}\xi_{22}-\xi_{21}\xi_{12}}
\spaligndelims{[}{]}\spalignmat[r]{\xi_{11} -\xi_{12}; -\xi_{21}  \xi_{22}}\spalignmat[r]{\xi_{10} ;  \xi_{20}}\]
\end{document}


text:
Q: Connection Pool Limit reached in NHibernate I'm having problem trying to get a correctly handled lifetime of my unit of work ( think it's an issue with my UoW anyway) for an MVC app using NHibernate. There is a chance for multithreading so it also needs to account for that. I decided to try and let NHibernate manage the connection instead of doing it in my Dependency Injector (StructureMap) but now I'm hitting problems with the Connection Pool limit being reached.
I've simplified some of this for posting the code but hopefully it will help to see what I'm missing...
NHibernate Config
var cfg = new Configuration()
    .DataBaseIntegration(x =>
    {
        x.ConnectionStringName = "ApplicationConnectionStringName";
        x.Dialect<CustomMsSql2008Dialect>(); //Inherits from MsSql2008GeographyDialect
        x.IsolationLevel = IsolationLevel.RepeatableRead;
        x.BatchSize = 100;
    })
    .CurrentSessionContext<WebSessionContext>()
    .Cache(c =>
    {
        c.Provider<SysCacheProvider>();
        c.UseQueryCache = true;
    });

Unit Of Work
public class NHibernateUnitOfWork : INHibernateUnitOfWork
{
    private ITransaction transaction;
    private bool isDisposed;
    private readonly ISessionFactory source;

    public NHibernateUnitOfWork(ISessionFactory source)
    {
        this.source = source;
        VerifyIsNotDisposed();
        if (CurrentSessionContext.HasBind(source))
        {
            CurrentSession = source.GetCurrentSession();
            this.transaction = CurrentSession.Transaction;
        }
        else
        {
            CurrentSession = this.source.OpenSession();
            CurrentSessionContext.Bind(CurrentSession);
            BeginNewTransaction();
        }
    }

    public ISession CurrentSession { get; private set; }

    public void Commit()
    {
        VerifyIsNotDisposed();
        this.transaction.Commit();
        BeginNewTransaction();
    }

    private void BeginNewTransaction()
    {
        if (this.transaction != null)
        {
            this.transaction.Dispose();
        }
        this.transaction = CurrentSession.BeginTransaction();
    }

    public void Rollback()
    {
        VerifyIsNotDisposed();
        this.transaction.Rollback();
        BeginNewTransaction();
    }

    private void VerifyIsNotDisposed()
    {
        if (this.isDisposed) throw new ObjectDisposedException(GetType().Name);
    }

    public void Dispose()
    {
        if (this.isDisposed) return;
        this.transaction.Dispose();
        CurrentSessionContext.Unbind(this.source);
        CurrentSession.Dispose();
        this.isDisposed = true;
    }
}

request Begin and End handlers via StructureMap
public class StructureMapScopeModule : IHttpModule {
    public void Dispose() {
    }

    public void Init(HttpApplication context) {
        context.BeginRequest += (sender, e) =>
        {
            StructuremapMvc.StructureMapDependencyScope.CreateChildContainer();
            var unitOfWork = StructuremapMvc.StructureMapDependencyScope.Container.GetInstance<IUnitOfWork>();
        };
        context.EndRequest += (sender, e) => {
            var unitOfWork = StructuremapMvc.StructureMapDependencyScope.Container.GetInstance<IUnitOfWork>();
            unitOfWork.Commit();
            HttpContextLifecycle.DisposeAndClearAll();
            StructuremapMvc.StructureMapDependencyScope.DisposeChildContainer();
        };
    }
}

Running a query to get the connection count right now gives almost 125 connections.

A: Please dispose off all the open connection, that is generally the reason for pool limit reached...
also implementing IDisposable correctly is not as simple as it seems... below is the sample implementation that I am using (copied it from the answers on SO)
using System;

namespace AlgoSys.Common.SharedUtils
{
    public abstract class Disposable : IDisposable
    {
        private bool _disposed;

        // Dispose() calls Dispose(true)
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // NOTE: Leave out the finalizer altogether if this class doesn't
        // own unmanaged resources itself, but leave the other methods
        // exactly as they are.
        ~Disposable()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        // The bulk of the clean-up code is implemented in Dispose(bool)
        protected virtual void Dispose(bool disposing)
        {
            if(_disposed) return;

            if (disposing)
            {
                OnDispose();
            }

            _disposed = true;
        }

        protected abstract void OnDispose();
    }
}

great that you tested it before commenting... putting the comment as answer.


text:
Q: Analog Vref for ADC on STM's Blue-Pill I am piecing together my own ADC example for STM's blue-pill module by reading the reference manual (btw I an inexperienced in embedded development).
The code outline so far is:
void do_adc(void)
{
    unsigned int ra;
    ra=GET32(ADC_CR2);

    ra|=1;   // ADON
    PUT32(ADC_CR2, ra);

    // wait for EOC flag
    while ((GET32(ADC_SR) & 0x02) == 1)
    {
        led_blink();
    }

    ra = GET16(ADC_DR);

    PUT32(USART1_DR,ra);
    sleep();

    PUT32(USART1_DR,'\r');
    sleep();
    PUT32(USART1_DR,'\n');
    sleep();
}

int notmain(void)
{

    init_led_adc_and_uart();
    disable_adc();
    calibrate_adc();
    enable_adc();
    while (1)
    {
        led_blink();
        do_adc();
    }
}

I have written code for each of those functions which most probably is not correct, but that's not the question at the moment.  I am still wondering where the Vref pin on the blue-pill; based on this diagram, is?
If my understanding is correct, then I would connect a temperature sensor to physical pin 10 (aka ADC channel 0), ensure that sensor has a voltage of ~3.3v.  Then for reference, connect the same input somewhere on the blue-pill so it can do the conversion.
However based on the diagram I linked, I am not sure where the analog referene is?
Btw: I flashed my code onto the chip and the led continuously blinks, so the code is probably fine, but I need to workout the connections!

A: There isn't one in a 48 pin package, it's too small to have extra functions like that. Even the 64 pin doesn't have one, only when you get to 100 do they include the ref pins.

They do have an internal reference, you'll have to configure it.

Sources: https://www.st.com/resource/en/datasheet/cd00161566.pdf


text:
Q: Functional equaliton on continuous function $f:[0,1]\to \mathbb{R}$ Let $f:[0,1]\to \mathbb{R}$ be continuous, and suppose that $f(0)=f(1).$ Show that there is a value $x\in [0, 1998/1999]$ satisfying $f(x)=f(x+1/1999)$.

A: Hint: examine the sign of the function$$g(x)=f(x+1/1999)-f(x)$$ on that domain and use the intermediate value theorem.


text:
Q: How to prevent Mouse Scroll in ToolStripComboBox? I am trying to disable Mouse Scroll in my ToolStripComboBox, I thought I can catch the Mouse Wheel event, but while the event is available for ComboBox, it is not available instead for the ToolStripComboBox. Any ideas?

A: The ToolStripComboBox helpfully exposes its underlying ComboBox control in its aptly named ComboBox property. This allows us to access its properties, methods, and events that were not been wrapped into the ToolStripComboBox.
And, as you probably know, the standard ComboBox control exposes a MouseWheel event that fires each time the mouse wheel is scrolled while the combo box has focus.
Putting these two things together, we can add a handler for the ToolStripComboBox control's underlying ComboBox control's MouseWheel event, and override its default behavior.
So, assuming you have a form that contains a ToolStrip and a ToolStripComboBox, you can use something like the following code:
public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();

      //Attach a handler for the MouseWheel event
      ToolStripComboBox1.ComboBox.MouseWheel += new MouseEventHandler(ToolStripComboBox_MouseWheel);
   }

   private void ToolStripComboBox_MouseWheel(object sender, MouseEventArgs e)
   {
      //Cast the MouseEventArgs to HandledMouseEventArgs
      HandledMouseEventArgs mwe = (HandledMouseEventArgs)e;

      //Indicate that this event was handled
      //(prevents the event from being sent to its parent control)
      mwe.Handled = true;
   }
}

Alternatively, of course, you could always subclass the existing ToolStripComboBox control and override its behavior there in the same way shown above.

A: In addition to what Cody Gray suggested you may want the wheel scolling to work when the combobox is dropped. Just chech the DroppedDown state in MouseWheel handle:

    public class MyToolStripComboBox : ToolStripComboBox
    {
        public MyToolStripComboBox()
        {
            this.ComboBox.MouseWheel += new MouseEventHandler(ComboBox_MouseWheel);
        }

        void ComboBox_MouseWheel(object sender, MouseEventArgs e)
        {
            if (!this.ComboBox.DroppedDown)
                ((HandledMouseEventArgs)e).Handled = true;
        }
    }

Scrolling dropped combobox with wheel doesn't change the selection, so it works as expected


text:
Q: Problems with defining UPLOADS constant I have a custom Wordpress file-structure like
web-root:

*

*content (folder)

*

*uploads (folder)

*plugins (folder)

*themes (folder)
... and so on

*wordpress (folder)

*

*wp-admin (folder)

*wp-includes (folder)
... more folders

*wp-blog-header.php

*wp-load.php

*wp-login.php
... and all other wp core files

.htaccess
index.php
wp-config.php
In my wp-config.php I have to define the path to my custom uploads folder like this:
if (!defined('UPLOADS')) {
    define('UPLOADS', '../content/uploads');
}

More or less out of nothing (maybe I updated the wp core) when trying to upload an image I get the error message saying: can't create folder check if parent folder is writeable.
BUT: if I put the same code into the wp-blog-header.php file uploading and building new folders within the upload folder works.
I thought using DEFINE(in my case) means that I just save a string value to a constant and where ever I use the constant the value is the same. But how can it be that there is a difference when defining a constant in wp-config.php or wp-blog-header.php? (which is inside the subfolder wordpress .
For my changes in wp-blog-header.php would disappear after the next Wordpress update I obviously can't solve it that way.
Any ideas what the problem could be?

A: (Converting my comment to an answer.)
Since you store themes and plugins in that folder as well, try setting the WP_CONTENT_DIR constant instead. (Always prefer absolute paths when possible.)
As to your specific case, why it worked in one file but not in another - this will probably involve more debugging, checking where exactly WP uses which constant, etc. If setting WP_CONTENT_DIR solves your problem, remove UPLOADS and work with it.


text:
Q: PCB exposure problems - can't get the board to develop This is my first time making a PCB, and I ran into a wall.  I have a design printed on two transparencies (with a laser printer), taped together; I've also done UV exposures in a commercial box-thing for (ridiculously) long times (i.e. 6-13 min), as well as the shorter recommended times.  Whenever I put the board into a 1% NaOH solution after exposure, nothing happens (agitating and brushing don't help), even after several minutes.  I thought there might be a problem with the UV exposure, so I drew something directly onto a board with a dry-erase marker and repeated the process; it worked.  The boards and equipment are new, and I make a fresh solution each time.  I'm really sorry if this is an obvious problem, but I haven't been able to work it out! Any suggestions are appreciated!

A: This works
Carry out the basic check in my comments - added at end as a note.
Once you know the board isn't upside down, that the developer is OK and that the resist "sort of works" but want to zero in on best exposure time, do as follows.
Note that this test is for exposure times of 1 2 4 8 16 & 32 "time units".
If each count is a second the totals are in seconds.
Scale as desired.
Adding extra steps is easy -  follow the pattern.
See image at end.
The digram MAY be slightly hard on the brain until you get the point.
There is a single test strip of photo sensitive board covered by an UNMOVING strip of exposed / dark resist material.
The whole strip is the size and shape of the green rectangle at bottom (scale dimensions to suit - this large is far too wasteful).
Start at top.
Row A is one exposure scenario.
Place an opaque (here = black) cover over the whole strip except trhe left hand end.
Expose for 16 time units (I'll say seconds from now on).
The left hand square has had 16 seconds exposure. All others = 0.
Pull the opaque strip one square right  = scenario B
Expose for 8 seconds.
The 1st squarte has now had 16+8 = 24 seconds.
The second has had 8 seconds.
Pull the opaque strip one square right  = scenario C
Expose for 4 seconds.
The 1st square has now had 16+8+4 = 28 seconds.
The second has had 8+4 = 12 seconds.
The 3rd has had 4 seconds.
Lather, wash, rinse, repeat ...
30 14 6 2
Again
31 15 7 3 1
This is starting to look familiar.
Finally
32 16 8 4 2 1 seconds.
Binary progression.
Develop.
Report back.
Image:

*

*Green rectangle is actual strip used.

*A B C D E F are subsequent exposure scenarios.

*Black opaque layer is pulled right by one square per exposure.

*Red numbers are cumulative exposure that each square has received.

FWIW: This is how one used to check basic photo exposure needs in the darkroom long long long ago before these newfangled digital cameras came along. I'm not complaining, mind

Notes: (From my prior comments)
Occam says the UV is getting through your photo resist in the exposure times used.
(Or you had the board upside down in the other cases.
You do not say how long you exposed the marker version for.
SO - Get some sure to be opaque material and
cover several places in a strip of darkened resist.
Expose for a small time - no more than correct time.
Develop.
If opaque material blocks UV but not where there is only "resist" you need to recalculate.
Consider: How do you know strength of light used compared to that in instructions –  it sounds like it's stronger than you are expecting.


text:
Q: C# Entity Foreign Key to List Array I have a class PromoCard and List<PromoCard> PromoCards. Is it possible to map element of List array in Entity Model?
This is my List:
public static List<PromoCard> PromoCards = new List<PromoCard>
{
    new PromoCard()
    {
        Id = 1,
        Crystal = 4500,
        Price = 100
    },
    new PromoCard()
    {
        Id = 2,
        Crystal = 24000,
        Price = 500
    },
    new PromoCard()
    {
        Id = 3,
        Crystal = 50000,
        Price = 1000
    },
};

public class PromoCard
{
    [Key]
    public int Id { get; set; }
    public int Crystal { get; set; }
    public int Price { get; set; }
}

And this is my model:
public class BonusCard
{
    [Key]
    public int Id { get; set; }
    public string User_id { get; set; }
    [ForeignKey("User_id")]
    public virtual ApplicationUser User { get; set; }
    public int PromoCard_id { get; set; }
    // is there way to link
    [ForeignKey("PromoCard_id")]
    public virtual PromoCard PromoCard { get; set; }
}

A: All I had to was change the getter of PromoCard property and put NotMapped Annotation on it
public class BonusCard
{

    [Key]
    public int Id { get; set; }
    public string User_id { get; set; }
    [ForeignKey("User_id")]
    public virtual ApplicationUser User { get; set; }
    public string Code { get; set; }
    public DateTime CreationDate { get; set; } = (DateTime)SqlDateTime.MinValue;
    public DateTime UsageDate { get; set; } = (DateTime)SqlDateTime.MinValue;
    public int? Player_id { get; set; } = null;
    [ForeignKey("Player_id")]
    public virtual Player Player { get; set; }
    public int PromoCard_id { get; set; }
    [NotMapped]
    public  PromoCard PromoCard { get { return PromoCards[PromoCard_id]; } set { } }
}


text:
Q: Not able to access response from promise function into a variable which can be passed to another function     function getToken()
    {
     return axios.request({
        url: "/xyz",
        method: "post",strong text
        baseURL: "https://api.testing.in/api/xyz",
        data: {
        "ClientKey" : "xyz",
        "ClientSecret" : "xyz"
        }
      }).then(response => {
        // tokeniw=response.data.accessToken
        // console.log('Check data inside then :' + tokeniw)
        // return tokeniw;
        this.response = response.data
        return response.data.accessToken
      })
    }

Here , i want to put response.data.accessToken into a variable outside this function

A: I would rewrite the code and call it as:
function getToken() {
    return new Promise((resolve, reject) => {
        axios.request({
            url: "/xyz",
            method: "post",
            baseURL: "https://api.testing.in/api/xyz",
            data: {
                "ClientKey": "xyz",
                "ClientSecret": "xyz"
            }
        })
            .then(response => resolve(response.data.accessToken))
            .catch(e => reject(e))
    })
}

const token = await getToken();


text:
Q: can i swap individual words in a text area? I have a text are that displays some user inputted text, what i aim to do is a simple translation?
For example could i swap all uses of the word dog for cat?
There will be lots of words to do, so would there be a quicker way using php, html or another language to do this, maybe streamwriter/reader?
this is the box that will show what the user has inputted:

<form method="GET" action="translate.php">
<textarea name="status2" cols="50" rows="5"<input type="text"/>
<?php echo $status ?>
</textarea>

<input type="submit" value="post to wall" />
</form>

any help or ideas would be greatly appreciated.
Unrelated Note: The past couple of questions i have posted did not initially let me post as they did not meet the quality standards, where can i find the quality standards?

A: PHP can handle this easily.
<?php echo str_replace('dog','cat',$status); ?>

First word is item to search for, second word is what to replace it with, third item is what to search within.
EDIT
As requested, an example of how to make it usable for a lot of items and not case-sensitive. First, make a PHP function:
function replaceWords($existing,$new,$content){
    str_ireplace($existing,$new,$content);
}

Then make arrays for all the words to find and all the words to replace (with the same order):
$existing_array = array('dog','elephant','bird');
$new_array = array('cat','eagle','your mom');
// dog replaced with cat, elephant replaced with eagle, bird replaced with your mom

Then use a for loop to call the function:
for($i = 0; $i < 150; $i++){
    function replaceWords($existing_array[$i],$new_array[$i],$status);
}

I did 150 because you said about that number, but the exact number of words should go there. That should do it.
More info can be found here.
SECOND EDIT
An even more automated for loop:
$cnt = count($existing_array); // you can use either array, since they're the same length
for($i = 0; $i < $cnt; $i++){
    function replaceWords($existing_array[$i],$new_array[$i],$status);
}

This way you just need to add items to the arrays, and the new word count will be the new length of the for loop. Less manual code the better.

A: If you use the below function, you can replace any work in a case in-sensitive manner:
str_ireplace ( "dog", "cat", $status );
If you want to replace multiple words, you can use arrays:
str_ireplace ( array('dog', 'mouse'), array('cat', 'hamster'), $status );
The array example will replace the words in the same index, e.g. dog will be replaced with cat, and mouse will be replaced with hamster.


text:
Q: Is it possible to install WordPress multisite in a Bitnami MAMP stack? I am using Bitnami's MAMP stack for local development of WordPress and MediaWiki in OSX, but I need one stack with WordPress multisite and MediaWiki installed. Bitnami's site has an installer for WordPress multisite (http://bitnami.org/stack/wordpress) but that is for a standalone stack, the only module they have there is for regular WordPress. Just enabling multisite in wp-config on that install does not work.
Is there anyway to accomplish this? Could I do a standalone install of WordPress Multisite, move it into the MAMP stack's apps folder and set the appropriate mySQL settings in wp-config?

A: it is possible. Try to install the WordPress Multisite Stack and then the Mediawiki module on top of it. I hope it helps.

A: http://bitnami.org/stack/wordpress/ goto the Amazon Machine Images section. Select your region then click the ami link under Ubuntu EBS 32-bit


text:
Q: Datatable did not show dynamic data which i fetch from database in react js I have integrated datatable in my react js web app.
It works with sample data as i have mentioned in the code pagelist

I have tried to make it component but did not get the result. I am new
  in react and did not able to clue to further progress.

Here the list of my import packages
import axios from 'axios'
import React, {Component} from 'react'
import {BrowserRouter,Route,Switch,Link} from 'react-router-dom'
import { MDBDataTable} from 'mdbreact';

// The below call get the data as i have confirmed in the console log
axios.get('/api/pagelist').then(response => {

    var pagelist = JSON.stringify(response.data);
    console.log(pagelist);

});

//Sample test data which works with the example
var pagelist = [{
    name: 'Tiger Nixon',
    position: 'System Architect',
    office: 'Edinburgh',
    age: '61',
    date: '2011/04/25',
    salary: '$12320'
},
{
    name: 'Gavin Joyce',
    position: 'Developer',
    office: 'Edinburgh',
    age: '42',
    date: '2010/12/22',
    salary: '$92'
},
{
    name: 'Jennifer Chang',
    position: 'Regional Director',
    office: 'Singapore',
    age: '28',
    date: '2010/11/14',
    salary: '$357'
},
{
    name: 'Donna Snider',
    position: 'Customer Support',
    office: 'New York',
    age: '27',
    date: '2011/01/25',
    salary: '$112'
}
];

// Just copy the function and change columns as guided by the documentation
const DatatablePage = () => {
    const data = {
        columns: [{
            label: 'ID',
            field: 'id',
            sort: 'asc',
            width: 60
            },
            {
                label: 'Name',
                field: 'name',
                sort: 'asc',
                width: 150
            },

            {
                label: 'Title',
                field: 'title',
                sort: 'asc',
                width: 150
            },
            {
                label: 'Slug',
                field: 'slug',
                sort: 'asc',
                width: 100
            },
            {
                label: 'Content',
                field: 'content',
                sort: 'asc',
                width: 250
            },
            {
                label: 'Created',
                field: 'created_at',
                sort: 'asc',
                width: 100
            }
        ],
        rows: pagelist
    };
    return (

        <MDBDataTable striped bordered hover data = {data}/>
    );
}

//Finally exported it
export default DatatablePage;

A: Looks like a scoping issue to me.  The data variable you're storing the page data in is scoped to the axios callback.  Once the code leaves that callback, your data is no longer accessible.
axios.get('/api/pagelist').then(response => {

    // pageList scoped locally.  not accessible outside.  this is why the
    // console.log works, but there's no data in the table.
    var pagelist = JSON.stringify(response.data);
    console.log(pagelist);

});

Assuming you're using a component, I suggest adding a constructor and that you create a state property. E.g.
constructor(props) {
    super(props);

    this.state = {pageList: []} ;

}

You need to then update this in the axios.get....
axios.get('/api/pagelist').then(response => {

    // The below line may not be exactly correct.  May need to review.
    this.setState({pagelist: JSON.stringify(response.data)}, console.log("state updated));

});

Finally, the rows assignment in the datatables method needs to be
rows: this.state.pagelist


text:
Q: Install modx in a subfolder I like my webspace tidy :)
Therefore if my root-folder is html/ I would like to install modx (version 2.2) in the subdirectory html/modx/
For my website-visitors everything should be the same as if I would have installed modx in the root folder (html/).
I also don't want to do without friendly urls.
To make it even more difficult: I also really like the builtin modx file browser and I would love to use it for every file and folder in the document root (so every file inside html/* should be displayed).
(How) is this possible?
Additional question: if it is possible, is it better to reinstall modx in the subfolder or to move my installation to the new location (html/modx). As my installation is only a few days old, either option would be fine.

A: What version of MODx are you using?
Usually you would do an advanced installation (a separate version of MODx). You can move the existing MODx install to your sub-directory but you will need to update all of the config.core.php files and MODX_CORE_PATH constants to reflect this. You will also need to leave and update at least the index.php file in your web root directory. The config files that would need updating include:

*

*config.inc.php

*manager/config.inc.php

*connectors/config.inc.php

*core/config/config.inc.php

core/config/config.inc.php is the most important file and you will want to make sure ALL of the paths listed in there are correct.
The file browser will work fine providing you check all the URL and filesystem paths are correct in the Manager settings.

A: Change your .htaccess setting:
RewriteBase /subfoldername/

and install it as typically you do.


text:
Q: Ruby / Rails: Automate form submission and scrape page data So, I'm trying to create my own personal mint.com type application for local use only. So, I want it to login to my bank account, and grab my transaction history.
So far, I've tried to use the ruby mechanize gem. This doesn't seem to work, as the form from my bank uses javascript to alter the form and then submit. I found that waitr will execute the javascript properly, but it opens a browser window to perform this task, and as far as I know I would have to manually click save, then run a separate command to my rails app to parse the script once i've manually saved it.
I would much rather the script be able to login (by filling out form and executing javascript), navigate to page after logged in, click a radio button and then a submit button. If you were to do this yourself, you would then get a save dialog box. So, I'd need to somehow be able to save the file where the app would know where it is. From there, it would parse the csv file and create some nifty things with the data (that part I can handle).
Any help would be greatly appreciated.


text:
Q: How do i use java boolean condition in camel route? I am using camel to transfer files from one endpoint to another. I am starting multiple routes in which some routes need to decrypt the files. How can i make the unmarshal process optional in a specific route based on a boolean condition?
from(source)
    .choice()
    .when(isEncrypted())) //Java boolean value
    .unmarshal(decrypt(pgpEncryptionDetails))
    .endChoice()
to(destination);

PGPDataFormat decrypt(PGPEncryptionDetails pgpEncryptionDetails) {
    PGPDataFormat pgpDataFormat = new PGPDataFormat();
    pgpDataFormat.setKeyFileName(pgpEncryptionDetails.getPrivateKeyPath());
    pgpDataFormat.setPassword(pgpEncryptionDetails.getPassphrase());
    pgpDataFormat.setKeyUserid(pgpEncryptionDetails.getUserId());
    return pgpDataFormat;
}

I know how to do with a simple expression but here my condition not depends on exchange.

A: You can use a method call expression to call a method on a java bean which implements the predicate
public class Foo {
  public boolean isSomething(Object body) {
    ... return true or false
  }
}

And then use the method in the Camel route
when(method(Foo.class, "isSomething"))

A: Its working for me.
from(source)
    .process(exchange -> decryptIfEncrypted(pgpEncryptionDetails))
to(destination);

ProcessDefinition decryptIfEncrypted(PGPEncryptionDetails pgpEncryptionDetails) {
    if (isPgpEncryped()) {
        PGPDataFormat pgpDataFormat = new PGPDataFormat();
        pgpDataFormat.setKeyFileName(pgpEncryptionDetails.getPrivateKeyPath());
        pgpDataFormat.setPassword(pgpEncryptionDetails.getPassphrase());
        pgpDataFormat.setKeyUserid(pgpEncryptionDetails.getUserId());
        return new ProcessDefinition().unmarshal(pgpDataFormat);
    }
    return new ProcessDefinition();
}


text:
Q: Silverstripe $searchable_fields over a $has_one, then a $many_many relationship In Silverstripe V2 it was possible to create searchable fields that spanned across relationships such as Obj1.Obj2.Obj3.Obj3Field but now in V3 this produces the following error...
[User Error] Uncaught LogicException: relation can't be called on an UnsavedRelationList.
GET /zz_silverstripe_default/admin/mymodeladmin/
Line 391 in C:\xampp\htdocs\zz_silverstripe_default\framework\model\UnsavedRelationList.php
Source
390     public function relation() {
391         throw new LogicException(__FUNCTION__ . " can't be called on an UnsavedRelationList.");
392     }
Trace
UnsavedRelationList->relation(EndObject)
DataObject.php:3009
DataObject->relObject(MiddleDataObjects.EndObject.Name)
DataObject.php:2285
DataObject->scaffoldSearchFields()
DataObject.php:2230
DataObject->getDefaultSearchContext()
ModelAdmin.php:173

The code to reproduce this is...
class MyModelAdmin extends ModelAdmin {
    static $managed_models = array('RootDataObject');
    static $url_segment = 'mymodeladmin';
    static $menu_title = 'MyModelAdmin';
    static $model_importers = array();
}

class RootDataObject extends DataObject {
    private static $db = array('Name' => 'Varchar(255)');
    private static $has_many = array('MiddleDataObjects' => 'MiddleDataObject');
    static $searchable_fields = array('MiddleDataObjects.EndObject.Name');
}

class MiddleDataObject extends DataObject {
    private static $db = array('Name' => 'Varchar(255)');
    private static $has_one = array('RootDataObject' => 'RootDataObject');
    private static $many_many = array('EndDataObjects' => 'EndDataObject');
}

class EndDataObject extends DataObject {
    private static $db = array('Name' => 'Varchar(255)');
    private static $belongs_many_many = array('OtherDataObjects' => 'OtherDataObject');
}

I've uploaded this code to http://pastebin.com/QBfU8Fub with more white space and some php tags to make it easier to reproduce this issue.  I'm after essentially the previous behaviour to work so I do not have to keep writing search contexts and filters manually to do something I've come to expect from this nice CMS.

A: This is a bug in the UnsavedRelationList object in the SilverStripe framework code.
Here is another user with this issue:
https://github.com/silverstripe/silverstripe-widgets/issues/123
There is a fix for this:
https://github.com/silverstripe/silverstripe-framework/pull/5348
However, this update won't be released until SilverStripe 3.4 / SilverStripe 4.0.


text:
Q: 2.16: Multitasking apps may only use background services for their intended purposes: VoIP etc I created an iBeacon app to detect beacons using phonegap/cordova.  How the app works is that once it detects a nearby beacon and the app is closed or running in the background i use local notification which includes an audio (common apple notication sound).  I don't know why apple rejects it with the below comment:

2.16: Multitasking apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion, local notifications, etc.
  Next Steps
  The audio key is intended for use by applications that provide audible content to the user while in the background, such as music player or streaming audio applications. Please revise your app to provide audible content to the user while the app is in the background or remove the "audio" setting from the UIBackgroundModes key.
  Your app does not provide continuous streaming audio. For details on delivering an audible alert for a local notification, please refer to the About Local and Remote Notifications Programming Guide.
  We hope you will consider making the necessary changes to be in compliance with the App Store Review Guidelines and will resubmit your revised binary.

A: Apple's comment is quite clear. Your app is incorrectly specifying that it needs the audio background mode. But it doesn't. That mode is only to be used to play audio (such as music) while the app is in the background. It is not to be used just to get audio from a local notification.
Remove the audio background mode setting from your app and Apple will be happy.

A: Even our App received a rejection last week for the same reason.
We didn't even need to submit a new binary. All we did was explained to the reviewer why we were using each of the background modes which we had listed in our plist. We did this by uploading a video in which we explained the purpose of each background mode. And then provided a link of this video in the resolution centre in iTunes connect. The reviewer had a look at it and later approved our app.
So you have to do a similar thing. If you need the background mode(audio in your case). Just explain it's intended purpose to the reviewer in the resolution centre. Else, just upload a new binary with the audio background mode removed from the plist.


text:
Q: Cannot read property "value" of undefined when selecting KeyboardDateTimePicker I'm using keyboard date time picker and this is the code I am trying to select starting and ending date:
Switch
const handleChange = (field, e, value) => {
let val = null
switch (field) {
   case "timeStart":
     val = DateUtil.toString(DateUtil.toUtc(new Date(e.target.value)))
     console.log("timeStart", e.target.value, val, DateUtil.toString(DateUtil.fromUtc(new Date(val))))
     setState({...state, timeStart: val})
     setErrorz({...errorz, timeStart: requiredValidation("Start Date", val)})
     break;
        }

This is how I call them
 <FormControl fullWidth error={errorz.timeStart !== ""} className={classes.formControl}>
       <KeyboardDateTimePicker
       id="timeStart"
       value={DateUtil.toString(DateUtil.fromUtc(new Date(state.timeStart)))}
       onChange={(e) => handleChange('timeStart', e)}
       inputVariant="outlined"
       format={DateUtil.FORMAT}
       label={t('event.startdate')}
       error={errorz.timeStart !== ""}
       onError={console.log}
       InputLabelProps={{
       shrink: true
       }} />

But after I try to pick a starting or ending date, I get an error Cannot read property "value" of undefined.
If I delete e.target.value the date I select is returning back to completely something else, if I pick October 5th, it returns, April 17th.

A: In React synthetic events are pooled and typically quickly nullified and returned to the pool for reuse. Since the console log isn't completely synchronous you should save the events value before using it in callbacks.
const { value } = e.target; // <-- save event value

...

switch (field) {
  case "timeStart":
    val = DateUtil.toString(DateUtil.toUtc(new Date(value))); // <-- use saved value
    console.log(
      "timeStart",
      value, // <-- use saved value
      val,
      DateUtil.toString(DateUtil.fromUtc(new Date(val))),
    );
    setState({ ...state, timeStart: val });
    setErrorz({ ...errorz, timeStart: requiredValidation("Start Date", val) });
    break;
}


text:
Q: Trouble finishing up the proof that ${\rm ord}(bab^{-1})={\rm ord}(a)$. In Pinter's "A Book of Abstract Algebra", Chapter 10 Exercise C4 asks for the reader to prove:

${\rm ord}(bab^{-1})={\rm ord}(a)$

After playing around a little bit...and making use of the fact that $(bab^{-1})^n = ba^nb^{-1}$, I was able to prove the following implications:

*

*${\rm ord}(bab^{-1})=q \implies a^q =e$

*${\rm ord}(a) = p \implies (bab^{-1})^p=e$
I have proven that both of these statements are true. For convenience, I can reformulate these statements as follows:

*

*if ${\rm ord}(bab^{-1})=q$, then ${\rm ord}(a) \leq q$

*if ${\rm ord}(a)=p$, then ${\rm ord}(bab^{-1}) \leq p$
Now I am a little troubled as to how to proceed from here.
May I combine these if-then statements in the following way?

If ${\rm ord}(bab^{-1})=q$ and ${\rm ord}(a)=p$, then $p\leq q$ and $q\leq p$

Which can only be true if $p=q$...which means ${\rm ord}(bab^{-1})={\rm ord}(a)$
It is this last step where I combine the implications into one statement that has me a little worried. Is this logically precise?
Cheers.

A: As it stands, your proof is valid. Normally we wouldn't phrase it as "If $\text{ord}(bab^{-1}) = q$ and..." Instead we would say "let $\text{ord}(bab^{-1}) = q$ and $\text{ord}(a) = p$. Then [insert deductions] $p=q$." This is a minor quibble.
Perhaps a more direct way to solve this problem is to note that $(bab^{-1})^p = e$ if and only if $a^p = e$.


text:
Q: session variable not available in global before(:each, :type => :controller) I'm refactoring some specs, in controller specs I have a before(:each) which sets up things required in the session, wanted to avoid duplication and put the initial setup global for each controller spec
my before filter is...
config.before(:each, :type => :controller) do

  #...

  session[:current_user] = @user
  session[:instance] = @instance

  #...

end

@user and @instance are also set in the before(:each)
i've just hidden them for readability here
I get the following error when running the controller tests
undefined method `session' for nil:NilClass

I would expect the global before callbacks to have the same things as the ones in the individual tests but I guess maybe they are loaded before the rails environment has been initialised?
Thanks

A: Use controller.stub!(:session, { :current_user => @user, :instance => @instance })

A: I think this is more to do with Ruby and blocks (which are closures).
The block passed to before is bound to the context in which it is created, and session is not available in that context.


text:
Q: Converting hexadecimal floating constant to 64-bit binary representation I have seen examples/references/previous questions, but I cannot seem to get my head around some of the cases.
To be more specific, when the numbers is 0x1.MMMMMpEEE, then I can parse out the mantissa representation, which is MMMMM and the exponent, which is EEE and convert them to binary representation. Putting them all together will give me what I want.
However, in cases like 0x8.60a91c16b9b28p-4 or 0x7.ffffffffffffcp-4, because of the 8 and 7 after the 0x, how do I parse this hexadecimal mantissa into bit-wise binary representation?


text:
Q: How to create a timer that starts as soon as something is put into the input field I want to create a timer that goes up (1,2,3,4,5) instead of down (5,4,3,2,1), but I want the timer to stay at 00:00. The timer can only start running when the user inserts something in the input field. I have this, but i'm not sure how to create the timer loop. The research I have done only brought up stuff about counters going down and it was related to python. So I kind of was hoping the sam ecould be achieved in javascript. the input field is created like this-> (it will later increment by name/id, because it can duplicate)
        var sylInput = $('<input/>', {
        'type': 'text',
        'class': 'form-control syl-input',
        'id': 'testid'
    });

this is my variable->
var T = '';

and this is the html where the timer and etc. will be made->

my apologies if this is a newbie question 101.

A: ok I assume you use jQuery
let timer;
let counter = 0;

function startTimer(){
    counter++;
    $("#timer").text(counter);
}

$(document).on('keypress', '#inputID', function() {
   if (timer !== undefined) //check if is already set
   timer = setInterval(startTimer, 1000);
});

A: var T = '';

    T = new TIMER('#timer');

  $(document).one('keydown', '.HereComesTheClassNameOfYourInputField', function(){
T.start();
});

the html:

if someone else wants to use this: Note that you do have to style ur timer first.


text:
Q: child process cannot be put in the foreground process group using tcsetpgrp I was trying to put the child process after fork() in the foreground process group, and I use setpgid() and tcsetpgrp() both in child process and parent process to avoid race condition. from the printed message, the foreground process group has already been made as the child process group in the parent process, but when executing the child process, the foreground process is set to process group of shell again, and an error occured when try to use tcsetpgrp() in child process.
int main(int argc, char *argv[])
{
    signal(SIGHUP, SighupHandler);
    signal(SIGCONT, SigcontHandler);
    int pid = fork();
     if (pid == 0){
        pid_t fpgid = tcgetpgrp(STDIN_FILENO);
        fprintf(stderr, "foreground process id %d\n", fpgid);
        setpgid(0, 0);
        if(tcsetpgrp(0, getpgrp()) == -1) {
            perror("tcsetpgrp");
            exit(1);
        }
        fpgid = tcgetpgrp(STDIN_FILENO);
        fprintf(stderr, "foreground process id %d\n", fpgid);
        fprintf(stderr, "child process pid %d, pgid %d\n", pid, getpgrp());
    }else if(pid > 0){
        fprintf(stderr, "parent process pid %d, pdid %d\n", getpid(), getpgrp());
        setpgid(pid, 0);
        if(tcsetpgrp(STDIN_FILENO, pid) == -1){
            perror("tcsetpgrp");
            exit(1);
        }
        pid_t fpgid = tcgetpgrp(STDIN_FILENO);
        fprintf(stderr, "pgid of foreground process group %d\n", fpgid);
    }
    return 0;
}

teminal output
parent process pid 471939, pdid 471939
pgid of foreground process group 471940
foreground process id 471814 //this shell's pid
tcsetpgrp: Inappropriate ioctl for device

If I ignore SIGTTOU before fork(), the child process can be successfully put in the foreground process group, but from the output above, the parent is first be executed, if it already set the child process in the foreground process group, then child process is no longer in background, so it shouldn't be sent SIGTTOU when try to use tcsetpgrp() right? why the foreground process group is set back to shell's process group later?