text:
Q: find all the answers of these equations find all the answers of these equations:
$x_{1} + x_{2} = x_{3} ^2$
$x_{2} + x_{3} = x_{4} ^2$
$x_{3} + x_{4} = x_{5} ^2$
$x_{4} + x_{5} = x_{1} ^2$
$x_{5} + x_{1} = x_{2} ^2$
My attempt:By summing all equations we can easily find that one answer is that all of them are zero but what about other answers?
In the hint of the book is written that first show $x_1=x_5$.

A: A non-trivial solution is given by
$$
(x_1,\ldots ,x_5)=(2,2,2,2,2).
$$
Edit: The system has $32$ complex solutions, two of them are real, even integral, namely $(0,0,0,0,0)$ and $(2,2,2,2,2)$. I used elimination and reduced the system to two equations in $x_1$ and $x_2$, but there will be more elegant solutions.

A: Not a full fledged answer but maybe you or someone else can take what I have worked on and turn it into an answer.
Given $x_1=x$ and $x_2=y$ you can determine $x_3,x_4,$ and $x_5$ by simply using three out of the 5 equations to define them namely

*

*$x_3=\sqrt{x+y}$ (Using the first equation)

*$x_5=y^2-x$      (Using the last equation)

*$x_4=x^2+x-y^2$  (Using the fourth equation)
Given that this is true it follows that the 2nd and 3rd equation only serve as checks for your solutions. So you can rewrite them in terms of x and y, and gain two equalities.
(1).   $x_2+x_3=x_4^2$ gets rewritten as $y+\sqrt{x+y}=(x^2+x-y^2)^2$
(2).  $x_3+x_4=x_5^2$ gets rewritten as $\sqrt{x+y}+x^2+x-y^2=(y^2-x)^2$
Simplifying this and subtracting the two equations will give you a quadratic in terms of y.
$y+\sqrt{x+y}=x^4+x^2+y^4-2xy^2+2x^3-2x^2y^2$  (Equation 1)
$-(\sqrt{x+y}+x^2+x-y^2=y^4-2xy^2+x^2)$    (-Equation 2)

$y-x^2-x+y^2=x^4+2x^3-2x^2y^2$(New Equation=Equation 1- Equation 2)
$(2x^2+1)y^2+y-(x^4+2x^3+x^2+x)=0$(Simplified)
Which will give you a 2 possible solutions for $y$ given an x. Problem is it is possible that both solutions are Extraneous(crops up from the use of elimination).
$\bar{y}(x)=y_{solution}=\frac{-1\pm \sqrt{1+4(2x^2+1)(x^4+2x^3+x^2+x)}}{2(2x^2+1)}$
This can be avoided by simply plugging the solutions into one of the prior equations (1) or (2) and verifying that it is also a solution there. Problem is the calculation and analysis is so messy at this point that, that verifying.
Verify that $\bar{y}(x)+\sqrt{x+\bar{y}(x)}=(x^2+x-(\bar{y}(x))^2)^2$ implies that $x=2$ or $x=0$(Pain in the ass right?)
Anyways at least it's down to one variable right?(Hell you might even be able to use some calculus on that mug.)


text:
Q: Can a program with an empty main() allocate memory? I have been chasing a memory problem in my program that links against -lcairo and -lX11. Finally, I decided to comment out all lines in my main() and make sure that valgrind is happy. To my surprise, it is not:
==7570== Memcheck, a memory error detector
==7570== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7570== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==7570== Command: ./Test
==7570==
==7570==
==7570== HEAP SUMMARY:
==7570==     in use at exit: 10,360 bytes in 5 blocks
==7570==   total heap usage: 5 allocs, 0 frees, 10,360 bytes allocated
==7570==
==7570== 2,072 bytes in 1 blocks are still reachable in loss record 1 of 5
==7570==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7570==    by 0x5FCCE9A: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCBACE: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCD585: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5F7F508: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x4010139: call_init.part.0 (dl-init.c:78)
==7570==    by 0x4010222: _dl_init (dl-init.c:36)
==7570==    by 0x4001309: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so)
==7570==
==7570== 2,072 bytes in 1 blocks are still reachable in loss record 2 of 5
==7570==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7570==    by 0x5FCCE9A: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCA61F: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCD5A0: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5F7F508: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x4010139: call_init.part.0 (dl-init.c:78)
==7570==    by 0x4010222: _dl_init (dl-init.c:36)
==7570==    by 0x4001309: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so)
==7570==
==7570== 2,072 bytes in 1 blocks are still reachable in loss record 3 of 5
==7570==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7570==    by 0x5FCCE9A: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FE5A8F: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FBC1A5: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCD5AB: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5F7F508: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x4010139: call_init.part.0 (dl-init.c:78)
==7570==    by 0x4010222: _dl_init (dl-init.c:36)
==7570==    by 0x4001309: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so)
==7570==
==7570== 2,072 bytes in 1 blocks are still reachable in loss record 4 of 5
==7570==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7570==    by 0x5FCCE9A: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x60053CF: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCD5AB: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5F7F508: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x4010139: call_init.part.0 (dl-init.c:78)
==7570==    by 0x4010222: _dl_init (dl-init.c:36)
==7570==    by 0x4001309: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so)
==7570==
==7570== 2,072 bytes in 1 blocks are still reachable in loss record 5 of 5
==7570==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7570==    by 0x5FCCE9A: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5FCFCBF: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x5F7F508: ??? (in /usr/lib/x86_64-linux-gnu/libpixman-1.so.0.30.2)
==7570==    by 0x4010139: call_init.part.0 (dl-init.c:78)
==7570==    by 0x4010222: _dl_init (dl-init.c:36)
==7570==    by 0x4001309: ??? (in /lib/x86_64-linux-gnu/ld-2.19.so)
==7570==
==7570== LEAK SUMMARY:
==7570==    definitely lost: 0 bytes in 0 blocks
==7570==    indirectly lost: 0 bytes in 0 blocks
==7570==      possibly lost: 0 bytes in 0 blocks
==7570==    still reachable: 10,360 bytes in 5 blocks
==7570==         suppressed: 0 bytes in 0 blocks
==7570==
==7570== For counts of detected and suppressed errors, rerun with: -v
==7570== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Can a program with an empty main() allocate memory and end up with some reachable blocks? Is there a way to get rid of this strange problem?

A: Yes. It is possible.
One way is that there might be some static objects in the libraries you are linking against. This has already been pointed out by @M.M
The other way is that if you are linking against shared libraries, with no static objects, and certain functions in such a library uses __attribute__((constructor)) . This attribute causes these functions to execute before main() (works only with gcc), and hence you see memory allocations. These functions are chiefly employed by libraries to declare certain attributes about their functions if they are used in your program. For more details about these attributes you can refer to :
http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inversion distance First of all let's recall definition of inversion.
Inversion of some sequence S which contains numbers is situation when S[i] > S[j] and i < j or frankly speaking it's situation when we have disordered elements. For instance for sequence:
1 4 3 7 5 6 2

We have following inversions (4,3), (4,2), (3,2), (7,5), etc.
We state problem as follows: distance of inversion is maximum (in terms of indexing) distance between two values that are inversion. For out example we can perform human-brain searching that gives us pair (4,2) <=> (S[1], S[6]) and there for index distance is 6-1 = 5 which is maximum possible for this case.
This problem can be solved trivial way in O(n^2) by finding all inversions and keeping max distance (or updated if we find better option)
We can also perform better inversion searching using merge sort and therefore do the same in O(nlogn). Is there any possibility for existence of O(n) algorithm? Take in mind that we just want maximum distance, we don't want to find all inversions. Elaborate please.

A: Yes, O(n) algorithm is possible.
We could extract strictly increasing subsequence with greedy algorithm:
source:                          1 4 3 7 5 6 2
strictly increasing subsequence: 1 4   7

Then we could extract strictly decreasing subsequence going backwards:
source:                          1 4 3 7 5 6 2
strictly decreasing subsequence: 1           2

Note that after this strictly decreasing subsequence is found we could interpret it as increasing sequence (in normal direction).
For each element of these subsequences we need to store their index in source sequence.
Now "inversion distance" could be found by merging these two subsequences (similar to merge sort mentioned in OP, but only one merge pass is needed):
merge 1 & 1 ... no inversion, advance both indices
merge 4 & 2 ... inversion found, distance=5, should advance second index,
                but here is end of subsequence, so we are done, max distance = 5

A: Maybe my idea is the same as @Evgeny.
Here is the explanation:
make a strictly increasing array from the beginning we call it array1
make a strictly decreasing array from the ending which is array2 (But keep the values in increasing order)

***Keep track of original indexes of the values of both arrays.

Now start from the beginning of both arrays.

Do this loop following untill array1 or array2 checking is complete

    While( array1[index] > arry2[index] )
    {
        check the original distance between array1 index and arry2 index.
        Update result accordingly.
        increase array2 index.
    }
    increase both array index

Continue with the loop

At the end of this process you will have the maximum result. Proof of this solution is not that complex, you can try it yourself.


text:
Q: python content loading and popup access problem I'm using chrome, the file is opening but there is no feature to add image send_keys
I don't know how to specify the exact file path with execute_script
enter image description here


text:
Q: bitwise comparison of large numbers Researching the possibility of using bitwise comparison to assess what options have been selected out a possible 100 options.
now as an integer the selection of all options would require storage of an integer of 2 to the power of 99 (6E29). way beyond the limit of circa 9E18.
just as with dir permissions ( 1 = read, 2= write, 4 = execute) 1+2+4 = 7 = full access.
I would like to know which of the 100 options have been chosen by the same method.
Any advice/tips much appreciated.
NB storage will be mysql
-- EDIT --
The end goal here is to simplify a check as to what currencies a user can be paid in.
assigning values to currency like so:
Currency OptVal
GBP      1
USD      2
EUR      4
AUD      8
CAD      16
ZAR      32

