text:
Q: Using Google KML to successfully draw routes/lines on web-based Google Map I want to be able to draw routes on a web-based Google Map.  I have spent quite a bit of time looking at the Google Maps API and I have written the following Javascript:
$(document).ready(function () {
            $(function() {
                loadScript();
            });
});

function initialize() {
    var myOptions = {
        zoom: 10,
        disableDefaultUI: true,
        center: new google.maps.LatLng(51.5001524, -0.1262362),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById('fullscreen'), myOptions);

    var ck = Math.floor(Math.random() * 1000);
    var ctaLayer = new google.maps.KmlLayer('http://xxx/storage/kml/test.kml');
    ctaLayer.setMap(map);

}

function loadScript() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
    document.body.appendChild(script);
}

My .kml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="blueLine">
      <LineStyle>
        <color>ffff0000</color>
        <width>4</width>
      </LineStyle>
    </Style>
    <Style id="pinkLine">
      <LineStyle>
        <color>ffff33ff</color>
        <width>4</width>
      </LineStyle>
    </Style>
    <Placemark>
      <name>LHR-BSS</name>
      <visibility>1</visibility>
      <styleUrl>#blueLine</styleUrl>
      <description><![CDATA[LHR-BSS]]></description>
      <LineString>
        <extrude>1</extrude>
        <tessellate>1</tessellate>
        <coordinates>
          -0.4534243,51.4703429,0
          4.4895353,50.9035504,0
        </coordinates>
      </LineString>
    </Placemark>
  </Document>
</kml>

Yet despite this, I can't get the second line to draw within Google Maps.  When I load the KML within Google Earth, it loads no problem. What am I doing wrong?

A: This was far easier than I ever expected.  I didn't need the KML or the KML layer (which was notorious for caching btw).  I simply used:
var p = new google.maps.Polyline({
   map: m.map,
   path: [hkg, end],
   strokeColor: color,
   geodesic: m.geodesic
});

Making sure that when setting up the map, geodesic is set to true:
var maps = {
            mymap: {
                map: null,
                geodesic: true,
                overlay: { path: null} }
 };

With the lat longs set as google lat longs:
var hkg = new google.maps.LatLng(22.3088856, 113.9141464); /*hong kong*/

This worked a treat :)


text:
Q: How to run pry on Debian Linux for ARM I installed rvm and Ruby 1.9.3p194 on a Raspberry Pi using Debian Linux.  When I installed pry using gem install pry, everything installed perfectly but typing pry in a terminal didn't work:
pi@raspberrypi ~ $ pry
bash: pry: command not found

there's a pry file in ~/.rvm/gems/ruby-1.9.3-p194/bin.  I have to call it with ruby_noexec_wrapper in the same directory:
pi@raspberrypi ~ $ .rvm/gems/ruby-1.9.3-p194/bin/pry
/usr/bin/env: ruby_noexec_wrapper: No such file or directory
pi@raspberrypi ~ $ cd .rvm/gems/ruby-1.9.3-p194/bin
pi@raspberrypi ~/.rvm/gems/ruby-1.9.3-p194/bin $ ./ruby_noexec_wrapper pry
[1] pry(main)>

What's the proper way to run pry in this Linux?  On Windows and Mac OS X I can simply type pry at any command prompt or terminal.
UPDATE: Here's my rvm info:
pi@raspberrypi ~/.rvm/gems/ruby-1.9.3-p194/bin $ rvm info

ruby-1.9.3-p194:

  system:
    uname:       "Linux raspberrypi 3.1.9+ #168 PREEMPT Sat Jul 14 18:56:31 BST 2012 armv6l GNU/Linux"
    bash:        "/bin/bash => GNU bash, version 4.2.20(1)-release (arm-unknown-linux-gnueabihf)"
    zsh:         " => not installed"

  rvm:
    version:      "rvm 1.14.10 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]"
    updated:      "1 day 23 hours 36 minutes 30 seconds ago"

  ruby:
    interpreter:  "ruby"
    version:      "1.9.3p194"
    date:         "2012-04-20"
    platform:     "armv6l-linux-eabi"
    patchlevel:   "2012-04-20 revision 35410"
    full_version: "ruby 1.9.3p194 (2012-04-20 revision 35410) [armv6l-linux-eabi]"

  homes:
    gem:          "/home/pi/.rvm/gems/ruby-1.9.3-p194"
    ruby:         "/home/pi/.rvm/rubies/ruby-1.9.3-p194"

  binaries:
    ruby:         "/home/pi/.rvm/rubies/ruby-1.9.3-p194/bin/ruby"
    irb:          "/home/pi/.rvm/rubies/ruby-1.9.3-p194/bin/irb"
    gem:          "/home/pi/.rvm/rubies/ruby-1.9.3-p194/bin/gem"
    rake:         "/home/pi/.rvm/gems/ruby-1.9.3-p194@global/bin/rake"

  environment:
    PATH:         "/home/pi/.rvm/gems/ruby-1.9.3-p194/bin:/home/pi/.rvm/gems/ruby-1.9.3-p194@global/bin:/home/pi/.rvm/rubies/ruby-1.9.3-p194/bin:/home/pi/.rvm/bin:/usr/lib/arm-linux-gnueabihf/libfm:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
    GEM_HOME:     "/home/pi/.rvm/gems/ruby-1.9.3-p194"
    GEM_PATH:     "/home/pi/.rvm/gems/ruby-1.9.3-p194:/home/pi/.rvm/gems/ruby-1.9.3-p194@global"
    MY_RUBY_HOME: "/home/pi/.rvm/rubies/ruby-1.9.3-p194"
    IRBRC:        "/home/pi/.rvm/rubies/ruby-1.9.3-p194/.irbrc"
    RUBYOPT:      ""
    gemset:       ""

A: first make sure rvm is loaded properly:
type rvm | head -n 1 # should be: rvm is a function
type gem | head -n 1 # should be: gem is a function

if they are not functions this means RVM is not properly loaded, this could be a bug in your shell (like limited bash), you can try to fix it with:
rvm get head --auto

It might be required to relogin after this command to run all shell configuration files.
next, make sure you use rvm:
rvm use 1.9.3
echo $PATH
echo $GEM_PATH # those two need match those from `rvm info`
rvm info

you can also set one ruby to be default:
rvm use 1.9.3 --default

refreshing PATH - type in terminal
hash -r # OR:
PATH="$PATH"

or even relogin should help for this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you go throught a Java list, and check if it equals multiple strings? I do not know if this is possible, but if it is would it be done like this?:
List<String> arrayList= new ArrayList<String>();
arrayList.add("ex1");
arrayList.add("ex2");
arrayList.add("ex12");

for (int i = 0; i < arrayList.length; i++) {
    switch (arrayList.get(i)) {
        case "ex1":
           //Do something
        default:
           //Do something else
    }
}

A: A ArrayList is an implementation of List which is backed by an array, so you need to use the List API to retrieve values, for example...
for (int i = 0; i < arrayList.size(); i++) {
    switch (arrayList.get(i)) {
        case "ex1":
        'Do something'
        default:
        'Do something else'
    }
}

You could also use a for-each loop...
for (String value : arrayList) {
    switch (value) {
        case "ex1":
        'Do something'
        default:
        'Do something else'
    }
}

Take a look at The Collections Trail, java.util.List and java.util.ArrayList for more details
You also might like to have a look at The for Statement trail

A: In Java 7, you can do:
List<String> arrayList = new ArrayList<>();
arrayList.add("ex1");
arrayList.add("ex2");
arrayList.add("ex12");

for (String element : arrayList) {
    switch (element) {
    case "ex1":
        // Do something
        break;
    default:
        // Do something else
    }
}


text:
Q: Where should I keep my company's parent POM? We have a root POM in one of our project which more and more people consume. So we're now considering to extract this into a real parent POM (i.e. without <modules> and specific build commands).
Now the question is where should this new parent POM go? I see two options:

*

*A new project

*Into a folder parent/ inside of the framework project.

I looked at Maven and it uses a distinct project for the parent POM (here is the latest release).
But that means the relativePath is most often wrong (I really don't want developers to have to checkout the parent POM with this approach).
What are the differences/advantages/drawbacks of the two approaches?

A: The simple reason having a separate project for such company pom is based on the release cycle of such a pom cause it's different of all other projects/artifacts within the different projects. A release is necessary to have a released version which means a defined state of the company pom. This release is simply being deployed into your company repository manager and can be consumed by many projects. During the time updates are comming in like plugin updates etc. so you can decide making a new release of your company pom. And the different projects can decide to pick the update by simply changing the version or not.


text:
Q: Move file names with path to a file in a directory along with files I was moving only the file names in a text file which was working using:
cd /data/sources/
find $PWD -type f -name "Asset_*">> /data/processing/asset_files.txt

But, I also need to:

*

*Move Asset_* files also in /data/processing/.

*Move first 1000 files into /data/processing/.

How do I add these two things?

A: Refactoring answer of @Dominique you can use find command and move the files. THis can take a lot of time (depend of number of files)
And the command is like:
cd /data/sources/
find $PWD -type f -name "Asset_*" -exec mv {} /target_dir \;

If you want to move exactly 1000 files you can do it with something like
a=1
cd /data/sources/
for i in $PWD/Asset_*
do
mv "$i" /target_dir
a=$(($a + 1))
if [ "$a" -gt 1000 ]
then break
fi
done

A: You're on the wrong track, wanting to copy/move 1000 entries. You seem to have a lot of Asset_* files (over 1000) and by limiting the number to 1000, you want to check if the behaviour is right and then do it for the whole bunch.
Although this seems correct, the limiting to 1000 is quite a burden and will make your script complicated for no purpose.
I'd propose another approach : imagine you have filenames like this:
Asset_00000
Asset_00001
Asset_00002
...
Asset_00010
Asset_00011
...
Asset_99999

Then, you might first try to do you thing, using Asset_0000*, and then, once you've verified everything is correct, do it for all Asset_* files.
As far as the moving is concerned, you can do this as follows:
find /directory -name "Asset_0000*" -exec mv {} /target_directory \;


text:
Q: Showing uniform continuity for two intervals Show that if $f$ is continuous on $[0, \infty)$ and uniformly continuous $[a, \infty)$ for some positive constant $a$, then $f$ is uniformly continuous on $[0, \infty)$.
Here is my attempt at the proof. A classmate is concerned my proof leaves a gap around $a$ that is not rigorously defined.
Proof:
Let $f: [0, \infty) \rightarrow \Bbb R$ continuous and let $f: [a, \infty) \rightarrow \Bbb R$ uniformly continuous for $a>0$
Consider the interval $I:= [0,a]$ and $[0,a] \subseteq \Bbb R$
Note the interval $[0,a]$ is closed and bounded. By the Heine-Borel Theorem, since $I$ is closed and bounded, $I$ is compact.
If a function $f$ is continuous on a compact space then it is uniformly continuous thus $f$ is uniformly continuous on $[0, \infty)$
This is a proof for my real analysis class and I've used a proof that I learned last semester in topology. So it may be the case that this technique is not allowable. Can anyone advise?
Is this proof sufficient to confirm that the points around $[0,a)$ are continuous?

A: Let $\epsilon > 0$.  Since $[0,a]$ is a compact subset of $\mathbb R$ and $f$ is continuous on $[0,\infty)$, $f$ is uniformly continuous on $[0,a]$.  Hence, there exists $\delta_1 > 0$ such that
$$
x,y \in [0,a], \quad |x - y| < \delta_1 \implies |f(x) - f(y)| < \epsilon/2.
$$
Since $f$ is uniformly continuous on $[a,\infty)$, there exists
$\delta_2 > 0$ such that
$$
x,y \in [a,\infty), \quad |x - y| < \delta_2 \implies |f(x) - f(y)| < \epsilon/2.
$$
Choose $\delta = \min{\delta_1,\delta_2}$.  By our choice of $\delta$, if $x,y \in [0,a]$ or $x,y \in [a,\infty)$, then $|x - y| < \delta \implies |f(x) - f(y)| < \epsilon/2 < \epsilon$.  If $x < a < y$ and $|x - y| < \delta$, then $|x - a| < \delta \leq \delta_1$  so
$$
|f(x) - f(a)| < \epsilon/2.
$$
Similarly, we have $|y - a| < \delta \leq \delta_2$ so that
$$
|f(x) - f(a)| < \epsilon/2.
$$
Thus, we see that if $x < a < y$ and $|x - y| < \delta$, then
$$
|f(x) - f(y)| \leq |f(x) - f(a)| + |f(y) - f(a)| < \epsilon.
$$


text:
Q: JPA 1.0 Hibernate & Derby HashMap with an Enum key usage I am looking for help in mapping a HashMap, using JPA, which is built like so..  <NflTeam, Integer>.  NflTeam is an enum of all the possible NFL Teams. The value for the map is unimportant at this stage.
I have tried, not using any annotation over the hash map field in the entity class, but what I have found is that when I attempt to update the map, I get the following error:

ERROR org.hibernate.util.JDBCExceptionReporter  - A truncation error
  was encountered trying to shrink VARCHAR () FOR BIT DATA '(Binary data
  value not displayed)' to length 255. 5371 [AWT-EventQueue-0] ERROR
  org.hibernate.event.def.AbstractFlushingEventListener  - Could not
  synchronize database state with session

