text:
Q: File transfer to the server CURL Trying to upload a file to server using CURL
The query is formed as:
$postdata = array(
'FileToLoad' => "@".$this->file."; filename=\"$this->filename\";",
'fileId' => $this->fileId);

$this->file contains the full path to the file on the server /var/www/site/data/www/site.ru/tmp/file.pdf
Send:
if( $curl = curl_init() ) {
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
 curl_setopt($curl,CURLOPT_ENCODING, '');
curl_setopt($curl, CURLOPT_COOKIE, ".ASPXAUTH=$this->token;");
$out = curl_exec($curl);
curl_close($curl);
}

The request is successful, but data is in $_POST, and I really want to see in $_FILES. Where am I wrong?


text:
Q: How does Apache Spark's CoarseGrainedScheduler get started? I'm trying to instrument a Spark (v 1.6.1) application with an APM (Application Performance Management System).  To do so with the APM of choice, I must instrument the JVM startup string(s) with a -javaagent flag, pointing to my APM along with any pertinent APM options (e.g., unique-host-id).
On the Spark Master server, I have done this successfully, and on the various Spark Worker servers, I have successfully instrumented the spark worker process as well.
However, when I look at the Java processes that are running, I see one additional process that does not contain my startup string: the CoarseGrainedScheduler.  The CoarseGrainedScheduler is the actual Spark executor which runs the worker application code submitted to the Worker by the Master.
I cannot determine from where the CoarseGrainedScheduler is invoked.
So, for more context, here's how I've instrumented the Spark Worker startup string: in {SPARK_HOME}/conf/spark_env.sh, I added the following environment variable:
SPARK_DAEMON_JAVA_OPTS="<java-agent-startup-string>"
This gets carried through to the eventual invocation of {SPARK_HOME}/bin/spark-class, which is the root of all Spark invocations; that is, all spark commands that emanate from {SPARK_HOME}/bin or {SPARK_HOME}/sbin eventually delegate to spark_class.
This is seemingly not, however, where CoarseGrainedScheduler is invoked from.  Looking at this document, though, that is where it gets invoked from:
$ ./bin/spark-class org.apache.spark.executor.CoarseGrainedExecutorBackend <opts>

Why, then, is my startup string not being picked up?  Working from the assumption/instruction that CoarseGrainedExecutorBackend is invoked via spark-class, I actually edited that file to add my startup string when running any java command, and that also fails to add my startup string to the CoarseGrainedExecutorBackend, although it does add it to the Spark Worker process itself.  So again, it seems as though CoarseGrainedExecutorBackend is not started via spark-class, even though the linked document says it is.
Can anyone help me find the root of the CoarseGrainedExecutorBackend process and how it's invoked?  If I can provide any additional details, just let me know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I control nginx reverse proxy with my java app? I use nginx reverse proxy with docker and want to automate my nginx configuration.
For example, I want to tell my java app a domain/server_name (e.g. myapp.example.com) and a backend system. And my java app should tell nginx to configure that.
Is this possible or is there an alternative reverse proxy software with that functionality.

A: One way to achieve that would be to use a shared volume that both containers (the java container and the nginx container) can access and where the nginx configuration file is placed. This would also work if java is not in docker then it just needs access to the mapped folder.
Whenever you want to update the config just rewrite it and then trigger nginx to reload. There are mutliple ways to achieve this. Most easily by using
docker exec nginx-container-name nginx -s reload

e.g. via Java ProcessBuilder or the awesome Java Docker Project https://github.com/docker-java/docker-java.
Note: If you run java inside a docker container you have to map the docker socket inside the container (e.g. using -v /var/run/docker.sock:/var/run/docker.sock from shell).


text:
Q: Regular expression negation in R I have a problem trying to find a way to implement negation in R regular expressions.
my_strings <- c("a non-rheumatic fever", "a nonrheumatic fever", "a rheumatic fever", "a not rheumatic fever")
my_strings
## [1] "a non-rheumatic fever" "a nonrheumatic fever" "a rheumatic fever" "a not rheumatic fever"

In the above string, I'm trying to find a regular expression that will output just the following:
## [1] "a rheumatic fever"

I've tried the following but I can't figure out how to negate the presence of "no(n|t)(\\s+|-)?" immediately preceding "rheumatic":
t_inc <- "\\b([^n][^o][^nt](\\s+|-)?(rheumatic))\\b"
grep(t_inc, my_strings, ignore.case = T, perl = T, value = T)
## character(0)

t_inc <- "\\b([^(no(n|t))](\\s+|-)?(rheumatic))\\b"
grep(t_inc, my_strings, ignore.case = T, perl = T, value = T)
## character(0)

Please could someone give me some pointers?

A: May be we can modify the syntax to a bit simpler one by making ue of invert as mentioned by @IceCreamToucan in the comments
grep("no[nt][- ]?rheumatic", my_strings, invert = TRUE, value = TRUE)
#[1] "a rheumatic fever"

the pattern matches 'no', followed by either letter 'n' or t', followed by a - or space if present and the word 'rheumatic'.  With invert= TRUE, it will return all those matches that are not matching with the pattern


text:
Q: ¿Condicionar un formulario en symfony2? Pues tengo el siguiente dato en un formulario de symfony:
->add('lugar', EntityType::class, array(
                'class' => 'AppBundle\Entity\Lugar',
                'mapped' => false,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('e')
                        ->orderBy('e.horaInicio', 'ASC');
                },
                'choice_label' => 'lugar',
                'label' => 'Desea acudir a las siguientes horas? (15:45-17:00)'
            ))

Actualmente este código me muestra todas las horas que hay en horaInicio, me gustaría saber si hay alguna forma de coger sólo las que muestro en el código, con un if o algún método por el estilo.

A: Ya que usas el parámetro query_builder, puedes usarlo para filtrar los elementos que se van a mostrar:
'query_builder' => function (EntityRepository $er) {
     return $er->createQueryBuilder('e')
               ->where(/* tu condición aquí */)
               ->orderBy('e.horaInicio', 'ASC');
},

Por ejemplo, para usar un rango de fechas:
'query_builder' => function (EntityRepository $er) {
     return $er->createQueryBuilder('e')
               ->where('e.date > :datetimeStart') // Campo fecha es mayor que...
               ->andWhere('e.date < :datetimeEnd') // Campo fecha es menor que...
               ->setParameter('datetimeStart', new \DateTime('now')) // mayor que hoy
               ->setParameter('datetimeEnd', new \DateTime('tomorrow')) // menor que mañana
               ->orderBy('e.horaInicio', 'ASC');
},

A: Otra forma que podeis usar (basada en la de Muriano) es pasarle al querybuilder parametros definidos antes del formulario. por ej:
'query_builder' => function (EntityRepository $er) use ($start, $end) {
     return $er->createQueryBuilder('e')
    ->where('e.date > :datetimeStart')
    ->andWhere('e.date < :datetimeEnd')
    ->setParameter('datetimeStart', $start)
    ->setParameter('datetimeEnd', $end) // menor que mañana
    ->orderBy('e.horaInicio', 'ASC');
},

$start y $end hay que definirlos antes de llamar al add del campo que estes definiendo.


text:
Q: While testing in javascript, Variables defined in 'before' block is showing undefined while using in 'It' block This is a sample test where I am testing that testNum should be 0,
code:
describe("Test Contract", () => {

    before(async () => {
        const testNum = 0;
    })

    it("should be zero", function () {
        expect(testNum).to.equal(0);
    })
  }

But I am getting an error saying testNum is undefined.
Error:
1) Test Contract
       should be zero:
     ReferenceError: testNum is not defined

What I am doing wrong?

