text:
Q: Want to highlight an image on mouseover on corresponding item.

        <link rel="stylesheet" type="text/css" href="troll.css">

                Flatkit

Main

Dashboard

Apps

 Inbox

Condact

Calendar

Layout

header

aside

footer

Widjet

associated CSS;
li a{
    text-decoration: none;
}
.parent li{
    list-style-type: none;
    display: none;
    text-decoration: none;
}
#bad .parent{
    cursor: pointer;
    font-family: sans-serif;
    line-height: 200%;

}
#bad{

    background-color: #023b3b;
        width: 15%;

    height: 100%;
    color: white;
}
/* #bad .parent {
    height: 100%;
    width: 100%;
    display: block;
    cursor: pointer;
    line-height: 3%;
    height: 30px;
    background: #023b3b;
    color: white;
    text-align: center;
}*/
#pappaya {
    background-color:#339933;
    width: 180%;
    margin-left: -28%;
    padding-left: 38%;
    padding-right: 40%;
    width: 50%;
    /*text-align: center;
    margin-right:122%;*/
}
 #pappayas {
        /*background-color:#339933;
         width: 100%;
    margin-left: -50%;
    padding-left: 50%;*/
    background-color:#339933;
    width: 180%;
    margin-left: -28%;
    padding-left: 38%;
    padding-right: 40%;
    width: 50%;
    }
#pappaya li:hover{
    background-color: #122112;
    color: white;
    width: 184%;
    margin-left: -75%;
    padding-left: 70%;
}
#pappaya li a:hover{
    color: white;

}
#pappayas li:hover{
    /*text-align: center;*/
    background-color: #122112;
    color: white;
    width: 184%;
    margin-left: -75%;
    padding-left: 70%;
}
#pappayas li a:hover{
    color: white;

}

#bad{

    background-color: #023b3b;
        width: 15%;

    height: 100%;
    color: white;
}
#bad .parent:hover
{
    background-color: #122112;
    color: white;
    width: 78%;
}
#bad ul:hover{
    background-color: #122112;}
#bad .parent:hover ~ .parent img{
    width: 13%;
    height: 3%;
}

/*new setup*/
#boa{
    height: 5%;
    width: 20%;
    float: left;

}
.bob{
    text-indent: 200%;
    line-height: 210%;
    font-size: 150%;
    font-family: sans-serif;
    color: white;
    font-weight: bold;

}
#buttnsec{
     margin-left: 94%;
        width: 10%;
        hyphens: 20%;
}
.boc{
    text-indent: 4%;
    color : white;
    font-size: 83%;
    font-family: sans-serif;

    font-weight: normal;
}
.parent img{
    float: left;
    width: 15%;
    height: 3%;
    margin-left: -12%;
    margin-right: 20%;
}
/*#bad .parent :hover{
     background: #122112;
}*/

In this code on mouseover on an item the images below the corresponding item  become smaller, instead of that I want to reduce the size of  the image of the item the mouse pointer currently stands/focused. view current output

A: Try changing
#bad .parent:hover ~ .parent img{
    width: 13%;
    height: 3%;
}

to
#bad .parent:hover img{
    width: 13%;
    height: 3%;
}

Now, it'll work if you just hover over the menu item.

A: Look at this:
#bad .parent:hover ~ .parent img{
    width: 13%;
    height: 3%;
}

to:
#bad .parent:hover > img {
    width: 13%;
    height: 3%;
}

Working example here


text:
Q: groovy.lang.MissingPropertyException within Jenkins-Job we're using an old groovy-script to generate a pdf for a build-report on our Jenkins-server. The Job did not run for some months but now we reveive the following error altough nothing was changed on the job and at server-side
    import hudson.model.*
import hudson.FilePath
import groovy.xml.MarkupBuilder
import java.text.SimpleDateFormat

// make variable bindings available in this script
binding.variables

// Timestamp format for output
def tsformat = "yyyy-MM-dd HH:mm:ss"
def to_ts_format = new SimpleDateFormat(tsformat)

// Integrity time format
def from_integrity_format = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss aa")

def today = Calendar.getInstance().getTime()

// get current build
def thr = Thread.currentThread()
def build = thr?.executable

// Get parameters

// reportname must be given as parameter binding - s. Jenkins groovy script extended ("erweitert") settings
String reportname = "${build.envVars.WORKSPACE}"+ "\\" + "${build.envVars.par_reportname}"

// Get job name from environment
String srcjobname = "${build.envVars.PAR_JOB}"

// Get from and to
int to = "${build.envVars.PAR_TO}".toInteger ()
int last_to = "${build.envVars.PAR_FROM}".toInteger ()
int from = last_to + 1

// End get parameters

// Get the job object ...
def job = Hudson.instance.getJob (srcjobname)

println ("\nCreating report for '"+ job.name + "' builds: " + from + " to " + to + "\n")

// Get job time preceding earliest job in range
def frompredecessorbuild = job.getNearestOldBuild (last_to)
def predectime
if (frompredecessorbuild != null) {
   println ("\nGot predecessor build: " + frompredecessorbuild.number + ".\n")
   predectime = frompredecessorbuild.getTime ()
} else {
   println ("\nDidn't get predecessor time, no cut off!\n")
   predectime = to_ts_format.parse ("1900-01-01 00:00:00")
}

// Get builds from jobs (alternative way, because getBuildByNumber () seems not to work reliably)
def builds = job.builds

def freport = new FilePath (build.workspace, reportname)
def stream = freport.write()

//
// Create the xml ...
//
println ("Now create xml.")
try {
  def writer = new StringWriter()
  def xml = new MarkupBuilder(writer)
  xml.changereport (job:srcjobname, time:today.format (tsformat), predecessortime:predectime.format (tsformat)) {
//    for (def i in to .. from) {
    for (def b in builds) {
//      def b = job.getBuildByNumber (i)

/*      if (b == null) {
        println ("Skipped build: " + i)
        continue
      } */
      b_no = b.getNumber ()
      if (b_no < from || b_no > to) {
        println ("Skipped build: " + b_no)
        continue
      } else {
        println ("Processing build: " + b_no)
      }

      buildinfo (number:b.number, time:b.getTime ().format (tsformat)) {
        for (cs in b.changeSet) {
          for (ci in cs) {
            citime =  from_integrity_format.parse (ci.date)
            if (citime > predectime) {

              // Add only entries whose date is bigger than the cut-off date
              changeinfo (time:to_ts_format.format (citime), stime:ci.date, action:ci.action, author:ci.getAuthor().getDisplayName()) {
                changedfile (fname:ci.file.toString (), "rev":ci.rev, ci.msg)
              } // changeinfo
            } // if
          } // for ci ...
        } // for cs ...
      } // buildinfo
    } // for i ...
  } // changereport

} // try

finally {

  // Need an encoding ... due to umlauts ...
  stream.write ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>".getBytes ())

  stream.write (writer.toString ().getBytes ())
  stream.flush ()
  stream.close ()
}

Following error:
groovy.lang.MissingPropertyException: No such property: writer for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
    at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
    at org.kohsuke.groovy.sandbox.impl.Checker$checkedGetProperty.callStatic(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:194)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:230)
    at Script1.run(Script1.groovy:123)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runScript(GroovySandbox.java:162)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:370)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:314)
    at hudson.plugins.groovy.SystemGroovy.run(SystemGroovy.java:95)
    at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:59)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1894)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:428)
Build step 'Execute system Groovy script' marked build as failure

Something went wrong with the write-object. But we don't know why. Do anybody has a clue for solving the problem?
Thanks!

A: You should be declaring your writer before the try block if you want to access it in the finally block.
def writer = null
try {
  writer = new StringWriter()
  def xml = new MarkupBuilder(writer)
  xml.changereport (job:srcjobname, time:today.format (tsformat), predecessortime:predectime.format (tsformat)) {
//    for (def i in to .. from) {
    for (def b in builds) {
//      def b = job.getBuildByNumber (i)

/*      if (b == null) {
        println ("Skipped build: " + i)
        continue
      } */
      b_no = b.getNumber ()
      if (b_no < from || b_no > to) {
        println ("Skipped build: " + b_no)
        continue
      } else {
        println ("Processing build: " + b_no)
      }

      buildinfo (number:b.number, time:b.getTime ().format (tsformat)) {
        for (cs in b.changeSet) {
          for (ci in cs) {
            citime =  from_integrity_format.parse (ci.date)
            if (citime > predectime) {

              // Add only entries whose date is bigger than the cut-off date
              changeinfo (time:to_ts_format.format (citime), stime:ci.date, action:ci.action, author:ci.getAuthor().getDisplayName()) {
                changedfile (fname:ci.file.toString (), "rev":ci.rev, ci.msg)
              } // changeinfo
            } // if
          } // for ci ...
        } // for cs ...
      } // buildinfo
    } // for i ...
  } // changereport

} // try