and so on (there are many many currencies and more will arise through crypto currencies I'm sure)
it would then be convenient to check which currencies a user has using bitwise operators...
so if a user had currency setting of 3 only GBP and USD.
5 GBP & EUR
63 GBP,USD,EUR,AUD,CAD,ZAR
and so on - hope this clarifies the goal.
The issue is to do this in its most simplistic form of storing that integer when you have > 100 currencies. you need a value 2E(n-1) for each option and for large n this number is very large and not storable as an integer (BIGINT Max value is 18446744073709551615)

A: You want advice.  Don't do it this way.
MySQL offers the boolean data type, which is convenient for flags.  Each value does occupy one byte, so the storage will be larger than using bits.
MySQL also offers the bit() data type, where you can put together up to 64 bits.  You can read about them here.
Using built-in data types is simply the right way to go.  They protect your from changes of server, from upgrades on the OS, and the possibility that your application and server have different endian-ness (if you don't know what this is, then you definitely should not be thinking about bit fiddling).
The good news is that there are data types for what you want to do.


text:
Q: Issue animating shape without leaving big gap at bottom etc - CSS/HTML I am currently trying to display a shape that animates behind other divs within the same container.
Everything looks fine, until I add additional content (inside or outside the same area)
The intended result is to look like this with space below to allow for other content to be added without having huge empty space and negative margins set (as I currently do for the shape):
https://media2.giphy.com/media/TJs23q70cgnyxAwJsA/giphy.gif
What I am currently getting is more like this:
https://media3.giphy.com/media/JNshdMa1gEdtmsnDYI/giphy.gif
Here is the code that I am presently implementing ( for this particular area ):

/* Blog Section */

#blog-section {
  padding-top: 7rem;
  height: 100%;
}

.blog-display {
  display: flex;
  margin: auto;
  width: 100%;
  position: relative;
  z-index: 1;
}

.blog-img img {
  text-align: center;
}

.blog-text {
  margin: auto 5rem;
  color: white;
}

.blog-text a {
  color: white;
}

.blog-plate {
  background: #0c3445;
  top: -800px;
  height: 700px;
  max-width: 100%;
  position: relative;
  animation: 20s ease-in 7s infinite blogmove;
  animation-direction: alternate-reverse;
}

@keyframes blogmove {
  0% {
    left: 0px;
    top: -800px;
  }
  25% {
    left: 0px;
    top: -705px;
  }
  50% {
    left: 0px;
    top: -600px;
  }
  75% {
    left: 0px;
    top: -705px;
  }
  100% {
    left: 0px;
    top: -800px;
  }
}

/* Recipe Section */

#recipe-section {
  padding-top: 7rem;
}

New Book By H. G. Cayton

If you haven't been backing up to iCloud but have backed up your phone to iTunes on your Mac or PC (or to Finder, if you're running macOS Catalina), you may be able to recover your text messages from there. And even if you think you didn't back
          up your messages, it's worth a few […]

        Read More

      Content within the same section

    Next Section Here, Why am I so far down?

Thank you for any assistance you can provide.
Best,

A: From what I am getting from your question, you want the shape to be animated just behind the upper section which have an image and content side by side and at the same time don't want the extra white space to come after that block. So if I am right, then you can achieve this by wrapping the shape which animates in one more div and place it using position:absolute; instead of position:relative; because using position relative and giving it top:-800px; is the main reason the white space after that div is created. Try the code below and let me know if it helps, I have also made few changes to the keyframes :-
HTML

New Book By H. G. Cayton

If you haven't been backing up to iCloud but have backed up your phone to iTunes on your Mac or PC (or to Finder, if you're running macOS Catalina), you may be able to recover your text messages from there. And even if you think you didn't back
          up your messages, it's worth a few […]

        Read More

      Content within the same section

    Next Section Here, Why am I so far down?

CSS
#blog-section {
  width: 100%;
}
.plate-wrap{
  padding-top: 7rem;
  position: relative;
  padding-bottom: 7rem;
}
.blog-display {
  display: flex;
  margin: auto;
  width: 100%;
  position: relative;
  z-index: 1;
}

.blog-img img {
  text-align: center;
}

.blog-text {
  margin: auto 5rem;
  color: white;
}

.blog-text a {
  color: white;
}

.blog-plate {
  background: #0c3445;
  top: 0;
  height: 80%;
  max-width: 100%;
  width:100%;
  position: absolute;
  animation: 20s ease-in 7s infinite blogmove;
  animation-direction: alternate-reverse;
}

@keyframes blogmove {
  0% {
    left: 0;
    top: 0;
  }
  50% {
    left: 0px;
    top: 20%;
  }
  100% {
    left: 0px;
    top: 0;
  }
}
/* Recipe Section */
#recipe-section {
  padding-top: 7rem;
}

I have also made a jsfiddle with same code for your reference, you can check it here
Hope it helps you.


text:
Q: Read a distributed Tab delimited CSV Inspired from this question, I wrote some code to store an RDD (which was read from a Parquet file), with a Schema of (photo_id, data), in pairs, delimited by tabs, and just as a detail base 64 encode it, like this:
def do_pipeline(itr):
   ...
   item_id = x.photo_id

def toTabCSVLine(data):
  return '\t'.join(str(d) for d in data)

serialize_vec_b64pkl = lambda x: (x[0], base64.b64encode(cPickle.dumps(x[1])))

def format(data):
    return toTabCSVLine(serialize_vec_b64pkl(data))

dataset = sqlContext.read.parquet('mydir')
lines = dataset.map(format)
lines.saveAsTextFile('outdir')

So now, the point of interest: How to read that dataset and print for example its deserialized data?
I am using Python 2.6.6.

My attempt lies here, where for just verifying that everything can be done, I wrote this code:
deserialize_vec_b64pkl = lambda x: (x[0], cPickle.loads(base64.b64decode(x[1])))

base64_dataset = sc.textFile('outdir')
collected_base64_dataset = base64_dataset.collect()
print(deserialize_vec_b64pkl(collected_base64_dataset[0].split('\t')))

which calls collect(), which for testing is OK, but in a real-world scenario would struggle...

Edit:
When I tried zero323's suggestion:
foo = (base64_dataset.map(str.split).map(deserialize_vec_b64pkl)).collect()

I got this error, which boils down to this:
PythonRDD[2] at RDD at PythonRDD.scala:43
16/08/04 18:32:30 WARN TaskSetManager: Lost task 4.0 in stage 0.0 (TID 4, gsta31695.tan.ygrid.yahoo.com): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/grid/0/tmp/yarn-local/usercache/gsamaras/appcache/application_1470212406507_56888/container_e04_1470212406507_56888_01_000009/pyspark.zip/pyspark/worker.py", line 98, in main
    command = pickleSer._read_with_length(infile)
  File "/grid/0/tmp/yarn-local/usercache/gsamaras/appcache/application_1470212406507_56888/container_e04_1470212406507_56888_01_000009/pyspark.zip/pyspark/serializers.py", line 164, in _read_with_length
    return self.loads(obj)
  File "/grid/0/tmp/yarn-local/usercache/gsamaras/appcache/application_1470212406507_56888/container_e04_1470212406507_56888_01_000009/pyspark.zip/pyspark/serializers.py", line 422, in loads
    return pickle.loads(obj)
UnpicklingError: NEWOBJ class argument has NULL tp_new

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

16/08/04 18:32:30 ERROR TaskSetManager: Task 12 in stage 0.0 failed 4 times; aborting job
16/08/04 18:32:31 WARN TaskSetManager: Lost task 14.3 in stage 0.0 (TID 38, gsta31695.tan.ygrid.yahoo.com): TaskKilled (killed intentionally)
16/08/04 18:32:31 WARN TaskSetManager: Lost task 13.3 in stage 0.0 (TID 39, gsta31695.tan.ygrid.yahoo.com): TaskKilled (killed intentionally)
16/08/04 18:32:31 WARN TaskSetManager: Lost task 16.3 in stage 0.0 (TID 42, gsta31695.tan.ygrid.yahoo.com): TaskKilled (killed intentionally)
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
/homes/gsamaras/code/read_and_print.py in <module>()
     17     print(base64_dataset.map(str.split).map(deserialize_vec_b64pkl))
     18
---> 19     foo = (base64_dataset.map(str.split).map(deserialize_vec_b64pkl)).collect()
     20     print(foo)