A: Variable testNum is scoped to the {} where you defined it. Also, const is used for read only values. I assume you want to reassign testNum multiple times. Therefore you should use let.
What you probably want is:
describe("Test Contract", () => {
    let testNum;
    before(async () => {
        testNum = 0;
    })

    it("should be zero", function () {
        expect(testNum).to.equal(0);
    })
  }


text:
Q: How to properly use NDK-Build in Android Studio 2.2 Preview 1 Android Studio 2.2 Preview 1 has a new external ndk build feature, but from app/build.gradle snippet shown in official blog post it's not clear at all how to set additional ndk build parameters which Application.mk file usually contains
I'm able to set Android.mk ndk build file via externalNativeBuild, but how could I set the required Application.mk variables?
My Application.mk contains:
NDK_TOOLCHAIN_VERSION := clang
APP_PLATFORM := android-16
APP_ABI := armeabi
APP_STL := c++_static
APP_CPPFLAGS += -std=c++11

A: Android Studio 2.2 Preview 3 with updated gradle plugin added support for additional arguments. You can set Application.mk and additional configuration like this:
defaultConfig {
  ndkBuild {
    arguments "NDK_APPLICATION_MK:=Application.mk"
    cFlags "-DTEST_C_FLAG1"  "-DTEST_C_FLAG2"
    cppFlags "-DTEST_CPP_FLAG2"  "-DTEST_CPP_FLAG2"
    abiFilters "armeabi-v7a", "armeabi"
  }
}

If possible I would recommend migrating to CMake build system, because of better C++ code editor and debugging integration in Android Studio. You will find more info on gradle plugin configuration here:
https://sites.google.com/a/android.com/tools/tech-docs/external-c-builds.
Edit:
From Android Studio 2.2 Preview 5 you must wrap cmake and ndkBuild groups under externalNativeBuild group:
defaultConfig {
  externalNativeBuild {
    ndkBuild {
      targets "target1", "target2"
      arguments "NDK_APPLICATION_MK:=Application.mk"
      cFlags "-DTEST_C_FLAG1", "-DTEST_C_FLAG2"
      cppFlags "-DTEST_CPP_FLAG2", "-DTEST_CPP_FLAG2"
      abiFilters "armeabi-v7a", "armeabi"
    }
  }
}

Edit 2: It seems that  wrapping ndkBuild under externalNativeBuild  group does not work because of a bug in build tools.

A: add-native-code
android {
  ...
  defaultConfig {...}
  buildTypes {...}

  // Encapsulates your external native build configurations.
  externalNativeBuild {

    // Encapsulates your CMake build configurations.
    cmake {

      // Provides a relative path to your CMake build script.
      path "CMakeLists.txt"
    }
  }
}

Note: If you want to link Gradle to an existing ndk-build project, use the ndkBuild {} block instead of cmake {}, and provide a relative path to your Android.mk file. Gradle also includes the Application.mk file if it is located in the same directory as your Android.mk file.


text:
Q: How to solve a "permission denied" error on git bash? I am using git bash to run my python program, but unfortunately more recently when trying to install some modules using git bash, I get a "permission denied" error.
Here is an example:
$ pip install mysql-connector-python.
bash: /c/Users/user/AppData/Local/Microsoft/WindowsApps/pip: **Permission denied**

A: Click the Start icon and click in the Search box.
Type git bash into the search box. You will see the git bash in the search window.
Hover the mouse over the git bash program and right-click.
Select "Run as administrator".
after that run  "pip install mysql-connector-python" command


text:
Q: Using powershell to manipulate URL header with real live system data I am trying to use powershell to manipulate a url value for a command program that is accessing a web Url.
Basically the case is like this
run in Powershell:
Program Argument https://www.example.com/dash/926846/l.php?link=bTP77O5LyLorxCtjnkdE0g&sectime=1598048132
The Sectime is in Unix time format. What i am trying to do is :
use the powershell command (Get-Date -Date ((Get-Date).DateTime) -UFormat %s) to generate the system time in real time,
Append the result to the end of the Url as a value for sectime.
I tried to concatnate the arguments using call operator :
Arg1=program
Arg2=parameter
Arg3=Url
& $Arg1 Arg2 $Arg3

now the issue is i can do
this is the issue. & $Arg1 Arg2 $Arg3 and that works , but i can not modify the URL to take the real time command (Get- Date -Date ((Get-Date).DateTime) -UFormat %s)
if i split the URL arg into two i cant not concatnate them like this
"https://www.example.com/dash/926846/l.php?link=bTP77O5LyLorxCtjnkdE0g&sectime=(Get-Date -Date ((Get-Date).DateTime) -UFormat %s)."
Since it is a string and an command
An idea how to do this?

A: $uriTemplate = 'https://www.example.com/dash/{0}/l.php?link={1}&sectime={2}'

$id = '926846'
$link = 'bTP77O5LyLorxCtjnkdE0g'
$timeunixseconds =  [System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds().ToString()

$uriSting = [String]::Format($uriTemplate, # Template with placeholders {0}, {1}, {2}...
    $id, # first argument goes {0}
    $link, # second goes {1}
    $timeunixseconds ) # third goes {2}, etc etc

$isUriOk = [System.Uri]::IsWellFormedUriString($uriSting, [System.UriKind]::Absolute)

DateTimeOffset class starting with some .net version (4.5th .net, 5th powershell, AFAIR) has To(From)UnixTimeSeconds and To(From)UnixTimeMilliseconds methods.
DateTime (and Get-Date, which returns DateTime) does not have such methods! Use DateTimeOffset.

And for your original case:
Inside double-quoted strings, variables (even simple, in my opinion) should be added in $() brackets:
"Hello, $($env:USERNAME), it's $(Get-Date -Format 'D') today!"
# Hello, User1, it's Aug 22 2020 today!

Single variables can be added without $() syntax, but I'd recommed add $() always.
Inside single-quoted strings, $() or $var does not work:
'Hello, $($env:USERNAME), it is $(Get-Date -Format "D") today!'
# Hello, $($env:USERNAME), it is $(Get-Date -Format "D") today!


text:
Q: How to handle errors while using Glib.Settings in Vala? I am using Glib.Settings in my Vala application. And I want to make sure that my program will work okay even when the schema or key is not available. So I've added a try/catch block, but if I'm using the key that doesn't exist, the program segfaults. As I understood, it doesn't even reach the catch statement.
Here is the function that uses settings:
GLib.Settings settings;
string token = "";
try
{
    settings = new GLib.Settings (my_scheme);
    token = settings.get_string("token1");
}
catch (Error e)
{
    print("error");
    token = "";
}
return token;

And the program output is:
(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)

(of course I'm using my real scheme string instead of my_scheme)
So can you suggest me where I'm wrong?

A: I know this is super late, but I was looking for the same solution so I thought I'd share one. As @apmasell said, the GLib.Settings methods don't throw exceptions—they just abort instead.
However, you can do a SettingsSchemaSource.lookup to make sure the key exists first. You can then also use has_key for specific keys. For example,
var settings_schema = SettingsSchemaSource.get_default ().lookup ("my_scheme", false);
if (settings_schema != null) {
    if (settings_schema.has_key ("token1")) {
        var settings = new GLib.Settings ("my_scheme");
        token = settings.get_string("token1");
    } else {
        critical ("Key does not exist");
    }
} else {
    critical ("Schema does not exist");
}

A: The methods in GLib.Settings, including get_string do not throw exceptions, they call abort inside the library. This is not an ideal design, but there isn't anything you can do about it.
In this case, the correct thing to do is fix your schema, install into /usr/share/glib-2.0/schemas and run glib-compile-schemas on that directory (as root).
Vala only has checked exceptions, so, unlike C#, a method must declare that it will throw, or it is not possible to do so. You can always double check the Valadoc or the VAPI to see.


text:
Q: Is there a way to switch boost::json::serializer to beautified output? Using boost::json::serializer as shown in the example in docs - quick look saves the json-tree in compact format.
Is there a way to instruct the serializer to output a human readable file (i.e. with newlines and whitespaces)? I searched around, but didn't find any hints.
NB: Even better would be writing the higher levels of the tree readably, and some objects, or arrays (maybe marked ones) in compact format.
The shortened example code could look like this:
#include <iostream>
#include <boost/json.hpp>
#include <boost/json/src.hpp> // use header-only
using namespace boost;

int main(int /*argc*/, char */*argv*/[]) {
    json::value jv = {
        { "pi", 3.141 },
        {"list", {1, 0, 2}},
        };

    json::serializer sr;
    sr.reset( &jv );
    do {
        char buf[ 16 ];
        std::cout << sr.read( buf );
    } while( ! sr.done() );
}

This (correctly) outputs {"pi":3.141E0,"list":[1,0,2]}, but I'd rather have:
{
  "pi":3.141E0,
  "list":
  [
    1,
    0,
    2
  ]
}

or (the "NB"-version):
{
  "pi":3.141E0,
  "list":[1,0,2]
}

Is this possible with boost::json without writing it myself?

A: This is not a feature of the library. The library has goals stated in the intro. It doesn't include user-friendly presentation formatting. In fact, even their number formatting can be said to be down-right user hostile.
The promise of the library centers at data interchange between computer systems:

This library focuses on a common and popular use-case: parsing and serializing to and from a container called value which holds JSON types. Any value which you build can be serialized and then deserialized, guaranteeing that the result will be equal to the original value. Whatever JSON output you produce with this library will be readable by most common JSON implementations in any language.

There's an example that shows how to do simple pretty printing if you want to avoid a large part of the work/have a reasonable starting point to not forget too many things: https://www.boost.org/doc/libs/1_76_0/libs/json/doc/html/json/examples.html
Alternatively, you can use any of the existing JSON libraries with a richer feature set. Keep in mind they will make difference trade offs, so you may run into other limitations.


text:
Q: VGA Splitter issues I have 3 monitors set up at the moment, 2 that I use as and extended desktop and the 3rd is in the other room, I bought a VGA splitter to split my main monitor between the 2 rooms and it works but only if I plug in the second monitor after the PC is logged in. If I leave it plugged in and restart no monitors start up.
Is there any way to make it work on start up or am I stuck unplugging and re-plugging monitors.
System info
Graphics card: NVidia GeForce 9800 GT (2 DVI output adapted to VGA)
Monitors that I'm trying to split are both the same resolutions.
OS: Windows 7 Ultimate

A: you could always create a script that switches to extended desktop mode then run that script on login through task scheduler.
You could use powershell ...something like this..
$screen = @'
    cmd.exe /c displayswitch.exe /extend
    '@
    invoke-expression -command:$screen
    exit
save it in a directory e.g. c:\temp\screen.ps1
make sure your execution policy is set to remotesigned
- open powershell.exe as admin and type set-executionpolicy remotesigned -force
create a scheduled task to run powershell.exe and pipe -file "C:\temp\screen.ps1" you can set it to run at logon.
Joe


text:
Q: Tomcat trial Thawte certificate I purchased a trial Thawte certificate. They gave me 3 certs:

*

*root certificate

*intemediate certificate

*trial certificate

I did the follows:

*

*Created keystore and local key pair (keytool -genkey -alias vskladchinu -keyalg RSA -keystore /usr/keystore)

*Created csr (keytool -certreq -keyalg RSA -alias vskladchinu -file certreq.csr -keystore /usr/keystore)

*I got 3 certificates from thawte (based on generated csr)

*I installed root and intermediate certs (keytool -import -alias root -keystore /usr/keystore -trustcacerts -file root.crt; keytool -import -alias intermediate -keystore /usr/keystore -trustcacerts -file intermediate.crt)

*I installed my trial thawte cert (keytool -import -alias vskladchinu -keystore /usr/keystore -file cert.crt)

i setup web.xml of tomcatr 7 server. And run the application. But browser said - there are only 2 certs in the certificate chain root and trial, but root can not be trusted (i guess without intermediate).
How do i make intermediate sertificate work?

A: For the most part you will always get an error associated with trust with a Thawte Trail certificate. This is because that trail root certificate is not by default installed on the browser. It how Thawte controls free certificates.
The actual certificates SSL123, WebServer, etc… are actual production certificates where the root is installed on the browser and you shouldn't get an error pertaining to not trusting the certificate with those ones.
The fact that you can connect and see the certificate that was issued to you means that SSL is working. But that error about trust will always happen with the trail certs.


text:
Q: images do not appear on my java applet Hey I'm trying to create a video game and I'm testing to see if I can make a sprite or image appear on the applet I've asked for help before from my peers and professor, but they don't seem to help. I don't know if I have the image in the wrong location or if my code is bugged, but I would appreciate if someone took a look at it Thanks! Oh! by the way I'm programming in Java and I'm using Eclipse JUNO.
enter code here

package meh;
import java.awt.*;
import javax.swing.JApplet;
import javax.swing.ImageIcon;

public class Draw  extends JApplet{
    public static void main(String[] args)
    {
        Draw test = new Draw();

    }
    private Image exImage;
    private boolean imagesLoaded;

    public void run()
    {

        imagesLoaded = false;

        try
        {
            loadImages();
            try
            {
                Thread.sleep(10000);

            }
            catch(InterruptedException ex){}
        }
        finally{}

    }
    public void loadImages()
    {
        exImage = loadImage("C:/Users/Temp/workspace/From Scratch/bin/Ma_rn_0");
        imagesLoaded = true;
        repaint();
    }
    private Image loadImage(String fileName)
    {
        return new ImageIcon(fileName).getImage();
    }
    public void paint(Graphics g)
    {
        if(g instanceof Graphics2D)
        {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        }
        if(imagesLoaded)
        {
            drawImage(g, exImage,0,0, null);
        }
        else
        {
            g.drawString("Loading...", 5, 12);
        }
    }

    public void drawImage(Graphics g, Image image, int x, int y, String caption)
    {
        g.drawImage(image, x, y, null);
        g.drawString(caption, x+5, y + 12 +image.getHeight(null));
    }

}

A: Unless they are signed, applets can only load images from the same location from where they originated. Here you are attempting to load an image from the local disk. All initialisation for applet resources should be done from the init method. Images can be loaded as resources from the same JAR file from which they are deployed. You could do
Image exImage = ImageIO.read(getClass().getResourceAsStream("images/MyImage.jpg"))

A: 1 public static void main(String[] args)
Applets are not supposed to have main(), it uses init, start, stop and destroy.
http://docs.oracle.com/javase/tutorial/deployment/applet/getStarted.html
2 Try to learn about EDT concept
3 Don't override paint method
4 Use ImageIO to load images


text:
Q: How can I stop using the radio in my app? How can I stop my app from using the mobile radio or WiFi while the phone is locked or the app is in the background?

A: You can use Meteor.disconnect().
See the docs here: http://docs.meteor.com/#/full/meteor_disconnect
You'd want to call this after a certain amount of time of inactivity, or on a window changed event.
Make sure to call Meteor.reconnect() once the user comes back to using the app.


text:
Q: Why am I getting a parse error on the closing bracket in Haskell? printExclamation :: Int -> IO()
pintExclamation n = do {
                        n <- getInt;
                        if n == n;
                        then return !
                      }

When compiling this, I get " parse error on input `}' " . I have no idea why.

A: The parser expects an else block. In Haskell it makes no sense to write if … then … without an else … block. An if … then … else … clause is not a statement, it is an expression. An expression that will use the value in the then … block in case the condition is True, and the part from the else … block otherwise.
You thus can write this as:
printExclamation :: Int -> IO()
printExclamation m = do
    n <- readLn
    if m == n
      then return ()
      else return ()
Beware that return :: Monad m => a -> m a injects a value in a monadic type. It is thus not equivalent to the return statement in (most) imperative languages that will "stop flow through the function".
You can for example print an exclamation mark in case the obtained number n is the same as m by using putStrLn :: String -> IO ():
printExclamation :: Int -> IO()
printExclamation m = do
    n <- readLn
    if m == n
      then putStrLn "!"
      else return ()
We then can test the function with:
Prelude> printExclamation 4
4
!
Prelude> printExclamation 3
4
Prelude>


text:
Q: nvd3 Bubble chart with log scale I am using NVD3 scatter/ Bubble chart. This is a continuation from the question here. I am plotting the log base 2 values for the y axis. But I want the y axis to have the original values as labels corresponding to the log base 2 scale. I am unable to understand how to do so.
Edit
This is what I have for plotting
data[i].values.push({
    x: random()
  , y: log2(yValue)
  , size: Math.random()
  });

function log2(val) {
console.log("val = " + val + " : " + Math.log(val) / Math.LN2)
    return Math.log(val) / Math.LN2;
}

Now, the y axis ticks have the log2 values. I want to change the y axis ticks to have the original values displayed and not the log2 values.
Thanks,

A: Instead of directly calculating the log when you create your data array, leave it as is and then use a log scale for your axis.
To use a custom scale in NVD3, you pass it as a parameter to the chart.yScale(scale) or chart.xScale(scale) methods.
var chart = nv.models.lineChart()
      .yScale( d3.scale.log() );

Just don't try to use a log scale for y values in a bar or area chart, since those automatically include 0 in the domain (and you'll get errors if you try to plot anything at log(0)!)
A couple warnings:

*

*Tick formating functions work different on log scales than for other scales; you'll probably want to just leave it as the default.  See the docs (link above) for more info.

*The .nice() method doesn't seem to work very effectively on log scales; when I was playing around on the NVD3 live code site, a domain of [1,99] was resulting in a final tick value of 98.999999999 on the axis.  You may want to explicitly check that the domain starts and ends at round numbers.
Also note that since you're never actually dealing with the calculated values for the logs (just with the relative positions on the scale) you don't need to specify a base to the logarithm.  The docs mention a logScale.base(number) method but that seems to be obsolete...


text:
Q: Creating versioned libraries in python We're setting up new branches at work which all will share the same libraries.
The problem with this is if we update one library you might break all apps that aren't updated.
Therefore we would like to version our libraries.
The way I was planning on doing this is either like this
loader.load(name='mylib', version='1.0')

or maybe like this:
import mylib
mylib.load(version='1.0')

The question is how this loader would work.
The naive approach is to have each version in their own folder, the problem with this however is that if there is a common bug in all versions every version needs to be fixed separately.
A slightly better approach (for maintainability) is to have all versions of a library in the same file and call some load function which creates links to functions.
I don't know how pretty this will be (we might end up with monster file of several thousand lines, we could of course remove old, unused versions).
To help with keeping the number of versions down I'm planning on only incrementing the version number when I break compatibility, not when bug fixing or adding new stuff.
Is there anything like this built into python or any other approach that would work?
Does anyone have experience of this sort of stuff?

I can add that things that are using the libs are test cases, we just want the tester to cd into the branch and run ./testit.py, nothing else.

Solution
The solution is based on Gringo Suave's suggestion.
class MyClass_1_0:
    def func1(self):
        return 'Baz'

    def func2(self):
        return 'Bar'

class MyClass_1_1(MyClass_1_0):
    # Overwriting a function:
    def func1(self):
        return 'Foo'

    # Definining a new function which uses a function
    # from a previous version:
    def func3(self):
        print("{} {}".format(self.func1(), self.func2()))

# Change this to the latest version for stuff that always wants the latest
class MyClass(MyClass_1_1): pass

Example usage:
>>> from my.module import MyClass_1_1 as MyClass
>>> m = MyClass()
>>> m.func3()
Foo Bar

A: Typically the way this is done is by incrementing the module name.  You could design a more robust method, but this is the easiest to understand/implement.
import package.modv2
import package.modv3

Create a new module version each time the API has changed.
It could also be done at the function level to minimize the number of files:
from package.module import functionv2
from package.module import functionv3

A: I believe this is what virtualenv was designed to do.  From the virtualenv website:

virtualenv is a tool to create isolated Python environments.
The basic problem being addressed is one of dependencies and versions,
  and indirectly permissions. Imagine you have an application that needs
  version 1 of LibFoo, but another application requires version 2. How
  can you use both these applications?
In [this case], virtualenv can help you. It creates an environment
  that has its own installation directories, that doesn't share
  libraries with other virtualenv environments (and optionally doesn't
  access the globally installed libraries either).

A: I know setuptools used to have something like this.  I can't find it right now but that doesn't mean it's gone.  You might want to look into it.


text:
Q: Ember Guide replacing LocalDSAdapter with REST Adapter I completed the ember getting started todo guide.
i then built a JSON Webapi using the correct naming conventions.
ember successfully calls the api and retrives the information i then get the following error messages, and i am unsure on how i am going to debug this
Assertion failed: No model was found for '0' ember.js:394
(anonymous function) ember.js:394
Ember.assert ember.js:53
DS.Store.Ember.Object.extend.modelFor ember-data-latest.js:2177
DS.RESTSerializer.DS.JSONSerializer.extend.extractArray ember-data-latest.js:6403
superWrapper ember.js:1218
(anonymous function) ember-data-latest.js:89
DS.JSONSerializer.Ember.Object.extend.extract ember-data-latest.js:196
(anonymous function) ember-data-latest.js:2649
invokeCallback ember.js:8055
(anonymous function) ember.js:8105
EventTarget.trigger ember.js:7878
(anonymous function) ember.js:8172
DeferredActionQueues.flush ember.js:5459
Backburner.end ember.js:5545
Backburner.run ember.js:5584
Ember.run ember.js:5915
hash.success ember-data-latest.js:7115
l jquery.js:9597
c.fireWith jquery.js:9597
k jquery.js:9597
(anonymous function) jquery.js:9597

Error while loading route: TypeError {} ember.js:394
(anonymous function) ember.js:394
Ember.Router.reopenClass._defaultErrorHandler ember.js:30563
triggerEvent ember.js:30520
trigger ember.js:29641
handleError ember.js:29903
invokeCallback ember.js:8055
(anonymous function) ember.js:8109
EventTarget.trigger ember.js:7878
(anonymous function) ember.js:8180
DeferredActionQueues.flush ember.js:5459
Backburner.end ember.js:5545
Backburner.run ember.js:5584
Ember.run ember.js:5915
hash.success ember-data-latest.js:7115
l jquery.js:9597
c.fireWith jquery.js:9597
k jquery.js:9597
(anonymous function) jquery.js:9597

Uncaught TypeError: Cannot set property 'store' of undefined ember-data-latest.js:2179
DS.Store.Ember.Object.extend.modelFor ember-data-latest.js:2179
DS.RESTSerializer.DS.JSONSerializer.extend.extractArray ember-data-latest.js:6403
superWrapper ember.js:1218
(anonymous function) ember-data-latest.js:89
DS.JSONSerializer.Ember.Object.extend.extract ember-data-latest.js:196
(anonymous function) ember-data-latest.js:2649
invokeCallback ember.js:8055
(anonymous function) ember.js:8105
EventTarget.trigger ember.js:7878
(anonymous function) ember.js:8172
DeferredActionQueues.flush ember.js:5459
Backburner.end ember.js:5545
Backburner.run ember.js:5584
Ember.run ember.js:5915
hash.success ember-data-latest.js:7115
l jquery.js:9597
c.fireWith jquery.js:9597
k jquery.js:9597
(anonymous function)

A: I think that the payload returned from the server, is missing the root key of the json array, for example:
this.store.find('user')

The expected response from server is:
{
  users: [ ... ]
}

Probally you are using:
[...]

If you see this fiddle the same error is throwed, because the missing people http://jsfiddle.net/marciojunior/8GfG4/


text:
Q: MYSQL Find entries that contain more than 7 numbers I need to find entries that contain more than 7 numbers in one of my mysql tables BUT the numbers are separated by letters or anything else.
What I have is this little piece of code I use to find entries like dsc123456789:
select * from crawl where title  regexp '[0-9]{7}'

How can I find entries like dsc-123-456_78B9? I tried different things but without success so far.
Thanks

A: You can use the following solution:
SELECT *
FROM crawl
WHERE title REGEXP '(([^[:digit:]])?[[:digit:]]){8,}';

Why the original query of the answer doesn't work?
-- this query doesn't work!
SELECT *
FROM crawl
WHERE title REGEXP '\d([^\d]?\d){7,}'

MySQL can't use character groups like \d (digits). So the query fails every time. On PHP and other languages the regular expression would look like this:
\d([^\d]?\d){7,}

but on MySQL this isn't valid. So you have to use the character classes of MySQL to solve this:
(([^[:digit:]])?[[:digit:]]){8,}

Hint: Make sure you use {8} or {8,} instead of {7} since you want to find all entries with more than 7 numbers / digits.


text:
Q: Intense hard drive access activity immediately after log in I upgraded my ubuntu karmic to lucid a few months ago. I don't know when it all started but the thing is that when I log in, I see a very intense disk access activity for a while that prevents any application from starting in a reasonable time (it takes from 10 to 20 seconds).
That's why I cannot launch a terminal window and top or iostat just in time to see what happens. When it prompts it's too late.
I tried to delimit the problem uninstalling zeitgeist, docky or whatever program I thought was behind that behaviour. I even deleted my Private encrypted folder to avoid decryption issues. Nothing changed.
Any idea about how to proceed? Thanks in advance.

A: I'd switch to a virtual terminal at the GDM login screen (Ctrl+Alt+F1), log in and start iotop (you maybe need to install it first). Then switch back to GDM (Ctrl+Alt+F7), log in, and immediately switch back to iotop using Ctrl+Alt+F1. You should now see, which process is responsible for the heavy IO.

Forgot to mention an alternative: you could try using bootchart to generate a chart that visualizes the boot process + desktop start. You maybe need to edit its configuration, so it shows more than just the first seconds of desktop loading:
Open the file '/etc/init/bootchart.conf' and remove the line:--crop-after=compiz,metacity,mutter,kwin,xfwm4 \
Two things:

*

*You maybe need to reboot twice after the first installation to get a useful result (it's possible that an index file needs to be rebuilt, I don't know for sure).

*Once installed, bootchart will run on every boot, unless you add bootchart=disable to the 'GRUB_CMDLINE_LINUX_DEFAULT' parameter in '/etc/default/grub' (followed by a sudo update-grub).


text:
Q: Virtual Lab on a server. What hypervisor? Proxmox, OpenStack, ESXi? I would like to run a virtual lab to show a piece of software - imagine 10 students, each using 3 VMs (somehow students shouldn't be able to touch each other's machines).
It's going to be a small factor server that has fake raid. I'm going to need mdadm - Intel says use mdadm for Intel RSTe fake raids.
I am in the process of choosing what hypervisor (if that's correctly termed) to install. I'd like a decent UI, preferable web-based, I won't shy away from ssh. mdadm support too.
My options so far:
I have some experience with ProxMox. I like it, the stuff missing from the UI i can do myself - create fake adapters to simulate NAT and to segregate machines with multiple network adapters. mdadm might be difficult to install - there are tutorials, but it's not officially supported.
I have tried ESXi, but I don't find it easy to use. It's not a normal linux. The UI is pretty, but I couldn't manage to import a Windows machine - neither from OVA/OVF, nor even a .vmware image - it needs to convert them, which makes no sense. It also cannot use mdadm, or if it can it will be very, very difficult.
XEN i've heard doesn't have a control panel, instead I have to install its windows client on one of the machines.
OpenStack is another software I'm considering. I'm trying to run DevStack to evaluate, but it's not going well. I've heard good things about it, and from what I've heard it's like AWS and suits my requirements fine. But I've been told it's quite complex and better suits a company with multiple servers, not a single machine. It contains multiple pieces (nova, keystone, glance, neutron ...) and it might not be easy to handle. I don't know about mdadm, but since it runs on multiple distributions, it might be doable.
I don't know about other options.
Any comments?


text:
Q: SigningConfig "release" is missing required property "storePassword" So recently I'm experiencing the following error when running gradlew assembleRelease on my RN App:

SigningConfig "release" is missing required property "storePassword".

To this date, I've already released a lot of versions of my app, but this started to happen recently in both my CI (Github) and locally.
My file keystore.properties is at the android root folder and configured with the proper values.
Besides that, my  app/build.gradle also seems to be correct:
    signingConfigs {
        releaseStaging {
            storeFile file('../keystores/liber-student-app.jks')
            storePassword keystoreProperties['SIGNING_KEYSTORE_PASSWORD']
            keyAlias keystoreProperties['SIGNING_KEY_ALIAS']
            keyPassword keystoreProperties['SIGNING_KEY_PASSWORD']
        }
        release {
            storeFile file('../keystores/liber-student-app.jks')
            storePassword keystoreProperties['SIGNING_KEYSTORE_PASSWORD']
            keyAlias keystoreProperties['SIGNING_KEY_ALIAS']
            keyPassword keystoreProperties['SIGNING_KEY_PASSWORD']
        }
    }

I also tried hardcoding the storePassword values (as suggested in this other stackoverflow question), but that didn't work (exact same error)
I've stuck on this for the past 2 days, so please, help, thanks.


text:
Q: Create Rotation Interactive Control in Visual Studio How can we Create interact Rotation Control in Visual Studio?
I see one control which Visual Studio used "Render Transform" Property , marked in attached screen shot.

May be we'll create through UserControl, but i'm not sure how to create. So please guide me

A: You can rotate any control you like.
How do I create a rotate animation on an image object using c# code only (inside a WPF window)
This link gives you an example with an Image and a Button.
The button is using a Storyboard that animated the rotation of the image.


text:
Q: How can I get a value from a specified position in an array list (processing)? I need to get a value from an array list. The objects in the list stores some values in variables (x- and y-coordinates).
I tried to use the get()-function but it only returns a string like this: linkTrackerTest$Object@20e76e47.
In addition I tried thinks like objects.get(0(x)) but nothing worked yet.
Could anybody help me with this?
Thank in advance :-)

A: The behaviour you get it's totally normal.
Since I guess you are trying to print the Object returned by get, and since you have not provided an Override for the Object's toString() method, the best Java can do is to print the so called identity hashcode - "kinda of the memory address" of it.
Try adding the following as a member of your class:
         @Override
        public String toString() {
            return x+" "+y;
        }

This way then you try to print your class, Java will automatically call the provided toString()

*

*The problem here is not in the way you access an element of an ArrayList, the get method all you need to do it.

A: You're getting that odd string because its returning the memory address of the data instead of the data itself because java is implicitly calling a toString().
Try:
yourObject x = list.get(i);
or
int x = list.get(i).xValue; / int y = list.get(i).yValue;
or just override the toString() completely by writing your own

A: Not sure if this is what you're asking, but if you have a list of Objects
you can get values you are looking for with a getter method in your Object class
public class Obj {

     private int x;
     private int y;

     // constructor in which x, y values are given
     public Obj(int x_val, int y_val) {
          this.x = x_val;
          this.y = y_val;
     }

     // getter
     public int get_x() {
          return this.x;
     }

     public int get_y() {
          return this.y;
     }

 public static void main(String[] args) {

      List<Obj> Obj_Lst = new ArrayList<Obj>();

      // adding objects to list
      Obj_Lst.add(new Obj(1,6));
      Obj_Lst.add(new Obj(2,5));
      Obj_Lst.add(new Obj(3,4));

      // getting values from object
      System.out.println(Obj_Lst.get(0).get_x());

 }

}

Output
1


text:
Q: ERESOLVE overriding peer dependency hello I found a warning like this when installing the npm package
what is the problem and how to solve it?
PS D:\Gogomall\GogoMobile\Project\Mobile\GoMobileApp> npm install @react-navigation/native
npm WARN ERESOLVE overriding peer dependency
npm WARN Could not resolve dependency:
npm WARN peer react@"^16.0.0 || ^17.0.0" from react-shallow-renderer@16.14.1
npm WARN node_modules/react-shallow-renderer
npm WARN   react-shallow-renderer@"16.14.1" from react-native@0.69.0
npm WARN   node_modules/react-native
npm WARN
npm WARN Conflicting peer dependency: react@17.0.2
npm WARN node_modules/react
npm WARN   peer react@"^16.0.0 || ^17.0.0" from react-shallow-renderer@16.14.1
npm WARN   node_modules/react-shallow-renderer
npm WARN     react-shallow-renderer@"16.14.1" from react-native@0.69.0
npm WARN     node_modules/react-native


text:
Q: After I split a string how can I use the list that is created to then create a dictionary? I have a file that has names put together that are related to each other, and I need the first set to a key, the second to a value, but when I run the program, I get the error
ValueError: too many values to unpack

I have researched this, but, I haven't found a way to fix it. Below is the code, and a link to some of the material I found in trying to fix this issue.
http://www.youtube.com/watch?v=p2BwrdjlsW4
dataFile = open("names.dat", 'r')
myDict = {}
for line in dataFile:
    k,v = line.strip( ). split(",")
    myDict[k.strip (":")] = v.strip ( )
    print(k, v)
dataFile.close()
def findFather(myDict, lookUp):
    for key, value in myDict.items ( ):
        for v in value:
            if lookUp in value:
                return key
lookUp = raw_input ("Enter a son's name: ")
print "The father you are looking for is ",findFather(myDict, lookUp)

the file is saved as "names.dat" and is listed all on one line with the values:
john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos

A: The code
line.strip( ). split(",")

returns a list like:
["jhon:fred", "fred:bill", "sam:tony", ...]

so, when you do
 k,v = line.strip( ). split(",")

you're trying to put all values of that list into k and v that are only two.
Try this code:
for line in dataFile:
    for pair in line.strip(). split(","):
        k,v = pair. split(":")
    myDict[k.strip (":")] = v.strip()
    print(k, v)

NOTE: The code above is just for remove the error you're getting. I do not guarantee that this code is going to do what you want to do. Also I've not idea about what are you trygin to du with the code:
myDict[k.strip (":")] = v.strip()


text:
Q: PHP - Find string in an Object Want to find a string in an object, found this code online, but doesn't seem to work off-the-shelf, so to speak:
private static function in_object($val, $obj) {
    if($val == ""){
        trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
        return false;
    }
    if(!is_object($obj)){
        $obj = (object)$obj;
    }

    foreach($obj as $key => $value){
        if(!is_object($value) && !is_array($value)){
            if(strpos($value,$val)!==FALSE){
                return true;
            }
        }elseif(is_array($value)) {
           if(in_array($val, $value)!==FALSE){
                return true;
            }
        }else{
            return self::in_object($val, $value);
        }
    }
    return false;
}

It does not return an error message, the screen simply stays blank. The object I am searching will include arrays, and it is one of the arrays that I want test for certain text strings.
Was hoping this had a minor error and could be easily fixed.  Or perhaps some other solution?

A: You could always do this, as a kind of work around.
$string_to_find = 'find_me';

foreach ($obj as $property => $value) {
    if ($property == $string_to_find) {
        // You found the string
        $found_string = $property;
    }
    if ($value == $string_to_find) {
        // You found the string
        $found_string = $value;
    }
}

This will find it either on the property or value. You should add in some error handling to prevent issues if you aren't 100% sure that you will always be using this on a valid object.


text:
Q: How to use `Linked Model` feature of Core ML 3? As WWDC suggested, a linked model feature is supported in Core ML 3., which allows developers re-use the same mlmodelc to save space.
There are also two parameters named linkedModelFileName and linkedModelSearchPath in the documentation.
But I didn't see any tutorials or examples about how to use it, except the proto of Linked Model is defined in the documentation of coremltools.
So I'm just wondering if there is anybody knowing the exact way to use it?

A: This example shows how to use a linked model and make it updatable (just ignore the updatable bit for your use case):
https://github.com/apple/coremltools/blob/master/examples/updatable_models/updatable_linked_model.ipynb


text:
Q: how to close colorbox? hi i have a link when clicked opens a colorbox with a form in it what i want that when i click on the submit button the form will be submitted via ajax and based on the returned data
 if(error on the server side){
   the error will be displayed at the top of the form;
   // colorbox still open
 }else{
   the returned data will be displayed on the original page;
   close the colorbox;
 }

so i did all that except the close colorbox part i used this code:
$.colorbox.close();

and this didn't work too:
parent.jQuery.colorbox.close();

any help, thanx in advance.

A: Had this a while back, cant remember which it is...
Try this...
$(window).colorbox.close();

or this...
jQuery(window).colorbox.close();

or this...
jQuery('#cboxClose').click();


text:
Q: Convert UIImage to UInt8 Array in Swift all!
I've been doing a lot of research into this and I've integrated several different solutions into my project, but none of them seem to work. My current solution has been borrowed from this thread.
When I run my code, however, two things happen:

*

*The pixel array remains initialized but unpopulated (Full of 0s)

*I get two errors:
CGBitmapContextCreate: unsupported parameter combination: set CGBITMAP_CONTEXT_LOG_ERRORS environmental variable to see the details
and
CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set

Any ideas? Here is my current built function that I'm calling for my Image class:
init?(fromImage image: UIImage!) {
    let imageRef = image!.CGImage
    self.width = CGImageGetWidth(imageRef)
    self.height = CGImageGetHeight(imageRef)
    let colorspace = CGColorSpaceCreateDeviceRGB()
    let bytesPerRow = (4 * width);
    let bitsPerComponent :UInt = 8
    let pixels = UnsafeMutablePointer<UInt8>(malloc(width*height*4))

    var context = CGBitmapContextCreate(pixels, width, height, Int(bitsPerComponent), bytesPerRow, colorspace, 0);

    CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)

Any pointers would help a lot, as I'm new to understanding how all of this CGBitmap stuff works.
Thanks a ton!

A: You should not pass an 0 as the bitmapInfo param for CGBitmapContextCreate. For RGBA you shall pass CGImageAlphaInfo.PremultipliedLast.rawValue.

Supported combinations of bitsPerComponent, bytesPerRow, colorspace and bitmapInfo can be found here:
 https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB
Note that 32 bits per pixel (bpp) is 4 bytes per pixel and you use it to calculate bytesPerRow

A: You need to convert the image to NSData and then convert NSData
to UInt8 array.
let data: NSData = UIImagePNGRepresentation(image)

// or let data: NSData = UIImageJPGRepresentation(image)

let count = data.length / sizeof(UInt8)

// create an array of Uint8
var array = [UInt8](count: count, repeatedValue: 0)

// copy bytes into array
data.getBytes(&array, length:count * sizeof(UInt8))


text:
Q: Connect a C++ function to Javascript event listener with Webkit/JavascriptCore I'm using the Webkit plugin facility to implement the <video> tag in an embedded environment. (for those interested, I was inspired by this)
I successfully connected my plugin's methods and properties to map the ones that the HTML5 tag should expose in the MediaPlayerPrivate class of Webkit (I know how to query properties and to invoke simple methods), but I'm now wondering how my plugin can pass back data to the MediaPlayer interface.
My plugin implements the addEventListener() interface in JavaScript, so I figured I could use it to register the MediaPlayer client as an EventListener, but I can't figure how.
What I would like to do is like this:
  Plugin                    WebKit
+--------------+         +-----------------------------+
|              |         |                             |
|          <-------------|-+addEventListener(callback) |
|              |         |                             |
|+----------+  |         |                             |
||          |  |         |                             |
|| onEvent  |  |         |                             |
|+----------+--------------> callback( EventData )     |
|              |         |                             |
+--------------+         +-----------------------------+

What I don't know, is how I can call the method addEventListener of my plugin and pass it a JSObject that refers to a static callback in my C++.
Do you have any idea on how to do that?
(ASCII drawings thanks to Asciiflow)

A: For those interested, the solution is as such:
// event name is the name of the event I want to subscribe to
// callback is a static function with the 'JSObjectCallAsFunctionCallback' prototype
JSObjectRef callbackObject = JSObjectMakeFunctionWithCallback(ctx, JSStringRef(), callback);
JSValue js_cb[3] = {
    toJS(state, (const JSValueRef)JSValueMakeString (ctx, JSStringCreateWithUTF8CString(eventName))),
    toJS(state, (const JSValueRef)callbackObject),
    toJS(state, (const JSValueRef)JSValueMakeBoolean(ctx, false))
};
ArgList args(js_cb, 3);

return invokeMethod("addEventListener", args);

With this code, whenever my plugin object broadcasts an event, I see the code landing in my callback static function.
Now I just have to find a way to pass the private data I need so that I can modify runtime values from this static function.


text:
Q: Will I lose my domain name on AWS if I delete the hosted zone associated with it? So I bought a domain name on AWS and it automatically created a Hosted Zone on Route 53 for my domain. I'm not using the domain anymore but I don't want to lose it. If I delete the auto-generated hosted zone, will it also delete my domain name? Or will I be able to create another hosted zone in the future?
Note that I want to delete the current hosted zone to save the monthly fee associated with it.....

A:
Will I lose my domain name on AWS if I delete the hosted zone associated with it?

No, you can delete the auto-generated one and configure your AWS registered domain to use other DNS providers, such as Cloudflare.


text:
Q: Grouping by rows in pandas? I would like a way to perform grouping and aggregate functions when my source data isn't already grouped nicely.  For example, given the following dataframe:
#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine',
            'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'],
'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1',
        'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'],