finally {

  // Need an encoding ... due to umlauts ...
  stream.write ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>".getBytes ())

  stream.write (writer.toString ().getBytes ())
  stream.flush ()
  stream.close ()
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running Sikuli X from command line I have figured out how to run Sikuli X from command line using:
@start C:\SikuliX\runIDE.cmd -r C:\Users\Robert\Documents\Automation\test.sikuli
exit
My problem is when it runs it opens up another command window, runs the program and finishes but then doesn't close the command window it opens. I was wondering if anyone knew how to close that command window it opens? I could get Sikuli to do the whole find the exit button and close it like that but i don't want to do that for fear something might not shutdown right.
Thanks in advance for anyone who can help me figure this out.

A: Try this:  it depends if the executable is a command line program or a gui window.
@echo off
start "" /w /b C:\SikuliX\runIDE.cmd -r C:\Users\Robert\Documents\Automation\test.sikuli
exit

Actually, I see it is a batch file, so try this:
@echo off
call C:\SikuliX\runIDE.cmd -r C:\Users\Robert\Documents\Automation\test.sikuli
exit

A: Running Sikuli scripts from command line
without arguments
open command prompt.
type cd "Sikuli directory" and enter
type the following command to run :
 runIDE.cmd -r "sikuli script path"

with argument
 runIDE.cmd -r "sikuli script path" -args "a1" "a2" "a3"

A: Ok so thanks to the answer below i figured it out. All you have to do is alter the runIDE.cmd that comes with Sikuli and simply add exit at the end of the program and it works perfectly.


text:
Q: Trigger click on appended elements by $.each I trying to append options to an existing select in HTML with this code
HTML:
<div class="booking-select-calender">
    <select id="booking-year-month">
    </select>
</div>

jQuery:
$(".booking-calendar-wrapper-in .month-title").each(function() {
    var month = $(this).text();
    $("#booking-year-month").append("<option>" + month + "</option>");
});

I want also do something when a user click on the option. I tried to add click function with .on or .trigger outside od each but it won't work.
Any tips what can be a good solution for this?

A: You can use on change handler but on your select element that i assume has id= #booking-year-month
$('body').on("change" , "#booking-year-month" , function() {
    console.log("selected option: " + this.value);
});

A: you can simpley put onchange method on you select htmly tag
<select id="booking-year-month" onchange="YourNewMethod()"></select>

and rather than appending option in select element also add value attribute in options like this
$(".booking-calendar-wrapper-in .month-title").each(function() {
  var month = $(this).text();
  $("#booking-year-month").append("<option value='" + month + "'>" + month + "</option>");
});


text:
Q: How can I install Google Chrome on my Windows XP computer? I can download Google Chrome from web page, but I can't install it. Every time it shows the message "please wait , installation in running". After this message I can't do anything on the Internet without restarting my PC. I need your advice.

A: You can remove the .exe file and get the new downloaded. Then you can try to install it. Make sure to connect with the internet.


text:
Q: How to use ".\" in -file in a command file I need to execute a command file (B.cmd) on Machine B from a Powershell script (A.ps1) on Machine A. I don't want to statically specify the path
B.cmd is supposed to execute C.ps1 which is in the same folder as B.cmd
MACHINE A: A.ps1
MACHINE B: B.cmd, C.ps1 (all in same folder)
so my command file looks like this B.cmd
@echo off
powershell.exe -file ".\C.ps1" -Iterations 10
echo
echo
pause

There's an error thrown in a A.ps1 file from which I'm calling the B.cmd file
A.ps1

Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {Invoke-Expression -Command: "cmd.exe /c C:\Temp\Batch\Test\B.cmd"}

A.ps1 throws error:
**The argument '.\C.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.**
+ CategoryInfo          : NotSpecified: (The argument '....File parameter.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName        : XXX

How do I make the .\ work or is there an alternative or is it wrong to use the .\ for a remote execution ?
Please forgive my ignorance anywhere as I'm very very new to PS, Thank You !

A: If you're able to change the ABC.cmd you could use the following
powershell.exe -file "%~dp0\XYZ.ps1"

This will get the folder the ABC.cmd script is running from. Note that %~dp0 won't work in cmd for testing you'll need to test it from within a script.

A: So don't wrap a batch file around it. A waste of time and confuses the issue.
invoke-command -comp $computername -filepath C:\Temp\Batch\Test\XYZ.ps1

If you need to run something 10 times, do it in a loop inside your PS script.


text:
Q: Clearing Class Foo with new(pFoo) Foo() I'm going to be honest. I'm feeling a bit under the weather so this might be a stupid question. If so yell at me and I'll delete it. Having issues with a program not clearing some data every once and a while and causing a mismatch with some dirty bits. Popular opinion is that we have a race condition. When i was looking at some of the old code however i noticed that the Fifo Array class has a bit of unique way of clearing itself. I've abstracted what i think are the relevant bits as follows.
File Foo.hpp
template<class T, unsigned N, intrptr_t nilVal>
class Foo {
    public:
        Foo();
    protected:
        data[N+1]
        size;
}
inline Foo<T, N, nilVal>::Foo(): nextIn(0), Size, nextOut(0) {
    for (unsigned i = 0; i <= N; ++i){
        data[i] = (T)nilVal;
    }
}

File Bar.hpp
#include "Foo.hpp"

class Bar{
    public:
        Bar() : fizz() {}
        ~Bar() {}

        static void Clear(Bar* pBar);
    private:
        Foo<void*, CAPACITY, 0U> fizz;

File Bar.cpp
#include "Bar.hpp"

void Bar::Clear(Bar *pBar){
    Lock lock;
    CRITICAL_REGION(lock){
        new(pBar) Bar();
    }
}

File Logic.cpp
#include "Bar.hpp"

logic(){
    Bar* bar = Woof::GetBar();
    bar->Clear(bar)
    ...
}

This code has been in there for years, and it appears to be working. Now i've done a bit of googling and gotten a bit suspicious. When Bar::Clear() is called in logic() if i were to check then check every location in data[], will data[] actually be empty? If so i would appreciate it if someone could elaborate on why this works, whereas new(this) is evil.

A: This is legal-ish and it will depend on what T is for whether or not this is legal. Doing
new(pBar) Bar();

is going to end the lifetime of the object pBar points to and puts a new object in its place.  That means fizz will look like it did when you created the Bar instance.
[basic.life]/5

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type. For an object of a class type, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression is not used to release the storage, the destructor is not implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

Tells us this is okay, as long as Bar's destructor has no observable side effects.  So if T was an int (void* in this case) then there is nothing observe in it being destroyed and the code is fine.  If T was a std::vector though, then there is an issue.  std::vector's destructor has side effects (desroys the elements, returns allocated memory) so the code would have undefined behavior.


text:
Q: When to open the connection using node-mysql module? I found a very good module (node-mysql) to connect to Mysql database.
The module is very good, I Only have a question about "WHEN" to open the connection to Mysql.
I always have used php-mysql before starting with node, for each request i opened a connection...then query....then close.
Is the same with node? for each request do I have to open a connection and then close it? or can i use persistent connection?
Thank you

A: The open-query-close pattern generally relies on connection pooling to perform well. Node-mysql doesn't have any built in connection pooling, so if you use this pattern you'll be paying the cost of establishing a new connection each time you run a query (which may or may not be fine in your case).
Because node is single threaded, you can get away with a single persistent connection (especially since node-mysql will attempt to reconnect if the connection dies), but there are possible problems with that approach if you intend to use transactions (since all users of the node client are sharing the same connection and so same transaction state). Also, a single connection can be a limit in throughput since only one sql command can be executed at a time.
So, for transactional safety and for performance, the best case is really to use some sort of pooling. You could build a simple pool yourself in your app or investigate what other packages are out there to provide that capability. But either open-query-close, or persistent connection approaches may work in your case also.

A: felixge/node-mysql now has connection pooling (at the time of this writing.)
https://github.com/felixge/node-mysql#pooling-connections
Here's a sample code from the above link:
var mysql = require('mysql');
var pool  = mysql.createPool(...);

pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( 'SELECT something FROM sometable', function(err, rows) {
    // And done with the connection.
    connection.end();

    // Don't use the connection here, it has been returned to the pool.
  });
});

So to answer your question (and same as @Geoff Chappell's answer): best case would be to utilize pooling to manage connections.


text:
Q: Where can the 'Fat32 Format' utility be downloaded from ? (shown in picture)
I know this is a silly question (if not a downright stupid one)
Where can the Fat32 Format utility be downloaded from ?
I obviously tried using Google but the only website I could find was this
which was odd considering it's supposedly free
I followed the Download button but the website didn't download anything or display any messages about the Download process
I tried using advanced google search to filter out specific phrases but it didn't work
I have windows 7 ultimate

It's not the topic of the question but here's the background story:
I have a 64GB USB drive that is NOT formated to FAT32 file system type, I need to change it to that file system type so that I can make it into a bootable ISO USB drive that is compatible with my computer's old and outdated BIOS (motherboard GR1M-VS3)

A: The image you linked gives the following URL as a donation page:
www.ridgecrop.demon.co.uk/guiformat.htm
This seems to redirect straight to the page for GuiFormat, what looks to be a GUI version of the Fat32 Formatter.
However, from there, it is easy to link back to this page to download the Fat32 Formatter (link is a bit down the page where it says "Now download a copy of fat32format.")

A: The thing is actually called GUIFormat and is available directly from the maker at thsi website
You didn't look closely enough at the screenshot. The web-site of the maker is shown at the bottom.


text:
Q: Select by attribute using modulo operation? In ArcMap 10.5, I want to select the rows where the modulus of the objectid by 3 equals 1.
How to write a SQL sentence in select by attribute window?
My current query statement is something like this:
MOD( [OBJECTID],3)=1

but unfortunately it selects all of the rows. What's the problem with that?

A: The following query works:
MOD("column_name", 3) = 1

where column values are of type integer belonging to a shapefile TOC.
Take a look at these related questions:

*

*Selecting contours which heights are integers?

*Selecting rows where remainder (modulo) is 1 after division by 2?
If you are querying a table from SQL Server using ArcGIS, then, the mod expression won't work. Use the modulo operator (%), instead. See:

*

*Using the MOD expression on an SQL Feature Class is not possible?


text:
Q: Problem with fetching data in React, Assignment to constant variable I just started to learn React and was trying to fetch some random data. i created a useState and have two values : const [name, setName] = useState([]);
when i try to do name : response.json();
I get an error that assignment to a constant variable, I'm following a tutorial which is doing the same.
surprisingly when I create a constant variable with a different name, it works. I only can't assign the name = await response.json();
Thank you
import React, { useEffect, useState } from "react";
import { ReactDOM } from "react";

const FetchData = () =>{

    const [name, setName] = useState([]);

    const fetchNames = async () =>{

        const url = `https://randomuser.me/api`;

        try {

            const response = await fetch(url);
            name = await response.json();
            console.log(name);
           setName(name);

        } catch (error) {

            console.log(error);
        }
    }

    useEffect(()=>{

        fetchNames();
    },[])

    return(

    );
}

export default FetchData;

A: there are 2 things that might help with this confusion

*

*any variable created using const will forever hold the value it had when it was declared, so for eg if we have const x = "", we later can't do something like x = "something else"

*in the snippet you shared name is a "state variable". state variables should NEVER be updated directly, state updates must happen through setState function only(i.e. setName in this case)
this is the part in official docs that talks about it https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly , https://reactjs.org/docs/hooks-state.html#updating-state

A: Check my example, as I understand you want to use name inside the try as variable not from state so you should add const. I also mapped the response in your render which you can see the results. Here also codesandbox example https://codesandbox.io/embed/friendly-ishizaka-57i66u?fontsize=14&hidenavigation=1&theme=dark
import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [name, setName] = useState([]);

  const fetchNames = async () => {
    const url = `https://randomuser.me/api`;

    try {
      const response = await fetch(url);
      constname = await response.json();
      console.log(name);
      setName(name?.results);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchNames();
  }, []);

  return (

      {name.map((el) => (
        <>

{el.email}

{el.phone}

        </>
      ))}

  );
}


text:
Q: Iteration to Match Line Patterns from Text File and Then Parse out N Lines

I have a text file that contains three columns. Using perl, I'm trying to loop through the text file and search for a particular pattern...
Logic: IF column2 = 00z24aug2016 & column3 = e01. When this pattern is matched I need to parse out the matched line and then the next 3 lines. to new files.
Text File:
site1,00z24aug2016,e01
site1,00z24aug2016,e01
site1,00z24aug2016,e01
site1,00z24aug2016,e01
site2,00z24aug2016,e02
site2,00z24aug2016,e02
site2,00z24aug2016,e02
site2,00z24aug2016,e02

Desired Output...
New File 1:
site1,00z24aug2016,e01
site1,00z24aug2016,e01
site1,00z24aug2016,e01
site1,00z24aug2016,e01

New File 2:
site2,00z24aug2016,e02
site2,00z24aug2016,e02
site2,00z24aug2016,e02
site2,00z24aug2016,e02

A: Based on your comment in response to zdim and Borodin, it appears that you're asking for pointers on how to do this with Perl rather than actual working code, so I am answering on that basis.
What you describe in the "logic" portion of your question is extremely simple and straightforward to do in Perl - the actual code would be far shorter than this description of it:

*

*Start your program with use strict; use warnings; - this will catch most common errors and make debugging vastly easier!

*Open your input file for reading (open(my $fh, '<', $file_name) or die "Failed to open $file_name: $!")

*Read in each line of the file (my $line = <$fh>;)

*Optionally use chomp to remove line endings

*Use split to break the line into fields (my @column = split /,/, $line;)

*Check the values of the first and third fields (note that arrays start counting from 0, not from 1, so these will be $column[1] and $column[2] rather than 2 and 3)

*If the field values match your criteria, set a counter to 4 (the total number of lines to output)

*If the counter is greater than zero, output the original $line and decrement the counter

*The logic mentions "new files" but does not specify when a new output file should be created and when output should continue to be sent to the same file.  Since this was not specified, I have ignored it and described all output going to a single destination.

Note, however, that your sample desired output does not match the described logic.  According to the specified logic, the output should include the first seven lines of your example data, but not the final line (because none of the three lines preceding it include "e01").
So.  Take this information, along with whatever you may already know about Perl, and try to write a solution.  If you reach a point where you can't figure out how to make any further progress, post a new question (or update this one) containing a copy of your code and input data, so that we can run it ourselves, and a description of how it fails to work properly, then we'll be much more able to help you with that information (and more people will be willing to help if you can show that you made an effort to do it yourself first).


text:
Q: Lotus Connection API issue I am working on Lotus Connection. I wanted to fetch the values in AboutMe section and Background section of profiles using the Lotus Connections API.
Is it possible to do so. I had gone through the wiki and other help , but could
not find any solution
Please help if any one got a solution

A: Got the solution for this. There is no api specifically designed for
updating the aboutMe and Background Information in Lotus Connection.
One who had to update it programmatically has to connect to Lotus Connection
backend(Database) and write an update query to update the prof_description (AboutMe)
and prof_experience(Background) fields of employee table in PeopleDB schema

A: There is an api for updating those fields, I don't know what version of Connections you are using but I linked to the 3.0 public API
What fields you are looking to update are for the "About Me" section the field "description" and for the "Background" you want "experience" field.


text:
Q: How to dissolve polygons that have been split back into their original polygons? I had a feature class containging about a thousand polygons.After some processing such as intersecting, dissolving, merging, more intersecting, I ended up with a feature class of about 6000 polys. This was several months ago, and since then more data has been added/removed, attributes have changed etc.
I now need to get the feature class back to its original state. Not original as in the actual shapes from before, but where one original polygon was split into 4 polys, it must now be dissolved back into one.

One method I considered was using Spatial Join with the match option of Shares_a_line_segment_with, as all the polys which share a line segment would have originated from the same polygon. Unfortunately, the unique IDs assigned to the original polygons were 'lost' a while ago, so I cannot just dissolve the result of the spatial join based on target or join ID, as multiple polys share line segments, and they would all be joined to each other (resulting in several join and target IDs in overlapping polys).
I don't need to preserve the attribute information, I only want the original polygons back. I was thinking of using a feature selection iterator to select by location on each feature where it shares a line segment with another, populating a list with the relevant IDs and then calculating a unique ID for the group, which I could use as my dissolve field, but that seems unnecessarily complicated, and I'm sure there is something simpler I could do.


text:
Q: Swashbuckle root error when i deploy on subfolder I begin with Swashbuckle, i make a Web API in .NET Core with Swashbuckle.
I need to deploy my API in a sub-application of an IIS site
IIS infrastructure

*

*IIS Site (site)

*

*myApi (subApplication)

http://ip:80/myApi
I would like the access to swagger UI to be done via this url :
http://ip:80/myApi/swagger

I would like the access to the methods to be done by this url :
http://ip:80/myApi/api/[controller]/methode

ConfigureServices(IServiceCollection services)
 services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My REST API", Version = "v1" });
        });