/home/gs/spark/current/python/lib/pyspark.zip/pyspark/rdd.py in collect(self)
    769         """
    770         with SCCallSiteSync(self.context) as css:
--> 771             port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
    772         return list(_load_from_socket(port, self._jrdd_deserializer))
    773

/home/gs/spark/current/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
    811         answer = self.gateway_client.send_command(command)
    812         return_value = get_return_value(
--> 813             answer, self.gateway_client, self.target_id, self.name)
    814
    815         for temp_arg in temp_args:

/home/gs/spark/current/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    306                 raise Py4JJavaError(
    307                     "An error occurred while calling {0}{1}{2}.\n".
--> 308                     format(target_id, ".", name), value)
    309             else:
    310                 raise Py4JError(

Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.

A: Let's try a simple example. For convenience I'll be using handy toolz library but it is not really required here.
import sys
import base64

if sys.version_info < (3, ):
    import cPickle as pickle
else:
    import pickle

from toolz.functoolz import compose

rdd = sc.parallelize([(1, {"foo": "bar"}), (2, {"bar": "foo"})])

Now, your code is not exactly portable right now. In Python 2 base64.b64encode returns str, while in Python 3 it returns bytes. Lets illustrate that:

*

*Python 2
type(base64.b64encode(pickle.dumps({"foo": "bar"})))
## str

*Python 3
type(base64.b64encode(pickle.dumps({"foo": "bar"})))
## bytes

So lets add decoding to the pipeline:
# Equivalent to
# def pickle_and_b64(x):
#     return base64.b64encode(pickle.dumps(x)).decode("ascii")

pickle_and_b64 = compose(
    lambda x: x.decode("ascii"),
    base64.b64encode,
    pickle.dumps
)

Please note that this doesn't assume any particular shape of the data. Because of that, we'll use mapValues to serialize only keys:
serialized = rdd.mapValues(pickle_and_b64)
serialized.first()
## 1, u'KGRwMApTJ2ZvbycKcDEKUydiYXInCnAyCnMu')

Now we can follow it with simple format and save:
from tempfile import mkdtemp
import os

outdir = os.path.join(mkdtemp(), "foo")

serialized.map(lambda x: "{0}\t{1}".format(*x)).saveAsTextFile(outdir)

To read the file we reverse the process:
# Equivalent to
# def  b64_and_unpickle(x):
#     return pickle.loads(base64.b64decode(x))

b64_and_unpickle = compose(
    pickle.loads,
    base64.b64decode
)

decoded = (sc.textFile(outdir)
    .map(lambda x: x.split("\t"))  # In Python 3 we could simply use str.split
    .mapValues(b64_and_unpickle))

decoded.first()
## (u'1', {'foo': 'bar'})


text:
Q: Is there a way to retrieve the generated HTML email body of a dynamic template via SendGrid API call? We have a site where our agents enter in some data, and then that data is sent to a client, via a SendGrid dynamic template.
The email content includes a lot of calculations based on the data entered, so we want our agents to have the ability to preview the email and verify the content first before sending it to the client.
Is there a way to use the SendGrid API to send a request with our json object, but instead of sending the email to the client, receive the generated email body so that we can display it to the agent and let them review it first?

A: Answered my own question. API v3 has GET methods for Dynamic Transactional Templates and Template Versions.
API Call:
/templates/{template_id}/versions/{version_id}

using sendgrid-ruby:
sg = SendGrid::API.new(api_key: sendgrid_api_key)
sg.client.templates._(template_id).versions._(template_version_id).get

(Note: the template_version_id is the ID and not the Name of the template version)
The response body then includes a field called html_content which is the full rendered HTML of a dynamic template version with any handlebar templating.

A: You can make API call via postman as:
https://api.sendgrid.com/v3/templates/d-d44fdfsdfdsfd342342343
with Bearer token along with Sendgrid API key like:
Bearer SG.Fvsdfsdjfksdfsdfjsdkjfsdfksjdfsdfksjdfkjsdkfjsdf
The response is:
{
"id": "d-d55d081558a641b48a8a1145b4549fbe",
"name": "Bt_Payment_Reminder (Active)",
"generation": "dynamic",
"updated_at": "2021-12-21 07:35:12",
"versions": [
    {
        "id": "a95c3652-e49f-4608-a9dd-5aa4831c2dc3",
        "user_id": 11702857,
        "template_id": "d-d55d081558a641b48a8a1145b4549fbe",
        "active": 1,
        "name": "Bt_Payment_Reminder_Updated",
        "html_content": "Hello {{firstName}}",
        "plain_content": "Hello {{firstName}}",
        "generate_plain_content": true,
        "subject": "{{subject}}",
        "updated_at": "2021-12-21 07:37:48",
        "editor": "code",
        "test_data": "{\n    \"firstName\":\"Virendra\"}",
        "thumbnail_url": "sdasdasdasdasdasdsd"
    }
]

}


text:
Q: sharing a jupyter notebook on a server I made a jupyter notebook that can read hdf5 files and use some functions to analyze the data. I would like to put this jupyter notebook on a server containing different hdf5 files and make it available for people who are working in other places. An exemple of functions would be to see the expression of some genes in a sample. Those people could open this jupyter notebook and add a list of specific genes to look at.
I am looking at JupyterLab, but I can see that people can read and modify the notebook. I would like that even if they modify it, when they finish, the notebook is as it was before they opened it. Do you think it is possible to do that ? I think I could do it locally with "read-only" but I don't know how to do it on jupyterLab.
I am a newbie for things related to servers. I will really appreciate your help and suggestions.
Thanks a lot :)

A: Some suggestions:
You could supply the notebook via a code sharing resource like GitHub and let them clone/copy/download use it as they see fit via their own resources. This insures they aren't changing your source notebook. And you don't have to worry about computational resources because they can run it where they prefer such as on their own cluster or at a cloud center.
Typically, I'd suggest the MyBinder project at https://mybinder.org/ for what you describe as it lets you share temporary active sessions that launch on remote servers. You set up a Github repository with notebooks and the data or a way to retrieve the data built in the notebook and when the temporary session launches, users can work through your notebook. This way they can extend and modify and run their own data and not change your source notebook. However, the resources are limiting as it is free, see here.
Examples:

*

*solve for sediment transport

*Resolving the measurement uncertainty paradox in ecological management

*A quick introduction to RNAseq

*bendit-binder

*blast-binder
I've seen others use Code Ocean, see an example here.
There are other national/government-funded centers that allow similar hosting of services and resources that can be shared with others. CyVerse is one that is now running in the United States and several place, such as CyVerseUK in association with the Earlham Institute, and elsewhere. They offer notebooks to be served via their VICE apps in their Discover environment. Their resource allows more computational power and storage than the free, public MyBinder service.

A: You can use Mercury framework. It is an open-source tool that converts Python notebooks into interactive documents, like web apps, reports, dashboards, slides.
It requires an YAML header in the first cell in the notebook. In the header you define the presence of the notebook in the Mercury (title, description, show-code). Additionally, you can add widgets to the notebook. Widgets are directly connected to variables in the notebook. The variables which values are controlled by widgets should be in the separate cell.
The example notebook

The example notebook with YAML header

The YAML header
There are two widgets defined in the below YAML header. The name and points widgtes have the same name as variables in the code. User can change the widgets values, click Run and the notebook will be executed with new values.
---
title: My notebook
description: Notebook with plot
show-code: False
params:
    name:
        input: text
        label: What is your name?
        value: Piotr
    points:
        input: slider
        label: How many points?
        value: 200
        min: 10
        max: 250
---

The Web Application from Notebook

The final notebook after execution can be downloaded as standalone HTML or PDF file.
Deployment
The Mercury framework is built on top of Django. It can be deployed on any machine with Python available. The deployment for Heroku is very simple, and can be done with two commands (you need to have Heroku CLI tool):
heroku create my-amazing-web-app-name-here
git push heroku main

Please make sure that there is Procfile created for Heroku deployment with:
web: mercury run 0.0.0.0:$PORT

You can also deploy Mercury with docker-compose. Please check the docs for more details. You can also check the article on how to share Jupyter Notebook with non-programmers with Mercury tool.

A: You can install a local Gitlab server instead of publishing on Github. Then publish your Jupyter notebooks in Gitlab. Share your server URL with people. Our company is running all internally.


text:
Q: filenet JAVA API retention periode not updated I've been working on a project that use filenet for multiple parts of the project.
I've been asked to remove a boatload of file's that need to be removed. The reason why I was asked is because the assumtion was made we could remove the data through a java application.
And so far so good honestly. I've been able to use code left by former project members to create a delete application. However, i've come to a single problem in this issue: the retention date.
When I delete a file it will display the error message: Content Engine cannot delete or move content because the retention period for the item has not yet expired. Current time: 9/16/21 8:43 AM; Storage period: 20-12-99 1:00.
I've created code that does change this. However the above error is still appearing. I;ve doubled checked the retentiondate property in the specifice file, and this has been changed.
I've looked through all the properties of the file and have not spotted anything that includes this date.
So my questions is, what am I missing? Is this something from filenet?

A: The retention period is probably additionally set on the storage device and the storage device is not aligned with filenet.
What type of storage backend are you using.

A: Please check this doc https://www.ibm.com/docs/en/filenet-p8-platform/5.2.1?topic=objects-retention-limitations-constraints
And this https://www.ibm.com/docs/en/filenet-p8-platform/5.2.1?topic=objects-security-permissions-required-setting-modifying-retention
Sure that you have enough permissions for the principal that you are using for API  calls.
And check this page https://www.ibm.com/docs/en/filenet-p8-platform/5.2.1?topic=sweeps-deleting-objects-sweep and this https://www.ibm.com/docs/en/filenet-p8-platform/5.2.1?topic=sweeps-updating-object-retention as alternative way to delete objects without API and custom app.


text:
Q: Suggestions for implementing a document management system in which some documents have runtime replaced fields One of my apps is a Document Management System in which the documents are stored as blob fields into a db. This is not a language specific question, anyway I put Delphi in tags since this is the community to which i tipically ask questions (and many people that uses Delphi faces these problems).
One feature I need to add is to programmatically add some data to the document. I make a simple example just to get the idea. One field is the date in which the document has been created. For this the user will type "a tag" for example <DOCUMENT_DATE> and the date will be automatically substituted when the docuemnt is extracted from db.
So I have 2 main concerns. ONe is what to use as "tag". The simplest thing is to use a text tag, so simply typing  into the docuemnt and then do Search & Replace text (using for example MS Word ActiveX). I already do this for other purposes. AN alternative could be using bookmarks or another technique.
The other question is strictly related with the previous.
How do I store it? My first idea is to store the document in DB with the "tags", so when it is "checked out" the user sees the tags, while when the user opens it (in readonly mode) he sees the subsituted text. (so in first case he sees  and in the second "12 october 2011").
In this way I store the file once, but every time it is opened there is an overhead in processing it and doing the Search Replace thing, that can be also relatively slow. So this is why I asked for other techniques. Like serach replace for bookmark. The fastest the better.
The alternative is to store the document twice: once with the "tags" and the other with the "substituted veresion". This will be good for performance: no Searh & Replace but simply when the document is openeed in "checkout" mode I will open the one with the tags, while whne I open it in readonly mode I will open the subsituted one.
This of course takes more storage, for every document version (revision1, revision2, ...) I need to store 2 files.
I feel double storage is the best, because it won't affect perfomance at all, I mean it will be as fast as now, just the checkin process will be slower since I need to save 2 files and not one. Moreover by not enabling this auto substitution feature on all documents by default I won't have double db size.
But anyway I would like to hear some comments, since it is a quite crucial decision.

A: It really does not make sense to store identical data twice.
in fact it is a really bad idea, mainly from a consistancy point of view.
The way you do this is to store stuff in different tables and create links between the tables.
This is a process called normalization.
Here's an example loosely inspired by your post using MySQL:
TABLE document
--------------
id UNSIGNED INTEGER AUTO_INCREMENT PRIMARY KEY,
data BLOB

TABLE tag
------------
id UNSIGNED INTEGER AUTO_INCREMENT PRIMARY KEY,
tag VARCHAR(20)

TABLE tag_link
-------------------
tag_id UNSIGNED INTEGER,
reference_nr UNSIGNED INTEGER,
PRIMARY KEY (tag_id, reference_nr)
FOREIGN KEY (tag_id) REFERENCES tag(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (reference_nr) REFERENCES post(reference_nr) ON DELETE CASCADE ON UPDATE CASCADE,

TABLE post
----------------
reference_nr UNSIGNED INTEGER NOT NULL,
revision UNSIGNED INTEGER NOT NULL DEFAULT 1,
document_id UNSIGNED INTEGER,
title VARCHAR(255),
creation_date TIMESTAMP,
other_fields .....
PRIMARY KEY (reference_nr, revision),
FOREIGN KEY (document_id) REFERENCES document(id) ON DELETE SET NULL ON CASCADE UPDATE

Now you can add tags to a post, all revisions of a post share the same tags.
Revisions of a post can link to the same document, or to different documents no need to duplicate data.
If you want to get all the lastest revisions of documents with certain tags, you use the following query:
SELECT p.title, d.data, GROUP_CONCAT(t.tag) AS tags
FROM post p
LEFT JOIN d.data ON (p.document_id = d.id)
INNER JOIN taglink tl ON (tl.reference_nr = p.reference_nr)
INNER JOIN tags t ON (tl.tag_id = t.id)
WHERE t.tag IN ('test','test2')
GROUP BY p.reference_nr  /*only works in MySQL because other db's do not support ANSI SQL 2003*/
HAVING p.revision = MAX(p.revision)
ORDER BY p.creation_date DESC

A: I see two other possibilities worth considering.
1. Use RTF
If your document templates are Word documents, I'd rather store them as RTF.
RTF is just plain ASCII, and even if it is a proprietary format, it is well documented, and can be easily parsed. Word is able to save its content and read it as RTF. If you have pictures within, it can grow, but you can zip it before storing as BLOB in your database (and you may embed EMF pictures).
Then you can process those RTF content very fast in your code, changing all <DOCUMENT_DATE> using the latest version of the date field value.
I use this technique in several applications, and it gives very good results. See for instance how our SynProject tool generates Word documents from plain text, replacing tags, setting bookmarks or indexes on the fly. With RTF, you can do much more than just replacing a tag, but create a whole document easily.
For end-user input, you can use a basic TRichEdit or a more advanced (but not free) TRichView instead of Word.
You may consider using HTML instead of RTF, but it is much less printing-friendly.
2. Use a report engine
Another possibility could be to use a code-based report engine, then create PDF files.
Our Open Source units can be used from a simple reporting class to create easily the file content, preview it on screen and/or print/export as PDF. It is much easier than RTF to work with, but the layout has to be set in your code, or with text-based / wiki-like templates to be stored in your DB.


text:
Q: Javascript - Evaluate "x(y)"? So for example, I would like to evaluate 2(3) [which equates to 6].
var string = "2(3)";
var ans = eval(string);

I typed in the above code in Chrome Console and they gave me the following error message: TypeError: number is not a function.
So how do I get "2(3)" to return 6? Thx.

A: You can use a regular expression to insert a * between any digit followed by an open bracket to convert your string from 2(3) to 2*(3) before passing it through eval():
var string = "2(3)",

    // Convert string to array (["2", "(", "3", ")"])
    array = string.split(''),

    ans;

// Insert * between digit and open bracket  (["2", "*", "(", "3", ")"])
array.splice(string.search(/\d\(/) + 1, 0, "*");

// Convert array back to string ("2*(3)")
string = array.join("");

// Run eval (6)
ans = eval(string);

console.log(ans);

JSFiddle demo.

A: JavaScript doesn't do that. What you you can do, however, is create a function that returns a function. The second function is called a closure. It's handy because when it's returned it maintains a copy of the local environment it was in when it was created. So you pass in a multiplier parameter to the first function which returns a function. This function, the closure, evaluates the parameter you pass into it when it's called by that multiplier.
Far better people have explained what a closure is than me.
function times(multiplier) {
  return function (num) {
    return num * multiplier;
  }
}

var bySix = times(2);
var result = bySix(3); // 6


text:
Q: Adobe Flex: Cannot Navigate to Dynamic URL Currently in my app I can access my database of users, but now I need to open the user's facebook page when I click on either their avatar or username. I can access the user's facebook id by data.facebook id. I did have working code earlier, but it required my to enter a static URL, but I need the URL to be generated based on the user's id.
This is my code so far
private function newBrowserWindow():void
{
    //Creating a URL for a facebook profile
    trace(data.facebookid);
    var facebookUrl:* = "http://www.facebook.com/" + data.facebookid;
    navigateToURL(facebookUrl);
}

I access this function with the following code:
<s:Image id="fbImg" source="http://graph.facebook.com/{data.facebookid}/picture?type=normal" x="0" y="0" click="newBrowserWindow()"/>
<s:Label id="usernameLbl" x="120" y="0" fontFamily="Calibri" fontSize="25" fontWeight="bold" text="{data.firstname} {data.lastname}" click="newBrowserWindow()"/>

My code is showing no errors so I don't know what's wrong. My previous working code required me to access the click handler via click="newBrowserWindow('http://www.mysite.com') and thus the function required an object to process, but I removed that because I couldn't seem to get around typing in a static URL.
Any ideas?

A: Use URLRequest in navigateToURL:
 navigateToURL(new URLRequest(facebookUrl));


text:
Q: Creating a Derived Class in C++ So im trying to make a Die class and a LoadedDie class where the Die class is the base and the LoadedDie class is derived. The only difference between the 2 classes is that the roll function in the LoadedDie has a 25% chance of getting the highest number, whereas the Die, has a 1/6 chance. This is my 1st time working with derived class and i seem to have quite a problem trying to complete this task. Can someone explain to me how it works and show me how i would do it with my classes (as im a visual learner and need examples). I know my base class (Die) works as i tested it out before moving to my LoadedDie.
Die.cpp
#include<iostream>
#include <cstdlib>
using namespace std;

class Die{
    public:
        Die();
        Die(int numSide);
        virtual int roll() const;
        int rollTwoDice(Die d1, Die d2);
        int side;
};

Die::Die():side(6){}

Die::Die(int numSide):side(numSide){}

int Die::roll() const{
    return rand() % side + 1;
}

int Die::rollTwoDice(Die d1, Die d2){
    return d1.roll()+d2.roll();
}

LoadedDie.cpp
#include<iostream>
#include <cstdlib>
#include "Die.cpp"
using namespace std;

class LoadedDie: public Die{
    public:
        LoadedDie();
        LoadedDie(int numSide);
        virtual int loadedroll() const;
};

LoadedDie::LoadedDie():side(6){}

LoadedDie::LoadedDie(int numSide):side(numSide){}

int LoadedDie::loadedroll() const{
    if ((rand() % 2)+1) = 1){
        return side;
    }
    return (rand() % (side-1)) + 1;
}

int LoadedDie::rollTwoDice(LoadedDie d1, LoadedDie d2){
    return d1.roll()+d2.roll();
}

My DieTester.cpp (just a main class to test if the above classes work):
#include "LoadedDie.cpp"
#include<iostream>
#include<time.h>
#include <stdlib.h>
using namespace std;

int main(){

    srand(time(NULL));

    Die d(6);
    LoadedDie dl(6);
    cout << d.roll()<<endl;
    cout<<"ld " << dl.roll()<<endl;
}

With the classes above, i get this error when i run my DieTester.cpp (if it helps):
In file included from DieTester.cpp:1:
LoadedDie.cpp: In constructor 'LoadedDie::LoadedDie()':
LoadedDie.cpp:13: error: class 'LoadedDie' does not have any field named 'side'
LoadedDie.cpp: In constructor 'LoadedDie::LoadedDie(int)':
LoadedDie.cpp:15: error: class 'LoadedDie' does not have any field named 'side'
LoadedDie.cpp: In member function 'virtual int LoadedDie::loadedroll() const':
LoadedDie.cpp:18: error: expected primary-expression before '=' token
LoadedDie.cpp:18: error: expected ';' before ')' token

I believe that these errors are due to me not deriving the classes properly. Can someone explain to me how this is done?

A: While the commends about splitting the code into header and code files are all valid (do that NOW) they have nothing to do with the remaining errors and your questions. Lets go through them one by one:
LoadedDie.cpp: In constructor 'LoadedDie::LoadedDie()':
LoadedDie.cpp:13: error: class 'LoadedDie' does not have any field named 'side'

LoadedDie indeed has no such member. It is a member of Die. You do not initialize the members of your base class in the derived class like that. Instead you have to call the constructor of the base class like this:
LoadedDie::LoadedDie() : Die() { }

LoadedDie.cpp: In constructor 'LoadedDie::LoadedDie(int)':
LoadedDie.cpp:15: error: class 'LoadedDie' does not have any field named 'side'

Same problem again. Same solution:
LoadedDie::LoadedDie(int numSide) : Die(numSide) { }

Note that you can take advantage of default values for arguments and simply write one constructor instead of two:
class Die {
public:
    Die(int numSide = 6);
    ....
}

if ((rand() % 2)+1) = 1){
LoadedDie.cpp: In member function 'virtual int LoadedDie::loadedroll() const':
LoadedDie.cpp:18: error: expected primary-expression before '=' token
LoadedDie.cpp:18: error: expected ';' before ')' token

'=' is assignment while you ment equal '=='. You can't assign 1 to (rand() % 2)+1).

A: It's generally bad form to #include CPP files.  But if you want to do it, get rid of the #include "Die.cpp" statement in main.cpp.  It's already included in LoadedDie.cpp and so you are including it twice and defining it twice--hence the 'redefinition' error.


text:
Q: python - beautifulsoup - removing a line of code I started to learn the beautifulsoup. I am trying to remove from html script a line of code containing
 .
The most examples in the documentation are presented for the whole tags (opening and closing part).

Is it possible to modify just one part of a tag?
For example:

Hello

foo!

how to remove just the first line of the code?

A: You can use BeautifulSoup's unwrap() to specify the invalid tag, which will only remove the extra tags that don't have a open/close counterpart, while retaining others:
soup = BeautifulSoup(html_doc, 'html.parser')

invalid_tags = ['
']

for tag in invalid_tags:
    for match in soup.findAll(tag):
        match.unwrap()

print(soup)

result:

Hello

foo!

A: you don't need do anything it will repaired automatically
from bs4 import BeautifulSoup

html_doc = '''

World

foo!''' # also invalid, no closing

soup = BeautifulSoup(html_doc, 'html.parser')
print(soup)

output

World

foo!

unwrap() is for removing not repairing tag.


text:
Q: Borders only between elements I need to know how to make a borders between my items like the following image:

I tried making it using border-right and -left but the last item shouldn't have a border-right.
My CSS:
border-top: 1px solid #000;
border-right: 1px solid #000;

How can I apply border-right to all but the last element on the row?

A: There is a better way to do it that works in older browsers: http://jsfiddle.net/mxV92/.
You simply apply a border on the left for every item that immediately follows another item:
ul > li + li {
    margin-left: 5px;
    padding-left: 5px;
    border-left: 1px solid #bbb;
}

A: If I understand correctly, what you want is to have borders on the right of all the items, except the last item.
You can use the 'last-child' selector for that. For example, if your objects were in a 'div' with the class 'foo', your CSS might look like:
div.foo {
   border-width: 1px 1px 0 0;
   border-color: #000;
   border-style: solid;
}

div.foo:last-child { border-width: 1px 0 0 0; }

This says that divs of class 'foo' should have solid black borders, with a width of 1px on top and right ('border-width' is followed by widths in the order top, right, bottom, left), except on the last item, where the width is '1px' only on the top.
':last-child' should be supported by most modern browsers.

A: add this to your style.css, turn off border-right every 4th books. (this only works on the desktop version of the site.)
.nspArt:nth-child(4n) .gkResponsive img.nspImage {
    border-right: none;
}

A: You can do this:
.books-collection {
    border-top: 1px solid #bbb;
    border-bottom: 1px solid #bbb;
    padding: 5px 0;
}

.books-collection .book:not(:first-child) {
    border-left: 1px solid #bbb;
    padding: 5px 0;
}


text:
Q: Is mathematica a functional programming language? Is mathematica a functional programming language? what i intend to ask his that i keep reading that mathematica is a conditional rewrite  system. I want to know what is this conditional rewrite system?
I also wanted to know whether we can apply the functional programming concepts like continuous passing style, memoization etc using mathematica language?

A: Mathematica supports multiple programming paradigms (procedural, functional and even object oriented). You can do CPS, memorization etc using the Mathematica language. But Mathematica is more about getting things done. If you want to learn more about the theory behind functional programming, I suggest using Scheme, Haskell, or ML as your vehicle.


text:
Q: How to create a list in react using redux? I am trying to make a list using redux. As react works on component. So I want to make list as a separate component.
When a User fills in an input field and presses the add button it should add a list item. But currently it is not showing a list item.
Here is my code:
https://plnkr.co/edit/eCZSo6Rl5odN1hTb6BCW?p=preview
I am currently doing it like this:
  <r names ={this.props.names}/>

const r = (props) => {
    alert('---')
    return (

            hiii

    );
};

When this.props.names changes it should fire the render function. But it is not calling the render function.

A: React Component must begin with UpperCase letters. Change that and it will solve your problem
render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    var listItems = this.props.names.map(function(d, idx){
      return (<R key={idx}></R>)
    })
    return (

      <input type="text" onChange ={this.changeEv}/>
      <button onClick={this.addName}>add</button>
      {listItems}

    );
  }
}
const R = (props) => {
    alert('---')
    return (

            hiii

    );
};

Plunkr

A: Your components should be capital. r should be R through out.
Updated plnkr:
https://plnkr.co/edit/ENpx2s7JdW0AZUYtzKOj?p=preview
This is because React treats lower case elements as browser native elements (div, p, span, etc) and capital elements as app level elements.


text:
Q: stdin doesnt work ruby I have the following script:
$stdin.each_line do |data|
  blocks = data.scan(/\+[^+]+\+/)
  blocks.reject! { |b| b.include? "AAAAAAAAA" }
  p blocks
end

This script will remove that string of A's in a stdin file.  I have two questions:

*

*The stdin doesnt seem to work, it outputs [].

*How can I modify the script to say that reject a stretch of single letters that have length 20 or above, so if there is a stretch of 20 or more A's, remove the block.

A: To reject all blocks with 20 or more identical uppercase characters:
$stdin.each_line do |data|
  blocks = data.scan(/\+[^+]+\+/)
  ('A'..'Z').each do |ch|
    r = Regexp.new("[" + ch + "]{20,}")
    blocks.reject! { |b| r =~ b }
  end
  p blocks
end

This builds 26 regexes (one for each uppercase character) and matches blocks against them.
Of course, it would be much more efficient to build them just once and store them in an array or similar instead of rebuilding them for each line in the input.
A more compact solution:
  r = /([a-z])\1{19,}/
  $stdin.each_line do |data|
      blocks = data.scan(/\+[^+]+\+/)
      blocks.reject! { |b| r =~ b }
      p blocks
  end

This one uses a single regular expression to match a single character, and 19 or more occurences of the same character directly afterwards (using a back reference).

A: The regular expression for your reject! statement is:
/([A-Z])\1{19}/

This matches any capital letter followed by 19 more of the exact same letter.


text:
Q: Model of Mosfet Switching in LTspice I would like to perform a simulation on LTspice about a switching MOSFETs.
In particular on how the parasitic inductance and capacitance affect the switching transient.
In order to perform this analysis I need a MOSFET model of SCT3022AL from Rhom semiconductor.
Following the link:
https://www.rohm.com/datasheet/SCT3022AL
Unfortunately it is not avaiable the LTspice model of this MOSFET.
I could create my own model but I saw that the information needed are:

*

*L (channel    length)

*W (channel    width)

*VT0   (zero-bias  threshold   voltage)

*KP    (transconductance,  μn/pCox)

*LAMBDA     (channel-length    modulation  coefficient,    λ)

These information are not avaiable in the datasheet.
How can I do to create my own model? Alternatively, do you know if this model is avaiable?
Thank You.

A: You do not need to create a model. You can download the finished model from the manufacturer's website.
https://www.rohm.com/products/sic-power-devices/sic-mosfet/sct3022al-product/documents
In the "Design Model" section are files for Spice to download.
If you do not know how to add a model, here is an example post about it on my blog:
http://sigaris-electronics.eu/2018/11/ltspice-adding-an-element-model-to-the-schema/

A: But these basic model parameters dos not include any information about the parasitic inductance and capacitance. Are you aware of this?
Also, you can download the model directly from Rhom sie.
https://www.rohm.com/products/sic-power-devices/sic-mosfet
And if you find some time you can try to watch this:
https://www.youtube.com/watch?v=eE-8Q0vPUak


text:
Q: Bootstrap modal not rendering inside ASP.NET main form I am trying to pull values entered by a user from a C# code file using a Bootstrap modal, which is in an ASPX page.
I found that Bootstrap is not allowing two forms in one page (blocking values of another form), and as we all know, we have a master form in master page, so I can't use another form for the modal, and my modal is rendering outside of the main form.
I used this code to render my modal inside the parent form:
function showDialog(id) {
    $('#paiddialog').on('show.bs.modal', function (e) {
        $(this).parent().appendTo("form");
    });

    $('#' + id).modal("show");
}

This is the modal's HTML:

    <asp:UpdatePanel ID="panels" runat="server">
        <ContentTemplate>

Update payment Information

                                            Select Assignment ID

                                            <asp:DropDownList ID="ddlassignmentid" runat="server" DataTextField="iassignmentidref" AppendDataBoundItems="true" DataValueField="iassignmentid" DataSourceID="sdassignmentid" CssClass="form-control">
                                                <asp:ListItem Text="Select" Value=""></asp:ListItem>
                                            </asp:DropDownList>
                                            <asp:LinkButton ID="btnbindassigdetails" runat="server" OnClick="btnbindassigdetails_Click" CssClass="btn btn-info">Pull info</asp:LinkButton>

                        <asp:LinkButton ID="btnupdate" OnClick="btnupdate_Click" runat="server" CssClass="btn btn-success large">Request Payment </asp:LinkButton>

                        <button aria-hidden="true" data-dismiss="modal" class="btn btn-default">
                            Close
                        </button>

        </ContentTemplate>
    </asp:UpdatePanel>

The rendered HTML is some thing like this

        <form id="mainform" action="page.aspx">

        </form>

But still no luck.

A: There is an ugly hack to allow another form tag.
</form><form action="blah.aspx" id="blah">

This will get a trailing form in there for you to work with. Not recommended but a way around the 1 form tag limit of .Net

A: For any new readers, i managed to fix this by adding bellow script
$(this).parent().appendTo("form");


text:
Q: writeToParcel() not called in implementation of BaseSavedState In my custom view I have:
 @Override
public Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    return new SavedState(superState,  mSomeBoolean);
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    final SavedState savedState = (SavedState) state;
    super.onRestoreInstanceState(savedState.getSuperState());
    this.mSomeBoolean = savedState.someBoolean;
}

My SavedState implements BaseSavedState, and the problem is that it appears that writeToParcel(Parcel out, int flags) does not get called, but, strangely enough, the state is correctly saved.
I do not understand why it happens and, more so, how the someBoolean state is saved despite not being written to parcel. Any help or direction would help.

Update:
Here is the SavedState implementation:
  class SavedState extends View.BaseSavedState {

boolean someBoolean;

SavedState(Parcelable superState, boolean someBoolean){
    super(superState);
    this.someBoolean = someBoolean;
}

private SavedState(Parcel in) {
    super(in);
    this.someBoolean  = (in.readInt() != 0);
}

@Override
public void writeToParcel(Parcel out, int flags) {
    super.writeToParcel(out, flags);
    out.writeInt(someBoolean ? 1 : 0);
}

public static final Parcelable.Creator<SavedState> CREATOR
        = new Parcelable.Creator<SavedState>() {
    public SavedState createFromParcel(Parcel in) {
        return new SavedState(in);
    }

    public SavedState[] newArray(int size) {
        return new SavedState[size];
    }
};

}


text:
Q: Frobenius Norm and Relation to Eigenvalues I've been working on this problem, and I think that I almost have the solution, but I'm not quite there.

Suppose that $A \in M_n(\mathbb C)$ has $n$ distinct eigenvalues $\lambda_1... \lambda_n$. Show that $$\sqrt{\sum _{j=1}^{n} \left | {\lambda_j} \right |^2 } \leq \left \| A \right \|_F\,.$$

I tried using the Schur decomposition of $A$ and got that $\left \| A \right \|_F = \sqrt{TT^*}$, where $A=QTQ^*$ with $Q$ unitary and $T$ triangular, but I'm not sure how to relate this back to eigenvalues and where the inequality comes from.

A: You are in the right way. The corresponding Schur decomposition is $A = Q U Q^*$, where $Q$ is unitary and $U$ is an upper triangular matrix, whose diagonal corresponds to the set of eigenvalues of $A$ (because $A$ and $U$ are similar). Now because Frobenius norm is invariant under unitary matrix multiplication:
$$||QA||_F = \sqrt{\text{tr}((QA)^*(QA))} = \sqrt{\text{tr}(A^*Q^* QA)} = \sqrt{\text{tr}(A^*A)} = ||A||_F$$
(the same remains for multiplication of $Q$ on the right) then we could write:
$$||A||_F = ||Q U Q^*||_F = ||U||_F \rightarrow \sqrt{\sum_{j=1}^n |\lambda_j|^2} \leq ||A||_F$$
directly proves your statement.
Note: The inequality comes from the definition of the Frobenius norm: The sum of the square of all entries in the matrix. Since $U$ contains the eigenvalues on his diagonal, the term in the left has to be less or equal to the sum over all entries, because $U$ could have non zero entries over his diagonal.


text:
Q: add item direction in tileList component I have Flash AS3 Project with tile list.
I have buttons on stage. each of them when clicked adds tile with a picture on it to the tileList using the addTile() function.
I'm using 2 columns in the tile list and I want the new tiles will appear from right to left (1st item - right column, 2nd item - left column..).
is it possible?
additionally, is it possible that each new item will be added to the top of the tileList instead of the bottom of it?
thank!

A: I am not sure weather this help you or not, But you can try layoutDirection = rtl property. this will change the direction of the tiles form right to left.


text:
Q: SQL trigger insert or update with same table avoid recursive I am SQL GUI kind of person and have less experience writing trigger.  I did some searching and came up the following code.  I cannot make any database level parameter change and cannot alter the table scheme.  A column called Myvalue will be numbers but some it shows decimal value.  My goal is to make sure the value of the column Myvalue is an integer when insert or update.  If a decimal value is updated or inserted, the trigger will fire and remove the decimal value.  Will the following code do the job?  Do I need to use the trigger_nestlevel command to avoid recursion?  How can I test to make sure the trigger run once even with multiple rows on insert or update?
DROP TRIGGER IF EXISTS 'Mytrigger'
CREATE TRIGGER ON Table1
AFTER insert, update
AS
BEGIN
    IF TRIGGER_NESTLEVEL(OBJECT_ID('Mytrigger')) <= 1
    BEGIN
        set nocount on
        UPDATE Mytable set Myvalue=substring(Myvalue,0,charindex('.',Myvalue))
        FROM Mytable t
        inner join inserted i on i.Myvalue like '%.%'
    END
END


text:
Q: @FormParam gives null Javascript to REST Jersey I am trying to do a POST request/fetch were I want to send some values and after reading around I found out that @FormParam is what I should use but I cant get it to work. I try to do my Fetch as such
  createOyster(){
  var resource = "version=" + this.state.version + "&customer=" + this.state.customer + "&userId=" + this.state.userId + "&oysterName=" + this.state.oysterName + "&backupFile=" + this.state.backupFile;
  console.log(resource)
  fetch('http://localhost:8080/sleepy-oyster/v2/oyster/', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: JSON.stringify({
      resource
    })
  })
}

And the console.log(resource) gives
version=[object Object]&customer=NCC&userId=johjon&oysterName=NCC_johjon2&backupFile=Kund_NCC_Prod_2018-03-22.228680192.bak

And when i try to do the request ot my REST that looks like this
 @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createOyster(@FormParam("version") String version, @FormParam("customer") String customer,
                             @FormParam("userId") String userId, @FormParam("oysterName") String oysterName,
                             @FormParam("backupFile") String backupFile) throws IOException {
    System.out.println(version + "HEJ HEJ HEJ HEJ HEJ HEJ HEJ");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    NexusResource resource = mapper.readValue(version, NexusResource.class);
    System.out.println(resource);

     dbWorker.restoreDatabase(userId, backupFile);
     oysterWorker.createOyster(userId, oysterName);
     oysterWorker.installOyster(oysterName);
     String selectedVersion = versionWorker.getVersionFromNexus(resource,oysterName,customer);

     return Response.ok(selectedVersion).build();
}

I get an NullPointerException that doesn't point to any of my code which makes me confused
javax.servlet.ServletException: java.lang.NullPointerException
at org.glassfish.jersey.servlet.WebComponent.serviceImpl (WebComponent.java:489)
at org.glassfish.jersey.servlet.WebComponent.service (WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service (ServletContainer.java:388)

I have probably screwed something up since its my first time using @FormParam. Can anyone see why it gives null. the Sout in my REST gives null as well so the REST does not get it. I guess it is because the version is an [object Object] because the rest does not give null. How would I handle that?
If I just console.log(this.state.version) I get my full object
{resourceURI: "http://nexus.ad.hrm.se/nexus/service/local/reposit…ent/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/", relativePath: "/se/hrmsoftware/hrm/hrm-release/16.1-SNAPSHOT/", text: "16.1-SNAPSHOT", leaf: false, lastModified: "2018-05-02 06:57:07.0 UTC", …}


text:
Q: Google Speech API how to pickup results of my asyncrecognize request I executed the following
curl -s -k -H "Content-Type: application/json" -H "Authorization: Bearer ${MY_ACCESS_TOKEN} " https://speech.googleapis.com/v1beta1/speech:asyncrecognize -d @json/automator.json

which returned
{
  "name": "376034185739864225"
}

I tried using the interactive GET available here`  passing in that name value above, (about 12 hours later),

but got back
{
 "error": {
  "code": 404,
  "message": "Requested entity was not found.",
  "status": "NOT_FOUND"
 }
}

Am I missing something? Like, how to perform this properly, or my speech recognition response? Is it out there in the cloud somewhere?

A: I just had the same problem. Long story short, you have to use the same API key you POST with.
If you POST with
https://speech.googleapis.com/v1beta1/speech:asyncrecognize?key=AWESOMEKEY123

You have to retrieve results with
https://speech.googleapis.com/v1beta1/operations/NAME?key=AWESOMEKEY123

Your specified page uses a different API key.

A: In my case, I followed the tutorial and created a Service Account with its corresponding credentials, but it seems that to retrieve results from the web you need to create an API key even though Service Account is the preferred method for authentication.
I think this is because to retrieve the results from the web you explicitly need an API Key for the project (tried all other keys I could get from the service account but none worked, but that's probably because I'm still new to this authentication mumbo jumbo).
After creating an API key in the credentials, you can pretty much use it without problem for viewing the recognition results. I'm new to this too but so far is the only method that has worked consistently for me.


text:
Q: Foreground service returns a Notification Error based on Channel ID on API 29, and not on API 26. How to retrieve proper Channel ID? I get the following error when running this Service on my smartphone (API 29) but not in another one (API26). For the error I assume that the problem is with the Channel ID when running my service as a ForegroundService, but I coulnd't find out how to solve it... I didn't know which Channel Id would be the appropiate. Any help?
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android.testworkmanager, PID: 22582
    android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=TestChannelID pri=2 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1969)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7520)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
E/MQSEventManagerDelegate: failed to get MQSService.

This is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.testworkmanager">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="false"
            android:icon="@drawable/ic_launcher_background"
            android:label="MyServiceLabel" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

and this is my service:
package com.example.android.testworkmanager;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

public class MyService extends Service {
    private static final int ONGOING_NOTIFICATION_ID = 2;
    private String channelID = "TestChannelID";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        Log.v("APP_TEST","Service_startCommand");

        Intent notificationIntent = new Intent(this, MyService.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification =
                new NotificationCompat.Builder(this, this.channelID)
                        .setContentTitle("TestNotification")
                        .setContentText("This is the text to display on notification")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentIntent(pendingIntent)
                        .setTicker("TickerText")
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .build();

        startForeground(ONGOING_NOTIFICATION_ID, notification);

        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v("APP_TEST","Service_Create");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v("APP_TEST","Service_destroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        //TODO for communication return IBinder implementation
        return null;
    }
}

And the service would be started and stopped with the following commands:
//For starting
        Intent intent = new Intent(this, MyService.class);
        startService(intent);

... (somewhere else)

//For stopping
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);

A: For starting a foreground service in Android O and above, you have to create a channel, before you create a notification. And you also have to put the same channel id in your Notification.Builder constructor. Here is an example on how to create a channel:
/**
 * Method that create a channel for notification showed to user, for foreground service
 */
@RequiresApi(api = Build.VERSION_CODES.O)
private void createChannel() {
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
            CHANNEL_NAME,  //name of the channel
            NotificationManager.IMPORTANCE_HIGH);   //importance level

    // Configure the notification channel.
    mChannel.setDescription("Description of your channel");
    mChannel.enableLights(true);

    // Sets the notification light color for notifications posted to this channel, if the device supports this feature.
    mChannel.setShowBadge(true);
    assert nm != null;
    nm.createNotificationChannel(mChannel);
}

A: It looks like You are missing a notification channel that is required from Android O and above.
Documentation: https://developer.android.com/training/notify-user/channels
Try this sample:
private String CHANNEL_ID;

private void createNotificationChannel() {
    CharSequence channelName = CHANNEL_ID;
    String channelDesc = "channelDesc";
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
        channel.setDescription(channelDesc);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        assert notificationManager != null;
        NotificationChannel currChannel = notificationManager.getNotificationChannel(CHANNEL_ID);
        if (currChannel == null)
            notificationManager.createNotificationChannel(channel);
    }
}

public void createNotification(String message) {

    CHANNEL_ID = UiUtil.getStringSafe(R.string.app_name);
    if (message != null ) {
        createNotificationChannel();

        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(UiUtil.getStringSafe(R.string.app_name))
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
        Uri uri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        mBuilder.setSound(uri);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        int notificationId = (int) (System.currentTimeMillis()/4);
        notificationManager.notify(notificationId, mBuilder.build());
       }
}

I hope this answered is helpful for you.
Thank You


text:
Q: a statement in the signature $\{c,f^1, R^2\}$ is satisfiable in a structure M $\iff $ for every element there exists a closed term t s.t. $t^M=a$ Question:
Prove/Disprove that there exists a statement A in the signature $\{c,f^1, R^2\}$ that is satisfiable in a structure M $\iff $ for every element in $a\in D^M$ there is a closed term t s.t. $t^M=a$.
My proof:
(I believe it's true)

*

*Assume that such a statement b exists.

*Denote $a_n = \exists x f^n(c)=x$ (= there's an element in the domain which is "reachable" via $f^n$.

*So $\neg a_n$ (= for every element in the domain - it's "unreachable" by $f^n$)

*Denote $T= \lbrace \neg a_n \mid n \in \mathbb N \rbrace \cup \lbrace b \rbrace$

*On one hand $T$ isn't satisfiable because it means (from b) that every element can be "reached" by some $f^n$, but the set of $a$s says that no element can be reached via $f^n$.

*On the other hand every subset $T' \subset T$ is satisfiable because:

*if $T'$ is a subset of the a's then it can be satisfied by a structure that defines $f$ to never reach some element no matter how many times it's applied.

*If $T'$ is $b$ then it can be satisfied by a structure that its domain is of size $1$ ($c$ itself) and $f^M=\operatorname{Id}$.

*If $T'$ is a mix of both $a$s and $b$ then we can define a structure in which $f$ reaches all elements only after the applying $f$ $q$ times ($q$ being maximal $n$ appearing in $T'$).

*This leads to a contradiction using the compactness theorem on $T$.
My problem with this proof is this - how can I define $f$ s.t it'll satisfy the requirements I've made in my proof (that it will reach all elements only after $n$ applies and not reach them before)?

A: You are heading in the right direction but haven't quite got there. Suppose the sentence $A$ holds in a structure $M$ for the given signature iff any element $a \in D^M$ is equal to $f^n(c)$ for some $n \in \Bbb{N}$. (We don't believe such an $A$ exists, so we want to derive a contradiction.) Now consider the model $M$ with $D^M = \Bbb{N}$, $c = 0$ and $f(n) = n + 1$ ($R$ is not relevant). $A$ must hold in $M$ (because if $n \in \Bbb{N}$, then $n = f^n(0)$). Now add a new constant symbol $d$ to our signature and consider the sentences $B_n \equiv A \land d \neq f^n(c)$. Any finite subset of the sentences $B_n$ is satisfiable in $M$. Hence, by compactness, there is a model $M'$ that satisfies every $B_n$. But then in $M'$, $A$ holds, but $d \neq f^n(c)$ for any $n$. This contradicts our assumption on $A$.


text:
Q: Ruby: Problem with Different Versions I posted this question before but I had 11.04 which is not supprted. So now I updated to 11.10, but still the problem is not solved.
I want to use ruby 1.9.1 . The problem I am facing is shown below. I wish someone could help me out.

$ cat /etc/lsb-release
  DISTRIB_ID=Ubuntu
  DISTRIB_RELEASE=11.10
  DISTRIB_CODENAME=oneiric
  DISTRIB_DESCRIPTION="Ubuntu 11.10"
$ sudo apt-get install ruby1.9.1-full
  Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  ruby1.9.1-full is already the newest version.
  0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.
$ update-alternatives --config ruby
  update-alternatives: error: no alternatives for ruby.
$ ruby -v
  ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-linux]
$ which ruby1.9.1
  /usr/bin/ruby1.9.1

A: You might find rvm helpful. Rvm is a command line program that allows you to manage multiple versions of ruby. If you are interested, you can read more about it here.
If you just want to get rid of Ruby 1.8.1, run the following command:
sudo apt-get remove ruby1.8

A: Aaron is correct, I am adding this answer to elaborate a bit and provide more details.
This is a huge thing in Rails land, and big (though not as bad) in ruby land.
The system version of ruby must be 1.8 or some installed applications will fail. There are quite a few UI applications that use ruby. However 1.9 is the new way to go, so you more then likely would want to use it on new projects (be they rails or pure ruby).
If your developing an application Ruby Version Manager should meet your needs. You can download and install it from this site. BUT if your trying to use 1.9 that was packaged for/with Ubuntu, RVM WILL NOT WORK
RVM only loads in your environment. Usually only in your command line environment (though this doesn't have to be true). It compiles ruby from source and does not use packaged versions. Again this is the accepted way to use ruby for development, not as a user or consumer, or in production.
If an app you want to run requires ruby, you should be able to give it a ruby path. If the app in question is built for Ubuntu then installing that app should be all you need.
If your working with rails
Do not use the system ruby or the packaged rails gems. They are totally and completely wrong for development. Instead use RVM + bundler + gemsets to manage your setup. On production boxes you would normally use just bundler.
If your working with ruby
Do not use the system ruby or packaged gems. rvm + gemsets are the accepted way to build new projects. In production this gets more complicated depending on targets.
If your deploying Ruby Apps
Then you need to make sure you run your test suite on the individual system versions that you are aware of. In ruby patch level is important and you need to make sure you code works, or is deployed with, a working ruby.
Shameless plug
Instructions for compiling a working ruby from source can be found on my website. Note that it's for production servers, and intended to be used in rails environments. But it should get you started if you decide to compile.
TL;DR;

*

*RVM + gemsets = developing ruby applications

*RVM + bundler + gemsets = developing rails applications

*bundler (and a complied specific version of ruby) = production rails applications

*system ruby + lots of testing = production ruby applications


text:
Q: Weather API call from Java web application I am calling an api: openweathermap.org. If I call the url (strUri as formed in the below code after passing the city name and API key properly) directly in the address bar, it works fine but from the application, it throws an exception as:
api.openweathermap.org; nested exception is java.net.UnknownHostException: api.openweathermap.org.
java.net.UnknownHostException: api.openweathermap.org
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178) ~[na:1.7.0_51]
Please help. I am using RESTTemplate and spring-boot for the application.
@RequestMapping(method = RequestMethod.POST)
public String weatherPost(@ModelAttribute City city, ModelMap model) throws URISyntaxException{
    String apiKey="myApIKey";//Removed my original API Key for posting.
    RestTemplate template = new RestTemplate();
    String strUri= "http://api.openweathermap.org/data/2.5/weather?q="+city.getName()+",AU&appid="+apiKey+"&units=metric";
    URI uri = new URI(strUri);
    RequestEntity<String> request = new RequestEntity<String>(HttpMethod.GET,uri);
    ResponseEntity <WeatherResponse> weatherResponse = template.exchange(uri, HttpMethod.GET, request, WeatherResponse.class);
    City myCity = new City();
    model.put("weatherResponse", weatherResponse);
    model.put("city", myCity);
    return "weather";
}


text:
Q: R keep rows with maximum value of one column when multiple rows have values close to each other in an other column I have a data frame with dates and magnitudes. For every case where the dates are within 0.6 years from each other, I want to keep the date with the highest absolute magnitude and discard the other.

*

*This includes cases where multiple dates are all within 0.6 years from each other. Like c(2014.2, 2014.4, 2014.5) which should give `c(2014.4) if that year had the highest absolute magnitude.

*For cases where multiple years could be chained using this criterion (like c(2016.3, 2016.7, 2017.2), where 2016.3 and 2017.2 are not within 0.6 years from each other), I want to treat the dates that are closest to one another as a pair and consider the extra date in the criterion as a next candidate for another pair, (so the output will read like this c(2016.3, 2016.7, 2017.2) if 2016.3 had the highest absolute magnitude).

data:
set.seed(1)
library(dplyr)
mydf <- data.frame(date = c(2014.25, 2014.41, 2014.53, 2016.3,
                            2016.7,2017.2,2018.5, 2019.35, 2019.8),
                   magnitude = round(rnorm(9, mean=0, sd=0.4),4))
mydf <- mydf %>% mutate(absmag = abs(magnitude))
mydf
> mydf
     date magnitude absmag
1 2014.25   -0.1222 0.1222
2 2014.41    0.6047 0.6047
3 2014.53    0.1559 0.1559
4 2016.30   -0.2485 0.2485
5 2016.70   -0.8859 0.8859
6 2017.20    0.4500 0.4500
7 2018.50   -0.0180 0.0180
8 2019.35   -0.0065 0.0065
9 2019.80    0.3775 0.3775

Desired output:
     date magnitude absmag
1 2014.41    0.6047 0.6047
2 2016.70   -0.8859 0.8859
3 2017.20    0.4500 0.4500
4 2018.50   -0.0180 0.0180
5 2019.80    0.3775 0.3775

The things I tried so far failed to incoropate the requirements in the bullet points.
This solution can only handle pairs of two items within 0.6 years from each other:
whichAreClose <- function(your.number, x, threshold = 0.6){
  x[which(abs(x - your.number) != 0 & abs(x - your.number) < thresh)]}
out1 <- sapply(mydf$date,
                FUN = whichAreClose,
                x = mydf$date) %>%
  unlist() %>%
  split(., cut(seq_along(.), 2, labels = FALSE)) %>%
  lapply(
    ., function(i){
      mydf %>%
        filter(date %in% i) %>%
        slice_min(absmag)}) %>%
  bind_rows(.) %>%
  anti_join(mydf, .)

> out1
     date magnitude absmag
1 2014.41    0.6047 0.6047
2 2014.53    0.1559 0.1559
3 2016.30   -0.2485 0.2485
4 2016.70   -0.8859 0.8859
5 2017.20    0.4500 0.4500
6 2018.50   -0.0180 0.0180
7 2019.80    0.3775 0.3775

and this solution cannot distinguish different pairs at all:
out2 <- mydf %>%
  mutate(prevdist = abs(date - lag(date)),
         nextdist = abs(date - lead(date)),
         ispair = case_when(prevdist < 0.6 ~ 'yes',
                            nextdist < 0.6 ~ 'yes',
                            TRUE ~ 'no')) %>%
  filter(ispair == 'yes') %>%
  slice_min(absmag) %>%
  anti_join(mydf, .)

> out2
     date magnitude absmag
1 2014.25   -0.5883 0.5883
2 2014.41   -0.1913 0.1913
3 2014.53    0.1672 0.1672
4 2016.30    0.5435 0.5435
5 2017.20    0.1551 0.1551
6 2018.50   -0.0215 0.0215
7 2019.35   -0.5508 0.5508
8 2019.80   -0.1660 0.1660

P.S.: feel free to edit the title. I struggled to come up with a good one myself.

A: You can try to perform complete clustering on dates by using hclust. The manhattan (i.e. absolute) distances are calculated between pairs of dates. The "complete" clustering method will ensure that every member of a cluster cut at h height will be distant at most h from the other members.
mydf |>
  mutate(k = {
    dist(date, method = "manhattan") |>
      hclust(method = "complete") |>
      cutree(h = .6)
  })

#>     date magnitude absmag k
#>1 2014.25   -0.2506 0.2506 1
#>2 2014.41    0.0735 0.0735 1
#>3 2014.53   -0.3343 0.3343 1
#>4 2016.30    0.6381 0.6381 2
#>5 2016.70    0.1318 0.1318 2
#>6 2017.20   -0.3282 0.3282 3
#>7 2018.50    0.1950 0.1950 4
#>8 2019.35    0.2953 0.2953 5
#>9 2019.80    0.2303 0.2303 5

Here is shown the dendrogram obtained:

mydf |>
  mutate(k = {
    dist(date, method = "manhattan") |>
      hclust(method = "complete") |>
      cutree(h = .6)
  }) |>
  group_by(k) |>
  filter(absmag == max(absmag)) |>
  as.data.frame()

#>      date magnitude absmag k
#> 1 2014.53   -0.3343 0.3343 1
#> 2 2016.30    0.6381 0.6381 2
#> 3 2017.20   -0.3282 0.3282 3
#> 4 2018.50    0.1950 0.1950 4
#> 5 2019.35    0.2953 0.2953 5

A: With cumsum and purrr::accumulate.
library(tidyverse)

mydf %>%
  group_by(cum = cumsum(accumulate(c(0, diff(date)), ~ifelse(.x + .y <= 0.6, .x + .y, 0)) == 0)) %>%
  slice_max(absmag)

     date magnitude absmag    cum
1 2014.53   -0.3343 0.3343      1
2 2016.30    0.6381 0.6381      2
3 2017.20   -0.3282 0.3282      3
4 2018.50    0.1950 0.1950      4
5 2019.35    0.2953 0.2953      5

Explanation:
purrr:accumulate takes the difference between the values of the vectors as input, and if the cumulative sum (.x + .y) is below 0.6, it outputs the cumulative sum (for instance for the first three elements), but if it's higher than 0.6, the cumsum resets to 0. So for the fourth element, because 0.28 + 1.77 > 0.6, the function sets the fourth element to 0.
c(0, diff(mydf$date))
# [1] 0.00 0.16 0.12 1.77 0.40 0.50 1.30 0.85 0.45

accumulate(c(0, diff(mydf$date)), ~ifelse(.x + .y <= 0.6, .x + .y, 0))
# [1] 0.00 0.16 0.28 0.00 0.40 0.00 0.00 0.00 0.45

Everytime the cumsum resets to 0, it is actually a new group with subsequent rows being below the thresholds. So, to capture groups, one can use cumsum(... == 0):
cumsum(accumulate(c(0, diff(mydf$date)), ~ifelse(.x + .y <= 0.6, .x + .y, 0)) == 0)
# [1] 1 1 1 2 2 3 4 5 5


text:
Q: Disk full while running hadoop I ran a recursive map/reduce program. Something went wrong and it nearly consumes all the disk space available in C drive. So i closed the resource manager, node manager, Name Node, data node consoles.
Now i have a C drive which is almost full and i don't know how to empty the disk space and make my C drive as it was before. What should i do now. Any help is appreciated.
Here is the code
public class apriori {
public static class CandidateGenMap extends Mapper<LongWritable, Text, Text, Text>
{
    private Text word = new Text();
    private Text count = new Text();
    private int Support = 5;

    public void CandidatesGenRecursion(Vector<String> in, Vector<String> out,
                                        int length, int level, int start,
                                        Context context) throws IOException {

        int i,size;

        for(i=start;i<length;i++) {
            if(level==0){
                out.add(in.get(i));
                } else {

                out.add(in.get(i));

                int init=1;
                StringBuffer current = new StringBuffer();
                for(String s:out)
                {
                    if(init==1){
                        current.append(s);
                        init=0;
                    } else {
                        current.append(" ");
                        current.append(s);
                    }
                }

                word.set(current.toString());
                count.set(Integer.toString(1));
                try {
                    context.write(word, count);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(i < length-1) {
                CandidatesGenRecursion(in, out, length,level+1,i+1, context);
            }
            size = out.size();
            if(size>0){
                out.remove(size-1);
            }
        }

    }

    @Override
    public void map(LongWritable key,Text value,Context context) throws IOException
    {
        String line = value.toString();
        StringTokenizer tokenizer = new StringTokenizer(line);
        String[] token=new String[2];
       int i=0;
        while(tokenizer.hasMoreTokens()){
           token[i]= tokenizer.nextToken();
           ++i;
        }

        StringTokenizer urlToken = new StringTokenizer(token[1],",");

        Vector<String> lst = new Vector<String>();
        int loop=0;
        while (urlToken.hasMoreTokens()) {

            String str = urlToken.nextToken();

                lst.add(str);
                loop++;

        }

        Vector<String> combinations = new Vector<String>();

        if(!lst.isEmpty()) {
            CandidatesGenRecursion(lst, combinations, loop,0,0, context);
        }

    }
}

public static class CandidateGenReduce extends Reducer<Text, IntWritable, Text, IntWritable>
{

    public void reduce(Text key,Iterator<IntWritable> values,Context context) throws IOException
    {

        int sum = 0;
        while (values.hasNext()) {
            sum += values.next().get();
        }
        try {
            context.write(key, new IntWritable(sum));
            } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

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

    Date dt;
    long start,end; // Start and end time

    //Start Timer
    dt = new Date();
    start = dt.getTime();

    Configuration conf1 = new Configuration();
    System.out.println("Starting Job2");
    Job job2 = new Job(conf1, "apriori candidate gen");
    job2.setJarByClass(apriori.class);

    job2.setMapperClass(CandidateGenMap.class);
    job2.setCombinerClass(CandidateGenReduce.class); //
    job2.setReducerClass(CandidateGenReduce.class);
    job2.setMapOutputKeyClass(Text.class);
    job2.setMapOutputValueClass(Text.class);
    job2.setOutputKeyClass(Text.class);
    job2.setOutputValueClass(IntWritable.class);

    job2.setInputFormatClass(TextInputFormat.class);
    job2.setOutputFormatClass(TextOutputFormat.class);

    FileInputFormat.addInputPath(job2, new Path(args[0]));
    FileOutputFormat.setOutputPath(job2, new Path(args[1]));
    job2.waitForCompletion(true);
    //End Timer
    dt = new Date();
    end = dt.getTime();

}

}

A: Hadoop needs sufficient disk space for its i/0 operations at each phase (map, reduce etc).

A: Check in your HDFS your job output path and delete the contents.
List contents:
$ sudo -u hdfs hadoop fs -ls [YourJobOutputPath]

Disk used:
$ sudo -u hdfs hadoop fs -du -h [YourJobOutputPath]

Delete contents (be careful!, it's recursive):
$ sudo -u hdfs hadoop fs -rm -R [YourJobOutputPath]

A: Deleting the output directory might help in freeing your disk from the files created by the MapReduce job.


text:
Q: How to exclude cyclic deprecated dependencies in maven without killing the dependencies completely? I have a case that I have the following cyclic dependencies in maven:
JAR A version 1.1 depends on JAR B version 1.0
JAR B version 1.1 depends on JAR A version 1.0

For some reason that I don't know, Maven brings all the 4 JARs: A 1.0, A 1.1, B 1.0 and B 1.1, which results in a classpath conflict.
This really sucks. I already ask the developers of both JARs to fix this, however I can't simply sit and wait for the day that they decide to fix this.
I tried this:
<dependency>
    <groupId>groupA</groupId>
    <artifactId>artifactA</artifactId>
    <version>1.1</version>
    <type>pom</type>
    <scope>compile</scope>
    <exclusions>
        <exclusion>
            <groupId>groupB</groupId>
            <artifactId>artifactB</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>groupB</groupId>
    <artifactId>artifactB</artifactId>
    <version>1.1</version>
    <type>pom</type>
    <scope>compile</scope>
    <exclusions>
        <exclusion>
            <groupId>groupA</groupId>
            <artifactId>artifactA</artifactId>
        </exclusion>
    </exclusions>
</dependency>

The result is that maven excludes all of the JARs as if none dependency were added, and the project does not compiles because there are missing classes.
So, other than just asking both JARs developers to solve this, what can I do? How can I import both the new dependencies while leaving out both the old ones?

A: Pragmatic solution would be to redeclare the unwanted dependencies as provided, for example:
<dependency>
  <groupId>groupA</groupId>
  <artifactId>artifactA</artifactId>
  <version>1.0</version>
  <scope>provided</scope>
</dependency>

I'm not particularly fond of using provided in such manner, since it leaves the dependency in the compile time and could lead to unwanted compile dependencies, but I see no other way in your case ;(.


text:
Q: why https://api.twitter.com/1/statuses/update not work? I use oauth to access twitter, failed to update when I use https:api.twitter.com/1/statuses/update with user token and secret, but succeed to use https:twitter.com/statuses/update.
Accordding the OAuth Authentication (dev.twitter.com/pages/basic_to_oauth), https:api.twitter.com/1/statuses is suggested, did something I miss? Anybody help me out?

A: I guess you figured it out in the mean while, but this works for me:
https://api.twitter.com/1/statuses/...
Perhaps it wasn't active when you tried ?


text:
Q: Can't add item to iesi.collections.generic.iset Trying to add item to iset, but it doesn't happens.
var controlPoint = new ControlPoint {Lon = 53.25253, Lat = 56.23422, Radius = 16};
//controlPoint.ApprovedRoutes = new HashedSet<ApprovedRoute>();
controlPoint.Save();

var route = new ApprovedRoute();
route.ControlPoints = new HashedSet<ControlPoint>();
route.ControlPoints.Add(controlPoint);
route.Name = "sometext";
route.Save();

//controlPoint.ApprovedRoutes.Add(route);
//controlPoint.Save();

classes:
public class GeoPoint: Entity<long>
{
    public virtual double Lon { get; set; }
    public virtual double Lat { get; set; }
}

public class ControlPoint: GeoPoint
{
    public virtual double Radius { get; set; }
    public virtual Iesi.Collections.Generic.ISet<ApprovedRoute> ApprovedRoutes { get; set; }
}

public class ApprovedRoute : Entity<long>
{
    public virtual string Name { get; set; }
    public virtual Iesi.Collections.Generic.ISet<ControlPoint> ControlPoints { get; set; }
}

here's mapping:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Transport" namespace="Transport.Models">
  <class name="GeoPoint" table="GeoPoint">
    <id name="Id">
      <column name="id" not-null="true" />
      <generator class="identity" />
    </id>
    <property name="Lon" />
    <property name="Lat" />

    <joined-subclass name="ControlPoint" table="ControlPoint">
      <key column="Id"/>
      <property name="Radius"/>

      <set name="ApprovedRoutes" table="M_ApprovedRoute_ControlPoint" inverse="true">
        <key column="PointId"></key>
        <many-to-many column="RouteId" class="ApprovedRoute" />
      </set>

    </joined-subclass>
  </class>
</hibernate-mapping>

one more:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Transport" namespace="Transport.Models">
  <class name="ApprovedRoute" table="ApprovedRoute">
    <id name="Id">
      <column name="id" not-null="true" />
      <generator class="identity" />
    </id>
    <property name="Name" />
    <set name="ControlPoints" table="M_ApprovedRoute_ControlPoint">
      <key column="RouteId"></key>
      <many-to-many column="PointId" class="ControlPoint" />
    </set>
  </class>
</hibernate-mapping>

what I'm doing wrong? ControlPoint and ApprovedRoute records appears in tables, but M_ApprovedRoute_ControlPoint is still empty.
p.s. .Save() calls Session.SaveOrUpdate(obj)

A: so easy. I just wrap SaveOrUpdate in a transaction and now it's work!
using (ITransaction tx = Session.BeginTransaction())
        {
            try
            {
                Session.SaveOrUpdate(obj);
                Session.Flush();
                tx.Commit();
            }
            catch (HibernateException)
            {
                tx.Rollback();
                throw;
            }
        }


text:
Q: How is Vocab and Integer (one hot) representation stored and what does the ('string', int) tuple means in torchtext.vocab()? I am trying to train an RNN for binary classification. I have my vocab made from 1000000 words and please find the below outputs...
text_field = torchtext.data.Field(tokenize=word_tokenize)
print(text_field.vocab.freqs.most_common(15))
>>
[('.', 516822), (',', 490533), ('the', 464796), ('to', 298670), ("''", 264416), ('of', 226307), ('I', 224927), ('and', 215722), ('a', 211773), ('is', 180965), ('you', 180359), ('``', 165889), ('that', 156425), ('in', 138038), (':', 132294)]

print(text_field.vocab.itos[:15])
>>
['<unk>', '<pad>', '.', ',', 'the', 'to', "''", 'of', 'I', 'and', 'a', 'is', 'you', '``', 'that']

text_field.vocab.stoi
>>
{'<unk>': 0,'<pad>': 1,'.': 2,',': 3,'the': 4,'to': 5,"''": 6,'of': 7,'I': 8,'and': 9,'a': 10, 'is': 11,'you': 12,'``': 13,'that': 14,'in': 15,....................

The documentation says:
freqs – A collections.Counter object holding the frequencies of tokens in the data used to build the Vocab.
stoi – A collections.defaultdict instance mapping token strings to numerical identifiers.
itos – A list of token strings indexed by their numerical identifiers.

Which not comprehensible by me.
Can Some one Please explain what are these by giving the intuition of each of those?
For example, if the is represented by 4, then does it mean that if a sentence contains the word the,

*

*Is it going to be a 1 at location 4?  OR

*Is it going to be a 1 at position 464796 OR

*Is it going to be a 4 at position 464796??

What happens when multiple the are there there??

A: If "the" is represented by 4, then that means that

*

*itos[4] is "the"

*stoi["the"] is 4

*there is a tuple ('the', <count>) somewhere in freqs, where count is the number of times that 'the' appears in your input text. That count has nothing to do with its numerical identifier 4.


text:
Q: Running oauth2-proxy kubernetes locally on wsl using minikube? Hey I was just trying to set-up a local kubernetes environment on wsl using minikube.
But i constantly struggling in using oauth2-proxy because of the redirect-urls and dns problems. I couldn't find a redirect solution using localhost, and also i couldn't access
http://oauth2proxy.namespace.svc.cluster.local/

from my windows machine.
Port-forwarding for via kubectl port-forward specific port does work but i still left with the host-ip:port and not the required dns name