'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science',
           'Mathematics','Mathematics','Mathematics','Science','Science','Science'],
'Score':[62,47,55,74,31,77,85,63,42,67,89,81]}

I would like to be able to print a table that aggregates the results by score ranges - for example:
Score        Subject        Qty
60-70        Mathematics    2
             Science        1
70-80        Mathematics    1
             Science        2

So far I haven't been able to figure this out... Any brilliant ideas?

A: Try:
(df.groupby([pd.cut(df['Score'],bins=[60,70,80]),
             'Subject'])
   .size()
   .to_frame('Qty')
)

Output:
                      Qty
Score    Subject
(60, 70] Mathematics    2
         Science        1
(70, 80] Mathematics    0
         Science        2


text:
Q: update column of all rows of table I have 1 table with 500 rows, and another table with 750 rows or so. What I'm doing is, I'm getting a random 500 rows of a certain column from the second table, and I want to update a newly added column on the first table with those 500 values.
I know how to do updates that look like this:
UPDATE schema.table1
SET column = cl.column FROM schema.table1 cl
INNER JOIN table2 cf ON cf.column = cl.column

but I don't have any columns that are matching in both tables. Is there a way to do this without having to match the columns on the inner join?
so basically, I want to update 500 rows of 1 column in one table, with 500 values coming from another table