I have also tried to add the following annotation to the field in the entity class @ElementCollection, as I have seen a few places say that this is the annotation use to map hash maps, but I am finding I get the following error when I attempt to map the entity:

Caused by: org.hibernate.AnnotationException: Illegal attempt to map a
  non collection as a @OneToMany, @ManyToMany or @CollectionOfElements:
  ie.madden.stats.core.beans.Player.teamsPlayedWithMap

Does anyone know the correct annotation to use in JPA, to map a genericized hashmap (constructed of an )?
Thanks in advance

EDIT::
Here is my persistence.xml file:
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">  <persistence-unit name="MaddenStatsPU" transaction-type="RESOURCE_LOCAL">    <provider>org.hibernate.ejb.HibernatePersistence</provider>    <class>ie.madden.stats.core.beans.Player</class>    <class>ie.madden.stats.core.beans.Fixture</class>    <properties>
     <property name="hibernate.show_sql" value="true"/>
     <property name="hibernate.format_sql" value="false"/>
     <property name="javax.persistence.jdbc.url" value="jdbc:derby:maddenstats;create=true"/>
     <property name="javax.persistence.jdbc.password" value="madden"/>
     <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
     <property name="javax.persistence.jdbc.user" value="madden"/>
     <property name="hibernate.hbm2ddl.auto" value="update"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
     <property name="hibernate.default_schema" value="MaddenStats"/>    </properties>  </persistence-unit> </persistence>

Secondly here is my entity class for Player where the hashmap is being used:
@Entity
public class Player implements IEntityBean
{
    @Id
    @GeneratedValue(generator="id_Gen")
    @SequenceGenerator(name="id_Gen", sequenceName="id_Seq")
    private Long playerId;

    private String name;
    private Long played = new Long(0);
    private Long wins = new Long(0);
    private Long losses = new Long(0);
    private Integer winPercentage = new Integer(0);

    private HashMap<NflTeam, Integer> teamsPlayedWithMap = new HashMap<>();
}

In the sample above I have removed any attempts I have tried for the mapping of the HashMap.
Oh also NflTeam is an enum, which like I have already said is a enum of all the NFL Teams...

A: JPA1 does not provide support for such a Map. You have to go to implementation specifics. JPA2 does.