Configure(IApplicationBuilder app..)
if (env.IsEnvironment("ProdIT"))
        {
            app.UseSwagger(c =>
            {

                c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/myApi/");
                c.RouteTemplate = "myApi/api-docs/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "myApi/swagger";
                c.SwaggerEndpoint("/myApi/api-docs/v1/swagger.json", "MY REST API V1");});

Route Controller
[Route("api/[controller]")]

Could you tell me what's wrong with my code?
Thanks in advance

A: I had the same issue and I resolved it by configuring the SwaggerUI like that;
app.UseSwaggerUI(c =>
{
     c.SwaggerEndpoint("v1/swagger.json", "MY REST API V1");});
}


text:
Q: What is a part in the youtube api v3, and how should I use it I was trying to make the "try it now" work on the youtube api page in this link:
https://developers.google.com/youtube/v3/docs/videoCategories/list#try-it
What do I need to write in each text box?
It is very unclear for a noob like me...
The explanation about what a part is is very unclear. What a property is, where should I use these. There are no examples of usage. It is very frustrating.
As a side note - this whole API documentation is as if written for someone who already knows how to use it.. very unfriendly.

A: Basic explanations are right next to each text box: more details can be found on the API Overview page, under Partial Resources.
part: The part parameter specifies the videoCategory resource parts that the API response will include Supported values are id and snippet.
Type in id, snippet, or id, snippet.
regionCode: instructs the API to return the list of video categories available in the specified country. The parameter value is an ISO 3166-1 alpha-2 country code. Type in us or your country code.
Click the 'Execute' button to get results.

A: First, make sure you "Authorize requests using OAuth 2.0"
Next, in addition to entering id and snippet (The "bold red = required") you must provide at least one filter such as 'us' or your country code in the regionCode.  Rather than give a bad request the instructions probably should have indicated that at least one filter is required.  The automatically generated request should then show as something like:
GET https://www.googleapis.com/youtube/v3/videoCategories?part=snippet&regionCode=us&key={YOUR_API_KEY}