A: You can do it by using ROW_NUMBER to generate column to join two tables. take a look at the example and the output
DECLARE @T1 TABLE ( column1 INT ,column2 VARCHAR(2) )

DECLARE @T2 TABLE ( column1 VARCHAR(2) )

INSERT INTO @T1 ( column1, column2 )
        VALUES  ( 0, 'A' ), ( 1, 'B' ), ( 2, 'C' )

INSERT INTO @T2 ( column1 )
    VALUES ( 'D'),( 'F'),( 'G' )

SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2

;WITH CTE_1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1)
    ,cte_2 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2)
UPDATE t1
SET t1.column2 = t2.column1
FROM CTE_1 t1
JOIN cte_2 t2
ON t1.rn = t2.rn

SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2


text:
Q: React-admin: getting error with nested item When I create an Input like:

The rendering is ok, but when submiting I get the error:
index.js:1446 Warning: Missing translation for key: "Cannot read property 'name' of null"
export const PatientCreate = props => (
  <Create {...props}>
    <SimpleForm>
      <NumberInput source="bsn" />
      <TextInput source="patientname.firstname" />
      <BooleanInput source="active" />
    </SimpleForm>
  </Create>
);

When I remove the nested item patientname.firstname, everythings works correctlty..Anyone idea ?
Using Prisma server data, but the error is in Create, before a put is happening, so I think I has something to do with react-admin..
Model is (Prisma MongoDB):
type Patient {
  id: ID! @id
  bsn: Int @unique
  active: Boolean! @default(value: true)
  patientname: Patientname
  deceased: DateTime
}