text:
Q: Errors running CutyCapt on Centos 5.7 without X Server Having everything installed and compiled successfully, I am getting this lovely output, anyone has an idea?  (it's a centos 5.7 without x server, so I am emulating this using the infamous xvfb-run)
./xvfb-run ./CutyCapt
Locking assertion failure.  Backtrace:
#0 /usr/lib64/libxcb-xlib.so.0 [0x7f58396d690c]
#1 /usr/lib64/libxcb-xlib.so.0(xcb_xlib_unlock+0x24) [0x7f58396d6a14]
#2 /usr/lib64/libX11.so.6 [0x7f58399260f0]
#3 /usr/lib64/libXfixes.so.3(XFixesQueryVersion+0x4f) [0x37e8a03c9f]
#4 /usr/lib64/qt47/libQtGui.so.4 [0x7f583b7268ce]
#5 /usr/lib64/qt47/libQtGui.so.4(_ZN19QApplicationPrivate9constructEP9_XDisplaymm+0xde)         [0x7f583b6a741e]
#6 /usr/lib64/qt47/libQtGui.so.4(_ZN12QApplicationC1ERiPPcbi+0x78) [0x7f583b6a8088]
#7 ./CutyCapt(_ZN8QWebPage13triggerActionENS_9WebActionEb+0x1756) [0x4049be]
#8 /lib64/libc.so.6(__libc_start_main+0xf4) [0x312481d994]
#9 ./CutyCapt(_ZN7QObject5eventEP6QEvent+0x161) [0x4039e9]
CutyCapt: xcb_xlib.c:82: xcb_xlib_unlock: Assertion `c->xlib.lock' failed.
./xvfb-run: line 168:  2362 Aborted                 DISPLAY=:$SERVERNUM XAUTHORITY=$AUTHFILE     "$@" 2>&1

for comparison, this one runs OK:
./xvfb-run /usr/bin/xclock

A: I have fixed this by setting LIBXCB_ALLOW_SLOPPY_LOCK environment variable:
export LIBXCB_ALLOW_SLOPPY_LOCK=1

A: The problem is in libX11.
I got this problem after Cpanel upgraded libX11 to a later version (1.1.3).
When I downgraded to version 1.0.3 then problem disappeared.


text:
Q: Is there way to return actual x,y-coordinates from the image? my dear py-experts.
I wrote a GUI program in python (Tkinter library) which displays a picture, to display an image i used the Canvas widget. The program does load a picture (its width/height always bigger than Canvas width/height) and when i make a mouse click on the Canvas it returns a x,y - coordinates (and color grayscale value), but it always a coordinates of Canvas, not an image ones. For example - image sizes are x=5040 and y=3360 and Canvas widget sizes are x=500 and y=400 and when i making a click on Canvas i never get values,even if i scrolling image, more than 500 for X-axis and 400 for Y-axis respectively.  What i did wrong, how to get right information from the image?
Thnx.

A: As the docs on Canvas explain:

Coordinate Systems
The Canvas widget uses two coordinate systems; the window coordinate system (with (0, 0) in the upper left corner), and a canvas coordinate system which specify where the items are drawn. By scrolling the canvas, you can specify which part of the canvas coordinate system to show in the window.
The scrollregion option is used to limit scrolling operations for the canvas. To set this, you can usually use something like:

canvas.config(scrollregion=canvas.bbox(ALL))

To convert from window coordinates to canvas coordinates, use the canvasx and canvasy methods:

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

Note that this will give you canvas coordinates, which are not necessarily the same as image coordinate—if you, e.g., left a border around the image within the canvas, you will have to correct for that manually.


text:
Q: Why does %autosetup perform patching BEFORE extracting sources? I have a very straightforward arrangement -- one source tarball, one patch:
Source: http://...../foo-%{version}.tar.gz
Patch: my-patch-for-foo.diff
...
%prep
%autosetup -v -n bar-%{version}

However, when I attempt to use the %autosetup in the %prep step, rpmbuild attempts to patch first -- before extracting:
/bin/cat ..../SOURCES/my-patch-for-foo.diff |
/usr/bin/patch
Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.8PV0PY
+ umask 022
+ cd /....
+ LANG=C
+ export LANG
+ unset DISPLAY
+ cd /....
+ rm -rf bar-0.12.18
+ /bin/tar -xvvf -
+ /usr/bin/gzip -dc ..../SOURCES/foo-0.12.18.tgz

For some reason, there is no error reported by patch -- but the extracted code ends up unpatched and my build fails later.
Using the ordinary %setup followed by %patch0 works fine, but what's wrong with %autosetup?
I'm on CentOS-6.8, if it matters, where RPM is of version 4.8.0. Thank you!
Update, splitting the %autosetup into %setup and %autopatch does not work either -- %autopatch does not do anything useful. Because my patches are all in default format, I'm going to use my reimplementation of %autopatch:
%prep
%setup -n bar-%{version}
%{lua:
    for i, p in ipairs(patches) do
        print("%patch"..i)
    end
}

Have I really found a bug, or am I doing something grotesquely wrong?

A: I observed the same issue on CentOS 6.7.
As mentioned above, RPM 4.8 supposedly doesn't support %autosetup; http://rpm.org/user_doc/autosetup.html also confirms that it's supported starting from 4.11.
However, I found that /usr/lib/rpm/macros (installed from rpm-4.8.0-55.el6.x86_64) does actually include a definition of the %autosetup macro, and rpm -q --changelog rpm shows that it was backported "recently":
* Mon Feb 08 2016 Lubos Kardos <lkardos@redhat.com> - 4.8.0-52
- Add %autosetup macros (#1265021)

Obviously that implementation seems to be broken, though.
The EPEL packaging guidelines says that "The %autosetup macro is available in all EPEL releases (via epel-rpm-macros for EPEL5 and EPEL6)" (emphasis mine), so I tried installing that package.  After installing epel-rpm-macros-6-16.noarch (instructions for adding the EPEL YUM repository if you haven't already done this), /etc/rpm/macros.zzz-epel-autosetup contained a different definition of %apply_patch (which is used by %autopatch, which is used by %autosetup).  This fixed the issue - patches are now applied after the sources are extracted.


text:
Q: How to escape an html tag in Razor In a View in ASP.NET MVC, I need to type following line of text:
"< h t m l > This is how you escape an HTML tag in Razor < / h t m l >"
Please remove spaces from < h t m l > to consider it a proper html tag.
How do I accomplish it? All answers are welcome.

A: Try this.
  @{ var myHtmlString = new HtmlString("<html> This is how you escape an HTML tag in Razor </html>");}
  @Html.Encode(myHtmlString)

Prints

Another Simple Way is :
  @Html.Encode(Html.Raw("<html> This is how you escape an HTML tag in Razor </html>"));

gives same output as above.


text:
Q: Separating Duplicate Rows into Separate Columns TSQL I have a block of data which has duplicate row ID's (CLIENT_DIWOR is the ROW ID) but relate to different groups. I can't just delete the duplicate row as they tie in to two different groups, so what I am trying to do is move the duplicate to the next column, so I can get the calculations correct at the end of my query. So for an example of what I am after
This is what I have
    CLIENT_DIWOR    GROUP_NAME
        -1          Priv Client Serv (Sector)
        -1          Social Business (Sector)

This is what I want
CLIENT_DIWOR    GROUP_NAME                    Second Group Name
     -1         Priv Client Serv (Sector)   Social Business (Sector)

I have tried using COUNT(*) with a group by but that doesn't bring the correct results as it will just tell me there are 1 of everything, and what I am after is every time client_DIWOR duplicates add 1 to the previous number, as that will give me what I need to separate them out and rebuild it into a table, but I just cant see how to count it without grouping the numbers together, this is what I have so far with the count removed as I know that is wrong.
SELECT A.CLIENT_DIWOR,B.GROUP_NAME
from CLIENT_GRP_MEMBER A
JOIN CLIENT_GROUP B on B.DIWOR = A.CLIENT_GRP_DIWOR
order by CLIENT_DIWOR

A: A more general solution, using ROW_NUMBER:
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY A.CLIENT_DIWOR ORDER BY B.GROUP_NAME) rn
    FROM CLIENT_GRP_MEMBER A
    INNER JOIN CLIENT_GROUP B
        ON B.DIWOR = A.CLIENT_GRP_DIWOR
)

SELECT
    CLIENT_DIWOR,
    MAX(CASE WHEN rn = 1 THEN GROUP_NAME END) AS GROUP_NAME,
    MAX(CASE WHEN rn = 2 THEN GROUP_NAME END) AS SECOND_GROUP_NAME
FROM cte
GROUP BY
    CLIENT_DIWOR;

The advantage of this approach is that you ever need to cater to more than two columns in the output, you can easily extend the query.

A: If you want to put two groups for each CLIENT_DIWOR, you can use aggregation:
SELECT CLIENT_DIWOR,
       MIN(GROUP_NAME) as GROUP_NAME
       NULLIF(MAX(GROUP_NAME), MIN(GROUP_NAME)) as GROUP_NAME_2
from CLIENT_GRP_MEMBER cgm
GROUP BY CLIENT_DIWOR ;


text:
Q: Array mutation error while creating a custom layer in Flux I created a neural network using Flux library. My code is based on the paper "neural importance sampling". I defined custom layers and custom loss function. Each layer returns two outputs. When I run my code, I receive this error:

Mutating arrays is not supported
  …[6] LinearLayer at .\In[6]:13

This is my code:
using Zygote: Buffer
using Flux;

function calculate_forward(xa, xb, q, A::Int64, B::Int64, K::Int64, batch_size::Int64)
    bins = Int64.(ceil.(K*xb))
    ctransforms = zeros(B, batch_size)
    output = zeros(A+B, batch_size)
    dets = Buffer(zeros(batch_size))
    for s=1:batch_size
        det = 1.
        for i=1:B
            b = bins[i,s]
            for j=1:b-1
                ctransforms[i,s] += q[i,j,s]
            end
            ctransforms[i,s] += (K*xb[i,s]-(b-1))*q[i,b,s]
            det *= K*q[i,b,s]
        end
        dets[s] = det
    end
    output[1:A,:] = xa
    output[A+1:end,:] = ctransforms
    return output, copy(dets)
end

function calculate_inverse(za, zb, q, A::Int64, B::Int64, K::Int64, batch_size::Int64)
    xb = zeros(B, batch_size)
    x = zeros(A+B, batch_size)
    inv_dets = Buffer(zeros(batch_size))
    for s=1:batch_size
        inv_det = 1.
        for i=1:B
            q_sum = 0.
            for j=1:K
                if q_sum <= zb[i,s] < q_sum + q[i,j,s]
                    xb[i,s] += (zb[i,s]-q_sum)/(K*q[i,j,s])
                    xb[i,s] += (j-1)/K
                    inv_det *= 1/(q[i,j,s]*K)
                    break
                else
                    q_sum += q[i,j,s]
                end
            end
        end
        inv_dets[s] = inv_det
    end
    x[1:A,:] = za
    x[A+1:end,:] = xb
    return x, copy(inv_dets)
end

struct LinearLayer
    model
    A::Int64
    B::Int64
    K::Int64
    batch_size::Int64
end

struct InverseLinearLayer
    model
    A::Int64
    B::Int64
    K::Int64
    batch_size::Int64
end

function (l::LinearLayer)(input)
    A, B, K = l.A, l.B, l.K
    batch_size = l.batch_size
    if length(input) == 1
        x = input[1]
        xa, xb = x[1:A,:], x[A+1:end,:]
        q = softmax(reshape(l.model(xa), B, K, batch_size), dims=2)
        output, det = calculate_forward(xa, xb, q, A, B, K, batch_size)
    elseif length(input) == 2
        x, prev_det = input
        xa, xb = x[1:A,:], x[A+1:end,:]
        q = softmax(reshape(l.model(xa), B, K, batch_size), dims=2)
        output, det = calculate_forward(xa, xb, q, A, B, K, batch_size)
        det = det .* prev_det
    end
    return output, det
end

function (l::InverseLinearLayer)(input)
    A, B, K = l.A, l.B, l.K
    batch_size = l.batch_size
    if length(input) == 1
        z = input[1]
        za, zb = z[1:A,:], z[A+1:end,:]
        q = softmax(reshape(l.model(za), B, K, batch_size), dims=2)
        output, det = calculate_inverse(za, zb, q, A, B, K, batch_size)
    elseif length(input) == 2
        z, prev_det = input
        za, zb = z[1:A,:], z[A+1:end,:]
        q = softmax(reshape(l.model(za), B, K, batch_size), dims=2)
        output, det = calculate_inverse(za, zb, q, A, B, K, batch_size)
        det = det .* prev_det
    end
    return output, det
end

Flux.@functor LinearLayer
Flux.@functor InverseLinearLayer

function loss(x,y)
    return sum((y./forward([x])[2]).^2)
end

m1 = Chain(Dense(3,7,relu), Dense(7,16))
m2 = Chain(Dense(2,5,relu), Dense(5,24))

forward = Chain(LinearLayer(m1, 3, 2, 8, 32), LinearLayer(m2, 2, 3, 8, 32))
inverse = Chain(InverseLinearLayer(m2, 2, 3, 8, 32), InverseLinearLayer(m1, 3, 2, 8, 32))

f(x::Array{Float64, 2}) = x[1,:].*x[2,:].*exp.(x[3,:]).*sin.(x[4,:]).*sqrt.(x[5,:])

x = rand(5,32)
opt = ADAM()
for i=1:100
    Flux.train!(loss, Flux.params(forward), [(x,f(x))], opt)
    println(loss(x, f(x)))
end

The error above says that this part of code is problematic:
output, det = calculate_forward(xa, xb, q, A, B, K, batch_size)

The calculate_forward function is:
function calculate_forward(xa, xb, q, A::Int64, B::Int64, K::Int64, batch_size::Int64)
    bins = Int64.(ceil.(K*xb))
    ctransforms = zeros(B, batch_size)
    output = zeros(A+B, batch_size)
    dets = Buffer(zeros(batch_size))
    for s=1:batch_size
        det = 1.
        for i=1:B
            b = bins[i,s]
            for j=1:b-1
                ctransforms[i,s] += q[i,j,s]
            end
            ctransforms[i,s] += (K*xb[i,s]-(b-1))*q[i,b,s]
            det *= K*q[i,b,s]
        end
        dets[s] = det
    end
    output[1:A,:] = xa
    output[A+1:end,:] = ctransforms
    return output, copy(dets)
end

What could I do to solve it?


text:
Q: Treat data of a XML file using FileProvider I want to read an XML file stored in downloads using the Android app I am developing.
I want to use File Provider to search for it but once I find it, I want to know the real path of that XML file in order to parse it and treat it.
How can I make this?
I've tried many things but nothing works for me.

A: You have to use the URI provided by the file provider
InputStream inputStream = getContentResolver().openInputStream(uri);

and pass the input string using xml parser library


text:
Q: Is it possible to replace Thymeleaf fragment via JQuery directly? I'm trying to figure out how to replace the Thymeleaf fragment with jQuery.
This is what I tried:
$("#dataTable").replaceWith("user_panel/fragments/languages_list_fragment.html :: #languages_list_element");

It performs a replacement, but the element is replaced with text rather than a fragment.
What I anticipate is simply reloading the data without involving the backend.
As I previously stated, I couldn't find any examples on the internet that directly answered my question, which is why I'm asking here.


text:
Q: Можно ли совместно с justify-content для подгонки к pixel perfect использовать еще margin и padding
Пытаюсь подогнать 3-и элемента к pixel perfect. Задал родительскому блоку header__container в стилях justify-content: space-between, однако после этого логотип не бьется с pixel perfect. Можно ли элементу burger задать margin-right?


text:
Q: How can I output the slug of a comment author? I'm trying to output the slug of the comment author. I'm able to output the username using get_comment_author() but I can'tfigure out how to output the slug.
For example, username might be Test User while the slug might be test-user1
Howw can I output the comment author slug?

A: If you have the username then you should be able to get the user using the get_user_by function, which will return the user object
https://developer.wordpress.org/reference/functions/get_user_by/
$user = get_user_by(field, value);


text:
Q: priority if numbers in heap in python 3 Can someone explain me what's wrong in this code:
import heapq
a = [[1, 2], [0, 4], [3]]
h = []
for index in range(len(a)):
    i = 0
    while i < len(a[index]):
        heapq.heappush(h, a[index][i])
        i += 1
print(h)

I want to have smth like that: [0, 1, 2, 3, 4], but when I add 0 it's not becoming [0, 1, 2] but becoming [0, 2, 1].WHY? Thank you in advance!

A: What you're observing is intended behavior. Generally speaking, the top n values of a heap are not necessarily the smallest n values in the heap. (If this were true, we'd be able to sort in linear time by heapifying a list. But, heapifying a list is a linear-time operation, and comparison-based sorting requires O(n log n) time.)
To extract the smallest n elements, use heappop() n times:
import heapq
a = [[1, 2], [0, 4], [3]]
h = []
for index in range(len(a)):
    i = 0
    while i < len(a[index]):
        heapq.heappush(h, a[index][i])
        i += 1

n = 3
for i in range(n):
    print(heapq.heappop(h)) # Prints 0, 1, 2


text:
Q: Change size of cursor "hittest" bounding area in WPF Is it possible to increase the size of the point that is used for hit testing using the cursor in WPF?
I would like to be able to hit test with something similar to the entire area covered by the cursors image, as opposed to just a single point.
Im doing some line drawing that I need to recieve mouse events (enter/leave/etc), but having to align the cursor over small strokethicknesses can be tricky, and simply increasing the thickness isnt an option for me.

A: One technique you can use here is to draw a second line or path with the same geometry and increased thickness, make it invisible and place it on top of the visible line. To do this set Stroke=Transparent, which will be invisible but still pick up mouse events.
This gives you control over the hit test area, admittedly with a little extra work on your part.


text:
Q: Symfony2 Profiler empty result in database panel I am currently working on a private project that needs a high count on sql queries per page.
Therefor i wanted to fix that by reviewing the requests and trying to optimize.
i am using Symfony2 with Doctrine2 and the Symfony2 profiler.
The problem is, that i get an empty result page by my browser when i try to open the panel=db tab.
In the profiler bar i can see the query count(140, can be higher depending on users entries).
When i open the database panel on a page with a lower count of db queries, the panel works without any remarks.
Has anyone else faced this problem and knows a solution?
Best regards
Freddy

A: By default the profile stores the collected data in files in the cache directory. You could try to change the storage system to a more suitable one for such amount of data.
Here you have information on how to do it-> Switching the Profiler Storage
Hope it helps.


text:
Q: Weighted moving average in python I have data sampled at essentially random intervals. I would like to compute a weighted moving average using numpy (or other python package). I have a crude implementation of a moving average, but I am having trouble finding a good way to do a weighted moving average, so that the values towards the center of the bin are weighted more than values towards the edges.
Here I generate some sample data and then take a moving average. How can I most easily implement a weighted moving average? Thanks!
import numpy as np
import matplotlib.pyplot as plt

#first generate some datapoint for a randomly sampled noisy sinewave
x = np.random.random(1000)*10
noise = np.random.normal(scale=0.3,size=len(x))
y = np.sin(x) + noise

#plot the data
plt.plot(x,y,'ro',alpha=0.3,ms=4,label='data')
plt.xlabel('Time')
plt.ylabel('Intensity')

#define a moving average function
def moving_average(x,y,step_size=.1,bin_size=1):
    bin_centers  = np.arange(np.min(x),np.max(x)-0.5*step_size,step_size)+0.5*step_size
    bin_avg = np.zeros(len(bin_centers))

    for index in range(0,len(bin_centers)):
        bin_center = bin_centers[index]
        items_in_bin = y[(x>(bin_center-bin_size*0.5) ) & (x<(bin_center+bin_size*0.5))]
        bin_avg[index] = np.mean(items_in_bin)

    return bin_centers,bin_avg

#plot the moving average
bins, average = moving_average(x,y)
plt.plot(bins, average,label='moving average')

plt.show()

The output:

Using the advice from crs17 to use "weights=" in the np.average function, I came up weighted average function, which uses a Gaussian function to weight the data:
def weighted_moving_average(x,y,step_size=0.05,width=1):
    bin_centers  = np.arange(np.min(x),np.max(x)-0.5*step_size,step_size)+0.5*step_size
    bin_avg = np.zeros(len(bin_centers))

    #We're going to weight with a Gaussian function
    def gaussian(x,amp=1,mean=0,sigma=1):
        return amp*np.exp(-(x-mean)**2/(2*sigma**2))

    for index in range(0,len(bin_centers)):
        bin_center = bin_centers[index]
        weights = gaussian(x,mean=bin_center,sigma=width)
        bin_avg[index] = np.average(y,weights=weights)

    return (bin_centers,bin_avg)

Results look good:

A: You could use numpy.average which allows you to specify weights:
>>> bin_avg[index] = np.average(items_in_bin, weights=my_weights)

So to calculate the weights you could find the x coordinates of each data point in the bin and calculate their distances to the bin center.

A: This won't give an exact solution, but it will make your life easier, and will probably be good enough... First, average your samples in small bins. Once you have resampled your data to be equispaced, you can use stride tricks and np.average to do a weighted average:
from numpy.lib.stride_tricks import as_strided

def moving_weighted_average(x, y, step_size=.1, steps_per_bin=10,
                            weights=None):
    # This ensures that all samples are within a bin
    number_of_bins = int(np.ceil(np.ptp(x) / step_size))
    bins = np.linspace(np.min(x), np.min(x) + step_size*number_of_bins,
                       num=number_of_bins+1)
    bins -= (bins[-1] - np.max(x)) / 2
    bin_centers = bins[:-steps_per_bin] + step_size*steps_per_bin/2

    counts, _ = np.histogram(x, bins=bins)
    vals, _ = np.histogram(x, bins=bins, weights=y)
    bin_avgs = vals / counts
    n = len(bin_avgs)
    windowed_bin_avgs = as_strided(bin_avgs,
                                   (n-steps_per_bin+1, steps_per_bin),
                                   bin_avgs.strides*2)

    weighted_average = np.average(windowed_bin_avgs, axis=1, weights=weights)

    return bin_centers, weighted_average

You can now do something like this:
#plot the moving average with triangular weights
weights = np.concatenate((np.arange(0, 5), np.arange(0, 5)[::-1]))
bins, average = moving_weighted_average(x, y, steps_per_bin=len(weights),
                                        weights=weights)
plt.plot(bins, average,label='moving average')

plt.show()


text:
Q: How to compose Python exe programs using pipes? Python newbie here.

*

*I created a Python program, msg.py, which outputs a message (Hello, World).

*I created a Python program, id.py, which reads input and outputs it.

*Using py2exe I created an executable of each of them: msg.exe and id.exe

*I created a DOS batch file, set PATH to the dist folder of msg.exe and the dist folder of id.exe.

*I then added this to the DOS batch file:
msg | id
When I ran the batch file I got this error message:
Traceback (most recent call last):
  File "id.py", line 4, in <module>
IndexError: list index out of range

I surmised that the pipe symbol is not feeding the output of msg.exe to the input of id.exe. Is that correct?

*So then I placed this in the batch file:
id < msg
When I ran the batch file I got this error message:
Access is denied.

I really want step 5 to work. That is, I really want to be able to compose programs using the pipe symbol, like so:
A | B | C | ...

Ideally A, B, C, ... could be executables written in various languages, such as Python, C, etc.
How do I get this to work?
Below are the details of what I did. I am running on Windows 7.
Here is msg.py
import stdio

stdio.writeln('Hello, World')

Here is id.py
import sys
import stdio

msg = sys.argv[1]
stdio.writeln(msg)

Here is my DOS batch file:
@echo OFF

set PATH=%PATH%;msg/dist;id/dist

msg | id

A: sys.argv is for command line parameters (id.py a b c).
To read from a pipe, you need to use sys.stdin.read() in id.py.
Edit: See also: https://stackoverflow.com/a/7608205/478656


text:
Q: Jmeter doesn't resolve parameter (from CSV Data Set Config) into request Is try to use the CSV Data Set Config to insert a different username password for each Thread.
When posting to a login page the value of the password variable isn't resolved. The username variable is no problem. The variable is correctly loaded into the Thread because the Debug Sampler is showing the correct value for the password. I already tried to change the name of the variable, perhaps it clashes with some other variable name, but that didn't work.
Perhaps it's because the password field is a different type of input field?
Please let me know if need to clarify this more.. :)
Screenshot to clarify the situation:
1 - CSV-File

2- CSV Data Set Config

3 - Result Debug Sampler

4 - HTTP Request of the login page

5 - Result of the send request to the login page
Because here the variable isn't translated to the value the login process fails.

A: In your CSV Data Set Config element, in Variable Names (comma-delimited) field you have usernamecsv, pwdcsv... You need to remove space after comma!

usernamecsv, pwdcsv ---> usernamecsv,pwdcsv

This will solve your problem.


text:
Q: C# P/Invoke structure problem I am trying to write a C# P/Invoke wrapper for a C API (a native Win dll), and generally this is working fine. The only exception is a specific method which takes a struct as a parameter in the C code. The function is invoked without any exceptions, but it returns false indicating that something failed in the execution.
In the API header file the involved method and structs are defined as follows:
#define MAX_ICE_MS_TRACK_LENGTH  256
typedef struct tagTRACKDATA
{
    UINT nLength;
    BYTE TrackData[MAX_ICE_MS_TRACK_LENGTH];
} TRACKDATA, FAR* LPTRACKDATA;
typedef const LPTRACKDATA LPCTRACKDATA;

BOOL ICEAPI EncodeMagstripe(HDC /*hDC*/,
             LPCTRACKDATA /*pTrack1*/,
             LPCTRACKDATA /*pTrack2*/,
             LPCTRACKDATA /*pTrack3*/,
             LPCTRACKDATA /*reserved*/);

I have made an attempt to create a C# P/Invoke wrapper using the following code:
public const int MAX_ICE_MS_TRACK_LENGTH = 256;

[StructLayout(LayoutKind.Sequential)]
public class MSTrackData {
    public UInt32 nLength;
    public readonly Byte[] TrackData = new byte[MAX_ICE_MS_TRACK_LENGTH];
}

[DllImport("ICE_API.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool EncodeMagstripe(IntPtr hDC,
                    [In]ref MSTrackData pTrack1,
                    [In]ref MSTrackData pTrack2,
                    [In]ref MSTrackData pTrack3,
                    [In]ref MSTrackData reserved);

Then I try to invoke the EncodeMagstripe method using the following C# code:
CardApi.MSTrackData trackNull = null;
CardApi.MSTrackData track2 = new CardApi.TrackData();
byte[] trackBytes = Encoding.ASCII.GetBytes(";0123456789?");
track2.nLength = (uint)trackBytes.Length;
Buffer.BlockCopy(trackBytes, 0, track2.TrackData, 0, trackBytes.Length);

if (!CardApi.EncodeMagstripe(hDC, ref trackNull, ref track2, ref trackNull, ref trackNull)) {
    throw new ApplicationException("EncodeMagstripe failed", Marshal.GetLastWin32Error());
}

This causes an ApplicationException to be thrown, and the error code is 801 which according to the documentation means "Data includes too many characters for the selected Track 2 format.". However the selected track format should allow up to 39 characters (I have also tried shorter strings).
I suspect the problem occurrs due to something I did wrong in the MSTrackData definition, but I cannot see what this may be. Does anyone have any suggestions?

A: All the answers given so far have a bit of the answer but are incomplete. You need the MarshalAs - ByValArray as well as the new, your MSTrackDatas are already references so you do not need to pass them by ref and you must check what calling convention ICEAPI represents, if it is StdCall you don't need to change anything but if it is cdecl you will need to add the CallingConvention to your DllImport attribute. Also, you may need to add a MarshalAs attribute to your bool return value to make sure it is marshaled as 4 byte WinApi style bool. Here are the declares you'll (probably) need:
public const int MAX_ICE_MS_TRACK_LENGTH = 256;

[StructLayout(LayoutKind.Sequential)]
public class MSTrackData {
    public UInt32 nLength;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
    public Byte[] TrackData = new byte[MAX_ICE_MS_TRACK_LENGTH];
}

[DllImport("ICE_API.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EncodeMagstripe(IntPtr hDC,
                [In] MSTrackData pTrack1,
                [In] MSTrackData pTrack2,
                [In] MSTrackData pTrack3,
                [In] MSTrackData reserved);

A: I would define the BYTE array not with new, but use  the following code instead to initialise the right size:

[MarshalAs(UnmanagedType.byValTSt, SizeConst =256)]
  public readonly Byte[] TrackData;

I have used this successfully on char arrays in the past.

A: Looks to me like the problem is that you're passing a reference by reference.  Since MSTrackData is a class (i.e. reference type), passing it by reference is like passing a pointer-to-pointer.
Change your managed prototype to:
public static extern bool EncodeMagstripe(IntPtr hDC,
                    MSTrackData pTrack1,
                    MSTrackData pTrack2,
                    MSTrackData pTrack3,
                    MSTrackData reserved);

See the MSDN article about passing structures.

A: I had almost exactly the same problem - but with ReadMagstripe. And the solution provided here for EncodeMagstripe did not work for ReadMagstripe! I think the reason it did not work was that ReadMagstripe has to return data into the TRACKDATA structure/class, while EncodeMagstripe only passes data to the dll and data in TRACKDATA does not need to be changed. Here is the implementation that eventually worked for me - both with EncodeMagstripe and ReadMagstripe:
    public const int MAX_ICE_MS_TRACK_LENGTH = 256;
    [StructLayout(LayoutKind.Sequential)]
    public struct TRACKDATA
    {
        public UInt32 nLength;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string szTrackData;
    }

    [DllImport("ICE_API.dll", EntryPoint="_ReadMagstripe@20", CharSet=CharSet.Auto,
        CallingConvention=CallingConvention.Winapi, SetLastError=true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool ReadMagstripe(int hdc, ref TRACKDATA ptrack1, ref TRACKDATA ptrack2,
         ref TRACKDATA ptrack3, ref TRACKDATA reserved);

    [DllImport("ICE_API.dll", EntryPoint="_EncodeMagstripe@20", CharSet=CharSet.Auto,
        CallingConvention = CallingConvention.Winapi, SetLastError=true)]
    public static extern bool EncodeMagstripe(int hdc, [In] ref TRACKDATA ptrack1, [In] ref TRACKDATA ptrack2,
        [In] ref TRACKDATA ptrack3, [In] ref TRACKDATA reserved);

/*
        ....
*/

    private void EncodeMagstripe()
    {
        ICE_API.TRACKDATA track1Data = new ICE_API.TRACKDATA();
        ICE_API.TRACKDATA track2Data = new ICE_API.TRACKDATA();
        ICE_API.TRACKDATA track3Data = new ICE_API.TRACKDATA();
        ICE_API.TRACKDATA reserved = new ICE_API.TRACKDATA();

        //if read magstripe
        bool bRes = ICE_API.ReadMagstripe(printer.Hdc, ref track1Data, ref track2Data,
            ref track3Data, ref reserved);

        //encode magstripe
        if (bRes)
        {
            track2Data.szTrackData = "1234567890";
            track2Data.nLength = 10;

            bRes = ICE_API.EncodeMagstripe(printer.Hdc, ref track1Data, ref track2Data, ref track3Data, ref reserved);
        }
    }


text:
Q: Which formula should I use to place a user ID in one column based on a name in another column? Edited to reformat: I have 530 rows of employees in a spreadsheet, each has their manager listed in column H. There are 15 managers. In Column I, I need to assign an auditor to review each employee. Auditors should be assigned based on who the manager is. Each auditor has a unique "ID."
I want to determine if there is a function that can look at column H, and based on the name therein, return the corresponding auditor's unique ID.
I tried VLOOKUP by making a new worksheet with the first column as the manager name, second column with the auditor ID, but it returns errors (probably due to incorrect syntax)?

A: What you want to do is set up another sheet with Managers in 1 column and the corresponding username in the next column. From there, you'll want column K to do a VLOOKUP using column H, going to the 2nd sheet and pulling the 2nd column.


text:
Q: MYSQL like + group Well I'm having a problem mainly caused by bad structure in database. I'm coding this for a company whose code is quite messy and the table is very large so I don't think it's an option to fix the structure.
Anyway, my issue is that I'm trying to somehow group a value that won't be alone in the string...
They are storing values separated with commas... So it would be like
field: "category" value: 'var1, var2, var3'

And I will search using this query:
SELECT name, category
FROM companies
WHERE (MATCH(name, category) AGAINST ('$search' IN BOOLEAN MODE)
       OR category LIKE '$search%')

It would match with for example var2 (it's not limited to 3 variables though, can be solo or many more) and I'd split it manually in PHP, no problem. Although I will not get enough matches, I want e.g. 10 matches by different searches. To be more specific I'm making an autosuggest feature, which means I will for example want to match "moto%" with motorbike, motor alone or whatever but I keep getting the same values, like there'd be a couple of 100 of results that contains "motorbike" and I don't know how to filter them, as I'm not able to use GROUP BY due to bad db structure...
I found this: T-SQL - GROUP BY with LIKE - is this possible?
It SEEMED as something that would be a solution, but as far as I've tried I could not get it work with what I wanted.
So I'm wondering which solutions there are... If there are ABSOLUTELY no way of working this around I might probably have to fix the db structure (but this really has to be the last option)

A: Start taking steps to make database structure proper. Make an extra table and fill it with split values.
Then you can use proper queries to select the data you need. Both you and next developer will have less troubles with this project in the future, not mentioning queries speed gain.

A: I am not sure why i cannot write a comment, but maybe you can try this:
SELECT name, category FROM companies WHERE category LIKE '$search%' or LOCATE('search', category)>0;

That would look if in category appears any of your 'search' value.

A: I would have to agree that you should make the database right.  It'll save you much trouble and time later.  However, using SELECT DISTINCT may fix your immediate issue.


text:
Q: K-fold validation on Google Earth Engine I have a satellite image "india_image" and data in form of a feature-collection "ft". I want to perform k-fold validation on this data in Earth Engine. How to do so?
var india_image = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
    .filterBounds(india)
    .filterDate('2014-03-01','2014-09-01')
    .sort('CLOUD_COVER')
    .map(maskClouds)
    .median();

var ft = ee.FeatureCollection('ft:1fWY4IyYiV-BA5HsAKi2V9LdoQgsbFtKK2BoQiHb0');

I am training a CART model using this data.
var training = india_image.sampleRegions(ft,['class'],30);
var trained = ee.Classifier.cart().train(training, 'class', bands);

I want to perform k-fold validation on this data. How can I achieve it?


text:
Q: Identify the number of neighbors that resulted in the max score in the training/testing dataset enter image description here
I am working on GridSearchKNN case study and am confused on how to "Identify the number of neighbors that resulted in the max score in the training/testing dataset." This is my first time working with KNN.
I Tried:
from sklearn.metrics import accuracy_score
b_m = knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print(accuracy_score(y_test, y_pred))

A: There are some options.
Option 1 - Using argmax.
best_k = np.argmax(test_scores) + 1

Option 2 - Update best k in iteration.
best_score = -1
for i in range(1, 10):
    knn = KneighborsClassifier(i)
    knn.fit(X_train, y_train)
    score = knn.score(X_test, y_test)
    if score > best_score:
        best_score = score
        best_k = i

If you want to find the best k only (that is, you don't want scores of not best k), the option 2 is better.


text:
Q: Search box to find user in rails I'm somewhat new to rails. I'm going through making the classic twitter clone right now. I want to have a search bar on my homepage that allows the user to search for a twitter handle, and if the handle exists, it will send the user to the show page for that twitter handle.
I've been following a RailsCast on how to implement a simple search, but instead of doing it on the index like the video, I want to do it on the show action. I've run into some problems though. The form sits on my user index view.
Here is the error:
ActionController::UrlGenerationError in Users#index
Showing c:/Sites/Projects/twitterapp/twitter/app/views/users/index.html.erb where line #2 raised:

No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]

Here is the form:
<%= form_tag(user_path, method: 'get') do %>
      <%= text_field_tag(:search, params[:search]) %>
      <%= submit_tag("Search", name: nil) %>
<% end %>

Here is my show action:
def show
        @user = User.search(params[:search])
end

And here is my search method in my user model:
def self.search(search)
        if search
            find(:all, conditions:['name LIKE ?', "%#{search}%"])
        else
            find(:all)
        end
end

A: Actually you cannot use the show method as a search result finder. Because according to the rails convention:
For any resource like users, rails scaffold generates index,new, show, create, update, delete methods based on your routes files.
Thus based on the conventional way, show method always asks for an object. Lets say you are using UserContoller show  method. It asks for a user object. Which you haven't provide in the form. that's why :id missing error is given.
I would tell you to do some more learning. And for searching create a different method in a different controller and define that controller method to the routes.rb file. This is the best way to do.
If you still want to use the show method, then change the show methods routing from the routes.rb file. You've to manually declare the show action on routes file.

A: you are using user_path and path need to inform id from present user
you can do this in action :index but I recommend you to create a action to this
view
<%= form_tag(search_users_path, method: 'get') do %>
      <%= text_field_tag(:search, params[:search]) %>
      <%= submit_tag("Search", name: nil) %>
<% end %>

routes.rb
resources :users do
  post 'search',  :on => :collection
end

users_controller.rb
def search
  @user = User.search(params[:search])
end

You should to create a view search.html.erb similar as index.html.erb

A: As Emu and Breno pointed what causing the problem user_path requires an user id
Solution idea:
Why not just point to users index action? like this:
<%= form_tag(users_path, method: 'get') do %>
      <%= text_field_tag(:search, params[:search]) %>
      <%= submit_tag("Search", name: nil) %>
<% end %>

users_controller.rb:
def index
   if params[:search]
      @user = User.search(params[:search])
   end
end

and you can use ajax remote: true to handle the returned user object

A: Found your question via Google, but the responses and suggestions didn't work for me. Found another solution that did, so seems worth posting here.
"Search and Filter Rails Models Without Bloating Your Controller":
http://www.justinweiss.com/articles/search-and-filter-rails-models-without-bloating-your-controller/


text:
Q: MySQL query to bind parent row values to children rows I have a table like this (greatly simplified):
| id | firstName | lastName | parent |
|------------------------------------|
|  1 | NULL      | Smith    | NULL   |
|  2 | John      | NULL     | 1      |
|  3 | Jack      | NULL     | 1      |
|  4 | Jimmi     | Joe      | 1      |
|  5 | Jane      | Doe      | NULL   |

And I'm trying to create a query that can return the data like this:
| id | firstName | lastName |
|---------------------------|
|  1 | NULL      | Smith    |
|  2 | John      | Smith    |
|  3 | Jack      | Smith    |
|  4 | Jimmi     | Joe      |
|  5 | Jane      | Doe      |

Basically I want it to include all rows, including parent rows. In all child rows (where parent != NULL) I want it to pick the child field value, unless it it NULL, then it should pick the parent field value. Parent rows are not modified.
I've been trying different setups with different joins, but I can't get it right. Is this even possible?

A: *

*Joining parent with id using the parent as the table 1, this is because if we put data_2.parent = data.id then it would have joined incorrectly and we would have 3 rows with id 1 instead of 1 row.

*Once we have the join we just take the first non-null value using coalesce() . If the last name is present in the original table then we take that otherwise we use the new one that we create using the join above
code 1 :
WITH data_ AS (
SELECT  data.*, data_2.last_name as new_last_name,

FROM [table name] as data
LEFT JOIN data_2
ON data.parent = data_2.id
)

SELECT
*,
COALESCE(data_.last_name,data_.new_last_name) AS final_name FROM data_

code 2: more direct
SELECT
data.id,
data.first_name,
COALESCE(data.last_name,data_2.new_last_name) as final_LAST NAME

FROM [table name] as data
LEFT JOIN data_2
ON data.parent = data_2.id

A: you can self join the table with an LEFT JOIN on parent and id

SELECT t1.`id`, t1.`firstName`, COALESCE(t1.`lastName`,t2.`lastName`) FROM table1 t1 LEFT JOIN table1 t2 ON t1.`parent` = t2.id

id | firstName | COALESCE(t1.`lastName`,t2.`lastName`)
-: | :-------- | :------------------------------------
 1 | null      | Smith
 2 | John      | Smith
 3 | Jack      | Smith
 4 | Jimmi     | Joe
 5 | Jane      | Doe

db<>fiddle here


text:
Q: Check for subclass in Java I have the following classes:
Class Dog extends Animal
Class Cat extends Animal
Class Mouse extends Animal

Furthermore, I have a List in which I put every Animal, regardless of the subclass:
List<? extends Animal> list = new ArrayList<? extends Animal>();

Populating said list with Dogs, Cats and Mice works perfectly, unless I want to later check what kind of Animal there is inside the list.
for (Animal animal: list) {
    if (animal instanceof Dog) {
        //do some dog stuff
    }
    if (animal instanceof Cat) {
        // do some cat stuff
    }
}

How can I check for each Animal in the list whether it is a Dog, a Cat or a Mouse?

A: If you want to avoid multiple instanceof checks, you could have Dog, Cat and Mouse derive from the common superclass Mammal (which itself would be a subclass of Animal). Then you only have to check:

if (animal instanceof Mammal) { }

A cleaner solution would be to move the processing into a method, which you override for each type of Animal:

abstract class Animal
{
    public abstract void feed ();
}

class Dog extends Animal
{
    public void feed()
    {
        // feed the dog
    }
}

A: Wildcards such as <? extends Animal> are useful when your list contains elements of a derived type (i.e. Cat/Dog etc), but you don't know or care what it is. They're made so that they match ArrayList<Dog> or ArrayList<Cat> etc when you work with them in a generic way in methods.
But since you seem to be adding all kinds of elements into your list, you're very well off with ArrayList <Animal> in which you could add Dogs, Cats or what have you, because they are derived from Animal and therefore they are Animals.
Instead of the instanceof checks, I'd recommend adding a polymorphic method in the superclass and overriding it in all subclasses, so that you could later call it without needing to care what type the actual object is.


text:
Q: Display the modified list using a java.util.Iterator object and a while loop A) Define the following method in MyList and implement it in MyAbstractList.
// Adds the elements in otherList to this list.
// Returns true if
// this list changed as a result of the call.
public boolean addAll(MyList<E> otherlist)

B) Add code to "TestMyArrayList.java" to demonstrate that this method works correctly.
Display the modified list using a java.util.Iterator object and a while loop.
OK so I've already finished the Part A and I'm confused on part B. I don't understand what my professor wants me to do. I've done some stuff in it but I'm pretty sure it's not correct. Anybody knows if I'm even doing it correctly?
This is my MyList class
package listapi;

/**
 * @author Y. Daniel Liang
 */
public interface MyList<E> extends java.lang.Iterable<E> {

/** Add a new element at the end of this list*/
public void add(E e);

/**Add a new element at the specified index in this list*/
public void add(int index, E e);

/**Clear the list*/
public void clear();

/**Return true if this list contains the element*/
public boolean contains(E e);

/**Return the element from this list at the specified index*/
public E get(int index);

/**Return the index of the first matching element in this list. Return -1 if
 * no match.*/
public int indexOf(E e);

/**Return true if this list contains no elements*/
public boolean isEmpty();

/**Return the index of the last matching element in this list Return -1 if
 * no match.*/
public int lastIndexOf(E e);

/**Remove the first occurrence of the element o from this list. Shift any
 * subsequent elements to the left. Return true if the element is removed.*/
public boolean remove(E e);

/**Remove the element at the specified position in this list Shift any
 * subsequent elements to the left. Return the element that was removed from
 * the list.*/
public E remove(int index);

/**Replace the element at the specified position in this list with the
 * specified element and returns the new set.*/
public Object set(int index, E e);

/** Return the number of elements in this list */
public int size();

public boolean addAll(MyList<E> otherList);
}

This is my MyAbstractList class
package listapi;

/**
 * @author Y. Daniel Liang
 */
public abstract class MyAbstractList<E> implements MyList<E> {

protected int size = 0; // The size of the list

/**
 * Create a default list
 */
protected MyAbstractList() {
}

/**
 * Create a list from an array of objects
 */
protected MyAbstractList(E[] objects) {
    for (int i = 0; i < objects.length; i++) {
        add(objects[i]);
    }
}

@Override
/**
 * Add a new element at the end of this list
 */
public void add(E e) {
    add(size, e);
}

@Override
/**
 * Return true if this list contains no elements
 */
public boolean isEmpty() {
    return size == 0;
}

@Override
/**
 * Return the number of elements in this list
 */
public int size() {
    return size;
}

@Override
/**
 * Remove the first occurrence of the element e from this list. Shift any
 * subsequent elements to the left. Return true if the element is removed.
 */
public boolean remove(E e) {
    if (indexOf(e) >= 0) {
        remove(indexOf(e));
        return true;
    } else {
        return false;
    }
}

public boolean addAll(MyList<E> otherList) {
    for (E e : otherList) {
        add(e);
    }
    if (otherList.size() > 0)
        return true;
    return false;
}

}

This is where I need to add code to demonstrate that my addAll method is working correctly by displaying modified list using java.lang.iterator and a while loop
package listapi;

/**
 * @author Y. Daniel Liang
 */
public class TestMyArrayList {

public TestMyArrayList() {
    // Create a list
    MyList<String> list = new MyArrayList<>();

    // Add elements to the list
    list.add("America"); // Add it to the list
    System.out.println("(1) " + list);

    list.add(0, "Canada"); // Add it to the beginning of the list
    System.out.println("(2) " + list);

    list.add("Russia"); // Add it to the end of the list
    System.out.println("(3) " + list);

    list.add("France"); // Add it to the end of the list
    System.out.println("(4) " + list);

    list.add(2, "Germany"); // Add it to the list at index 2
    System.out.println("(5) " + list);

    list.add(5, "Norway"); // Add it to the list at index 5
    System.out.println("(6) " + list);

    // Remove elements from the list
    list.remove("Canada"); // Same as list.remove(0) in this case
    System.out.println("(7) " + list);

    list.remove(2); // Remove the element at index 2
    System.out.println("(8) " + list);

    list.remove(list.size() - 1); // Remove the last element
    System.out.print("(9) " + list + "\n(10) ");

    for (String s : list) {
        System.out.print(s.toUpperCase() + " ");
    }
Iterator itr = list.iterator();
    while(itr.hasNext()){
        Object a = itr.next();
        System.out.println(a);

}

public static void main(String[] args){
    new MyArrayList();

}

}


text:
Q: Coordinate geometry, finding the locus of a point. Is the solution in the text book incorrect? I spent some time on this question earlier today - the most difficult part was understanding the language used in the question and being able to visualise the point stated in the question as a point in the plane. After some wrestling I have managed to get an answer similar to the text but I appear to out by a factor of two, i.e. my solution is half of that quoted in the text. I'll stop waffling and give you the question, apologies for my lack of a diagram and if my algebra isn't perfect.
Question is as follows:
The equations of the sides of a rectangle are $x=0$, $x=2a$, $y=0$ and $y=a$. A point moves so that the sum of the squares of its distances from the sides of the rectangle is $k$, a constant. Show that the path of the point is a circle and find the coordinates of its centre.
If the radius of the circle is $5a$, find $k$.
Solution gives: $(a,\frac{a}{2})$ and $k=105a^2$
My working is as follows and apologies once again for lack of a diagram.
Let $P(\alpha,\beta)$ be a point on the locus.
Then we have:
$$(\alpha-2a)^2+\alpha^2+(\beta-a)^2+\beta^2=k$$
$$\implies 2\alpha^2+2\beta^2-4a\alpha-2a\beta+4a^2+a^2-k=0$$
$$\implies\alpha^2+\beta^2-2a\alpha-a\beta+\frac{5a^2}{2}-\frac{k}{2}=0\qquad(1)$$
This has the general form of a circle i.e., $\alpha^2+\beta^2+2f\alpha+2g\beta+c=0$ with centre $(-f,-g)$ and radius, $$r=\sqrt{f^2+g^2-c}\qquad(2)$$
Therefore, as $x=\alpha,\text{and},\ y=\beta$, equation of circle is:
$$x^2+y^2-2ax-ay+\frac{5a^2}{2}-\frac{k}{2}=0$$
$$\therefore\quad\text{locus is a circle with centre at}(a,\frac{a}{2})$$
$$\text {and radius},r=\sqrt{a^2+(\frac{a}{2})^2-\frac{5a^2}{2}+\frac{k}{2}}$$
Now, when $r=5a$, we have:
$$25a^2=\frac{5a^2}{4}-\frac{5a^2}{2}+\frac{k}{2}$$
$$\implies100a^2=-5a^2+2k$$
$$\therefore\qquad k=\frac{105a^2}{2}$$
I hope the above is clear and there are no errors in the algebra. If anyone can offer any advice with regards to whether or not my solution is correct then I would be very grateful.
Many thanks in advance.


text:
Q: How do I delete an incorrect cname record in Windows Server 2019? So I mistakenly create a cname record in my Windows 2019 server.  It is set in this naming context -
server.company.local.company.local
I know, silly mistake.  It does not show up in DNS mmc but does in powershell.  I cannot delete it from powershell though.  Can anyone help?

A: Hello according to the Microsoft documentation, you have to use the following syntax :
Remove-DnsServerResourceRecord -ZoneName "company.local" -RRType "CName" -Name "server.company.local.company.local."

According to what @Massimo says the -Name parameter has to have a dot at the end of the name. It is to prevent the command to add the ZoneName to the Resource record.
So you can check out more information in this website https://docs.microsoft.com/en-us/powershell/module/dnsserver/Remove-DnsServerResourceRecord?view=win10-ps but remember when you have an Add Verb most of the time you will have a Remove Verb too.


text:
Q: long blog post on self hosted wordpress blog not displayed I have my self hosted wordpress blog here I recently created a blog post which is very long with so many pictures and text, but i suddenly found that my blog post was not displayed
but if i cut short the length by deleting some content then the blog gets displayed
can anyone help ?
Thanks in advance
here is the link to my blog post which is not getting displayed

A: Really long posts need to be paginated in order to be dispalyed.
So using <!--nextpage--> tag I paginated the post and it finally works.


text:
Q: Why is it not inserting to the database? <?php
                    if(!isset($_GET['nick']))
                    {
                        echo '<form action="ban.php" method="get">
                              <input placeholder="Username" type="text" name="nick"/>
                              <input placeholder="Reason" type="text" name="reason"/>
                              <input type="submit" value"Ban!"/>';
                    } else
                    {
                        $nick = mysql_real_escape_string($_GET['nick']);
                        $reason = mysql_real_escape_string($_GET['reason']);

                        $query = mysql_query("SELECT Name FROM users WHERE Name='".$nick."'");
                        if (mysql_num_rows($query) != 0)
                        {
                            while($rows = mysql_fetch_assoc($query))
                            {
                                $IP = $rows['IP'];
                            }
                        }
                        else
                        {
                            echo "No user found!";
                        }
                        $today = date("d/m/y");
                        $sql = "INSERT INTO bans (`Name`, `IP`, `BReason`, `BAdmin`, `BDate`) VALUES ('$nick', '$IP', '$reason', '$name', '$today')";
                        if ($connect->query($sql) === TRUE)
                        {
                            echo "May his account rest in peace.";
                        }
                        else
                        {
                            echo "Error: " . $sql . "<br>" . $conn->error;
                        }
                    }
                    ?>

For some reason, it doesn't insert into the database. It doesn't show any message. I tried a lot but I can't seem to find a fix for it.
Help please? Thank you.

A: You have several issues, firstly really, really replace all MySQL with MySQLi and read a bit about how to edit the SQL to make it MySQLi - it doesn't take much time or effort to change the MySQL for the better.
as for the code:
$query = mysql_query("SELECT Name FROM users WHERE Name='".$nick."'");
                 if (mysql_num_rows($query) != 0)
                    {
                        while($rows = mysql_fetch_assoc($query))
                        {
                            $IP = $rows['IP'];
                        }
                    }

You are running $query as returning all the values of Name where Name = '"$nick"'.
It may not be an issue but I seems for me to work better to just contain the strings straight into the MySQL -
Name = '$nick'

But you're only returning the Name from searching for the name so the output of the $Query will only ever be $rows['Name'] = $nick.
If you want IP set Query to:
$Query = mysql_query("SELECT IP FROM users WHERE Name='$nick' ");

So that will return in the $row the key value pair of
$row['IP'] = The IP value you want.
$connet->query() may well work but it looks like a different form to the above MySql code, and may not work with old MysqL (rather than MySQLi). So try:
if(mysql_query("INSERT INTO bans (`Name`, `IP`, `BReason`, `BAdmin`, `BDate`) VALUES  ('$nick', '$IP', '$reason', '$name', '$today')")){
    print "Inserted ok!";
}
else {
 print mysql_error(); <== this will output any error if the previous query fails.
}

Try the above and see what you discover .
EDIT:
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
Gives you a decent guide on how to turn MySQL into MySQLi . Also check what version of PHP you run as MySQL is deprecated and doesn't work with more recent PHP. Also check your PHP error log file for background info as to why you don't get the responses you expect.

A: Your current query relies on a select that returns the name field, but then stores the IP field (which the query does not return). You need to return and store both
However I would do the return of the values and the insert as just a single piece of SQL:-
INSERT INTO bans (`Name`, `IP`, `BReason`, `BAdmin`, `BDate`)
SELECT Name, IP, '$reason', '$name', '$today'
FROM users
WHERE Name= '$nick'


text:
Q: Getting 32-bit grub to automatically boot Ubuntu After so, so much pain and a lot of time (this is too common a prelude), I've managed to get Ubuntu 15.10 installed on the infamous Asus X205TA. It is currently set up in the following way:

*

*/dev/mmcblk0p1 is the fat32 bootloader

*/dev/mmcblk0p2 is the ext4 OS

*/dev/mmcblk0p3 is swap

Now I managed to hack-and-slash my way through a bunch of guides and eventually get a 32-bit grub (2.02 beta, as it were) installed onto the boot partition in a way that boots up the grub command prompt. I can then boot by entering the following commands [and typing veeery carefully due to the oversensitivity of the keyboard at this stage]:
grub> set root=(hd0,gpt2)
grub> linux /boot/vmlinuz-4.2.0-16-generic root=/dev/mmcblk0p2
grub> initrd /boot/initrd.img-4.2.0-16-generic
grub> boot

This boots just fine into Ubuntu.
The question is, how can I make this automated (or kick me into the grub menu with the countdown ...)?

I also attempted to use Boot Repair, which did some magic but ultimately did not fix the problem. However, it did seem to mount appropriately and persistently the /dev/mmcblk0p1 to /boot/grub. I believe this, in combination of the accepted answer terminal commands, were the key.

A: In theory, typing sudo update-grub should do the task if your GRUB is based on Ubuntu's GRUB. If not, sudo grub-mkconfig -o /boot/grub/grub.cfg should do it.
Alternatively, IF your installation is of a 32-bit Ubuntu, you might find it easier to install my rEFInd boot manager. You can install the PPA and it should set everything up automatically to boot without GRUB. This will work only on a same-bit-depth basis, though -- that is, if you've installed a 32-bit Ubuntu on a 32-bit EFI (or more commonly, a 64-bit Ubuntu on a 64-bit EFI). If you've installed a 64-bit Ubuntu on a 32-bit EFI, you'll still need GRUB to do the job.

A: I have the x205ta too. I originally used Lopaka's guide which has since been updated and not tested by me.
You may have also seen KemyLand's guide on this Ubuntu Forums thread. This uses a chroot method, but if you boot from GRUB the commands to do after the chroot might fix your problem. Maybe you just need the packages  efibootmgr, grub-efi-ia32, and grub-efi-ia32-bin (you probably already have them) and these two lines
sudo grub-install --target=i386-efi --efi-directory=/boot --bootloader-id=grub_uefi --recheck
sudo grub-mkconfig -o /boot/grub/grub.cfg

Recently I installed 16.04 with the automated installer after making a usb to live boot to test it out. Just for fun, I let it attempt to reboot
And I could hardly believe my eyes when it booted! So apparently compiling or even tweaking GRUB for 32-bit UEFI is no longer needed in 16.04 for this device. Happy days if you feel like moving to 16.04...


text:
Q: How to configure systemd journal-remote? How to configure systemd journal-remote to listen on specific port?
All I can find are command line examples. And base on man page, there don't seems to be any option in journal-remote.conf.

A: Seeing that there is not even a single comment, I decided to continue my research and finally pieced the configuration together.
OS: Ubuntu 16.04
systemd: 229-1ubuntu2
systemd-journal-remote: 229-1ubuntu2
Upload server configuration
This one is actually simple, online example are correct and only need to touch one configuration file.
Use following command to install systemd-journal-remote
sudo apt-get install systemd-journal-remote

Edit /etc/systemd/journal-upload.conf.
/etc/systemd/journal-upload.conf
[Upload]
URL=http://10.0.0.1:19532
# ServerKeyFile=/etc/ssl/private/journal-upload.pem
# ServerCertificateFile=/etc/ssl/certs/journal-upload.pem
# TrustedCertificateFile=/etc/ssl/ca/trusted.pem

To make sure journal-upload auto start on boot
sudo systemctl enable systemd-journal-upload.service

Restart journal-upload after configuration.
sudo systemctl restart systemd-journal-upload.service

If you are using http, you can do as above and leave the bottom 3 lines commented. For active mode https, uncomment them and create those cert files.
The URL actually dictate the transfer protocol(http/https) and the destination port to use.
Additionally if you want to prevent accidental overwrite by future package update, you can create a /etc/systemd/journal-upload.conf.d directory and put your config file inside, as long as the file end with a .conf extension.
As a side notes, I am doing this within a LXC container and seems the service will not use /etc/hosts for dns resolution, I end up using IP address here. So if you use hostname and see error message that journal-upload cannot reach the target, try with IP address.
Receiving server configuration
The receiving server give me most of the trouble when looking for configuration information. And unlike the uploading server, configuration is scattered on this side.
Use following command to install systemd-journal-remote and enable the listening port
sudo apt-get install systemd-journal-remote
sudo systemctl enable systemd-journal-remote.socket

There are two ways, active and passive, to configure journal-remote. I am using passive mode here.
Port number
The configuration file for journal listening port is /etc/systemd/system/sockets.target.wants/systemd-journal-remote.socket as follow. ListenStream is the port number.
Unlike the uploading side, this setting has nothing to do with which protocol(http/https) to use. It only specify the listening port number.
[Unit]
Description=Journal Remote Sink Socket

[Socket]
ListenStream=19532

[Install]
WantedBy=sockets.target

Protocol(http/https) and journal/log location
To change the protocol of the journal transfer and the save location, copy /lib/systemd/system/systemd-journal-remote.service into /etc/systemd/system/, then edit /etc/systemd/system/systemd-journal-remote.service.
[Unit]
Description=Journal Remote Sink Service
Documentation=man:systemd-journal-remote(8) man:journal-remote.conf(5)
Requires=systemd-journal-remote.socket

[Service]
ExecStart=/etc/systemd/systemd-journal-remote \
          --listen-http=-3 \
          --output=/var/log/journal/remote/
User=systemd-journal-remote
Group=systemd-journal-remote
PrivateTmp=yes
PrivateDevices=yes
PrivateNetwork=yes
WatchdogSec=3min

[Install]
Also=systemd-journal-remote.socket

The --listen-http=-3 specify the incoming journal is using http. If you want to use https, change it to --listen-https=-3.
--output=/var/log/journal/remote/ specify the sink (saving directory) of incoming journal. If it does not exist, create it and change its owner to systemd-journal-remote.
sudo mkdir /var/log/journal/remote
sudo chown systemd-journal-remote /var/log/journal/remote

Restart journal-remote.socket after configuration.
sudo systemctl daemon-reload

What about the most obvious /etc/systemd/journal-remote.conf?
[Remote]
# Seal=false
# SplitMode=host
# ServerKeyFile=/etc/ssl/private/journal-remote.pem
# ServerCertificateFile=/etc/ssl/certs/journal-remote.pem
# TrustedCertificateFile=/etc/ssl/ca/trusted.pem

Since I am not using https, don't need to change anything.


text:
Q: Is a hyphen necessary in the compound adjective "the already quite surprising idea"?
[I just wrote]: The expression "you may/might (just) as well + infinitive" can be used sarcastically and emphatically to introduce a more exaggerated, extreme example than the already quite surprising idea mentioned in the preceding sentence.

In the case of a more-than-two-word compound adjective, the choice of whether to link some part of it with a hyphen(s) or not does not always come easily...

A: "The already quite surprising idea" actually isn't a compound adjective; it's a noun phrase, headed by the noun idea, and is parsed as "the [[already [quite surprising]] idea]".
However, "already quite surprising" is a multiword adjective phrase used attributively before a noun, so it's possible to hyphenate it; we can write "the already-quite-surprising idea". I don't recommend that, though; already and quite are both recognizably adverbs, so the hyphens aren't needed for clarity, and would be unnecessarily informal. (Not that there's anything wrong with being informal; but "the already quite surprising idea" is not the sort of thing you'd say if that's what you were going for!)


text:
Q: Turning on ATX power supply with no load There are some rumurs around the web that ATX power supplies should not be turned on with no load. I have a partially unstable PSU that I want to turn it on out of PC case and check the voltages with multimeter.
Can you tell me having no load is dangerous or not? is it a myth?

A: There should be no danger in turning on an ATX power supply at zero load.
That being said, the outputs may be out of regulation, hunting (overshooting and undershooting their setpoints), or absent. None of these things are 'dangerous' per the definitions of safety used by regulatory agencies like UL.
What this means is unless you apply some load, you won't be able to determine anything useful by probing it while disconnected from the PC. How much "some load" is will likely vary from model to model, but if you don't want to shell out for a full-blown PSU tester as Kruug suggested, try loading each rail with power resistors to 10% of its label-rated maximum, then test with your multimeter. If the behaviour is still bad, you may indeed have a defective power supply.

A: It is not a myth. In older/cheaper units the same transformer is used to provide power for both rails - 3.3/5V and 12V. The load on those 2 rails had to be balanced. Otherwise the voltage regulator could not guarantee that the voltage would to stay within the standard limits for both rails. People were not in any real danger but devices connected to such supplies were. Modern power supplies (but the cheapest ones you don't want to use anyway) do not have this problem anymore.

A: Not true. Switch mode power supplies (typical PC PSU) will blow up with no load. The fan counts as a load. Take out the fan and watch the voltage go up until it smokes. I know, I fix the things and have blown up many with no load. Switch mode means it takes the AC in, converts it to DC, then switches it to high voltage, high frequency, then steps it back down again, then converts back to DC. This is far more efficient as transformers don't perform as well at lower frequencies and lower voltages.
It's not like mains power or a battery which can sit around doing nothing. I would say from experience that one in four can be blown up in this way, most likely not much to do with cheapness or quality of design as just about every PSU brand (nearly every brand is different) has a different circuit for it, and even the same brands scarcely keep the same circuit for long as they always source the cheapest components available at the time.
The underlying technology has hardly changed since the the days of XT computers, nothing really "modern" about it. You won't find any more modern fancy components in newer PSU's.


text:
Q: code is executed long time when app starts first time I have an WPF application, which has the following code:
    public static BitmapSource ToBitmapSource()
    {
        using (var screenBmp = new Bitmap(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth),
            Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight),
            System.Drawing.Imaging.PixelFormat.Format32bppArgb))
        {
            using (var bmpGraphics = Graphics.FromImage(screenBmp))
            {
                bmpGraphics.CopyFromScreen(0, 0, 0,
                    0, screenBmp.Size);
                return Imaging.CreateBitmapSourceFromHBitmap(screenBmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
        }
    }

and some code below. Its code executes when user selects the feature in app. Problem is this code executes long time, but only when app starts first time on this PC. If user deinstall and install again this app - it works quickly.
Questions:

*

*How to "rollback" a system to check this problem again and again (don't want to reinstall Windows for one start)

*The best way to debug (place, which really do program slowly)

*How to fix it :)

Thanks

A: *

*You probably can't rollback Windows. A better alternative would be to use VMware or another virtual machine software, and just keep recopying the disk file.

*If you start up a process which uses a lot of RAM and CPU (something like Prime95) you will be able to really slow down your machine.

*You are basically loading a bunch of separate DLLs in this function. To make it appear faster, create and run this function on a background thread. This will initialize all the classes. Then, when the user needs it, all of the DLLs will already be loaded into memory, making the function feel much faster.

A: i dont work in wpf, but try doing the time consuming work in a separate thread, that might solve your problem.

A: First of all, use a profiler (SlimTune, for example) to find out the boutleneck.


text:
Q: Code organisation for native interoperability in .NET I am currently porting some native code to C#, which consists of various structures, delegates, enumerations and external method calls.
Some of the fields within structures expect certain constants to be applied to them. It seems logical to list the constants within the structure, rather than in a separate location, as this should keep everything organized, but I am unsure what effect this would have on the structure during marshaling / interoperability with native calls.
Say for example my structure was defined as such:
[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
     public int Value;
}

Value in this instance might require one of the following constants
VALUE1 = 0x0001;
VALUE2 = 0x0002;

So is it safe for me to write these structures like so:
[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
     public int Value;

     public const int VALUE1 = 0x0001;
     public const int VALUE2 = 0x0002;
}

Can anyone shed some light onto how this might affect the code at runtime (if at all). Thanks.

A: It's better to use enums. Something like this:
[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
    public NativeFoo FooValue;
}

public enum NativeFoo
{
   VALUE1 = 0x0001,
   VALUE2 = 0x0002,
}


text:
Q: Python typehint int as positive I am curious what would be the best way to specify that a type is not just a int but a positive int in Python.
Examples:
# As function argument

def my_age(age: int) -> str:
    return f"You are {age} years old."

# As class property

class User:
    id: int

In both of these situations a negative value would be erroneous. It would be nice to be warned by my IDE/linter.
Is there a simple way to specify an integer as positive using type-hints?

A: My approach would be to define a NewType:
PositiveInt = NewType('PositiveInt', int)

and maybe a helper like:
def assert_positive(n: int) -> PositiveInt:
    assert n > 0
    return PositiveInt(n)

This isn't ironclad (because you can still say PositiveInt(-5) or something like that), but most typing can be overridden via casting anyway; just forcing that explicit declaration goes a long way to prevent most mistakes.

A: If you are using FastAPI, you can use PositiveInt from pydantic.
from pydantic.types import PositiveInt

class Pizza:
    price: PositiveInt

Read more: https://pydantic-docs.helpmanual.io/usage/types/#pydantic-types

A: This is a little bit around 2 corners, but if you use pydantic (for some reason), you have this built in
https://pydantic-docs.helpmanual.io/usage/types/#constrained-types

A: Little late to the party but there is now a library called annotated-types that provides exactly what you want and is the 'official' way to go about this, per PEP-593. So for your example of positive integers, you could make use of the built-in typing.Annotated and annotated-types' Gt predicate, like this:
from typing import Annotated
from annotated_types import Gt

def my_age(age: Annotated[int, Gt(0)]) -> str:
    return f"You are {age} years old."

# As class property

class User:
    id: Annotated[int, Gt(0)]

Note that like all things related to type hints in Python, this doesn't actually enforce the constraint at runtime. If you want to enforce it you would still have to build assertions yourself.


text:
Q: Function for pow using only addition? I have to make a function for pow, but cannot use multiplication. I know I have to make a function for multiplying then another function for finding the exponent. The function for multiplication works, but I'm having issues with the exponent function. Why isn't it multiplying as many times as the for loop?
#include <iostream>

using namespace std;

int multiply(int, int);
int exponent(int, int);

int main()
{
    int a, b;

    cout << "Please enter a base number: ";
    cin >> a;
    cout << "Please enter another the exponent: ";
    cin >> b;
    cout << endl;
    cout << "Number: "<< exponent(a, b) << endl;

    return 0;
}

int multiply(int a, int b)
{
    int x = 0;
    for (int i = 0; i < b; i++)
        x += a;
    return x;
}
int exponent(int a, int b)
{
    int y = 0;
    for (int i = 0; i < b; i++)
       y = multiply(a, a);
    return y;
}

A: Change your int exponent(int a, int b) to:
int exponent(int a, int b)
{
    int y = 1;
    for (int i = 0; i < b; ++i)
        y = multiply(y, a);
    return y;
}

Key point 1: Since you are multiplying things, the initial value should be 1. You know, n*0=0 for all n.
Key point 2: To "accumulate" the multiplication, you need to use the "previous y" to get the "new y". It is the same idea as the += operator in the multiply function, but it is a little bit tricky to think of since they looks differently.
Minor point A: We prefer pre-increment (++i) to post-increment (i++). In the near future, when you increment something not int (e.g. iterator), pre-increment has a little less overhead in case of your optimizer is not smart enough.

A:  y = multiply(a, a);

Should be,
 y = multiply(y, a);

Also, as mentioned in comment, initilize y with 1.
y = 1

A: The logic behind exponent is not right. You need to use:
int exponent(int a, int b)
{
   int y = 1;
   for (int i = 0; i < b; i++)
      y = multiply(y, a);
   return y;
}

A: Your exponent() algorithm is wrong.  You have not implemented "x to the power of y", you have implemented "x multiplied by x, when y > 0" instead.
Try this:
int exponent(int a, int b)
{
    if (b == 0)
        return 1;
    int y = a;
    for (int i = 1; i < b; i++)
        y = multiply(y, a);
    return y;
}

In the future, you may or may not also need to handle negative powers (b < 0), so think about that.


text:
Q: Perl - How do I update (and access) an array stored in array stored in a hash? Perhaps I have made this more complicated than I need it to be but I am currently trying to store an array that contains, among other things, an array inside a hash in Perl.
i.e. hash -> array -> array
use strict;

my %DEVICE_INFORMATION = {}; #global hash

sub someFunction() {
    my $key = 'name';
    my @storage = ();

    #assume file was properly opened here for the foreach-loop
    foreach my $line (<DATA>) {
        if(conditional) {
            my @ports = ();

            $storage[0] = 'banana';
            $storage[1] = \@ports;
            $storage[2] = '0';

            $DEVICE_INFORMATION{$key} = \@storage;
        }

        elsif(conditional) {
            push @{$DEVICE_INFORMATION{$key}[1]}, 5;
        }
    }#end foreach
} #end someFunction

This is a simplified version of the code I am writing. I have a subroutine that I call in the main. It parses a very specifically designed file. That file guarantees that the if statement fires before subsequent elsif statement.
I think the push call in the elsif statement is not working properly - i.e. 5 is not being stored in the @ports array that should exist in the @storage array that should be returned when I hash the key into DEVICE_INFORMATION.
In the main I try and print out each element of the @storage array to check that things are running smoothly.
#main execution
&someFunction();

print $DEVICE_INFORMATION{'name'}[0];
print $DEVICE_INFORMATION{'name'}[1];
print $DEVICE_INFORMATION{'name'}[2];

The output for this ends up being... banana ARRAY(blahblah) 0
If I change the print statement for the middle call to:
print @{$DEVICE_INFORMATION{'name'}[1]};

Or to:
print @{$DEVICE_INFORMATION{'name'}[1]}[0];

The output changes to banana [blankspace] 0
Please advise on how I can properly update the @ports array while it is stored inside the @storage array that has been hash'd into DEVICE_INFORMATION and then how I can access the elements of @ports. Many thanks!
P.S. I apologize for the length of this post. It is my first question on stackoverflow.

A: I was going to tell you that Data::Dumper can help you sort out Perl data structures, but Data::Dumper can also tell you about your first problem:
Here's what happens when you sign open-curly + close-curly ( '{}' ) to a hash:
use Data::Dumper ();

my %DEVICE_INFORMATION = {}; #global hash
print Dumper->Dump( [ \%DEVICE_INFORMATION ], [ '*DEVICE_INFORMATION ' ] );

Here's the output:
%DEVICE_INFORMATION  = (
                         'HASH(0x3edd2c)' => undef
                       );

What you did is you assigned the stringified hash reference as a key to the list element that comes after it. implied
my %DEVICE_INFORMATION = {} => ();

So Perl assigned it a value of undef.
When you assign to a hash, you assign a list. A literal empty hash is not a list, it's a hash reference. What you wanted to do for an empty hash--and what is totally unnecessary--is this:
my %DEVICE_INFORMATION = ();

And that's unnecessary because it is exactly the same thing as:
my %DEVICE_INFORMATION;

You're declaring a hash, and that statement fully identifies it as a hash. And Perl is not going to guess what you want in it, so it's an empty hash from the get-go.
Finally, my advice on using Data::Dumper. If you started your hash off right, and did the following:
my %DEVICE_INFORMATION; # = {}; #global hash
my @ports = ( 1, 2, 3 );

# notice that I just skipped the interim structure of @storage
# and assigned it as a literal
# * Perl has one of the best literal data structure languages out there.
$DEVICE_INFORMATION{name} = [ 'banana', \@ports, '0' ];
print Data::Dumper->Dump(
      [ \%DEVICE_INFORMATION ]
    , [ '*DEVICE_INFORMATION' ]
    );

What you see is:
%DEVICE_INFORMATION  = (
                         'name' => [
                                     'banana',
                                     [
                                       1,
                                       2,
                                       3
                                     ],
                                     '0'
                                   ]
                       );

So, you can better see how it's all getting stored, and what levels you have to deference and how to get the information you want out of it.
By the way, Data::Dumper delivers 100% runnable Perl code, and shows you how you can specify the same structure as a literal. One caveat, you would have to declare the variable first, using strict (which you should always use anyway).

A: You update @ports properly.
Your print statement accesses $storage[1] (reference to @ports) in wrong way.
You may use syntax you have used in push.
print $DEVICE_INFORMATION{'name'}[0], ";",
      join( ':', @{$DEVICE_INFORMATION{'name'}[1]}), ";",
      $DEVICE_INFORMATION{'name'}[2], "\n";
print "Number of ports: ", scalar(@{$DEVICE_INFORMATION{'name'}[1]})),"\n";
print "First port: ", $DEVICE_INFORMATION{'name'}[1][0]//'', "\n";
# X//'' -> X or '' if X is undef


text:
Q: Usage of SED for text replacing I need to replace a pattern containing string like ?: , ?' , ?? and ?+ within a line of text.
If it ?: then it should be : , ?' then ' , ?? then ? and ?+ then + .
I tried
sed -i 's/\?:/:/g' ,
sed -i "s/\?'/'/g" ,
sed -i 's/\??/?/g' and
sed -i 's/\?+/+/g'.
While 's/\?:/:/g' and sed -i "s/\?'/'/g" worked fine but I am facing some issues while using sed -i 's/\??/?/g' and sed -i 's/\?+/+/g'.
The pattern are not getting replaced correctly.
Please help.
Thanks.

A: Using perl, you could do:
perl -api -e  "s/\?(?=[:'?+])//g" file.txt

This will remove every question mark ? that is followed by any of :, ', ? or +

A: With sed :
sed -i -r "s/\?([\?:\+'])/\1/g" input_file.txt

It modifies input_file.txt in place (-i) and used extended regular expressions (-r), so ? and + need to be escaped.
If the pattern is found, it replaces the whole pattern with the second character.


text:
Q: nginx reverse proxy error: The page you are looking for is temporarily unavailable I have a Nginx reverse proxy. I config it like this :
 server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name miro.behinwebsite.com;
        #root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        #include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass https://mail.behinwebsite.com;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

    error_page 500 502 503 504 /50x.html;

            location = /50x.html {
        }
    }

but i get an error when i browse http://miro.behinwebsite.com in browser
nginx error!
The page you are looking for is temporarily unavailable. Please try again later.


text:
Q: Converting Extended ASCII Characters to Hexadecimal or Plain Text I have a program written in VB.NET and I have a textbox for the RFID tag (which is in ASCII format) and then convert it to a simple text format to be saved to my database.
How can I convert ASCII to plain text to save to my database?

A: Look into using the Chr function for conversion.  For example,
Dim c As Char = Chr(asciiInt)

Chr documentation is here


text:
Q: Conditionally Hide Delete Button in DataGrid I have an ASP .NET Datagrid in which I am trying to hide the delete and edit button columns if a certain condition is true (say, the value in one of the columns is X). I found a solution that is exactly what I need here;
Conditionally hide CommandField or ButtonField in Gridview
But it is for a GridView. I have not been able to find anything similar for a Datagrid, and I am not able to implement that solution. Does anyone have a solution similar to the one linked above, but for data grids? Thanks!

A: You can use same solution for datagrid also:
<asp:Button ID="btnReject" runat="server" CommandName="Reject" Visible='<%# DataBinder.Eval(Container.DataItem, "Age") > 35 ? 1 : 0 %>' CommandArgument='<%# Eval("ID") %>'></asp:Button>

A: Beside using the DataBinder.Eval, which is much simpler approach, you could also use the `GridHeaderText' to hide the columns.
See this link for more on how to hide DataGrid columns via HeaderText