And you should see a response starting with something like:
200 OK
- Show headers -
{
 "kind": "youtube#videoCategoryListResponse",
 "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/ktNNfqmO8tgQADyscLhmrqfzsa4\"",
 "items": [
  {
   "kind": "youtube#videoCategory",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/Xy1mB4_yLrHy_BmKmPBggty2mZQ\"",
   "id": "1",
   "snippet": {
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Film & Animation",
    "assignable": true
   }
  },


text:
Q: Adding hello world to cpanel I've just signed up with host gator and created my own domain. I am trying to create my own website from scratch without using WordPress or trying to use it as less as possible. I have watched multiple tutorials and most of them are about using WordPress but that implements the code for you. As of now, I am just trying to test my HTML code using "hello world" through cPanel. I'm not sure what file I need to delete in order to start implementing my own code through cPanel. I've also downloaded FileZilla and connected the two but, I still can't see my "hello world" test. Please help with a detailed description of what I need to exactly do. Here is the code I am testing it on.
<!DOCTYPE html>

This is hello world!

A: *

*Log in to your cPanel account in your browser with the username and password provided by your Web hosting service.

*Click the "File Manager" icon from the main page. If prompted, select "web root" as your desired location, because this is where you need to place files to make them available online.

*Click the "New File" icon to create a new file. Create the front page on your site. This file should be named "index" or "default." For example, your host will recognize "index.php" as the front page or "default.html."


text:
Q: Meta functions to use outputs from single function I am using a library that requires two functions as inputs for a method where these two functions are evaluated multiple times. For example
def the_func ( H, dH ):
    many_iterations = 10
    for i in xrange( many_iterations ):
       # internal calculations to yield a value of x
       x = np.random.randn(10) # say!
       foo = H(x)
       bar = dH(x)
       # do something with foo and bar e.g
       print foo,bar

However, calculating H and dH shares a lot of code, and evaluating each is expensive, so I have them calculated inside a single function that returns both. As an example, consider this function that returns two values, that correspond to H and dH above.
def my_func ( x ):
    # lots of calculations...
    return x.sum(), x/2.

Without changing the_func (which is coming from a library), I would like to still calculate only one run of my_func when the_func evaluates H and dH. At the moment, I'm solving the problem calling the_func as
the_func ( H=lambda x: my_func(x)[0], dH=lambda x: my_func(x)[1] )

This works fine, but for each iteration inside the_func, it needs to my_func the same function twice with exactly the same argument. I would like to evaluate this function only once per iteration, but without changing any of the_func.

A:
so it occurred to me to use a memoization pattern, but given that x will be a numpy array (and thus unhashable), this needs some spelunking into the library code to make the array hashable that I would like to avoid.

So I still don't quite understand your question, just like everyone else, but if you simply want to memoize some function that takes an array argument, you may look at this question: Most efficient property to hash for numpy array  tl;dr version: use tostring() method to compute the hash key of the underlying array, if the array is not too large.  This may not port well due to endianness/layout/etc., so beware of dragons.  For large arrays you may need to consider a real hash function that is fast, such as xxhash, and manage the hash collisions.
Now there's a nice library called cachetools that is useful for building a memoizer function.  It actually provides its own implementation as handy decorators, but it doesn't handle custom hash function well.  If you don't mind, you can look at my (admittedly makeshift) attempt to create method decorators for array-taking methods, on top of cachetools: https://github.com/congma/simplecache  It may not be flexible or elegant but you got some ideas to build your own ;)
For your case you may do something like this, in pseudo-Python:
import simplecache  # that's my module
class ThingClass(simplecache.ArrayMethodCacheMixin, ...):
    ... ...
    @simplecache.memoized()
    def _common_code_for_both(self, x):   # x is array argument
        ... ...  # expensive computation using x
        return intermediate_state

    def h(self, x):
        intermediate_state = self._common_code_for_both(x)
        return do_something_with(x, intermediate_state)

    def dh(self, x):
        intermediate_state = self._common_code_for_both(x)
        return do_something_else_with(x, intermediate_state)

thing = ThingClass(...)

Now if thing.h() and thing.dh() are called in succession with the same argument, the intermediate computation won't be repeated.  Now you just pass thing.h and thing.dh to the library function.
It ain't pretty but it may save some unnecessary evaluation.


text:
Q: weird internet connection - pages not loading correctly I've been facing a weird internet problem. I can open sites like google, warez-bb fine without any problems, but when I try to open any blogs, Hotmail, turbobit (I'm not sure what category of sites) I'm simply thrown a server not found error.
Sometimes if I keep on hitting F5(refresh) for 30 seconds or even more than that, pages load fine, sometimes only a text version opens without any images, sometimes they won't open at all. Before writing this in superuser, I had to hit refresh button for the site to open.
I'm totally frustrated with this problem. I've tried firefox, chrome, IE even booted ubuntu and tried opening them. The problem remains same. I don't think this is a virus or some kind of malware because as I said I've already tried browsing in Linux as well. I think it is a problem with my ISP (BSNL India). I've contacted few of my friends with same ISP and they seem to open all sites without any issues.
Any ideas or any pointers to solve this problem would be helpful.

A: I would recommend resetting the BSNL modem(the pin-press reset switch on back panel).
Also, borrow a modem from friend for a day and see it that works fine..
If that is working fine, just export his modem settings and import them in your modem...
Also visit BSNL office and ask them to reset your connection/socket o whatever they call it.

A: Change the DNS settings.
Set up Google DNS settings and once done, everything should work fine again.


text:
Q: Using Clojure deftype as a parameterized function I am trying to use clojure in a compiler and thus need to parameterize calls to deftype; however, I am having difficulty making the type hints carry through.  Consider the following code:
(defn describe [x]
  (let [fields (.getDeclaredFields x)
        names (map #(.getName %) fields)
        types (map #(.getType %) fields)]
    (interleave types names)))

(defn direct [] (deftype direct-type [^int x]))
(defn indirect-helper [] (list ^int (symbol "x")))
(defn indirect [] (eval `(deftype ~(symbol  "indirect-type") ~(indirect-helper))))

And the following session from the REPL:
Clojure 1.2.0-master-SNAPSHOT
1:1 user=> #<Namespace dataclass>
1:2 dataclass=> (direct)
dataclass.direct-type
1:3 dataclass=> (indirect)
dataclass.indirect-type
1:4 dataclass=> (describe direct-type)
(int "x")
1:5 dataclass=> (describe indirect-type)
(java.lang.Object "x")

Notice that the generated class for indirect-type has lost the ^int hints that direct-type has.  How do I get those hints to carry through?

A: You'll need to change indirect-helper to read
(defn indirect-helper [] [(with-meta (symbol "x") {:tag 'int})])

The reason is that ^int parses as ^ followed by int; ^, in Clojure 1.2, introduces reader metadata (in 1.1 you'd use #^, which still works, but is deprecated in 1.2). Thus ^int x in direct gets read in as a clojure.lang.Symbol whose name is "x" and whose metadata map is {:tag int} (with the int here being itself a symbol). (The final component of a symbol -- its namespace -- is nil in this case.)
In the version of indirect-helper from the question text ^int gets attached to (symbol "x") -- the list comprising the symbol symbol and the string "x" (meaning in particular that (list ^int (symbol "x")) evaluates to a list of 1 element). This "type hint" is lost once (symbol "x") is evaluated. To fix things, some way to attach metadata to the actual symbol generated by (symbol "x") is needed.
Now in this case, the symbol is generated at runtime, so you can't use reader metadata to attach the type hint to it. Enter with-meta, which attaches metadata at runtime (and is frequently useful in writing macros for the same reason as it is here) and the day is saved:
user> (indirect)
user.indirect-type
user> (describe indirect-type)
(int "x")

(BTW, I thought deftype expected a vector of field names, but apparently a list works as well... A vector is still certainly more idiomatic.)


text:
Q: Are there any good editors for asp.net on smartphones? I came across coderun the other day does anyone know any better editors/ide's espeially that can be used relatively easily on some of todays smartphones for asp.net ?

A: Some more background might be helpful so we can understand your needs. My immediate response is that smartphones are great at content consumption but suck for content generation. This is particularly true when you're talking about such syntactically picky activities as programming.

A: There won't an IDE that would be productive to use on this generation of smart phones. The amount of input required to program is impractical on such a small device, especially considering that the input device is the display.
Especially, considering that the highest voted answer to this question on best investment for programming is "Dual Monitors and a decent keyboard."
Use the time you spend programming on a smart phone to read specs/articles or switch your brain off to prevent burn out.


text:
Q: How can I get iTerm 2 to copy only what I select? iTerm2 has a very nasty habit of making an assumption of what I want to copy and paste from the terminal. Instead of just allowing me to copy exactly what I highlight, it will expand to what it considers more useful.
As an example maybe I have the following command
rsync <file> server.example.com:/home/user/<file>

If I was to select via cursor and highlight server.example.com, it will instead re-highlight the entire command and copy that.  It is so annoying because I copy stuff all day long.
I copy by either pressing Command+C, or right clicking to get the dialog menu and selecting copy which is the same as doing "Edit" → "Copy", on the toolbar.
I have disabled the automatic select text and copy function. That is something I do not want enabled.
Is there anyway to fix this?

A: It is an option under Preferences>General>Selection.
I am using iTerm Build 3.1.6.

A: If you do a double-click to select it go into "all-word" mode, which automatically grabs each word.
If you just click and drag it'll take whatever your selection is.

A: If you go to Preferences ( ⌘ + , )
Under the Appearance Tab, there is an option "Show tabs in fullscreen by holding ⌘ for:" and there is a slider from 0 - 10 sec.
I had the option set at 0 sec and was getting the issue described here.
When I set the slider to 10 sec, this was not an issue.
I like being able to see the tabs, but do not like it messing with my copy selection, so I went with 1 second, enough time for me to copy the text without it fudging with my selection and showing the tabs.


text:
Q: MySQL Installation problem in wsl2 ubuntu 22.04 I'm using wsl2 in windows 10 pro. I try a lot to install mysql but I've gotten this error evry time.
I try to uninstall and install again with these command:
    sudo service mysql stop
    sudo apt purge mysql-server mysql-client mysql-common
    sudo rm -rf /etc/mysql /var/lib/mysql /var/log/mysql
    sudo apt autoremove
    sudo apt autoclean

and again install it.
and I got this error
Unpacking mysql-server (8.0.29-0ubuntu0.22.04.3) ...
Setting up mysql-client-8.0 (8.0.29-0ubuntu0.22.04.3) ...
Setting up mysql-server-8.0 (8.0.29-0ubuntu0.22.04.3) ...
invoke-rc.d: could not determine current runlevel
 * Stopping MySQL database server mysqld                        [ OK ]
update-alternatives: using /etc/mysql/mysql.cnf to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Renaming removed key_buffer and myisam-recover options (if present)
mysqld will log errors to /var/log/mysql/error.log
mysqld is running as pid 4602
dpkg: error processing package mysql-server-8.0 (--configure):
 installed mysql-server-8.0 package post-installation script subprocess returned error exit status 1
No apport report written because the error message indicates its a followup error from a previous failure.
                                   dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-8.0; however:
  Package mysql-server-8.0 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.10.2-1) ...
Errors were encountered while processing:
 mysql-server-8.0
 mysql-server
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: To install mySQL you need to ensure none of your other WSL environment already running it.
You can run mySQL in only one environment.


text:
Q: Error when converting a date from a form to sql.date format SimpleDateFormat df = new SimpleDateFormat("yyyy'-'MM'-'dd");
String sbd=request.getParameter("begindate");
java.util.Date bd2=df.parse(sbd);
java.sql.Date bd = new java.sql.Date(bd2.getTime());

I am trying to send data from a form to a JSP page and insert it in an SQL database, but I'm having problems with the date format. yyyy-MM-dd is the default format for my dates, but still I get an exception in the following line when executing the code:
java.util.Date bd2=df.parse(sbd);

I have looked at similar questions and tried changing a few things, but I can't seem to find what's the real issue.
Edit: Here's the stacktrace
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Update:
When removing the apostrophes the exception remains, but the exception message changes:
org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

A: Try changing the format that you initialize df with to "yyyy-MM-dd" without the apostrophes surrounding the hyphens.

A: In JSP, you should use JSTL fmt tag library that provides a set of tags for parsing and formatting locale-sensitive numbers and dates and try to avoid Scriplet.
Read more Oracle Tutorial - Internationalization Tag Library and JSP Standard Tag Library
Sample code:
<%@ taglib prefix="c"   uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<c:set value="2014-10-23" var="dateString" />

<fmt:parseDate value="${dateString}" var="dateObject" pattern="yyyy-MM-dd" />

<fmt:formatDate value="${dateObject}" pattern="dd/MM/yyyy" />

Note: The format completely depends on the data string.

You can use ${param.begindate} to get the begindate from request parameter using param implicit object in jsp.
Sample code:
<fmt:parseDate value="${param.begindate}" var="dateObject" pattern="yyyy-MM-dd"/>

To avoid NullPointerException you should first check it.
<c:if test="${not empty param.begindate}">
      ...
</c:if>


text:
Q: How to alter and merge columns with SQLAlchemy? I am confused as to how to drop entire columns on a Flask server using SQLAlchemy. I changed a variable name in one of my models, and after running $ flask db migrate and $ flask db upgrade the associated table now has two columns: one with the old name and one with the new name. My first part of the question is, how can I, at that point, change the column name when I have these two columns in the table? I have tried following the advice in this similar question's answer by modifying the script.py.mako file in my /migrations folder:
op.alter_column('table_name', 'old_col', nullable=False, new_column_name='new_col')

with no luck. I also tried using the batch_mode version of this code.
To make things worse, somewhere in the process I accidentally added data to this new column and now have two columns. So presently, I'd like to merge these two (over the NULL records), but haven't been able to find any relevant solutions to this.
I'd like to understand the answers to both situations should they arise again.

A: I have found how to call op commands when upgrading. I have been editing the scripts.py.mako file when in fact I should've been editing the latest migration script, found in migrations/versions.  To make changes to the table, I just needed to add the op.<sql_command> in the upgrade() function. So to drop columns I just inserted
with op.batch_alter_table("project") as batch_op:
    batch_op.drop_column('descr')

To avoid the shenanigans from the beginning that occurred from changing variable names all I had to do was:
op.alter_column('project', 'descri', new_column_name='descr')
That said I still haven't figured out how to merge.


text:
Q: dataListAdapter gives me an error when trying to create it - Android I am trying to create a class that extends BaseAdapter but when I try to declare the class is gives me an error here is my code,
    l1=(ListView) findViewById(R.id.list);
        l1.setAdapter((ListAdapter) new dataListAdapter(comments,numbers,usernames));

     class dataListAdapter extends BaseAdapter {
               //example

    }

When I place the code
    l1.setAdapter((ListAdapter) new dataListAdapter(comments,numbers,usernames));

dataListAdapter is underlined and says i need to create a class named dataListAdapter and I do? It's right underneath it?

A: Make sure your dataListAdapter is a inner Static class - it should be positioned inside of the parent class (not inside a method). It needs to be static so it 'appears' as it's own class file, when really its inside another class file.
Also java naming conventions are that a class starts with an Upper case letter, so DataListAdapter :)


text:
Q: How to change Font Size in Simulink Scope? I'm trying to change font size of axes, legend and title of a scope used in simulink. I've seen lots of answers for changing font size in a plot made from workspace, like using 'setgca' and 'fontsize' property, but couldn't find anything about changing font size within a simulink scope.

A: I have tried couple methods, but there's no direct way to implement this. However, we could adjust the font size of titles and x/y labels inside the Figure associated with scope

*

*Directing to scope to figure
After you run the scope, click the scope. In the task bar, select
File > Print to Figure
This will bring you to a figure where we can edit figure's fonts.

*Edit font inside the figure
Edit > Figure Properties
In the pop-up window, edit the font.

A: In simulink is possible to change the font style and size using going to:

Diagram > Format > Font Styles for Model

There you can change the font style and size for blocks, lines and annotations.

A: There isn't any functionality to change these from a pulldown menu, however, they can all be changed using code.
The primary thing to note is that a Simulink Scope is just a MATLAB Figure Window in disguise, and hence it can be manipulated using standard Handle Graphics commands once you have the handle to the scope block you want to manipulate.
For instance to change the size of the legend you'd do:
% Get the Name of the block you want to change
scope_name = get_param(gcb,'Name');
% Get the handle of the figure window used for the scope
hs = findall(0,'Tag','SIMULINK_SIMSCOPE_FIGURE','Name',scope_name);
% Get the handle to the axes on the scope
% (For simplicity, here we'll assume there is only one axis on the scope.
% If there are multiple axes, then you'll need to select which one to manipulate.)
ha = findall(hs,'Type','Axes');
% Get the handle to the legend
hl = get(ha,'Legend');
% Change the font size
set(hl,'FontSize',12);

Given any of the above handles you can manipulate it using set and get just like any Handle Graphics object.

A: I am not sure how to access the scope object from MATLAB, however, I managed to change the legend and titles text sizes by simply resizing the scope window. I know it's not exactly the right way to do this but it works.


text:
Q: AchievementsUI and LeaderboardsUI won't popup. Signing in works and unlocked achievements popups work So. I have made a game with unity 5. And i have downloaded and configured the google play services plugin. I can sign in and unlock achievements with success. But for some reason the
    Social.ShowAchievementsUI();
and
    Social.ShowLeaderboardUI();
Won't work. Or anything won't popup.
So I'm trying to show the list of achievements and show the list of leaderboards available. I have 5 Achievements and 4 Leaderboards. I have this version of the game on Google Play alpha test. With the 2 buttons for Opening achievements menu and leaderboards but those won't work.
My code for login is:
void Start () {
    if (PlayGamesPlatform.Instance.IsAuthenticated() == false)
    {
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
        SignIn();
    }

void SignIn()
{
        Social.localUser.Authenticate((bool success) =>
        {});
}

for showing achievementsUI :
public void ShowAchievementsUI()
{
    Social.ShowAchievementsUI();
}

for showing Leaderboard ui:
public void ShowLeaderboardsUI()
{
    Social.ShowLeaderboardUI();
}

These 2 are called from buttons.
i am using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using GooglePlayGames.BasicApi;

A: Adding:
 <activity android:name="com.google.games.bridge.NativeBridgeActivity"
       android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />

To AndroidManifest.xml fixed the issue

A: First create a script for your PlayGames Commands. The script itself will just be a public class; however, all of the commands will be static so that you can call them from other scripts.
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine;

public class PlayGamesScript : MonoBehaviour {

// Use this for initialization
void Start () {
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();
    PlayGamesPlatform.InitializeInstance(config);
    PlayGamesPlatform.Activate();
    SignIn ();
}

// PRE: None
// POST: Logs player into Google Play Games
void SignIn()
{
    Social.localUser.Authenticate (success => {});
}

#region Achievements
// PRE: Achievement created in Google Play Developer and the
// achievement has been achieved by the player
// POST: Unlocks the achievement for the player
public static void UnlockAchievement(string id)
{
    Social.ReportProgress(id, 100, success => { });
}

// PRE: Achievement created in Google Play Developer and set to Incremental
// achievement
// POST: Increments the achievement by selected steps established by
// the stepsToIncrement variable
public static void IncrementAchievement(string id, int stepsToIncrement)
{
    PlayGamesPlatform.Instance.IncrementAchievement(id, stepsToIncrement, success => { });
}

// PRE: Achievements created in Google Play Developer and player
// is logged in
// POST: Shows the Achievements UI
public static void ShowAchievementsUI()
{
    if(PlayGamesPlatform.Instance.IsAuthenticated())
        Social.ShowAchievementsUI();
    else
        Social.localUser.Authenticate((bool success)=>{
            Social.ShowAchievementsUI();
        });
}
#endregion /Achievements

#region Leaderboards
// PRE: Leaderboard created in Google Play Developer and player is logged in
// POST: Reports the score to the leaderboard id specified for Google Play
public static void AddScoreToLeaderboard(string leaderboardId, long score)
{
    Social.ReportScore(score, leaderboardId, success => { });
}
// PRE: Leaderboard created in Google Play Developer and player is logged in
// POST: Accesses the PlayGamesScript to display the Leaderboard UI
public static void ShowLeaderboardsUI()
{
    if(PlayGamesPlatform.Instance.IsAuthenticated())
        Social.ShowLeaderboardUI();
    else
        Social.localUser.Authenticate((bool success)=>{
            Social.ShowLeaderboardUI();
        });
}
#endregion /Leaderboards

}

You call these functions from another script (the script that calls to view the leaderboard or achievement UI), for example:
public class GooglePlayUIController : MonoBehaviour {

    // PRE: Leaderboard created in Google Play Developer
    // POST: Accesses the PlayGamesScript to display the Leaderboard UI
    public void ShowLeaderboards() {
        PlayGamesScript.ShowLeaderboardsUI ();
    }

    // PRE: Achievements created in Google Play Developer
    // POST: Accesses the PlayGamesScript to display the Achievement UI
    public void ShowAchievements() {
        PlayGamesScript.ShowAchievementsUI();
    }
}

From there you can add these functions onto your buttons through the Unity editor on the OnClick() function; this is how I set mine up.
Of course, do not forget to add your resource data into Unity at the tabs Window --> Google Play Games --> Android Setup so that you may call the ID of each of your achievements, or call to the leaderboard id, via GPGSIds. For example,
// PRE: A game has been played until all lives equal zero
// POST: A score has been posted to the online leaderboards
private void PostScore() {
    PlayGamesScript.AddScoreToLeaderboard (GPGSIds.high_score, player.score);
}


text:
Q: Manipulating two different rows I have the following SQL statement:
SELECT   TRUNC(TIDSPUNKT) AS PERIOD,
         QUEUE,
         ROUND(SUM(CASE WHEN BESVARET_25_SEK > 0 THEN BESVARET_25_SEK END ) / SUM(CASE WHEN ANTAL_KALD > 0 THEN ANTAL_KALD END) * 100) AS SVAR_PROCENT
FROM     KS_DRIFT.PERO_NKM_KØ_OVERSIGT
WHERE    TIDSPUNKT >= '2013-06-17'
AND      TIDSPUNKT <= '2013-07-02'
AND      ANTAL_KALD > 0
AND QUEUE not in ('TekniskHotline')
GROUP BY TRUNC(TIDSPUNKT), QUEUE
ORDER BY PERIOD

This gives me the following result:

As you can see i have highlighed two rows. in the above SQL statement im calculating two rows to get a percentage now here is the tricky part and my question instead of having "Erhverv" and "ErhvervOverflow" on a row i want to count them as one!
is there any way to achieve this?

A: You can use a case statement to assign the values both in the select and the group by:
SELECT   TRUNC(TIDSPUNKT) AS PERIOD,
         (case when QUEUE in ('Erhverv', 'ErhvervOverflow') then 'Erhverv'
               else QUEUE
          end) as QUEUE,
         ROUND(SUM(CASE WHEN BESVARET_25_SEK > 0 THEN BESVARET_25_SEK END ) / SUM(CASE WHEN ANTAL_KALD > 0 THEN ANTAL_KALD END) * 100) AS SVAR_PROCENT
FROM     KS_DRIFT.PERO_NKM_KØ_OVERSIGT
WHERE    TIDSPUNKT >= '2013-06-17'
AND      TIDSPUNKT <= '2013-07-02'
AND      ANTAL_KALD > 0
AND QUEUE not in ('TekniskHotline')
GROUP BY TRUNC(TIDSPUNKT),
         (case when QUEUE in ('Erhverv', 'ErhvervOverflow') then 'Erhverv'
               else QUEUE
          end)
ORDER BY PERIOD;

Note that I included both values in the when clause.  You could do:  when QUEUE = 'ErhvervOverflow' then 'Erhverv' else QUEUE end).  I think including both values makes the intention more clear.


text:
Q: how to join two dataframe by picking couple of column from each if one of the column has same data there are two dataframes df_one and df_two I want to create a new data frame by with selective column from each of the dataframes
df_one
e b c d
1 2 3 4
5 6 7 8
6 2 4 8
9 2 5 6

and
df_two

e f g h
1 8 7 6
5 6 6 4
6 6 2 4
9 5 3 2

I want to create a new dataframe new_df
e b g h d
1 6 7 6 4
5 2 6 4 8
6 2 2 4 8
9 2 3 2 6

enter image description here

A:  result = pd.merge(df_one, df_two, on='e')
 result=result.loc[:,["e","b","g","h","d"]]

A: Use:
pd.merge(df1[["e", "b", "d"]], df2[["e", "g", "h"]], on="e")


text:
Q: Highchart Js Column Chart Stacked and Grouping I using column stacked and grouped chart for comparing.
Check this example code : @fiddle http://jsfiddle.net/wvT85/
I am trying to compare two male stacks
I want the grouped chart have same colors for the item and no repeated legends.
i.e where ever john is used it should have same color and legand should have only one john not two.
Can any one help me on this code.
$(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({

            chart: {
                renderTo: 'container',
                type: 'column'
            },

            title: {
                text: 'Total fruit consumtion, grouped by gender'
            },

            xAxis: {
                categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
            },

            yAxis: {
                allowDecimals: false,
                min: 0,
                title: {
                    text: 'Number of fruits'
                }
            },

            tooltip: {
                formatter: function() {
                    return ''+ this.x +'
'+
                        this.series.name +': '+ this.y +'
'+
                        'Total: '+ this.point.stackTotal;
                }
            },

            plotOptions: {
                column: {
                    stacking: 'normal'
                }
            },

            series: [{
                name: 'John',
                data: [5, 3, 4, 7, 2],
                stack: 'male'
            }, {
                name: 'Joe',
                data: [3, 4, 4, 2, 5],
                stack: 'male'
            }, {
                name: 'John',
                data: [2, 5, 6, 2, 1],
                stack: 'male2'
            }, {
                name: 'Joe',
                data: [3, 0, 4, 4, 3],
                stack: 'male2'
            }]
        });
    });

});

A: Use LinkedTo...
http://api.highcharts.com/highcharts#plotOptions.series.linkedTo
The demo of it is below:
linkedTo: ':previous',

http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/arearange-line/
That way the legend is still functional, and you don't need to set the colors the same.

A: I ran into the same problem recently. So what I did is, combine two of the answers above to solve the problem.
http://jsfiddle.net/sanshila/2g79dhds/1/
series: [{
            name: 'John',
            data: [5, 3, 4, 7, 2],
            stack: 'male',
            color: '#6666FF',
            events: {
                legendItemClick: function (event) {
                    this.visible ? this.chart.get('johnId').hide() : this.chart.get('johnId').show();
                }
            }
        }, {
            name: 'John',
            id: 'johnId',
            color: '#6666FF',
            showInLegend: false,
            data: [2, 5, 6, 2, 1],
            stack: 'male2'
        }]

A: You can manually define the series colors and hide the 2nd set in the legend to do what you want, but this doesn't really link the data.  It won't hide both johns if you click in the legend for instance.  This type of associating 2 points in different series isn't supported as far as I know.  I would say that I think you might want to rethink how you're representing your data, I still don't understand what you're trying to accomplish.
series: [{
                name: 'John',
                color:'blue',
                data: [5, 3, 4, 7, 2],
                stack: 'male'
            },  {
                name: 'John',
                color:'blue',
                showInLegend:false,
                data: [2, 5, 6, 2, 1],
                stack: 'male2'
            }]
        });
http://jsfiddle.net/wvT85/2/

A: I think this is what you want: http://jsfiddle.net/b3AF9/21/
As Ben said, manually set the color for the stacks. Then give ids to the second stack and add
event: {
  legendItemClick: function(event){
     this.visible?
       this.chart.get('Joe2').hide() :
       this.chart.get('Joe2').show();
  }
}

to series in the first stack.


text:
Q: How to add Cordova app to browser list in Android I would like to register my app so that Android recognizes it as a browser and so that users when seeing "Open with" for http links, can choose my application.
Is there any plugin or configuration to perform in the configurations?
Thank you.

A: I have found the answer to my question and I hope this might help someone else looking for this.
You can refer to Custom URL Plugin  which works pretty well, you just need to set the scheme to "https" for your application to receive https calls.
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=https

Now, if you want it to also accept https and maybe add other schemes, you need to edit your AndroidManifest file and add intends:
 <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="http" />
        </intent-filter>

Thank you.


text:
Q: MongoDB+Scala: Accessing deep nested data I think there should be an easy solution around, but I wasn't able to find it.
I start accessing data from MongoDB with the following in Scala:
val search = MongoDBObject("_id" -> new ObjectId("xxx"))
val fields = MongoDBObject("community.member.name" -> 1, "community.member.age" -> 1)

for (res <- mongoColl.find(search, fields)) {
    var memberInfo = res.getAs[BasicDBObject]("community").get
    println(memberInfo)
}

and get a BasicDBObject as result:
{
"member" : [
    {
        "name" : "John Doe",
        "age" : "32",
    },{
        "name" : "Jane Doe",
        "age" : "29",
    },
    ...
]
}

I know that I can access values with getAs[String], though this is not working here...
Anyone has an idea? Searching for a solution for several hours...

A: If you working with complex MongoDB objects, you can use Salat, which provides simple case class serialization.
Sample with your data:
case class Community(members:Seq[Member], _id: ObjectId = new ObjectId)

case class Member(name:String, age:Int)

val mongoColl: MongoCollection = _

val dao = new SalatDAO[Community, ObjectId](mongoColl) {}

val community = Community(Seq(Member("John Doe", 32), Member("Jane Doe", 29)))
dao.save(community)

for {
    c <- dao.findOneById(community._id)
    m <- c.members
} println("%s (%s)" format (m.name, m.age))

A: I think you should try
val member = memberInfo.as[MongoDBList]("member").as[BasicDBObject](0)
println(member("name"))

A: This problem has not to do really with MongoDB, but rather with your data structure. Your JSON/BSON data structure includes

*

*An object community, which includes

*

*An array of members

*

*Each member has properties name or age.

Your problem is completely equivalent to the following:
case class Community(members:List[Member])

case class Member(name:String, age:Int)

val a = List(member1,member2)

// a.name does not compile, name is a property defined on a member, not on the list

A: Yes, you can do this beautifully with comprehensions. You could do the following:
for { record <- mongoColl.find(search,fields).toList
      community <- record.getAs[MongoDBObject]("community")
      member <- record.getAs[MongoDBObject]("member")
      name <- member.getAs[String]("name") } yield name

This would work just to get the name. To get multiple values, I think you would do:
for { record <- mongoColl.find(search,fields).toList
      community <- record.getAs[MongoDBObject]("community")
      member <- record.getAs[MongoDBObject]("member")
      field <- List("name","age") } yield member.get(field).toString


text:
Q: Spring Boot 2 JUnit Test for rest api failed at 'jwtAuthenticationEntryPoint': I am writing Junit test for spring boot service ,for testing api call,but It failed to run throwing following exception
Caused by:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'resourceServerConfig': Unsatisfied dependency expressed through field 'entryPoint'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'jwtAuthenticationEntryPoint': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)

Junit Test:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Application.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class ServiceTest {

  @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.wac).build();
    }

        @Test
        public void validateApiCall() throws Exception {
            String token = "Bearer xxxxxxxx";
         mockMvc.perform(MockMvcRequestBuilders.get("http://localhost::8060/api").header("Authorization", token)).andExpect(status().isOk());

        }
}

A: I was able to fix it by autowiring javax.servlet.Filter[] this way
        @RunWith(SpringRunner.class)
        @SpringBootTest
        @ContextConfiguration(classes = Application.class)
        @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
        public class ServiceTest {

          @Autowired
          protected WebApplicationContext wac;

          @Autowired
          private javax.servlet.Filter[] springSecurityFilterChain;

          @MockBean private JwtAuthenticationEntryPoint jwt;

          protected MockMvc mockMvc;

          @Before
          public void setup() {
              MockitoAnnotations.initMocks(this);
              mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
            }

                @Test
                public void validateApiCall() throws Exception {
                    String token = "Bearer xxxxxxxx";

 mockMvc.perform(MockMvcRequestBuilders.get("http://localhost::8060/api").header("Authorization", token)).andExpect(status().isOk());

                }
        }


text:
Q: Is Threshold an early Earth pyramid? The final paragraph in Threshold is:

"No.  It has taken eight generations to build, and would take two or three to pull down.  More would die in the process, and I do not think I could stand that.  No.  Fill the shafts and corridors with stone and block up all the entrances.  Then leave the sand to drift over the stone and the memories.  Leave Threshold for future millennia to puzzle over - but leave them no trace of its secret."

Threshold is a very large pyramidal building with a capstone and various internal corridors and chambers.  There is only one.
Is this meant to hint that this was the first Earth (Egypt/Mesoamerican) pyramid, found thousands of years later (and copied by the builders of the rest)?
This is the impression I get from the final sentence, along with "how the pyramids were really built" being a moderately common element of stories, but I don't know enough about them to know whether Threshold matches any close enough or whether this is unrelated (with the story set on a totally different world).

A: I don't know what her original intentions were when this book was written, but then it was a standalone novel and that could have been a possibility.
However, Douglass really liked this story, and she folded it into her Tencendor universe (The Wayfarer's Redemption) and used it as backstory, along with The Hanging Wall (a stand alone set in the Tencendor universe) for a final trilogy, Darkglass Mountain.
She died of cancer a few months after the final book, The Infinity Gate, was released.

A: Threshold, which is later named Darkglass Mountain, is set in the Tencendor universe, and is located near Aqhat, a major city in the Tyranny of Isembaard.  At the end of The Wayfarer Redemption Trilogy (the second trilogy set in the universe), we learn that

Tencendor is not on Earth, although the StarGate was created by a crash landing of a vessel from Earth that contained the pieces of Qeteb.  The end of the trilogy shows that DragonStar and Faraday are the origin of Angels (and perhaps Adam and Eve), as they return to Earth to guide the humans.

Because we know definitively that the planet in the Tencendor universe is not Earth, we know that Threshold is not an early Earth pyramid.


text:
Q: How to use OVRInput in a custom DLL for unity? I working on Oculus using Unity. Initially I created a script in unity which directly and used the OVRInput for reading inputs. It's working fine.
Now, I wanted to create a DLL of that script.
I followed these steps to do it.(Please do suggest me if there are easier ways of doing it)

*

*Created a Class Library project in VS2019.

*Added UnityEngine.dll as a reference.

I am able to use all Unity related functions now. But VS isn't recognising OVRInput because I haven't added any references corresponding to it.
Adding the reference to OVRInput is my problem. I'm not sure how to do it.
What should I do if I want VS to recognise OVRInput? Is it possible to do so in the first place?
If it's not possible, is there any alternative way of creating the above dll?

A: give this a try:

*

*In Solution Explorer, right-click on the References or Dependenciesnode and choose Add Reference. You can also right-click on the project node and select Add > Reference.
Reference Manager opens and lists the available references by group.

*Specify the references to add, and then select OK.
If you can't find the referenced DLL, set its Copy Local property to true.
Another way around is to set your Reference Paths. This will force, on compile-time, your project to update itself with DLLs from the specified reference paths.
The best practice was to create a Shared folder where all referenced libraries were in so that you could write your reference paths once and for all per project.
I hope this helps, cheers!


text:
Q: Dojo build package configuration In our Dojo system, we have something like the following specified in our dojoConfig:
packages: [{
    name: "myWidgets",
    location: "/js/libs/widgets"
}]

So that in our require statements, all we have to do is something like:
 require(["myWidgets/myCalendarWidget"....

The problem is when I run the build, this dojoConfig is not available and I get numerous missing dependency errors because 'myWidgets' isn't defined according to the build profile.
Now, I've tried adding a package block to the build profile also, but the end result of that is to create an actual 'myWidgets' package, which I don't want.
So, is there any way to make the build see the definition of the 'myWidgets' alias, yet have the end result of the build output still mirror the regular file structure (i.e. /js/libs/widgets)?  I tried to define these path aliases in the defaultConfig element in the build profile and that doesn't work either.

A: If you are using a profile, you can specify the packages in the profile
/util/buildscripts:./build.sh profile=../../../myProfile.js

http://dojotoolkit.org/reference-guide/1.8/build/buildSystem.html#profile-basics
You can also specify a javascript file that holds the dojoConfig
/util/buildscripts:./build.sh --dojoConfig ../build/examples/dojoConfig.js

http://dojotoolkit.org/reference-guide/1.8/build/buildSystem.html#using-a-package-configuration

Answer to your comment.  The path is relative from where dojo.js is.
var dojoConfig = {
    parseOnLoad: true,
    isDebug: true,
    locale: 'en-us',
    paths: {
        "evf":      "../../evf"
    }
};

My directory structure looks like
js/dojo-1.8.0
  dijit
  dojo <-- contains dojo.js
  dojox
  util
js/evf
  myCustomWidget.js


text:
Q: HDBSCAN approximate_predict always returning probability of 0 I am using HDBSCAN to generate prediction data for a given cluster model. I then attempt to classify new points using the approximate_predict function to find the correct cluster for a new point. The model returns the correct cluster for a new point but the probability/strength is always 0.0. To generate the model and classify new points I use:
# Generate the model
cluster_model = hdbscan.HDBSCAN(metric='euclidean', min_cluster_size=3, cluster_selection_epsilon=0.4,
                                prediction_data=True).fit(data)

# Classify new point
cluster, prob = hdbscan.approximate_predict(cluster_model, new_point)
print(cluster, prob)

As I understand, if the strength/probability is 0.0 the point has been classified as noise. From manual analysis of the new points I can see they do fit into the heart of the original clusters so I don't understand why the probability is always 0.0?


text:
Q: How to feed a command substitution to the "yes" command? If I run yes "I like cheese" in bash, I will get an endless output of
I like cheese
I like cheese
...
...

However, I would like to print a random string on each line and thought using yes could be a way to get there. So I have tried this command:
yes `echo $(tr -dc A-Za-z0-9 </dev/urandom | head -c 10)`

The problem is it prints the same string over and over because yes only takes the first result that
`echo $(tr -dc A-Za-z0-9 </dev/urandom | head -c 10)`

evaluates to, which is a random string (e.g. d8pTVeZYyi)
So the result is and endless output of:
d8pTVeZYyi
d8pTVeZYyi
d8pTVeZYyi
...

How can I make that command substitution run on every line? So that the result is:
d8pTVeZYyi
HCmjUpGOIq
K3e8aquaiK
mMJBZYkHJM
...

P.S. The overall goal is to be able to generate huge text files with a random string on each line in a reasonable amount of time. Those are needed for test purposes.

A: The problem is that the expression echo $(tr -dc A-Za-z0-9 </dev/urandom | head -c 10) is only evaluated once, at the moment when yes is laucnhed, so all subsequent iterations just print out the result of that expression.
Some other options:
while true; do
    tr -dc A-Za-z0-9 </dev/urandom | head -c 10
    echo ""
done

or
while true; do
    rand=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 10)
    echo "$rand"
done

Or, better (shamelessly stolen from @steeldriver's comment):
tr -dc A-Za-z0-9 </dev/urandom | fold -w10


text:
Q: Dynamic range of an ADC is 6n dB? In the book Art of Electronics, it says that an ADC with a sampling depth of n bits has a dynamic range of 6n dB. Where does 6n dB come from?

A: \$20 \log_{10}2 \approx 6\$
Each bit added to the width of the output of an ADC increases the dynamic range by a factor of 2. Therefore it increases the dynamic range by 6 dB.


text:
Q: Is creating new thread for displaying PyQt message box several time a good practice? I am trying to create and run a new thread each time I want to pop a message box from main thread.  Wondering if this code below will cause memory leak or even a good practice.  If it can be improved, how to?
class UIThread (threading.Thread):
    def __init__(self, message):
        print "UIThread init(). msg = " + message
        this_thread = threading.Thread.__init__(self)
        this_thread.daemon = True
        self.message = message
        self.qtapp = QApplication(sys.argv)
        self.w = QWidget()

    def run(self):
        print "UIThread running"
        result = QMessageBox.warning(self.w, 'WARNING', self.message, QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if result == QMessageBox.Yes:
            print 'Yes.'
        else:
            print 'No.'

        sys.exit(self.qtapp.exec_())

...
    messagebox = UIThread("Test")
    messagebox.start()

....
    messagebox = UIThread("Test 2")
    messagebox.start()

....
    # will pop up more message boxes throughout the program

A: No it's not good practice. You should only do GUI stuff, including showing message boxes, from the main thread. Use signals and slots to communicate with the main thread, which can show the message box and provide a response for your secondary thread.
Here's a simple example where a worker thread signals the main thread to show a message box, then checks the responses dictionary for the message box response (basic dictionary operations are thread safe). This example should also work for multiple threads as the responses are keyed under the thread name.
from PyQt4 import QtCore, QtGui
import threading, time, sys

class Worker(QtCore.QObject):
    def __init__(self, app):
        super(Worker, self).__init__()
        self.app = app

    def do_stuff(self):
        thread_name = threading.current_thread().name
        self.app.responses[thread_name] = None
        self.app.showMessageBox.emit(thread_name,
                                     'information',
                                     'Hello',
                                     'Thread {} sent this message.'.format(thread_name))
        while self.app.responses[thread_name] is None:
            time.sleep(0.1)
        print 'Thread {} got response from message box: {}'.format(thread_name, self.app.responses[thread_name])

class MainWindow(QtGui.QMainWindow):
    showMessageBox = QtCore.pyqtSignal(str, str, str, str)
    def __init__(self, sys_argv):
        super(MainWindow, self).__init__(sys_argv)

        self.responses = {}
        self.showMessageBox.connect(self.on_show_message_box)

        self.worker = Worker(self)
        self.thread = QtCore.QThread()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.do_stuff)
        self.thread.start()

    def on_show_message_box(self, id, severity, title, text):
        self.responses[str(id)] = getattr(QtGui.QMessageBox, str(severity))(self, title, text)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MainWindow(None)
    win.show()
    sys.exit(app.exec_())


text:
Q: Cannot read property from undefined - Google Script I have issues with this code, I can't make JSON splitting part correctly. I constantly get the following error: TypeError: Cannot read property "cu_id" from undefined.
part of JSON data looks like this (it is too big to show all, but the rest is the same)
{"started":"2022-01-15T12:56:08.197","finished":"2022-01-15T12:56:08.207","action":"RECEIVE","status":"SUCCESS","username":"sciarlo","subject":"340382659301954864","object":"10834376","result":"Created lots 5265995","trace_id":"LC3tS16A","properties":{"arrival_id":"ARR-98fc5b2b-cad2-4033-9bff-3af5cd779946","cu_id":"10834376","cu_quantity":"62","freshness_date_format":"NONE","load_carrier_barcode":"340389301954864","location":"3403826554864","purchase_orders":"366469","receive_type":"SSCC","temperature_zone":"AMBIENT","tu_id":"10834376","tu_quantity":"62"}}

Here is the part of code with issues:
  var receiveActions = []
  var latestTimestamp = receiveTab.getRange(2, 19).getValue();
  var actionTime = new Date(outputArray[0].finished)
  receiveTab.getRange(3, 19).setValue(actionTime);

  for (var i in outputArray) {
    var receiveAction = outputArray[i];
    if (new Date(receiveAction.finished) > new Date(latestTimestamp)) {

      var article = receiveAction.properties.cu_id;
      var location = receiveAction.properties.location;
      var temperatureZone = receiveAction.properties.temperature_zone;
      var cuQuantity = receiveAction.properties.cu_quantity;
      var tuQuantity = receiveAction.properties.tu_quantity;
      var tuSize = cuQuantity/tuQuantity;
      var timestamp = new Date(receiveAction.finished);
      var user = receiveAction.username;

      receiveActions.push([timestamp,user,temperatureZone,article,location,tuQuantity,tuSize])
    }
  }

Thank you in advance for help!

A: Your JSON is not valid, it begins with a bracket/array but doesn't end with a bracket/array.
This makes me feel that you have more than one object entry in your JSON, and that the one you're showing us isn't the problem.
Are you sure that all of your objects in the JSON structure contains the  receiveAction.properties element?


text:
Q: DRY voting methods I have a prompt asking to write my up_vote and down_vote methods in only two lines using 'redirect_to' and the 'update_vote!' method as presented below. Implementing redirect_to is easy enough, but I'm not quite sure how to write my up/down_vote methods concisely using the existing 'update_vote!' method. Any help is appreciated.
 class VotesController < ApplicationController
      before_action :load_post_and_vote

      def up_vote

        if @vote
          @vote.update_attribute(:value, 1)
        else
          @vote = current_user.votes.create(value: 1, post: @post)
        end

        # http://apidoc.com/rails/ActionController/Base/redirect_to
        redirect_to :back
      end

      def down_vote

        if @vote
          @vote.update_attribute(:value, -1)
        else
          @vote = current_user.votes.create(value: -1, post: @post)
        end

        # http://apidoc.com/rails/ActionController/Base/redirect_to
        redirect_to :back
      end

      private

      def load_post_and_vote
        @post = Post.find(params[:post_id])

        @vote = @post.votes.where(user_id: current_user.id).first
      end

      def update_vote!(new_value)
        if @vote
          authorize @vote, :update?
          @vote.update_attribute(:value, new_value)
        else
          @vote = current_user.votes.build(value: new_value, post: @post)
          authorize @vote, :create
          @vote.save
        end
      end
    end

A: You should invoke the update_vote! method. How about:
def up_vote
  update_vote!(1)
  # http://apidoc.com/rails/ActionController/Base/redirect_to
  redirect_to :back
end

def down_vote
    update_vote!(-1)
    # http://apidoc.com/rails/ActionController/Base/redirect_to
    redirect_to :back
end

Also your method can be re-written as :
def update_vote!(new_value)
  Vote.find_or_create_by post: @post do |v|
    authorize v, :update?
    v.user_id = current_user.id
    v.value = new_value
    v.save!
  end
end

Read find_or_create_by.

A: seems that answer was easy enough =]
def up_vote
  update_vote(1)
  redirect_to :back
end

def down_vote
  update_vote(-1)
  redirect_to :back
end


text:
Q: Jackson: Deserialize interface without annotations and mix-ins I am trying to create a way to serialize and deserialize objects to JSON using Jackson without having to rely on annotations, mix-ins or any code that is object-specific (ie: specific deserializers). However, I'm having trouble deserializing interfaces.
An idea that I had was to store the class name of the object within the JSON. For instance, if I have the following classes:
MyClassOne.java
package test.classes;

public class MyClassOne{

    private String myString;
    private MyClass myReference;

    public MyClassOne(String myString, MyClass myReference) {
        this.myString = myString;
        this.myReference = myReference;
    }
    public String getMyString() {
        return myString;
    }
    public MyClass getMyReference() {
        return myReference;
    }
}

MyClassTwo.java
package test.classes;

public class MyClassTwo implements MyClass{

    private int myInt;

    public MyClassTwo(int myInt) {
        this.myInt = myInt;
    }
    public int getMyInt() {
        return myInt;
    }
}

I would like to use Jackson to serialize MyObjectOne instances into something similar to:
{
"_class":"test.classes.MyClassOne" ,
"myString":"Hello World",
"myReference":{
    "_class":"test.classes.MyClassTwo",
    "myInt":2
    }
}

I was wondering if that could work and how to accomplish it with Jackson.

A:
An idea that I had was to store the class name of the object within the JSON.

You could consider enableDefaultTypingAsProperty() for automatic inclusion of type information:
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, "_class");

I am trying to create a way to serialize and deserialize objects to JSON using Jackson without having to rely on annotations, mix-ins or any code that is object-specific (ie: specific deserializers).

Consider the following code using the types defined in your own question:
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "_class");

MyClass myClass = new MyClassTwo(2);
MyClassOne myClassOne = new MyClassOne("Hello World", myClass);

String json = mapper.writer()
        .withDefaultPrettyPrinter()
        .writeValueAsString(myClassOne);

It will produce the following JSON:
{
  "_class" : "com.example.examples.foo.MyClassOne",
  "myString" : "Hello World",
  "myReference" : {
    "_class" : "com.example.examples.foo.MyClassTwo",
    "myInt" : 2
  }
}

To deserialize the above JSON, however, your classes must have a default constructor (or use @JsonCreator).


text:
Q: Copy character string to character pointer in C Here is a simple program to demonstrate my problem.
I have a function functionB which passes pointer to a character array to functionA. functionA finds the value and stores it to a character array. The content of character array should be copied to character pointer fdate. How can I achieve this?
int functionB() {
    char fdate[20];
    functionA(&fdate[0]);
    return 0;
}

int functionA(char *fdate) {
    char date[20] = "20 May 2016";
    strcpy(fdate, date);
    return 0;
}

A: You cannot copy a string into a character pointer, but you can copy a string to a memory block pointed to by a character pointer. You cannot do this:
char *ptr;
functionA(ptr);

and expect ptr to point to the string. You need to pass a pointer to a valid memory block into your function, like this:
char buf[100];
functionA(buf);

Now the copy would work, but the function would be unsafe because it wouldn't know how much memory is available for writing its string, and could cause buffer overruns. A better approach is to pass the size of the buffer along with the buffer:
functionA(buf, sizeof(buf));

Another alternative is to pass a pointer to pointer, and have the function allocate the string dynamically. In this case, however, the caller is responsible for freeing the memory after its use:
char *ptr;
functionA(&ptr);
...
free(ptr);
...
int functionA(char **fdate) {
    char date[20] = "20 May 2016";
    *fdate = malloc(sizeof(date));
    memcpy(*fdate, date);
    return 0;
}


text:
Q: Use .htaccess but ignore URLs beginning with two characters I have some RewriteRule commands setup in .htaccess. But, I want anything that begins like this:
www.mydomain.com/xq/...

...to be ignored. How can I do this without disturbing my other rules? I tried this, but it doesn't seem to work:
RewriteRule ^/xq$ /xq$1

Thanks.

A: Put this rule above others (after RewriteEngine directive)
RewriteRule ^xq/.*$ - [L]

Note: in this case, your htaccess has to be in root folder


text:
Q: SQL Concat and merge values How to make it correct, whats wrong with this?
SELECT Name, Surname, CONCAT(NAME + ' '+ SURNAME) 'name and surname'
FROM Worker
WHERE Born = '1988';

or
SELECT Name, Surname, 'NAME' + ' '+ 'SURNAME' AS 'name and surname'
FROM Worker
WHERE Born = '1988';

A: The standard SQL operator for concatenation is ||, so you want:
SELECT Name, Surname, (NAME || ' ' || SURNAME) as full_name
FROM Worker
WHERE Born = '1988';

Many databases also support a CONCAT() function, although logically you want at least two arguments.  SQL Server uses + for string concatenation, but that is not widespread.

A: Your syntax is wrong in the two queries:
SELECT Name, Surname, CONCAT(NAME, ' ', SURNAME) "name and surname"
FROM Worker
WHERE Born = '1988';

or
SELECT Name, Surname, NAME + ' '+ SURNAME AS "name and surname"
FROM Worker
WHERE Born = '1988';

Suposing you are using Microsoft SQL Server, keep in mind there are actually few differences between regular + operator and concat() function.

*

*concat() will implicitly converts any parameter to a string while + will throw an error if you mix strings and other types

*concat() will always return a not null string even if all parameters are null. + will return null as soon as any column is null.


text:
Q: How do I install `libmysqlclient-dev` on 18.04? I'm trying to install mysqlclient in a Python 3.6 environment on Ubuntu 16.04 using the recommended $ pip install mysqlclient.  This produces an error OSError: mysql_config not found.  I don't know what this mysqlclient file is, but I verified that it doesn't exist on my system.
Ubuntu Package Search tells me that the file /usr/bin/mysql_config is provided by the packages libmariadb-dev-compat, libmariadbclient-dev, and libmysqlclient-dev.  Since I'm using MySQL and not MariaDB, I try to install libmysqlclient-dev through apt-get.  It fails with the error
The following packages have unmet dependencies:
libmysqlclient-dev : Depends: libmysqlclient20 (= 5.7.21-1ubuntu1) but 5.7.24-0ubuntu0.18.04.1 is to be installed
E: Unable to correct problems, you have held broken packages.

I have version 5.7.24-0ubuntu0.18.04.1 of libmysqlclient20 already installed on the system, but libmysqlclient-dev is set to depend on version 5.7.21-1ubuntu1 exactly.  Can mysqlclient not be installed on Ubuntu 18.04?  If it can, how do I resolve this and install libmysqlclient-dev?
Also, what does it mean that I "have held broken packages"?  Is there a way to determine which package is broken and what's broken about it?
Edit I performed apt-get update and apt-get upgrade multiple times while trying to troubleshoot this myself, and I just did so again to be sure.
Here is the output of apt-cache policy libmysqlclient-dev libmysqlclient20:
$ apt-cache policy libmysqlclient-dev libmysqlclient20
libmysqlclient-dev:
  Installed: (none)
  Candidate: 5.7.21-1ubuntu1
  Version table:
     5.7.21-1ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 Packages
libmysqlclient20:
  Installed: 5.7.24-0ubuntu0.18.04.1
  Candidate: 5.7.24-0ubuntu0.18.04.1
  Version table:
 *** 5.7.24-0ubuntu0.18.04.1 100
        100 /var/lib/dpkg/status
     5.7.21-1ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 Packages

EDIT 2 According to my notes, on 2Dec2018 I added the line
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates main restricted

to my /etc/apt/sources.list to solve a similar problem, because for some reason unknown to me it wasn't there already.  Checking the file now, the line was not there.  I am 100% certain that I never knowingly removed it.
How the hell does this keep happening?  What package or program has the ability to edit my sources.list for me?  I never use any graphical package management system, only apt-get from the command line, and I've never knowingly altered my sources after install except in these specific instances.
EDIT 3 Re-adding the line
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates main restricted

to /etc/apt/sources.list worked.  I was able to update and then install libmysqlclient-dev, and /usr/bin/mysql_config now exists on my system.  I still can't install mysqlclient, but now it's because of a completely different missing file.  Just another lost day of productivity in the ongoing saga of trying to accomplish something using this shitstain open source software, and at least one more lost day to come.