type Patientname @embedded {
  firstname: String
}

In React-admin documentaion:
https://marmelab.com/admin-on-rest/Inputs.html#textinput
<TextInput source="author.firstName" />

Tnx I anyone can help me ...
Paul

A: In your i18n translation files need to respect the nested reference.
React admin tries to translate using property `resources.[resourcename].fields.[fieldname] (see docs) if none is present it uses the string on source prop. If you have nested resources and no translation file with nested reference that error will be presented because can't find nested source.
If you create a translation file like this:
const language = {
  resources: {
    patient: {
      patientname: {
        firstname: "firstname"
      }
    }
  }
};

Your problem is fixed. Take note that you need to add this translation resource to react-admin, more information can be found here.


text:
Q: How change inputs type in VUE? I have a input with type=radio

        <input type="radio" class="abc" disabled>

How can on click button i can change all inputs with class="abc" from radio to checkbox

is any simple way to do this in this changeInputType function ?

A: bind the input type to variable and change that variable
<template>

    <input :type="inputType" />
    <button @click="changeType />

</template>

A: Here is the solution of your answer, By clicking on button all input types will be changed from radio to checkbox.

            <input :type="input" class="abc" disabled>

Change Input Type

A: On butt click change the type variable to checkbox.


text:
Q: Infinite loop when printing an N x N table Consider the following Java program:
public class RelativelyPrime {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // Dimensions of grid
        int i, j;
        int r; // Remainder when i is divided by j

        for (i = 1; i <= N; i++) {
            for (j = 1; j <= N; j++) {
                do { // Using Euclidean algorithm
                   r = i % j;
                   i = j;
                   j = r;
                } while (r > 0);
                if (i == 1) System.out.print("*");
                else System.out.print(" ");
            }
            System.out.println();
        }
    }
}

This program prints an N x N table (or matrix, if you like) where N is a command-line argument.
The (i, j)-entry is a * if i and j are relatively prime, or a single whitespace if they are not relatively prime. When I run the program by entering, for instance, java RelativelyPrime 3 it endlessly prints *. Why is this happening?

A: You changed i and j in the while loop.
    for (i = 1; i <= N; i++) {
        for (j = 1; j <= N; j++) {
            int ii = i, jj = j;
            do { // Using Euclidean algorithm
               r = ii % jj;
               ii = jj;
               jj = r;
            } while (r > 0);
            if (ii == 1) System.out.print("*");
            else System.out.print(" ");
        }
        System.out.println();
    }

A: This is where using the debugger would have helped you solve the problem.
Inside your loops, you alter both i and j which means they never reach N and thus you have an infinite loop.
I suggest you not alter these variables but instead use two new variables, ideally with meaningful names.


text:
Q: Bitwise operations on enums based on attributes I have quite big enum with custom numbers like
 public enum DataSources
    {
        Undefined = 0,
        [Description(nameof(Resources.Web))]
        Web = 1,
        [Description(nameof(Resources.Mail))]
        Email = 2,
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.VoIP))]
        Voip = 5,
        [Parent(Value = (int)Other)]
        [Description(nameof(Resources.ProcessAndApplications))]
        Processes = 257,
        ...

And now I'm looking a way to store multiple DataSources (enum above) values  in another class let's call it Role (it's db entity represents row in database).
class Role : DbEntity
{
        [PrimaryKey, Identity]
        public override long Id { get; set; }
        [Column(Name = "name"), NotNull]
        public string Name { get; set; }
        public DataSources dataSources {get;set;}
}

Usually I could use [Flags] but I can't change already assigned values for DataSources enum.
Is there any solution in this case? May be I could use additional attributes for bit values?

A: You could store multiple values in a single column by using bitwise OR. But this requires that all enum values occupy unique bits. I can already see this is not going to be possible in your case because you have more than one odd number.
The next option is to extract the DataSources column into its own table and add a FK to it from Role. Your Role class changes as shown below.
class Role : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [Column(Name = "name"), NotNull]
    public string Name { get; set; }
    public IList<RoleDataSources> DataSources {get;set;}
}

class RoleDataSources : DbEntity
{
    [PrimaryKey, Identity]
    public override long Id { get; set; }
    [ForeignKey("Role"), Identity]
    public long RoleId { get; set; }
    public Role Role { get; set; }
    public DataSources Value { get; set; }
}


text:
Q: R Shiny --> FillOpacity Argument in AddCircles Function Ignored I am working on a R Shiny project to visualize all of the airports in the world.  The code included below is a sample of my project.  Functionally, the app works as expected - The data table and map update when you choose a different country.  However, I'm having a bit of an issue with the points on the maps.  Since I have the radius of the points dependent on the number of routes from an airport, in densely populated areas where there might be multiple large airports (eg: Chicago), some larger points overlap smaller ones.  I used the FillOpacity argument in the AddCircles function to be more transparent so you could see potentially masked points.  However, it seems that this argument is ignored when I use it in the code below:
#Dataset 1: Routes
routes=read.csv(url("https://raw.githubusercontent.com/jpatokal/openflights/master/data/routes.dat"))
dim(routes)
#67662  9
str(routes)

#Dataset #2: Airports
airports=read.csv(url("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports-extended.dat"))
dim(airports)
#12667 14

#Rename columns
colnames(routes)=c("Airline","AirlineID","IATA","SourceAP_ID","DestinationAirport","DestAP_ID","Codeshare","Stops","Equipment")
colnames(airports)=c("AirportID","Name","City","Country","IATA","ICAO","Latitude","Longitude","Altitude","Timezone","DST","TzDatabaseTz","Type","Source")

#Join datasets on Source Airport
#-------------------------------#
#IATA in airports
#SourceAirport in routes (IATA)

fullair=merge(x=routes,y=airports,by="IATA",all.x=TRUE)

fullair2=subset(fullair,fullair$Type=="airport")

library(dplyr)

#Make a new unique ID by combining IATA and Destination Airport
fullair2$UniqueID=paste0(fullair2$IATA,"_",fullair2$DestinationAirport)

#Create column that assigns number of unique routes to single airport
fullair3=fullair2 %>%
  group_by(IATA) %>%
  mutate(Count=n_distinct(UniqueID)) %>%
  ungroup()
fullair3=as.data.frame(fullair3)

#Get rid of duplicates
fullair3=fullair3[!duplicated(fullair3[c("UniqueID")]),]

library(rowr)
library(sqldf)
library(RSQLite)

#-----------Number of Routes from Destination------------#
SpitOutNum=sqldf("select IATA,count(*)
                 from fullair3
                 group by IATA")
SpitOutNum=as.data.frame(SpitOutNum)
colnames(SpitOutNum)=c("IATA","DestinationCount")
fullair3=merge(x=fullair3,y=SpitOutNum,by="IATA",all.x=TRUE)

#Create the full name
fullair3$NamePart1=paste("(",fullair3$IATA,")",sep ="")
fullair3$FullName=paste(fullair3$Name, fullair3$NamePart1)
fullair3$NamePart1=NULL

fullair3$Name2Part1=paste("(",fullair3$DestinationAirport,")",sep ="")
fullair3$DestFullName=paste(fullair3$DestAirportName, fullair3$Name2Part1)

fullair3$Name2Part1=paste("(",fullair3$DestinationAirport,")",sep ="")
fullair3$DestFullName=paste(fullair3$DestAirportName, fullair3$Name2Part1)

table2=sqldf("select Country, FullName as 'Airport Name', City, count(*) as 'Number of Routes'
             from fullair3
             group by Country, FullName, City
             order by count(*) desc")

#Sort by FullName
fullair3= fullair3[order(fullair3$FullName),]

#-----------------------------------------------------
library(shinydashboard)
library(shiny)
library(leaflet)
library(leaflet.extras)
library(rgdal)
library(sp)
library(raster)
library(DT)
library(markdown)
library(geosphere)
library(htmltools)

airportchoices=unique(fullair3$FullName)
countrychoices=unique(fullair3$Country)

countrychoices=as.character(countrychoices)
countrychoices=sort(countrychoices)

# Define UI for application
ui <- fluidPage(
  dashboardPage(
    dashboardHeader(title="Airport Analysis"),
    dashboardSidebar(
      sidebarMenu(
        menuItem("Country Maps",
                 tabName = "CountryMaps",
                 icon=icon("flag")
        ))
    ),
    dashboardBody(
      tabItems(
        tabItem(
          tabName = "CountryMaps",
          tags$style(type="text/css","#country_airports {height:calc(100vh - 80px) !important;}"),
          fluidRow(column(4),
                   column(8, selectInput(inputId = "countryselect",label="Select a country:",choices=countrychoices)
                   )),
          DTOutput("countrydata"),
          leafletOutput("country_airports")

        )
      )
    )
  )
)
# Define server logic
server <- function(input, output) {

  #----------COUNTRY FILTERING---------#

  CountryData=reactive({
    filteredData=subset(fullair3,Country == input$countryselect)
    return(filteredData)
  })

  CountryDataTable=reactive({
    filteredDataTable=subset(table2,Country==input$countryselect)
    filteredDataTable$Country=NULL
    return(filteredDataTable)
  })

  #-------------------COUNTRY PLOTS-------------------#
  output$countrydata=renderDT({

    data_table = CountryDataTable()

    datatable(data_table,options=list(pageLength=5,
                                      lengthMenu=c(5,10,15,20)
    ),rownames = FALSE)
  })

  output$country_airports=renderLeaflet({

    data=CountryData()

    pal=colorNumeric("Yellow",data$DestinationCount)

    leaflet(data=data) %>%
      addTiles(group="CartoDB.Positron")  %>%

      addProviderTiles(providers$CartoDB.Positron,
                       options = tileOptions(minZoom =0, maxZoom = 13),
                       group = "CartoDB.Positron") %>%

      addCircles(radius = ~data$DestinationCount*1000,
                 weight = 1,
                 color = "black",
                 fillColor = ~pal(data$DestinationCount),
                 fillOpacity = 0.4,
                 popup = paste0("Airport Name: ", data$Name, "
",
                                "City: ", data$City, "
",
                                "Destination Count: ",data$DestinationCount,"
"
                 ),
                 label = ~as.character(data$IATA),
                 group = "Points")

  })
}

# Run the application
shinyApp(ui = ui, server = server)

Does anyone have any suggestions for how to fix this issue?  Any help would be appreciated!  Thank you!

A: I think that fillOpacity = 0.4 is too high to get transparency for points near Chicago, for example. I got the transparency in the image below setting fillOpacity = 0.01. With a lower value of alpha it takes a higher number of points to make the point completely opaque. And I think that with 0.4 and more than 200 rows for airport ORD, for example, you reach this threshold.

You could try to solve this plotting only one point per airport (that is, only one row in your dataset).
For example with fillOpacity = 0.4 and adding this code before leaflet function
data <- data %>%
  dplyr::distinct(IATA, Latitude, Longitude, DestinationCount, Name, City)

I got the map in the image below

Answering your further question in the comment, it seemed that a possible way was playing with the z-index parameter, but I found that SVGs (like Circles) do not support z-index and the order is based on the order in which the elements were added to the map. So I tried to change the code above in the following way:
data <- data %>%
  dplyr::distinct(IATA, Latitude, Longitude, DestinationCount, Name, City) %>%
  dplyr::arrange(desc(DestinationCount))

And got this result

You can try also using addCircleMarkers instead of addCircles, changing only radius = ~data$DestinationCount*0.3. If you zoom in enough, you will see that ORD and MDW are not overlapping.


text:
Q: updating same value in angular directive i have been trying to update value of input in angular directive
issue: when i update value first time it works but when i update it with same value as the first one . it add values
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {

    element.datetimepicker({
        weekStart: 1,
        todayBtn: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        format: attrs.format ? attrs.format : "yyyy/MM/dd"
    }).on('changeDate', function(ev) {
        var dateUTC = new Date(ev.date.getTime() + (ev.date.getTimezoneOffset() * 60000));
        var masking = $filter('mapDateTimeFormat')(attrs.format ? attrs.format : "yyyy/MM/dd");
        var filterApply = $filter('date')(dateUTC, masking);
        $parse(attrs.ngModel).assign(scope, filterApply);
        scope.$apply();
    });
}

first time when i select value from calendar its like
23-10-15  but if i update same value again, it becomes something like
23-1010-2015 and if i select other date it gives me 23-10-16 value.
i cant figure out what m doing wrong as
$parse(attrs.ngModel).assign(scope, filterApply);

provide me 23-10-15, so dont know how wrong value gets update
Angular : angular 1.2.2
Calendar : Bootstrap calendar
any help will be appreciated

A: You need to reformat the date after selecting from UI. When you select date by using Bootstrap calendar, It's date format is different while normal Date() returns different date. You can just use $watch on date and change date format and again set to same variable.
check below link for some more ref.
https://github.com/angular/angular.js/issues/3615
//copied from some other place
You would not want to replace the scope.ngModel variable, but the value that's behind that variable. You did it already when you read the value in the first line of the link function:
 currValue = parseInt(scope.$eval(attrs.ngModel))

If it's a plain value, like myProperty, you could use that on the scope:
scope[attr.ngModel] = newValue

But this will not work, if you have an expression-value, like container.myProperty. In that case (and this is the more generic type, you should be aiming for) you'd have to eval the value being set to the scope, like this:
scope.$eval(attrs.ngModel + "=" + newValue)

I must admit, that the $eval part is a bit ugly, as it is in JavaScript with the eval pendant, but it does the trick. Just keep in mind that it might not work this way, when you want String values to be set. Then you'd have to escape those values.
Hope that helps ;)


text:
Q: Do I need to explicitly pass a combobox as a reference in a function, or will the compiler do this for me? In C#.NET (WinForms), I have a function that fills up an existing combobox on a form with the result of a query:
FillComboBox("SELECT Value FROM Table", comboBox1);

public void FillComboBox(string query, ComboBox combobox)
    {
        cmd = new MySqlCommand(query, connection);
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            combobox.Items.Add(reader[0]);
        }
        combobox.SelectedIndex = 0;
    }

The above appears to work fine, however I also have the option of using a reference, as shown below:
FillComboBox("SELECT Value FROM Table", ref comboBox1);

public void FillComboBox(string query, ref ComboBox combobox)
    {
        cmd = new MySqlCommand(query, connection);
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            combobox.Items.Add(reader[0]);
        }
        combobox.SelectedIndex = 0;
    }

Again, both functions work identically - however is it more efficient or safer in any way to use the latter one, passing the combobox as a reference? Or is the compiler doing this implicitly anyway in the first function?

A: Your second example, while working, is wrong and misleading of your intentions.
A reference variable (suppose we have declared it as ComboBox cbx = new ComboBox(); in the calling code of this method) holds a simple value that represents the memory address where the instance of a combobox is stored. The same variable (cbx) is allocated on the heap and has its own address where it stores the address of the combobox instance returned by the new ComboBox() call.
When, in the first example, you pass the cbx variable to the FillCombo method  a new variable local to the method is created on the stack and the value of cbx is stored there (the memory address of the combobox instance).
So now you are able to change the combobox properties freely and the caller see the changes made to the combobox data.
When you use the ref keyword things changes. The FillCombo method, in the second example, still creates a local variable named combobox but this local receives the address of cbx, not its value. The intent here is to create a new instance of a ComboBox calling something like combobox = new ComboBox(); (different address for a different instance) and use the address value of the passed variable to let the passed variable 'point' to the new instance.
From a point of view of performance I think that there is no measurable difference if any, but the presence of the ref keyword is just misleading.
Good reference articles are:
C#Concepts: Value Types vs Reference Types  from Joseph Albahari
Parameter Passing in C# from Jon Skeet

A: In the first code sample you pass a copy of combobox1 reference. So you can access properties of comboBox1, because combobox parameter refers to the same object as comboBox1. If you try to make new object: combobox = new ComboBox() - you will not change comboBox1, because combobox is a copy of it.
In the second code sample you pass comboBox1 reference (not a copy). You also can access comboBox1 properties like in the first code sample, but now you can change comboBox1, because you passed straight reference: combobox = new ComboBox() will be the same as comboBox1 = new ComboBox().


text:
Q: Global access to view properties A containerView1 with 3 buttons which will need their text changed and their visibility modified according to user interaction with views in  a different containerView2.
Each containerView has its viewController and there is the main viewController for the main storyBoard. The buttons will need to be Outlets as well as Actions.
Since the buttons are in a container whose controller is embedded segue, no prepareForSegue is allowed since there is no "segueing" here since the embed type is called during setup only.
What mechanise is best fit to be able to access the properties of the buttons from anywhere and how to implement it?
thanks


text:
Q: Run time issue in ballerina I have a run time issue in ballerina. I have saved all urls in a ballerina.conf file in the root directory.
so i call them like this in s service file which is at src/folder/service.bal file. for an example this is the code fragment i used
http:Client PeopleHrClient = new (config:getAsString("ROLE_SERVICE"));

In the config file the value for the NETSUITE_ROLE_SERVICE is like below
ROLE_SERVICE = "https://example/rest/roles"

after a successful build I ran the ballerina service at the target/bin directory.
ballerina run opdClaims.jar

but I met with the below error

but when I run the ballerina service from the root directory it works fine
ballerina run target/bin/opdClaims.jar

Can anyone help me to solve the issue.
Thanks!

A: I think I found two ways as answers to my question.

*

*If I can copy and paste the ballerina.conf file into the target/bin
directory and run the ballerina service, this issue will be solved.

*And also as I got to know, we can pass the path of the config file
as a parameter when we start running the service.
ballerina run serviceFileName.bal --b7a.conf.file=pathToConfFile

A: To provide a config file to your program, use the --b7a.config.file=path/to/file property when running your program.
e.g.,
$ ballerina run program.bal --b7a.config.file=path/to/file

In addition to the above, there's another method in which Ballerina automatically picks up the config file (i.e., without having to provide the above mentioned property). For this, you have to:

*

*Have the config file named as ballerina.conf

*Place the ballerina.conf file in the current directory (i.e., the directory from which you run your program)

Note that this is just a convenience mechanism for providing a config file.


text:
Q: Android checking multiple checkboxes        for(int i=3;i<plates1.length();++i)
        {
            final CheckBox cb=new CheckBox(this);

            JSONObject jObj1 = plates1.getJSONObject(i);
            String date=jObj1.getString("Name");
            cb.setText(date);
            cb.setId(i);
         }

I have my for loop here. I have created checkboxes using the for loop but I am not able to figure out the logic on how I should select two checkboxes at a time making use of the checkbox ID. Could you please help me out.

A: for(int i=3;i<plates1.length();++i)
        {
            final CheckBox cb=new CheckBox(this);

            JSONObject jObj1 = plates1.getJSONObject(i);
            String date=jObj1.getString("Name");
            cb.setText(date);
            cb.setId(i);
            parentView.addView(cb) // you should add it in parent layout
         }

an then this is how you access it..
((CheckBox)parentView.findViewById(3)).setChecked(true) // i took the first check box added

// do the same with others


text:
Q: Split VPN on IIS Server I have a very complex (At least I think it is) issue to work around.
The problem
I have an AWS Elastic Beanstalk server running Windows Server 2012 and IIS.
This server has a dynamically created network adapter from the AWS setup and a public IP address.
This IIS server is hosting a C# web API that needs to communicate with a locally hosted database and other AWS databases.
The local business has a VPN, when I configure this VPN on the AWS server (As expected) the server falls off the air. Can't be pinged or published too.
The question
This there some scheme that would allow tagging to happen, so when for instance I hit a DNS of locally_"hostname" windows would know to route that via the VPN while all other traffic goes via the standard adapter.
Or I am even willing to go the other way, only put a port or so via the standard adapter, enough to let me remote to it and 80 and 8080 for the API to keep functioning correctly.
Thanks in advance


text:
Q: How to find the min and max of a set of numbers in C without loops? Lets say I have 10 numbers (doubles) and I have to find the smallest number and the biggest number without using loops, how would I do so?

A: In psuedo-code, in case this is homework:
min = arr[0]
max = arr[0]
for n in 1..size(arr)-1:
    if arr[n] > max:
        max = arr[n]
    if arr[n] < min:
        min = arr[n]

If, for some reason, you can't use loops (and this certainly marks it as homework - no-one in their right mind would try this without a loop), just unroll the loop:
min = arr[0]
if arr[1] < min min = arr[1]
if arr[2] < min min = arr[2]
if arr[3] < min min = arr[3]
if arr[4] < min min = arr[4]
if arr[5] < min min = arr[5]
if arr[6] < min min = arr[6]
if arr[7] < min min = arr[7]
if arr[8] < min min = arr[8]
if arr[9] < min min = arr[9]
max = arr[0]
if arr[1] > max max = arr[1]
if arr[2] > max max = arr[2]
if arr[3] > max max = arr[3]
if arr[4] > max max = arr[4]
if arr[5] > max max = arr[5]
if arr[6] > max max = arr[6]
if arr[7] > max max = arr[7]
if arr[8] > max max = arr[8]
if arr[9] > max max = arr[9]

That's not too bad for ten entries but it's going to get cumbersome as the number rises.
Or a recursive solution for the more bizarrely-minded of us :-)
def findMax (arr, cur, idx):
    if idx < 0:
        return cur
    if arr[idx] > cur
        return findMax (arr, arr[idx], idx-1)
    return findMax (arr, cur, idx-1)

def findMin (arr, cur, idx):
    if idx < 0:
        return cur
    if arr[idx] < cur
        return findMin (arr, arr[idx], idx-1)
    return findMin (arr, cur, idx-1)

max = findMax (arr, arr[9], 8)
min = findMin (arr, arr[9], 8)

But I wouldn't hand that recursive solution in - if you haven't done loops yet, it's probably well beyond the level at which your class is operating.

And, since the recursive solution is a rather nifty, no-loop, solution (and you have a near-zero chance of using it and not being found out as a plagiarist), here it is:
#include <stdio.h>

static int findMin (int *arr, int cur, int idx) {
    if (idx < 0)
        return cur;
    if (arr[idx] < cur)
        return findMin (arr, arr[idx], idx-1);
    return findMin (arr, cur, idx-1);
}

static int findMax (int *arr, int cur, int idx) {
    if (idx < 0)
        return cur;
    if (arr[idx] > cur)
        return findMax (arr, arr[idx], idx-1);
    return findMax (arr, cur, idx-1);
}

int main (void) {
    int nums[] = {27,18,28,18,28,45,93,14,15,92,65,35,89};
    int min, max;
    int x = sizeof(nums) / sizeof(*nums) - 1;

    max = findMax (nums, nums[x], x-1);
    min = findMin (nums, nums[x], x-1);

    printf ("min=%d, max=%d\n", min, max);
    return 0;
}

This outputs:
min=14, max=93

as expected but don't use it on large lists since you'll probably run out of stack space.

A: Biggest number recursively:
double fun( double * ar, uint idx, uint size, double max )
{
    double rv;
    if( idx < size )
    {
        if( max < ar[idx] )     { rv = fun( ar, 1 + idx, size, ar[idx] ); }
        else                    { rv = fun( ar, 1 + idx, size,     max ); }
    }
    else                        { rv = max; }
    return rv;
}

Invocation:
double ray[] = { .0, -16.0, 2.0, -4.0, 8.0, -1.0, 7.0, -3.0, 5.0, -10.0 };
printf( "max %lf\n", fun( ray, 1, sizeof( ray ) / sizeof( ray[0] ), ray[0] ) );

Smallest is almost the same:
        if( ar[idx] < min )     { rv = fun( ar, 1 + idx, size, ar[idx] ); }


text:
Q: Argument requires that _ is borrowed for 'static - how do I work round this? I have a lifetime/borrowing error from the Rust compiler that I can't get my head around. The problem seems to be that Rust assumes that when an argument is passed to a function that returns a reference to a static value, the argument reference must also be static.
#[derive(Debug)]
struct TestThingy<'a> {
    label: &'a str,
}

const TEST_VALUES: [TestThingy; 3] = [
    TestThingy { label: "one" },
    TestThingy { label: "two" },
    TestThingy { label: "three" },
];

pub fn value_for_num(num: &str) -> Option<&'static TestThingy> {
    TEST_VALUES.iter().find(|value| value.label == num)
}

pub fn test_out_thingy() {
    let tmp_val = String::from("two");
    if let Some(test_thingy) = value_for_num(&tmp_val) {
        println!("test_thingy: {:?}", test_thingy);
    }
}

fn main() {
    test_out_thingy();
}

Rust errors with: error[E0597]: `tmp_val` does not live long enough - E0597 refers to when a value gets dropped whilst its still borrowed, which isn't happening here - I don't know how to convince Rust of that though.
The idea behind this code, for more context, is it's a lookup mechanism for compile-time/static config (in my codebase they are Syntax values, matched on the basis of a provided filename &str). So the provided argument genuinely does not live as long as the static config, but I don't understand why that's a problem. The returned value doesn't/can't contain the argument as a reference, so I'm super unclear why this borrowing error is happening.

A: The problem lies in the function signature of value_for_num.
You indicate that you return a static reference to a TestThingy but have no indication what kind of references that TestThingy<'x> might hold. Thus the compiler assumes that the unspecified input reference lifetime may be tied to the unspecified output lifetime of references inside the TestThingy.
i.e. the compiler sees this:
pub fn value_for_num<'a>(num: &'a str) -> Option<&'static TestThingy<'a>>

If you change the signature to specify that the contained references are also static then it compiles.
pub fn value_for_num(num: &str) -> Option<&'static TestThingy<'static>>


text:
Q: In PostgreSQL how can an array column be filtered and searched for unique values only? I'm trying to compare values in a history table populated by update trigger to see if certain columns in the old and new values of the JSON fields are equal and if all are equal then be able to create a case when query. Here's what I'm trying to do:
SQL
create table history
(
    id           serial not null,
    ts           timestamp default now(),
    table_schema text,
    table_name   text,
    operation    text,
    updated_by   text      default CURRENT_USER,
    new          json,
    old          json
);

With t AS (
select id,
       old->>'field1' = new->>'field1' as isMatchField1,
       old->>'field2' = new->>'field2' as isMatchField2,
       old->>'field3' = new->>'field3' as isMatchField3,
       old->>'field4' = new->>'field4' as isMatchField4
from history)

select id, array [isMatchField1, isMatchField2, isMatchField3, isMatchField4] from t

OUTPUT
1, {true, true, false, null}
How do filter out all nulls from the array and do a case when query to see if only true valuesexists. basically I want to do something like:
select id,
case when array field is only true and null then 'no changes made'
else
  'changes made'
end as updated
from t


text:
Q: Python program that reads file, then calculates sum, average, min, max, and give message if it only has one number in it or is empty def main():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]
        if len(data) > 2:
            print('The smallest number in the file is: ', + min(data))
            print('The largest number in the file is: ', "{:,}".format(+ max(data)))
            print('The total sum of the number in the file is: ', "{:,}".format(sum(data)))
            print('The average from the numbers in the file is: ', "{:,.2f}".format(sum(data)/len(data)))
        elif len(data) == 1:
            print ('There is only one number in your file to process.')
        else:
            print('There are no numbers in your file to process.')
        f.close()

main()

A: Based on your comment, I think the problem is with your data, to get around that, you could use something like:
lines = filter(None, (line.strip() for line in f))
data = [int(line) for line in lines if line.isnumeric()]

Please note that this only addresses the exception you're getting - I haven't gone through the rest of the code and verified the logic.


text:
Q: A problem to get data from store in react-redux I'm creating to do list app so I created API using laravel and it works fine . The scenario is when user login I dispatch an action to check his email and password then update the store in redux with the user tasks . The tasks reach to the reducer fine but I cannot get it in the TasksComponent I get undefined when console.log(this.props.tasks)  or even console.log(this.props.isLoading)
The reducer login

import * as ActionTypes from './ActionTypes';

export const Login = (state = {
    tasks: [],
    categories: [],
    error: null,
    isLoading: true
}, action) => {
    switch(action.type) {
        case ActionTypes.AUTH_LOADING:
            return {...state, tasks:[], categories:[], error: null, isLoading: true}
            case ActionTypes.AUTH_SUCCESS:
            console.log(action.payload.user.tasks)
             return {...state, tasks: action.payload.user.tasks, categories: action.payload.user.categories,error: null, isLoading: false}
        case ActionTypes.AUTH_FAIL:
             return {...state, tasks:[], categories:[], error: action.error, isLoading: false}
        default:
            return state;
    }

}

The Action creator

import * as ActionTypes from './ActionTypes';
import { baseUrl } from '../shared/baseUrl';

export const authSuccess = (authData) => ({
    type: ActionTypes.AUTH_SUCCESS,
    payload: authData
});

export const authFail = (error) => ({
    type: ActionTypes.AUTH_FAIL,
    error: error
});

export const authLoading = () =>({
    type: ActionTypes.AUTH_LOADING
})

export const auth = (email, password) => dispatch => {
    dispatch(authLoading());

    const user = {
        email: email,
        password: password
    }

    return fetch('http://localhost:8000/api/users/login',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(user)
    })
    .then(data => data.json())
    .then(user => {
        dispatch(authSuccess(user));
    })
    .catch(error => dispatch(authFail(error)));
}

The tasks component

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { Loading } from './LoadingComponent';

class Tasks extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        if(this.props.isLoading) {
            <Loading />
        } else {
            return(
Yes
)
        }
    }
}

const mapStateToProps = state =>{
    return {
        isLoading: state.isLoading // Always get undefined
    }
}

export default connect(mapStateToProps)(Tasks);


text:
Q: Solr Spellcheck Query term modification I am using Solr for spell checking. Enabled both DirectSolrSpellChecker & WordBreakSolrSpellChecker. I have the following issue:
A. When I am querying for "worry". Solr is converting this term to "worri" and returning results for the same. If word is ending with "y" [ "injury","worry" etc..], the ending "y" is replaced with "i".
Example Query:
http://localhost:8983/solr/MY_CORE/spell?df=text&spellcheck.q=worry&spellcheck=true&spellcheck.extendedResults=true&spellcheck.onlyMorePopular=true

Solr Result:
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">5</int>
</lst>
<result name="response" numFound="0" start="0"/>
<lst name="spellcheck">
<lst name="suggestions">
<lst name="worri">
<int name="numFound">9</int>
<int name="startOffset">0</int>
<int name="endOffset">5</int>
<int name="origFreq">5</int>
<arr name="suggestion">
<lst>
<str name="word">wo r ri</str>
<int name="freq">90</int>
</lst>
<lst>
<str name="word">worst</str>
<int name="freq">12</int>
</lst>
<lst>
<str name="word">wo r r i</str>
<int name="freq">5246</int>
</lst>
<lst>
<str name="word">work</str>
<int name="freq">2920</int>
</lst>
<lst>
<str name="word">w o r ri</str>
<int name="freq">530</int>
</lst>
<lst>
<str name="word">worn</str>
<int name="freq">81</int>
</lst>
<lst>
<str name="word">w o r r i</str>
<int name="freq">5246</int>
</lst>
<lst>
<str name="word">wors</str>
<int name="freq">79</int>
</lst>
<lst>
<str name="word">worm</str>
<int name="freq">10</int>
</lst>
</arr>
</lst>
</lst>
<bool name="correctlySpelled">false</bool>
</lst>
</response>

B. Also above output have words like "w o r r i", and I couldn't find any of those words in the solr field. I also don't know why solr is returning such words where letters are separated by spaces.
Below is schema file:
<field name=MY FIELD type="text_en" multiValued="false" indexed="true" stored="true"/>

Below is the config file:
<!-- a spellchecker built from a field of the main index -->
        <lst name="spellchecker">
            <str name="name">default</str>
            <str name="field"> MY FIELD </str>
            <str name="classname">solr.DirectSolrSpellChecker</str>
            <!-- the spellcheck distance measure used, the default is the internal levenshtein -->
            <str name="distanceMeasure">internal</str>
            <!-- minimum accuracy needed to be considered a valid spellcheck suggestion -->
            <float name="accuracy">0.5</float>
            <!-- the maximum #edits we consider when enumerating terms: can be 1 or 2 -->
            <int name="maxEdits">2</int>
            <!-- the minimum shared prefix when enumerating terms -->
            <int name="minPrefix">1</int>
            <!-- maximum number of inspections per result. -->
            <int name="maxInspections">5</int>
            <!-- minimum length of a query term to be considered for correction -->
            <int name="minQueryLength">4</int>
            <!-- maximum threshold of documents a query term can appear to be considered for correction -->
            <float name="maxQueryFrequency">0.01</float>
            <!-- uncomment this to require suggestions to occur in 1% of the documents
             <float name="thresholdTokenFrequency">.01</float>
             -->
        </lst>

        <!-- a spellchecker that can break or combine words.  See "/spell" handler below for usage -->

         <lst name="spellchecker">
         <str name="name">wordbreak</str>
         <str name="classname">solr.WordBreakSolrSpellChecker</str>
         <str name="field">MY FIELD</str>
         <str name="combineWords">false</str>
         <str name="breakWords">true</str>
         <int name="maxChanges">10</int>
         </lst>

    </searchComponent>

    <requestHandler name="/spell" class="solr.SearchHandler" startup="lazy">
        <lst name="defaults">
            <str name="spellcheck.dictionary">default</str>
            <str name="spellcheck.dictionary">wordbreak</str>
            <str name="spellcheck">on</str>
            <str name="spellcheck.extendedResults">true</str>
            <str name="spellcheck.count">10</str>
            <str name="spellcheck.alternativeTermCount">5</str>
            <str name="spellcheck.maxResultsForSuggest">5</str>
            <str name="spellcheck.collate">false</str>
            <str name="spellcheck.collateExtendedResults">false</str>
            <str name="spellcheck.maxCollationTries">10</str>
            <str name="spellcheck.maxCollations">5</str>
        </lst>
        <arr name="last-components">
            <str>spellcheck</str>
        </arr>
    </requestHandler>

I would really appreciate if someone can help me regarding this.
Thanks in advance !

A: The "strange" suggestions that you have like "wo r r i". You have them, because you're using WordBreakSolrSpellChecker and it breaks tokens trying to provide you some spellcheck capabilities, so if you will remove you shouldn't get these kind of suggestions. Here is the quote from the official documentation:

WordBreakSolrSpellChecker offers suggestions by combining adjacent
  query terms and/or breaking terms into multiple words. It is a
  SpellCheckComponent enhancement, leveraging Lucene's
  WordBreakSpellChecker. It can detect spelling errors resulting from
  misplaced whitespace without the use of shingle-based dictionaries and
  provides collation support for word-break errors, including cases
  where the user has a mix of single-word spelling errors and word-break
  errors in the same query. It also provides shard support.

So, basically, in your example - you're getting normal suggestions from Solr index like: worst, work, worm, worn, wors. all other are just the result of WordBreakSolrSpellChecker and you will never find them in your index.