text:
Q: Add id or name property or other means of identification for Flutter Web applications? Writing a Flutter Web application, I try to leverage a Web-UI-Testing framework based on Selenium. Sadly I fail to identify a HTML-Element representing a certain flutter widget by its id or name attribute. The widget key is not present in the HTML document.
I manage to use Text widget contents to find an widget's text portion and can find its parent element representing the widget containing the text but this fails for images, canvas etc.
Is there any mechanism I can use to add id/name (or any other means of identification) to the HTML tag soup?
Using JavaScript, is there a way to traverse the internal logical widget tree and from there conclude the representing HTML element (for example by its location and size)?

A: I do not think it is right way to use any Selenium kind of testing framework for Flutter Web.
Reason for that is that you (as web developer) have no control on how generated DOM looks like. Which means you can not use XPath and other means to select elements.
I suppose the only way of testing Flutter apps (including Flutter Web) is using Flutter Driver:  https://api.flutter.dev/flutter/flutter_driver/flutter_driver-library.html

A: You currently can not consistently add identification information to Widgets rendering on different devices.
To achieve your goal however you can use Flutter Driver. The flutter_driver Dart package is specifically designed to enable UI testing of Flutter apps and provides an API to the apps on real devices, simulators or emulators. To get started with Flutter Driver testing you need to:

*

*Get the flutter_driver package

*Set up a test directory

*Create an instrumented app for testing

*Write UI tests using flutter_driver API

*Execute the UI tests in the real device or simulator

To find a Flutter widget you can use SerializableFinder, e.g.:
test('verify the text on home screen', () async {
    SerializableFinder message = find.text("Widget Title");
    await driver.waitFor(message);
    expect(await driver.getText(message), "Widget Title");
});

For more information check out:

*

*https://blog.codemagic.io/flutter-ui-testing/

*https://medium.com/flutter-community/testing-flutter-ui-with-flutter-driver-c1583681e337

*https://api.flutter.dev/flutter/flutter_driver/flutter_driver-library.html


text:
Q: SSE delay in golang I'm trying to make console using sse that shows client what server is doing. Currently it does what I want except it has a delay (about 2sec). I added http.Flusher but is seems to do absolutely nothing. I call UpdateLogMessage using goroutines: go UpdateLogMessage("Example")
SSE:
type Upl struct {
    log string
}

var Log chan *Upl

func DashboardHandler(w http.ResponseWriter, r *http.Request) {
    f, ok := w.(http.Flusher)
    if !ok {
        fmt.Println("Streaming unsuported")
    }

    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    msg := <-Log
    fmt.Fprintf(w, "data: %v\n\n", msg.log)
    f.Flush()
}

//Updates log message with curent time and message content
func UpdateLogMessage(msg string) {
    curentTime := time.Now().Format("15:04:05")
    ul := fmt.Sprintf("<%v> %v", curentTime, msg)
    up := &Upl{
        log: ul,
    }
    Log <- up
}

func MakeChan() {
    Log = make(chan *Upl)
}

Javascript:
function onLoaded(){
    var source = new EventSource("sse/dashboard")
    var logg = "";
    var currentmsg = "";

    source.onmessage = function (event){
        var dashboard = event.data;
        //If message changed print it to console
        if (dashboard != currentmsg){
            console.log("OnMessage called:");
            console.dir(event);
            currentmsg = dashboard;
            logg += currentmsg + "<br/>";
            console.log(logg);
            document.getElementById("console").innerHTML = logg;
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: $not operator is not working inside an $and operator in query I want to query my database with the following restrictions, for all records where all these conditions are true:

*

*property is propertyID

*active is true

*startDate is NOT greater than Y

*endDate is NOT less than X

I am having a hard time getting MongoDB to accept my $match:
$match:{
    $and:[
        { property : propertyID },
        { active   : true },
        { $not: { start : {$gte: 1498780800 } } },
        { $not: { end   : {$lte: 1497052800 } } }
    ]
}

Right now I am getting the error: MongoError: unknown top level operator: $not. You might say just do startDate less than X and endDate less than Y, but this won't work because startDate might be greater than X and endDate less than Y which is a record I want etc.. which is why that won't work. How can I fix this?
UPDATE:
My logic is not correct, this is what I am trying to do...

A: The problem is that you've got $not in the wrong place. Per the documentation:

Syntax: { field: { $not: { <operator-expression> } } }

Thus, $not should be used not as a top level operator, the field should be at the top level.
On to the logical side of this problem. You want to select records where start is in between the restricted dates or end is in between the restricted dates, there's no reason to use $not here. Also, make sure you are checking for greater than the minimum and less than the maximum, not the other way around. Try the following query:
$match: {
  $and: [
    { property: propertyID },
    { active: true },
    { $or: [
      { start: { $lte: 1498780800, $gte: 1497052800 } },
      { end: { $lte: 1498780800, $gte: 1497052800 } }
    ] }
  ]
}

This will check if either start or end is in between the restricted dates.


text:
Q: Integral Help - $\int \frac {\sqrt{u^2-a^2}}{u}du$ As per the integral table, how do I show $\int \frac {\sqrt{u^2-a^2}}{u}du$ = $  {\sqrt{u^2-a^2}} - \arccos^{-1}(\frac {a}{u})+c$
I can't figure out how to start it.
I can do it for:
$$
\int \frac {\sqrt{u^2-a^2}}{u}du
 = \sqrt{u^2-a^2} - \mathrm{arcsec}^{-1}(\frac{u}{a})+c
$$
by starting with $\mathrm{arcsec}\ \theta = u$
Is it just a matter of showing the relationship between $\mathrm{arcsec}$ and $\arccos$?

A: Yep. Since $\sec x=1/\cos x$, if we set $$\sec x=1/\cos x=y,$$
then $$x=\sec^{-1}y$$
and $$x=\cos^{-1}\frac1y,$$
so $\sec^{-1}y=\cos^{-1}\frac1y$.

A: You can think it like a right triangle with hypotenuse $u$ and base $a$, such that $\cos x=\frac{a}{u}$, where $x$ is the angle between hypotenuse and side $a$. Then from this you have $u = a\cdot\sec x$ and $du = a\cdot \sec x\cdot\tan x\cdot dx$, with $0<x<\pi/2$. Plugging this on the integral finally you get:
$$a\int \tan^2 xdx=a\int (\sec^2 x - 1)dx=a\tan x - ax$$
From right trianle $\tan x = \sqrt{u^2-a^2}/a$ and $x = \sec^{-1}(u/a)$, so replacing finally we get
$$\int\frac{\sqrt{u^2-a^2}}{u}du = \sqrt{u^2-a^2}-a\sec^{-1}\big(\frac{u}{a}\big)+c$$


text:
Q: Organizar tabela de horários no Banco de Dados Para a construção de uma tabela no site que conterá uma listagem de todos os dias da semana, como posso criar essas tabelas no banco de dados? Por exemplo:
Horarios da linha de onibus de uma cidade para outra:
De CidadeA para cidadeB
Seg à Sex
7:00h
7:30h
10:00h
  ...
Sab
7:15h
11:30h
Dom
12:00h
...
CidadeB à CidadeC
.....
Como organizo os dias da semana e horarios no banco? para que o próprio admin do sistema possa alterar essas informações constantemente.

A: Você pode organizar da seguinte forma:
id_horario // auto increment
id_linha // linha pré cadastrada
id_saida // cidade saida
id_destino // cidade destino
dia_da_semana // segunda a domingo
horario // horário de saida

Com base nessa tablela, você faz a inserção dos registros de horários e linhas dos ônibus. Quando você for gravar, verifica se já tem esse horário agendado nessa linha, se não tem, grava, se tem edita.
Espero ter ajudado!


text:
Q: Linux dialog consuming 100% CPU in the broken session when I'm using /usr/bin/dialog by ssh (PuTTY from windows) for example:
dialog --ok-label Select --cancel-label Cancel --stdout --backtitle BACKTITLE --menu TITLE 0 50 0 '1' 'alfa' '2' 'beta'

and when the dialog is displayed, I close my putty by Alt-F4 (or mouse click on X) dialog process not exit but exists and get 100% CPU:
PID  USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
9928 user      20   0  113m 2308 1092 R 100.0  0.0   0:30.99 dialog

Bellow is my gdb session:
$ gdb -p 9928
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-56.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Attaching to process 9928
Reading symbols from /usr/bin/dialog...(no debugging symbols found)...done.
Reading symbols from /usr/lib64/libdialog.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libdialog.so.6
Reading symbols from /lib64/libncursesw.so.5...(no debugging symbols found)...done.
Loaded symbols for /lib64/libncursesw.so.5
Reading symbols from /lib64/libm.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib64/libm.so.6
Reading symbols from /lib64/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib64/libc.so.6
Reading symbols from /lib64/libtinfo.so.5...(no debugging symbols found)...done.
Loaded symbols for /lib64/libtinfo.so.5
Reading symbols from /lib64/libdl.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libdl.so.2
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
Reading symbols from /usr/lib64/gconv/ISO8859-2.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/gconv/ISO8859-2.so
0x00007f902081e315 in fcntl () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install dialog-1.1-9.20080819.1.el6.x86_64
(gdb) bt
#0  0x00007f902081e315 in fcntl () from /lib64/libc.so.6
#1  0x00007f9020fa3b5d in ?? () from /usr/lib64/libdialog.so.6
#2  0x00007f9020fa4230 in dlg_getc () from /usr/lib64/libdialog.so.6
#3  0x00007f9020fa15a3 in ?? () from /usr/lib64/libdialog.so.6
#4  0x00007f9020fa0668 in dlg_menu () from /usr/lib64/libdialog.so.6
#5  0x00007f9020fa131c in dialog_menu () from /usr/lib64/libdialog.so.6
#6  0x0000000000403916 in ?? ()
#7  0x000000000040415c in ?? ()
#8  0x00007f9020761cdd in __libc_start_main () from /lib64/libc.so.6
(gdb) continue
Continuing.
^C
Program received signal SIGINT, Interrupt.
0x00007f902081de00 in __read_nocancel () from /lib64/libc.so.6
(gdb) bt
#0  0x00007f902081de00 in __read_nocancel () from /lib64/libc.so.6
#1  0x00007f9020d6a277 in _nc_wgetch () from /lib64/libncursesw.so.5
#2  0x00007f9020d7f430 in wget_wch () from /lib64/libncursesw.so.5
#3  0x00007f9020fa401f in dlg_getc () from /usr/lib64/libdialog.so.6
#4  0x00007f9020fa15a3 in ?? () from /usr/lib64/libdialog.so.6
#5  0x00007f9020fa0668 in dlg_menu () from /usr/lib64/libdialog.so.6
#6  0x00007f9020fa131c in dialog_menu () from /usr/lib64/libdialog.so.6
#7  0x0000000000403916 in ?? ()
#8  0x000000000040415c in ?? ()
#9  0x00007f9020761cdd in __libc_start_main () from /lib64/libc.so.6

Any ideas what should I do? Now I have task in cron which finds old dialogs and kills them.

A: The given version 1.1-20080819 is old.  For instance a related problem was fixed in 2009/02/22:

modify dlg_result_key() to map curses ERR to dialog's error exit
  (adapted from patch by Domagoj Pensa).

which in turn was an improvement on a change made in 2007/07/04:

add a check when ERR returned from wgetch() to ensure that the
  input/output streams are still valid.  If that happens, force
  ESC to be returned, quitting dialog (report by Reiner Huober).

At the moment, the current version is 1.2-20150225.

A: Compilation the newest dialog resolved my problem.
I had 1.1-20080819 dialog version while now I have 1.2-20140911 where problem is resolved.@ThomasDickey thanks for suggestion.


text:
Q: Trouble with overriding a variable in abstract class I'm new to scala and have the following question about overriding a variable in an abstract class.
abstract class ExampleClass1 {
    val testVar = (i: String) => {
        i + " A"
    }

    def exampleMethod1() = {
        print testVar
    }
}

object ExampleObject1 extends ExampleClass1 {
    def getExampleValue() = {
        exampleMethod1()
    }
}

ExampleClass1 and ExampleObject1 are in one module. My module is calling ExampleObject1.getExampleValue. I want to change the behavior of testVar in ExampleClass1. Is it possible to do this without changing ExampleObjectt1?
Thank you

A: If you want to change a value after the class is instantiated, then you should use var instead of val, but without any further information it seems that there is a flaw in your design.
If you want to set the value of the given string on object creation, you can use something like this:
scala> abstract class ExampleClass1(val i: String)
defined class ExampleClass1
scala> object ExampleObject1 extends ExampleClass1("A")
defined object ExampleObject1
scala> ExampleObject1.i
res1: String = A

Or if you want to use given string as a parameter:
scala> abstract class ExampleClass2 {
 | def test(i: String) = i + " A"
 | }
defined class ExampleClass2
scala> object ExampleObject2 extends ExampleClass2
defined object ExampleObject2
scala> ExampleObject2.test("B")
res2: String = B A

What is your goal?


text:
Q: Disable window shadow on 10.11 / 10.12? Like in the title, I've used ShadowKiller (very old but worked until 10.11) but it doesn't work in 10.11 and 10.12 as well (tried disabling SIP).
I've tried using the command line trick, toggle-osx-shadows from github and couple of others, it seems that something changed in 10.11
Does anybody have a solution?

A: edit 01-11-2019: Works on Mojave.
There is a solution - plugin called winBuddy which is available through MacForge (previously known as mySIMBL).
It allows you to turn off window shadow and/or window borders for every app.
I've just tested it and it seems to work properly, there are some minor glitches here and there but nothing major.
Minor glitches include:

*

*You can't change window options for apps which don't have menu - like Bartender for example

*You can't change window options for some apps, as winBuddy does not show up under 'Window' in menu.


text:
Q: Specify a maximum size in d3 circle packer I'm using the d3 circle packing algorithm. It's set up to make inner circles occupy all available space. So if I have two circles of equal size, one containing three sub circles, and one containing 50, the three appear very large.
Is there a simple modification I can make to the script so that inner circles will not exceed a particular size - perhaps floating in the centre?
Source here:
https://github.com/mbostock/d3/blob/master/src/layout/pack.js

A: In short, no. While you can limit the size each circle can have quite easily, doing this in a context-sensitive way will require more work. In particular, you would have to check the size of the containing circle (possibly with respect to the overall size) as well as the number of children and their children. You may also want to check how far down in the nesting hierarchy you are to make these decisions.
Nothing of this is particularly difficult, but it wouldn't be a simple change.


text:
Q: Android video record error Can anybody point out the error I am doing? I am trying to record a short video, but somehow it finds a way to crash.
Source Code:
public class Start_recording extends Activity implements SurfaceHolder.Callback
{
    MediaRecorder recorder;
    SurfaceHolder surfaceHolder;
    SurfaceView myVideoView;
    Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        camera = Camera.open();
        camera.unlock();
        recorder = new MediaRecorder();
        setContentView(R.layout.activity_main_rst);
        myVideoView = (SurfaceView)findViewById(R.id.surface_camera);
        surfaceHolder = myVideoView.getHolder();
        surfaceHolder.addCallback(this);
        initMediaRecorder();
        boolean exists = (new File(android.os.Environment.getExternalStorageDirectory() + "/Record/")).exists();

        if (!exists)
        {
            new File(android.os.Environment.getExternalStorageDirectory() + "/Record/").mkdirs();
        }

        try
        {
            recorder.prepare();  // This is the line of error.
            recorder.start();
            Thread.sleep(36000);
            recorder.stop();
            setupActionBar();
        }
        catch(Exception e)
        {
            Log.v("Error is there : ",e.toString());
            e.printStackTrace();
        }
    }

    public void initMediaRecorder()
    {
        try
        {

            recorder.setPreviewDisplay(surfaceHolder.getSurface());
            recorder.setCamera(camera);
            recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(android.os.Environment.getExternalStorageDirectory()+"/Record/test.3gp");
            recorder.setMaxDuration(300000);
        }
        catch(Exception f)
        {
            Log.v("Exception here : ",f.toString());
            f.printStackTrace();
        }
    }
}

Error :
E/MediaRecorderJNI(1575): Application lost the surface
V/Error is there :(1575): java.io.IOException: invalid preview surface
W/System.err(1575): java.io.IOException: invalid preview surface
W/System.err(1575):     at android.media.MediaRecorder._prepare(Native Method)
W/System.err(1575):     at android.media.MediaRecorder.prepare(MediaRecorder.java:666)
W/System.err(1575):     at com.example.project.Start_recording.onCreate(Start_recording.java:51)

I have added the permissions correctly in the Manifest file and also set the setPreviewDisplay(). But I get as invalid preview surface.Please correct me.

A: One has to use SurfaceHolder.Callback to start recording only after the surface really is created.


text:
Q: Python: variables assigned before for loop I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me:
1. The for loop is "returning" somehow values k and v to the previous statement (k,v).
2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.
I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.
Thank you in advance.

A: param.items() = [(key1, val1), (key2, val2) ... ]

Extended code for this list comprehension.. Generate the list inside the square brackets first, then join the list together by passing it to the join method.
new_list = []
for each_tuple in param.items():
    k = each_tuple(0)
    v = each_tuple(1)
    new_list.append("%s==%s" % (k, v,))
":".join(new_list)         # new_list = ['k1==v1', 'k2==v2', 'k3==v3',...]

>>> 'key1==value1:key2==value2:key3==value3....'

A: List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.
If you're familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:
>>> doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
>>> doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension.
If you can rewrite your code to look just like this for loop, you can also rewrite it as a list comprehension:
new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append("something with " + ITEM)

You can rewrite the above for loop as a list comprehension like this:
new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]


text:
Q: How CallableStatement in Oracle Works? I need to know whether Oracle CallableStatement makes a DB call to compile ( or bind) IN/OUT parameters in the stored procedure?
If the answer is yes, what is the request sent by the JDBC driver to DB?

A: Your question isn't clear, but maybe this will help.
OracleConnection.prepareCall does not make a database round trip.
OracleCallableStatement.setXXX does not make a database round trip.
OracleCallableStatement.registerOutParameter does not make a database round trip.
The only method on OracleCallableStatement that always makes database round trips is execute.
OracleCallableStatement.getXXX may make a database round trip. Mostly this depends on the type of the OUT parameter. If the OUT parameter is an ARRAY, STRUCT, REF, or OPAQUE there may be a database round trip if the driver has not yet seen the type description for the type. Type descriptions are cached by the connection so once the driver has retrieved the type description it will not have to do a database round trip to construct an instance of the type. Calling getString or getBytes (or some other getXXX that needs the complete value) on a BLOB, CLOB, NCLOB, or BFILE type may require a database round trip if the entire value was not retrieved in the initial call. Calling getBlob, getClob, getNClob or getBfile (as appropriate) on a BLOB, CLOB, NCLOB, or BFILE out parameter does not do a database round trip.


text:
Q: How to use a token for a rex in Splunk? I have a token $token_rex$ set up as follows in the dashboard:
<set>mvjoin(mvmap('token_keywords_mv',"(?<".'token_keywords_mv'.">".'token_keywords_mv'."+?)"), "|")</set>

token_keyrowrds_mv is basically the following:
lorem
ipsum
situs

The resulting token looks like this:
(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)

The query I am trying to run is as follows:
index=* | rex field _raw "(?i)".$token_rex$

Ideally the above should be rendered like so:
index=* | rex field _raw "(?i)(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)"

I have tried using the token filters $token_rex|s$ and $token_rex|n$ but neither work. I have even tried to return the value from a subsearch:
index=* | rex field _raw [| makeresults | eval string_rex=$token_rex$ | return $token_rex]

Update: Found out that the token is being given as verbose to the rex command. My token is set as follows:
<set token="token_rex">mvjoin(mvmap('token_keywords_mv',"(?>".'token_keywords_mv'."<".'token_keywords_mv'."+?)"), "|")</set>

When I used it as ... | rex field=_raw '(?i)$token_rex$' it gives me the following error:

Error in 'rex' command: Encountered the following error while compiling the regex ''(?i)mvjoin(mvmap('token_keywords_mv'': Regex: missing closing parenthesis.

When I set it as the value directly, however, it works:
<set token="token_rex">(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)</set>

Update: Here's a sample dashboard.
<dashboard theme="dark">
  <init>
    <set token="token_keywords_mv">split("lorem,ipsum,situs", ",")</set>
    <set token="token_keywords_starred">"*".mvjoin($token_keywords_mv$, "* OR *")."*"</set>
    <set token="token_rex">"(?i)".mvjoin(mvmap('token_keywords_mv', "(?<".'token_keywords_mv'.">".'token_keywords_mv'."+?)"), "|")</set>
    <set token="token_raw">(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)</set>
  </init>
  Test Search
  <description>Multivalue</description>
  <row>
    <panel>

        <search>
          <query>index=*
    [| makeresults
    | eval string_search=$token_keywords_starred$
    | return $string_search]
| rex field=_raw $token_raw|s$
| stats count(lorem) AS Lorem, count(ipsum) AS Ipsum, count(situs) AS Situs
| eval header="Count"
| transpose column_name="String" header_field=header</query>
          <earliest>-24h@h</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>
        <option name="refresh.display">progressbar</option>

    </panel>
  </row>
  <row>
    <panel>

        <title>ECHO</title>
        <search>
          <query>| localop
| makeresults
| eval token_keywords_starred=$token_keywords_starred$, token_keywords_mv=$token_keywords_mv$, token_rex=$token_rex$, token_raw=$token_raw|s$</query>
          <earliest>-24h@h</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>
        <option name="refresh.display">progressbar</option>

    </panel>
  </row>
</dashboard>

If any other token replaces $token_raw|s$, there will be an error. Using Splunk 8.0.3.

A: When I try to reproduce your results with this dashboard code:
<form>
  test
  <fieldset submitButton="false">
    <input type="text" token="token_rex">
      field1
    </input>
  </fieldset>
  <row>
    <panel>
      <event>
        <title>test</title>
        <search>
          <query>| makeresults | eval _raw="lorem ipsum dolor"
| rex "(?i)$token_rex$"
|  table lorem ipsum situs</query>
          <earliest>$earliest$</earliest>
          <latest>$latest$</latest>
        </search>
        <option name="refresh.display">progressbar</option>
      </event>
    </panel>
  </row>
</form>

I get this optimized search (as reported by Job Inspector):
| makeresults | rex field=_raw "(?i)(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)"

It looks like the concatenation is not needed.

Update: Change all the set tags to eval and use mvzip instead of mvmap. The set tag does not compute, while the eval tag does.
    <eval token="token_keywords_mv">split("lorem,ipsum,situs", ",")</eval>
    <eval token="token_keywords_starred">"*".mvjoin($token_keywords_mv$, "* OR *")."*"</eval>
    <eval token="token_rex">"(<".mvjoin(mvzip('token_keywords_mv','token_keywords_mv',">"),"+?)|(?<")."+?)"</eval>
    <set token="token_raw">(?<lorem>lorem+?)|(?<ipsum>ipsum+?)|(?<situs>situs+?)</set>


text:
Q: oo-spaghettio web architecture I've noticed that the majority of enterprise web apps I've worked on over the past few years have seemingly mis-used the powers of oo.
That is, what once would have been perhaps 1000 lines of HTML and script, has often now morphed into 10,000 lines of code, 50 classes, and 2000 method calls to do basically the same thing.  I.e. oo and layered architecture appears to be over-used and/or ill-used, often leading to longer development times, higher-cost, and often nightmarish maintenance.

*

*How often are other people seeing this happen?

*How can oo be effectively utilized to, as the Buddha himself has said:  as much as possible try not to harm...as much as possible try to help...

A: I see these all the time :( Basically if people are going to do a mess they will do it trying or not to use oo design. It gets equally awful on either case.
Update 1: it is important to understand how/what will be reused (but not going crazy on it as that would hinder productivity), since we don't want to get tons of classes where every single one of them aren't reused and fulfill tons of different functions.
Basically the main issue is understanding and caring for what is being built, as you could apply oo, tdd, ddd, anything, and if the devs doesn't understand what they are doing it will end up in the same mess ... or worst :(
Bottom line, these things do help, but they aren't magic, they won't replace the developers skills to create maintainable code.
Update 2: Also note that a checklist or some bullet points won't do it. I mean I love SOLID, and plenty things going on and I think they really clear things up, but they usually make the most impact on the people that have been trying to avoid the mess.

A: "The road to hell is paved with the best of intentions."
I haven't personally encountered this myself, but all the times I've heard stories it seems to be an issue of architecture astronauts (people who spend too much time thinking) or bad developers (people who spend too little time thinking).
In the earlier days of programming, you didn't see as much of this because of the limits of the hardware, languages, etc.
However, developers are now are trying to focus on writing code that's understandable by humans for loose coupling and higher maintainability by incorporating as many design patterns and OO principles as they can, but just like everything it can be over-done.
On the other hand, some developers might just not be thinking enough about the problems they're attempting to solve and writing extra code just because it gets the job done and not thinking about the bigger picture.
In either case, developers might not be malicious or even incompetent and want the best for the projects their working on, but they still over-do principles simply because they are trying too hard.
So I would say the solution is to remind developers to use OOP principles as guidelines, but just that.  There comes a point when you have to find a happy medium between thinking and programming and just stop thinking and start programming.
See: Jeff wrote a good blog post about just this kind of thing: KISS and YAGNI.


text:
Q: How to bind users to different organizations, universities, companies with different roles?           USERS

 1. GFER: SUPERADMIN

Foundation(VAG):
  2. John: Incharge
  3. Jessi: IT Head

University(MIT):
 4: Bill: Adminstrator
 5: Gates: Prinicipal investigator
 6: Donald: Researcher

Organizations(YE):
 6. Jason: Head of R&D
 7. Johnny: Researcher

University, organization or company can't exist without a user. There would always exist a user who'll create it or own it. And every user would have a personal profile as well.
Schema looks like this:
User
- email
- name

Roles:
 - id
 - name

University(Profile):
 - name
 - short history

Organizatons(Profile):
  - name
  - logo of the brand

Foundation(Profile):
  - name
  - Adminstrative contacts

How can i know a user is bind to which table(foundation, organization or university) and what role does it have in that group(foundation, organization or university)? I thought to create a bridge table like this:
  Group:
    - id
    - name
    - type(University, Foundation, Organization)

 Group_members:
   - id
   - roleId
   - groupId
   - userId

But the problem is that i can't create a groups table as data for university, foundation and organization is totally different for each other. So i'll have to create a separate table for each. How can i solve this problem?

A: -- User USR exists.
--
user {USR}
  PK {USR}

-- Role ROL exists.
--
role_ {ROL}
   PK {ROL}

Xorg is a generic term for a university, an organization, or a foundation.
Discriminator TYP is used to distinguish between these three.
-- Xorg XOG, of type TYP, named XNM was created
-- (is owned) by user USR.
--
xorg {XOG, TYP, USR, XNM, ...common_cols}
  PK {XOG}
  SK {XOG, TYP}

CHECK TYP in {'U', 'O', 'F'}

FK {USR} REFERENCES user {USR}

-- University (xorg) XOG, of xorg-type TYP = 'U', exists.
--
university {XOG, TYP, ...university_specific_cols}
        PK {XOG}

CHECK TYP = 'U'

FK {XOG, TYP} REFERENCES xorg {XOG, TYP}

-- Organization (xorg) XOG, of xorg-type TYP = 'O', exists.
--
organization {XOG, TYP, ...organization_specific_cols}
          PK {XOG}

CHECK TYP = 'O'

FK {XOG, TYP} REFERENCES xorg {XOG, TYP}

-- Foundation (xorg) XOG, of xorg-type TYP = 'F', exists.
--
organization {XOG, TYP, ...foundation_specific_cols}
          PK {XOG}

CHECK TYP = 'F'

FK {XOG, TYP} REFERENCES xorg {XOG, TYP}

-- User USR is member of xorg XOG, of xorg-type TYP,
-- in role ROL.
--
user_xorg {USR, XOG, TYP, ROL}
       PK {USR, XOG}

      FK1 {XOG, TYP} REFERENCES
     xorg {XOG, TYP}

      FK2 {USR} REFERENCES user  {USR}
      FK3 {ROL} REFERENCES role_ {ROL}

Note:
All attributes (columns) NOT NULL

PK = Primary Key
AK = Alternate Key   (Unique)
SK = Proper Superkey (Unique)
FK = Foreign Key

A word about subtypes. The proper way to implement constraints for subtypes would be to use assertions (CREATE ASSERTION), but it is still not available in major DBs. I am using FKs instead, and as all other substitute methods it is not perfect. People argue a lot,  on SO and SE-DBA, what is better. I encourage you to check other methods too.


text:
Q: Is there another way to describe the category $\mathbf{Top}$ of topological spaces? The category $\mathbf{Top}_\ast$ of pointed topological spaces can be viewed as the comma category $(\bullet\downarrow\mathbf{Top})$.
The objects of the category $\mathbf{Top}$ are topological spaces and the morphisms are the continuous maps between them. The composition of morphisms is the usual composition of maps and the identity morphisms are the identity maps.
Is there exists another way to describe the category $\mathbf{Top}$ of topological spaces with other concepts in category theory?

A: Most certainly. One interesting way is to write the category of spaces as the category of relational algebras for the ultrafilter monad on sets. This is a fancy way of saying that a space is the data of a set together with the choice of a set of limit points for every ultrafilter on that set, such that principal ultrafilters converge to the point they're based at and there's a compatibility with the composition of ultrafilters on the set of ultrafilters.


text:
Q: Squid Same IP in two different ACL's? If we set new acl with name 'ips_with_no_bandwidth_limit' file & it contain list of ips where we would not apply bandwidth limit. So can we write as follows ?

acl ips_with_bandwidth_limit_x_bytes src 10.5.1.1-10.5.1.255/32
acl ips_with_no_bandwidth_limit src "/etc/squid/ips_with_no_bandwidth_limit"
delay_pools 1
delay_class 1 1
delay_parameters 1 32000/32000
delay_access 1 allow ips_with_bandwidth_limit_x_bytes
delay_access 1 deny ips_with_no_bandwidth_limit
delay_access 1 deny all

Is the above will work? If ips_with_no_bandwidth_limit file contain the some of ips from mentioned ip range?
Thanks


text:
Q: Average Proofs, where $n\ge 2$ is greater than the average of real numbers Prove that at least one of the real numbers $a_1; a_2;... a_n,$ where $n \ge 2$, is
greater than or equal to the average of these numbers.
I'm stuck on how I am supposed to prove this. Honestly proofs are my worst skill in all of my math classes.

A: Suppose that all $a_i$ are less than the average, which we'll call $a$, so $a_i<a$. Then
$$
a=\frac1n\sum_{i=1}^n a_i<\frac1n\sum_{i=1}^n a=a.
$$
This is a contradiction.

A: Without loss of generality, we can suppose that $a_1\le a_2\le\dots\le a_n$ (if not, we can just reindex them). If they are all less than the average, then in particular,$$a_n<\frac1n\sum_{k=1}^na_k\le\frac1n\sum_{k=1}^na_n=\frac{na_n}n=a_n.$$


text:
Q: Simple Form for - Nested Resources paths I'm trying to make an app in Rails 5 for post answer to the task.
The Task content and the answer form in the same page.
When the user come into the task page, he can see the task content.
And he can post(create) an answer or edit the answer.
I get an error:

NoMethodError in Tasks#show
  undefined method `to_key' for #
  Did you mean?  to_query
               to_set
               to_ary

What am I doing wrong?
What else information do you need that can help debug this issue?
I'd really apprieciate any help!

Models
```
# task.rb

class Task < ApplicationRecord
 belongs_to :post
 has_many :answers, dependent: :destroy

end
# answer.rb
class Answer < ApplicationRecord
 belongs_to :task
 belongs_to :user
end

```
routes.rb
```
resources :tasks, only: [:show] do
 resources :answers #, only: [:new, :create, :edit, :update]

end
```
Controllers
```
# tasks_controller.rb

class TasksController < ApplicationController
  before_action :authenticate_user!, only: [:show]

  def show
    @task = Task.find(params[:id])
    @post = @task.post

    if @task.answers.present?
      @answer = Answer.where("task_id = ? and user_id = ?", @task.id, current_user.id)
    else
      @answer = Answer.new
    end
  end

 end

# answers_controller.rb

def new
  @task = Task.find(params[:task_id])
  @answer = Answer.new
end

def create
  @task = Task.find(params[:task_id])
  @answer = Answer.new(answer_params)
  @answer.task_id = @task.id
  @answer.user_id = current_user.id

  if @answer.save
    redirect_to post_path(@task.post), notice: "Answer Added."
  else
    render :new
  end

end
```
Views
```
<div class="answer-form">

<%= simple_form_for [@task, @answer], :url => task_answer_path(@task, @answer), method: :put  do |f| %>
  <% if @task.answers.present? %>
   <%= f.input :content, id: "x", value: @task.answers.first.content,
               input_html: {class: "hidden"}, name: "content", label: false %>
   <trix-editor input="x" class="formatted_content trix-content"></trix-editor>

   <div class="form-actions">
     <%= f.submit "Submitting", class: "assignment-btn", data: {disable_with: "Submitting..."} %>
   </div>
<% end %>

<% else %>

   <%= simple_form_for [@task, @answer], :url => task_answers_path(@task), method: :post do |f| %>
                <%= f.input :content, id: "x", value: "content",
                            input_html: {class: "hidden"}, name: "content", label: false %>
                <trix-editor input="x" class="formatted_content trix-content"></trix-editor>

                <div class="file-upload-block">
                    <input name="fileToUpload[]" id="fileToUpload" type="file">
                </div>

                <div class="form-actions">
                  <%= f.submit "提交", class: "assignment-btn", data: {disable_with: "Submitting..."} %>
                </div>
               <% end %>

<% end %>
</div>

```

A: I know what may be wrong, the line below was returning an ActiveRecord::Relation, not the instance itself, you need to append 'first' in the end of the answer query, like such:
 @answer = Answer.where(task: @task, user: current_user).first


text:
Q: simple php countdown with javascript reload I would like this countdown to start at 10 then count down to 1, but for the user to see it in real time - this script waits 50 seconds and then shows me all the numbers (1-10). What am I doing wrong here?

Countdown

<?php
for($i = 10; $i >= 1; $i--) {
   echo $i;
   sleep(5);
};
?>

I tried the above example


text:
Q: Unexpected JQuery behaviour when accessing dynamically generated elements by class I have the following JQuery code that dynamically generates some checkboxes:
var container = $('#checkbox_list_container');
var html = '<input type="checkbox" class="selection_checkboxes" name="ids[]" value="1" />';
container.append($(html));

I also have the following code that pops up an alert when any of these checkboxes are clicked:
$(document).ready(function() {
 $('.selection_checkboxes').click(function() {

   alert('click detected');

   if ($(this).attr('checked'))
   {
     if ($('.selection_checkboxes:checked').size() > 3)
     {
       alert('You can only select up to 3 items');
       return false;
     }
   }
 });
});

For some reason, JQuery is unable to detect when any of the dynamically generated checkboxes have been clicked on and display the alert('click detected') message, let alone get a count of all the checked checkboxes with the same class name.
Any idea what I'm doing wrong?

A: You need to use jQuery's live to attach handlers to dynamically created elements:
$('.selection_checkboxes').live('click', function() {
    //stuff
});

If all your checkboxes are in #checkbox_list_container, then delegate is more efficient:
$('#checkbox_list_container').delegate('.selection_checkboxes', 'click', function() {
    //stuff
});

*

*http://api.jquery.com/live/

*http://api.jquery.com/delegate/


text:
Q: I need a wait command in VB hello am writing a code in VB to send commands to cygwin terminal and i want the code to wait for the first command to wait untill the first command is excuted (or wait about 2 min) and then continue to the next command, the a part of the code:
Shell("C:\cygwin\bin\mintty.exe")
SendKeys.Send("tracert -h  " & _h & " " & domain.Text & " > temp1.txt{ENTER}")

the program should wait 2 min here and then continue to the next command, thanks.

A: Try this:
System.Threading.Thread.Sleep(120000)

The value is in millseconds.

A: You need to add:
Wscript.Sleep 120000


text:
Q: Bash: search up a directory tree I have a source code tree whose root is at something like /home/me/workspace.  There are many subdirectories many levels deep.  In particular there is a path containing some tools:
/home/me/workspace/tools/scripts

I am writing a bash function which I can call from any place in the tree to which I pass the string tools/scripts.  The function should iterate its way from the present working directory to / looking for path fragment tools/scripts, then if it finds it, print out the absolute path in which it is found.  In this example, /home/me/workspace would be printed.  If the path fragment is not found at all, then nothing is printed.
I already have the following bash function which does this for me:
search_up ()
(
    while [ $PWD != "/" ]; do
        if [ -e "$1" ]; then
            pwd
            break
        fi
        cd ..
    done
)

but this seems a bit long-winded.  I am wondering if there are any other ways to do this either in bash itself, or in perhaps a single find command, or any other common utility.  I'm particularly looking for readability and brevity.
Note I am not looking for a full recursive search of the entire tree.
Also my bash is not the latest, so please no tricks using the latest, greatest:
$ bash --version
GNU bash, version 3.00.15(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2004 Free Software Foundation, Inc.
$

A: This should work but tell me if it needs compatibility with POSIX. The advantage of this is that you don't need to change your directory to higher level just to make the search, and also no need to use a subshell.
#!/bin/bash

search_up() {
    local look=${PWD%/}

    while [[ -n $look ]]; do
        [[ -e $look/$1 ]] && {
            printf '%s\n' "$look"
            return
        }

        look=${look%/*}
    done

    [[ -e /$1 ]] && echo /
}

search_up "$1"

Example:
bash script.sh /usr/local/bin

Output:
/

A: For the record, here is what I ended up using:
while [ $PWD != "/" ]; do test -e tools/bin && { pwd; break; }; cd .. ; done

Similar to my OP, but in the end I was able to drop the subshell parentheses () completely, because this line is itself invoked using the "shell" command from another program.  Hence also stuffing it all onto one line.
I still liked KonsoleBox's well-reasoned answer as a possibly more general solution, so I'm accepting that.


text:
Q: Simple but safe password hashing I'm looking for a simple (or as simple as possible) yet secure method for hashing and salting a users password when submitting it to the database and then retrieving from the database. Having spent the past 3 hours researching, there are literally hundreds of different methods that each person will say is the best method.
I'm looking for a relatively simple method that will also keep users accounts secure. Obviously the term secure can be interpreted differently, but i just want it, at the very least, be very difficult for a would-be hacker (or whatever you'd call these saddo's) to gain access to a users account.
I appreciate that i should have at least tried a few things, but they all seem so convoluted and overly secure for my purpose.
I tried using password_hash() but it appears i'm running an earlier PHP version than 5.5. I understand there are issues with the code below, but it's simply a starting point for a person project i'm working on in order to better learn PHP.
Current registration form
$username = $_POST['username'];
$password = $_POST['password'];

try {

    $result = $db->prepare("INSERT INTO
                            user_info
                            SET
                            username = :user,
                            pass = :pass
                            ");
    $result->bindParam(':user', $username);
    $result->bindParam(':pass', $password);
    $result->execute();
}

catch (Exception $e) {
    echo "Could not create username";
}

if (isset($_POST['submit'])) {
    foreach ($_POST as $field) {
        if (empty($field)) {
            $fail = true;
        }
        else {
            $continue = false;
        }
    }
    if ($field == $fail) {
        echo "You must enter a username and/or password";
    }
    else {
        echo "Your account has been successfully created.";
    }
     }

The login logic
$username = $_POST['username'];
$password = $_POST['password'];

try {

    $result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
    $result->bindParam(':user', $username);
    $result->bindParam(':pass', $password);
    $result->execute();
    $rows = $result->fetch(PDO::FETCH_NUM);
}

catch (Exception $e) {
    echo "Could not retrieve data from database";
    exit();
}

if ($password = $rows) {
    session_start();
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['loggedin'] = true;
    include("inc/redirect.php");

} else {
    if (isset($_POST['login'])) {
        echo "Username or password incorrect (passwords are case sensitive)";
    }
}

A: Use sha1 function http://www.php.net/manual/en/function.sha1.php
It's really simple. Pass the password in input parameter then save it in the database.
When you want to check if password is correct you just have to compare the sha1(password) with the stored value.
Example :
$passwordEncrypted = sha1($password)

save $passwordEncrypted in your database

When the user want to login :
check this condition :
if (sha1($password) ==$passwordEncrypted )
Here is the complete code :
$username = $_POST['username'];

$password = $_POST['password'];
$passwordEncrypted = sha1($password)

    try {

        $result = $db->prepare("INSERT INTO
                                user_info
                                SET
                                username = :user,
                                pass = :pass
                                ");
        $result->bindParam(':user', $username);
        $result->bindParam(':pass', $passwordEncrypted);
        $result->execute();
    }

    catch (Exception $e) {
        echo "Could not create username";
    }

    if (isset($_POST['submit'])) {
        foreach ($_POST as $field) {
            if (empty($field)) {
                $fail = true;
            }
            else {
                $continue = false;
            }
        }
        if ($field == $fail) {
            echo "You must enter a username and/or password";
        }
        else {
            echo "Your account has been successfully created.";
        }
         }

A: Look at this question:
https://stackoverflow.com/questions/3897434/password-security-sha1-sha256-or-sha512
You can use hash function
http://www.php.net/manual/en/function.hash.php

A: Use salt and sha256 encryption algorithm
<?php
// create user
$password = $_POST['password'];
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$pass = hash("sha256", $salt.$password.$salt);
// save salt and password hash into database

// to validate user
// 1 - get salt and password hash from database
// 2 - prepend and append salt to the posted password
// 3 - encrypt with the same algorithm
// 4 - compare with stored password hash.

A: With password_hash() you are on the right track. For PHP versions 5.3.7 - 5.5 you can use the compatibility pack, later when you switch to a newer PHP version, you can simply remove this php file from your project and the code will still run.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

Even for lower PHP versions than 5.3.7 you can use the compatibility pack. You only have to edit line 55 and change the algorithm from sprintf("$2y$%02d$", $cost); to sprintf("$2a$%02d$", $cost);. This is of course not optimal, but it is the best you can do for PHP between 5.3 and 5.3.7.
The problem with other algorithms like SHA* or MD5 is, that they are ways too fast. It is possible to calculate about 3 Giga SHA-1 per second with common hardware, that makes brute-forcing too easy. To test a whole english dictionary you would need only a fraction of a millisecond. That's why one should use a hash algorithm with a cost factor like BCrypt or PBKDF2, they allow to control the necessary time to calculate a single hash.


text:
Q: What is the minimum value of? On positive reals if $3x+4y+7z=1$ what is the minimum value of $\frac{1}{x}+\frac{1}{y}+\frac{1}{z}?$ I have tried using the arithmetic mean and harmonic mean inequality but I failed. Not good at inequalities though. Please help.

A: By Cauchy-Schwarz
$$(3x+4y+7z)(x^{-1}+y^{-1}+z^{-1})\ge(\sqrt3+\sqrt4+\sqrt7)^2.$$
One can get equality, when the vector $(x,y,z)=t(1/\sqrt3,1/\sqrt4,1/\sqrt7)$ for some $t$. The $t$ in question is $1/(\sqrt3+\sqrt4+\sqrt7)$
and the minimum is $(\sqrt3+\sqrt4+\sqrt7)^2$.

A: From $3x+4y+7z=1$ I got $z= \frac{1}{7} (-3 x-4 y+1)$ and plugged in
$$\frac{1}{x}+\frac{1}{y}+\frac{1}{z}$$
gives $$f(x,y)=\frac{7}{1-3 x-4 y}+\frac{1}{x}+\frac{1}{y}$$
$$f'_x=\frac{21}{(1-3 x-4 y)^2}-\frac{1}{x^2};\;f'_y=\frac{28}{(1-3 x-4 y)^2}-\frac{1}{y^2}$$
$f'_x=0$ gives $21x^2=(1-3x-4y)^2$ and $f_y=0\to 28y^2=(1-3x-4y)^2$
so we have $21x^2=28y^2$ which for positive reals means $y=\frac{\sqrt 3}{2}\,x$
furthermore we have from the first equation
$x\sqrt{21}=1-3x-4y$ which after substituting becomes
$x\sqrt{21}=1-3x-2\sqrt{ 3}x$
$$x=\frac{1}{3+2 \sqrt{3}+\sqrt{21}};\;y=\frac{\sqrt{3}}{2 \left(3+2 \sqrt{3}+\sqrt{21}\right)};\;z=\frac{1}{7+2 \sqrt{7}+\sqrt{21}}$$
So minimum of $\frac{1}{x}+\frac{1}{y}+\frac{1}{z}$ is
$2 \left(7+2 \sqrt{3}+2 \sqrt{7}+\sqrt{21}\right)\approx 40.676$


text:
Q: HTTP.get function synchronously execution in angular I have to call HTTP. get function synchronously so that it will wait until its response didn't come. it should not go to execute next line until below line executes. Where I am wrong please help me out
this.classCheck.checkD().then(present => present ? console.log("Present==true  " + present) : console.log(" Present==false  " + present));

async checkD() {
    let present: boolean = true;
    let status : number;
    const res = await this.http.get(url,{ headers: header, observe:'response'}).toPromise().then( response => {
      console.log(response.status);
      status = response.status;
    });

    if(status >= 400) {
      present = false;
    }
    return present;
  }

A: You need to await on your promise. You or await or .then.
One is synchronous, the other asynchronous.
async checkD() {
    let present: boolean = true;
    let status : number;
    const res = await this.http.get(url,{ headers: header, observe:'response'}).toPromise();
    status = res.status;
    if(status >= 400) {
      present = false;
    }
    return present;
}


text:
Q: C++ Win32 GetWindowText buffer capacity I'm learning to write basic Win32 apps in C++ and am trying to pass typed text from one editable textbox to a new window after pressing a button.

I noticed that the default text buffer capacity for such a transfer is 20 characters in Visual Studio 2019 (I am on 64-bit Windows 10). After I try to pass a string longer than 20 characters, I get an exception thrown.

I would like to know how to increase that buffer capacity, since eventually I want to be able to pass a filepath into the text input window and open that file.
My code:
#include <windows.h>
#include <string>
#include <iostream>

//lresult callback prototype
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//window handles
HWND hMainWindow;
HINSTANCE hMainInstance;

HWND hLblOutput;
HWND hTxtInput;
HWND hButton;

#define IDC_TEXTBOX 1000
#define IDC_BUTTON 1001

//call to winmain - equivalent of main for win32 environments
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    MSG msg = { 0 };
    WNDCLASS wc = { 0 };
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
    wc.lpszClassName = TEXT("NiceWindowsApp");
    if (!RegisterClass(&wc))
        return 1;

    hMainWindow = CreateWindow(wc.lpszClassName, TEXT("My Windows Application"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 640, 480, 0, 0, hInstance, NULL);

    hMainInstance = wc.hInstance;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}
//callback definition
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int offset = 0;
    switch (message) {

    case WM_CREATE:
        hMainWindow = hWnd;
        hTxtInput = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT("Type something here"),
            WS_VISIBLE | WS_CHILD | ES_LEFT, 50, 50, 400, 25, hWnd,
            (HMENU)IDC_TEXTBOX, hMainInstance, NULL);
        hButton = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("BUTTON"), TEXT("Press Me!"), WS_VISIBLE |   WS_CHILD | WM_COPY | ES_LEFT, 500, 30, 100, 60, hWnd,
            (HMENU)IDC_BUTTON, hMainInstance, NULL);
        break;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_BUTTON)
        {

            //CANNOT HANDLE MORE THAN 20 CHARACTERS!!!
            std::string input;
            GetWindowTextA(hTxtInput, reinterpret_cast<char*> ((char*)input.c_str()), 400);

            ++offset;

            hLblOutput = CreateWindowEx(WS_EX_STATICEDGE, TEXT("EDIT"), input.c_str(), WS_VISIBLE | WS_CHILD | ES_READONLY | ES_LEFT, 50, 200 + offset * 26, 800, 25, hWnd,
                (HMENU)IDC_TEXTBOX, hMainInstance, NULL);

        }

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);

    }

    return 0;
}

I have tried to increase the third parameter in GetWindowTextA() to various numbers up to 4000, but it didn't seem to help.

A: One correct way to do this is:
std::wstring text;
text.resize(GetWindowTextLengthW(hTxtInput));
text.resize(GetWindowTextW(hTxtInput, text.data(), text.size() + 1));

A: Solved as per the below:
#include <windows.h>
#include <string>
#include <iostream>

//lresult callback prototype
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//window handles
HWND hMainWindow;
HINSTANCE hMainInstance;

HWND hLblOutput;
HWND hTxtInput;
HWND hButton;

CHAR s_text_1[]{ "Some text.." };
CHAR s_text_2[]{ 0 };

#define IDC_TEXTBOX 1000
#define IDC_BUTTON 1001

//call to winmain - equivalent of main for win32 environments
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{

    MSG msg = { 0 };
    WNDCLASS wc = { 0 };
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
    wc.lpszClassName = TEXT("NiceWindowsApp");
    if (!RegisterClass(&wc))
        return 1;

    hMainWindow = CreateWindow(wc.lpszClassName, TEXT("My Windows Application"), WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        0, 0, 640, 480, 0, 0, hInstance, NULL);

    hMainInstance = wc.hInstance;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}
//callback definition
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int offset = 0;
    switch (message) {

    case WM_CREATE:
        hMainWindow = hWnd;
        hTxtInput = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), s_text_1,
            WS_VISIBLE | WS_CHILD | ES_LEFT, 50, 50, 400, 25, hWnd,
            (HMENU)IDC_TEXTBOX, hMainInstance, NULL);
        hButton = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("BUTTON"), TEXT("Press Me!"), WS_VISIBLE | WS_CHILD | WM_COPY | ES_LEFT, 500, 30, 100, 60, hWnd,
            (HMENU)IDC_BUTTON, hMainInstance, NULL);
        break;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_BUTTON)
        {

            //CANNOT HANDLE MORE THAN 20 CHARACTERS!!!
            std::wstring input;

            //GetWindowTextW(hTxtInput, reinterpret_cast<char*> ((char*)input.c_str()), 400);
            int lgth = GetWindowTextLength(hTxtInput);
            //GetWindowTextW(hTxtInput, reinterpret_cast<wchar_t*> ((wchar_t*)input.c_str()), lgth);
            //GetWindowTextA(hTxtInput, char[], 400);
            GetWindowText(hTxtInput, s_text_1, 255);

            ++offset;

            hLblOutput = CreateWindowEx(WS_EX_STATICEDGE, TEXT("EDIT"), s_text_1, WS_VISIBLE | WS_CHILD | ES_READONLY | ES_LEFT, 50, 200 + offset * 26, 800, 25, hWnd,
                (HMENU)IDC_TEXTBOX, hMainInstance, NULL);
            SetWindowText(hLblOutput, s_text_1);

        }

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);

    }

    return 0;
}

Thanks for your hints everybody.
EDIT: I now realise that this solution is not technically perfect and can lead to undefined behaviour and/or memory leaks. I'll take the advice presented in the other answers and comments into account and adjust the code accordingly.
EDIT 2.0 (2023.02.04): My most recent code is below. Hopefully it's more robust.
#include <windows.h>
#include <string>
#include <iostream>
//last update - 04.02.2023 as per StackOverflow thread recommendations.

//lresult callback prototype
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//window handles
HWND hMainWindow;
HINSTANCE hMainInstance;

HWND hLblOutput;
HWND hTxtInput;
HWND hButton;

CHAR s_text_1[]{ "Some text.." };

#define IDC_TEXTBOX 1000
#define IDC_BUTTON 1001

//call to winmain - equivalent of main for win32 environments
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{

    MSG msg = { 0 };
    WNDCLASS wc = { 0 };
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
    wc.lpszClassName = TEXT("NiceWindowsApp");
    if (!RegisterClass(&wc))
        return 1;

    hMainWindow = CreateWindow(wc.lpszClassName, TEXT("My Windows Application"), WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        0, 0, 640, 480, 0, 0, hInstance, NULL);

    hMainInstance = wc.hInstance;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}
//callback definition
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int offset = 0;
    switch (message) {

    case WM_CREATE:
        hMainWindow = hWnd;
        hTxtInput = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), s_text_1,
            WS_VISIBLE | WS_CHILD | ES_LEFT, 50, 50, 400, 25, hWnd,
            (HMENU)IDC_TEXTBOX, hMainInstance, NULL);
        hButton = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("BUTTON"), TEXT("Press Me!"), WS_VISIBLE | WS_CHILD | WM_COPY | ES_LEFT, 500, 30, 100, 60, hWnd,
            (HMENU)IDC_BUTTON, hMainInstance, NULL);
        break;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_BUTTON)
        {

            std::wstring input;

            //resize added as suggested

            input.resize(GetWindowTextLengthW(hTxtInput));
            GetWindowTextW(hTxtInput, input.data(), input.size() + 1);

            ++offset;

            hLblOutput = CreateWindowEx(WS_EX_STATICEDGE, TEXT("EDIT"), s_text_1, WS_VISIBLE | WS_CHILD | ES_READONLY | ES_LEFT, 50, 200 + offset * 26, 800, 25, hWnd,
                (HMENU)IDC_TEXTBOX, hMainInstance, NULL);
            SetWindowTextW(hLblOutput, input.data());

        }

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);

    }

    return 0;
}


text:
Q: Delphi tidhttp encoding special characters I have upgraded an app from D2007 to XE6. It posts data to a webserver.
I cannot work out what encoding will send the left and right quote characters correctly (code snippet below). I have tried every option I can find, but they get encoded as ? when sent (as far as I can see in WireShark).
D2007 had no problem, but XE6 is all about Unicode, and I am not sure if the problem is encoding or codepages or what.
  Params := TIdMultipartFormDataStream.Create;
  params.AddFormField('TEST', 'Test 'n' Try', 'utf8').ContentTransfer := '8bit';
  IdHTTP1.Request.ContentType := 'text/plain';
  IdHTTP1.Request.Charset := 'utf-8';
  IdHTTP1.Post('http://test.com.au/TestEncoding.php', Params, Stream);

A: When calling params.AddFormField(), you are setting the charset to 'utf8', which is not a valid charset name.  The official charset name is 'utf-8' instead:
params.AddFormField('TEST', 'Test 'n' Try', 'utf-8').ContentTransfer := '8bit';

When compiling for Unicode, an invalid charset ends up using Indy's built-in 8bit encoder, which encodes Unicode codepages > U+00FF as byte 0x3F ('?').  The quote characters you are using, ' and ', are codepoints U+2018 and U+2019, respectively.
The reason you do not encounter this issue in D2007 is because the TIdFormDataField.Charset property is ignored for encoding purposes when compiling for Ansi. The TIdFormDataField.FieldValue property is an AnsiString, and its raw bytes get transmitted as-is, so you are required to ensure it is encoded properly before adding it to TIdMultipartFormDataStream, eg:
params.AddFormField('TEST', UTF8Encode('Test 'n' Try'), 'utf-8').ContentTransfer := '8bit';

On a side note, you do not need to set the Request.ContentType or Request.Charset properties when posting a TIdMultipartFormDataStream (and especially since 'text/plain' is an invalid content type for a MIME post anyway).  This version of Post() will set those properties for you:
Params := TIdMultipartFormDataStream.Create;
params.AddFormField(...);
IdHTTP1.Post('http://test.com.au/TestEncoding.php', Params, Stream);


text:
Q: Log files get truncated with TimedRotatingFileHandler and Django I have log handlers configured to rotate at midnight:
'request_handler': {
        'level': 'DEBUG',
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'when': 'midnight',
        'interval': 1,
        'filename':  os.path.join(LOG_ROOT, 'django_request.log'),
        'backupCount': 30,
        'formatter': 'standard',
        },

Also have cron job to archive/purge logs with command, which runs at 01:00 every day (crontab -e -> "0 1 * * * /cronscripts/archive_logs.sh"):
gzip --quiet *\.log\.[0-9]*
find $LOGS_DIR -mtime +$LOGS_KEEP_DAYS -exec rm {} \;

With that configuration log files get truncated by some reason, here description:

*

*Rotated log django_request.log.2014-09-30 will have records from 00:00 to ~2:30 (the end time can vary a bit)

*Meanwhile django_request.log before rotation has records after 02:30

*django_request.log.2014-09-30 file has records dated 1-th of Oct instead of 30-th of Sep

Example:
alex@localhost$ tail django_request.log.2014-09-30
2014-10-01 02:02:48,562 [WARNING] django.request: Not Found: /admin_media/i...

Are there any ideas what's wrong? Django is running with apache/mod_wsgi.


text:
Q: AllureRestAssured , how to ignore logging headers I am using rest-assured and allureRestAssured for testing api ,
given().header("Content-Type", "application/json")
                .header("key", key()).filter(new AllureRestAssured())
                .body(body.toString())
                .post(baseURI);

Problem here is its logged headers also , which contains auth key , which I dont want to be exposed in report generated , how can I ignore that .

A: You can extend the AllureRestAssured filter and override it. There is the private method toMapConverter I add it to my implementation. I just remove by Key what I don't want to show in the report.
    private static Map<String, String> toMapConverter(final Iterable<? extends NameAndValue> items) {
    final Map<String, String> result = new HashMap<>();
    items.forEach(h -> result.put(h.getName(), h.getValue()));
    result.remove("key");
    return result;
}


text:
Q: Excerpt text P tag open issue Text length limited, shows the whole contents after clicking. But if someone could check the code, the first P tag opens fine, but from the 2nd one, it doesn't open completely.
$(document).ready(function(){
function excerpt(text, len) {
    return text.substring(0, len)+"…";
}

var $div = $('.container');
$div.each(function() {
  var $p=$(this).find("p:first");
   var theExcerpt = excerpt($p.text(), 230);
    $p.data('html', $p.html()).html( theExcerpt);
});

$('span').click(function() {
    var isHidden = $(this).text() == 'Show';
   var $p = $(this).parent().find("p:first");
    var theExcerpt = excerpt($p.text(), 230);
    $p.html( isHidden ? $p.data('html') : theExcerpt);
    $(this).remove();
});

});

Online sample here.
If I have return text.substring(0, len)+"…" + show;
http://jsfiddle.net/M6wzh/3/
Many thanks.

A: You can fix this just by altering the HTML: the Shows need to be inside the 'container' divs. http://jsfiddle.net/M6wzh/1/
(The jquery code finds the first paragraph within the same parent element as the Show and expands it. Since none of the Shows were inside container elements, it simply found the first paragraph on the page and expanded that.)


text:
Q: is it possible to return both Values on a hashtable in a single variable? I have the following Hashtable in powershell:
$hash = @{"server" = "ou"; "server1" = "ou1"}

I use this to authenticate users against two ad servers and it works fine. I use a "foreach" loop to verify each user against both servers. I can return the right value if the user exists in just one server, but I do not know how to make it return both values if the user exits in both servers. Can anyone help?
foreach($user in $csv.GetEnumerator())
{
  foreach($server in $hash.Keys)
}


text:
Q: Order of elements in free $\mathbb{Z}$ module In Dummit and Foote, the authors state that "Free $\mathbb{Z}$-modules have no nonzero elements of finite order."
Why is this true? If $M$ is a free $\mathbb{Z}$-module, then for any $x\in M$, there exists a subset $A\subseteq M$, unique nonzero elements $a_1,...,a_n\in A$ and unique $z_1,.,,,.z_n\in\mathbb{Z}$ such that $x=z_1a_1+\cdots +z_na_n$. Why does this imply that $x$ has infinite order assuming $x$ is nonzero?

A: I am assuming that the set $A$ you refer to is the basis of the module $M$. Since $x$ is nonzero, you may assume without loss of generality that $z_1\ne0$. Let $n\in\Bbb N$ satisfy $nx=0$, then
$$
0\cdot a_1 +\cdots + 0\cdot z_n = 0 = nx = nz_1\cdot a_1 +\cdots + nz_n\cdot a_n.
$$
This implies $nz_1=0$ because of the uniqueness of this expression and because $z_1\ne0$ we can conclude that $n=0$. Hence, there is no positive $n$ that annihilates $x$, which means that $x$ has infinite order.


text:
Q: How to do Partition in Pig? I am learning HADOOP for last 1 months.
I am using Partition in hive table.
How to do Partition in Pig?
It would be very useful for my assessment if any one says the answer.
Thanks,
Anbu K.

A: Hcatalog provides metadata and table management layer for hadoop.
It allows Hadoop users—whether they use MapReduce, Pig, Hive, or other tools—to view their data in HDFS as if it were in tables. These tables are partitioned and have consistent schemas.
Pig can work with HCatalog's partitioning. If you place the filter statement that describes which partitions you want to read immediately after the load, Pig will push that into the load so that HCatalog returns only the relevant partitions.
 /* myscript.pig */
    A = LOAD 'tablename' USING org.apache.hcatalog.pig.HCatLoader();
    -- date is a partition column; age is not
    B = filter A by date == '20100819' and age < 30;
    -- both date and country are partition columns
    C = filter A by date == '20100819' and country == 'US';


text:
Q: Flutter - Sliver Layout horizontal scroll inside Sliver List I try to make horizontal scrollable list inside Sliver List (CustomScrollview - SliverList)
This is my Code:
import 'package:flutter/material.dart';
class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
   return Scaffold(
    body: CustomScrollView(
        slivers: <Widget>[
        DetailAppBar(),
        SliverPadding(
          padding: EdgeInsets.all(16.0),
          sliver: SliverList(
            delegate: SliverChildListDelegate(
              [
                Card(child: Text('data'),),
                Card(child: Text('data'),),
                Card(child: Text('data'),),
                Card(child: Text('data'),),

                // Scrollable horizontal widget here
              ],
            ),
          ),
        ),
      ],
    ),
    bottomNavigationBar: NavigationButton());

 }

}

Can you give me example or solution to this case? i really need some help.

A: Use a ListView inside of a SliverToBoxAdapter.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverPadding(
            padding: EdgeInsets.all(16.0),
            sliver: SliverList(
              delegate: SliverChildListDelegate(
                [
                  Card(
                    child: Text('data'),
                  ),
                  Card(
                    child: Text('data'),
                  ),
                  Card(
                    child: Text('data'),
                  ),
                  Card(
                    child: Text('data'),
                  ),
                ],
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              height: 100.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: 10,
                itemBuilder: (context, index) {
                  return Container(
                    width: 100.0,
                    child: Card(
                      child: Text('data'),
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

A: the other solution doesn't work for me as it gives error when I use a ListView
here is a class I wrote called HorizontalSliverList which does the job nice and easy
here is the class you need to copy:
class HorizontalSliverList extends StatelessWidget {
  final List<Widget> children;
  final EdgeInsets listPadding;
  final Widget divider;

  const HorizontalSliverList({
    Key key,
    @required this.children,
    this.listPadding = const EdgeInsets.all(8),
    this.divider,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Padding(
          padding: listPadding,
          child: Row(children: [
            for (var i = 0; i < children.length; i++) ...[
              children[i],
              if (i != children.length - 1) addDivider(),
            ],
          ]),
        ),
      ),
    );
  }

  Widget addDivider() => divider ?? Padding(padding: const EdgeInsets.symmetric(horizontal: 8));
}


text:
Q: class declaration with generics java class a{}
class b extends a{}
class c <? extends b> extends b{}
public class d {
      public static void main(String[] args) {
        c<c> n = new c<c>();
      }
}

I am reading SCJP. I didn't get the concept of generic class with class<?> and class<? extends anything>.....if it means we can pass any class which extends "anything" then why above code is not working?
Please explain this , its very confusing
Regards

A: It makes no sense to declare a class with a type parameter without ever referring to that parameter. Therefore it is not foreseen to declare such a class. You have to give the type parameter a name.
Change
class c <? extends b> extends b{}

to
class c <T extends b> extends b{}

Within the class c you can now refer to the type parameter T, e.g. to declare methods and variables.

A: You didn't give the exact error message, but I guess it's about that you can't use wild cards when you define the type parameters.
Try:
class c <T extends b> extends b{}

Note: It's a convention to start class names with a capital letter, so use:
class C <T extends B> extends B{}


text:
Q: Fabric-sdk-go 'ld.exe: cannot find -lltdl' error When I try to get the fabric-sdk-go I get the following error:
$ go get github.com/hyperledger/fabric-sdk-go/pkg/fabric-client
# github.com/hyperledger/fabric-sdk-go/vendor/github.com/miekg/pkcs11
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/6.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lltdl
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/6.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lltdl
collect2.exe: error: ld returned 1 exit status

Does anyone have an idea what is the issue and how to resolve this?

A: The error message told us that the library libltdl which is required by github.com/miekg/pkcs11 is missing. Although you didn't mention it explicitly, I think you're using MSYS2 as the development environment. Do the following steps to install the missing library.

*

*Search for the missing library, type pacman -Ss ltdl in MSYS2 terminal to get the exact package name. Here, ltdl is the keyword related to missing library which we got from error message. You should get something like:
msys/libltdl 2.4.6-2
    A system independent dlopen wrapper for GNU libtool

From the result we know that the missing library is provided in libltdl package. It seems trivial, but sometimes a library may be provided by more than one package, e.g. a package which has prefix mingw-w64-i686-* for 32-bit system and the other with prefix mingw-w64-x86_64-* for 64-bit system.

*Install the package by: pacman -S libltdl.

*Reinstall the go package by: go get -v github.com/hyperledger/fabric-sdk-go/pkg/fabric-client.


text:
Q: Given an array of positive integers. Divide it into 2 arrays where avg of each array is same Example:
[1,2,4,5] output would be [1,5] and [2,4]
So here is what I tried but code breaks at one point need help with decision making at that point.From below code if(avgArr1 < avgArr2){ is the point where I decide which needs to be the source array which needs to be destination array for inserting and deleting elements. This condition is not reliable and empties one of the array.
package test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

public class ArrayAvg {
    static int[] arr1;
    static int[] arr2;
    public Map<String,int[]> swap(int[] src,int[] dest,int num,boolean swapLeft){
        Map<String,int[]> arrMap = new HashMap<String,int[]>();
        System.out.println("num"+num);
        ///System.out.println(Arrays.toString(src));
        ///System.out.println(Arrays.toString(dest));
        int[] tempL;
        int[] tempR;
        int myNumber = num;
        int distance = Math.abs(src[0] - myNumber);
        int idx = 0;
        for(int c = 1; c < src.length; c++){
            int cdistance = Math.abs(src[c] - myNumber);
            if(cdistance < distance){
                idx = c;
                distance = cdistance;
            }
        }
        int theNumber = src[idx];
        System.out.println("the num"+theNumber);
        if(swapLeft){
            tempL= new int[dest.length+1];
            tempR= new int[src.length-1];
            tempR = Arrays.stream( src ).filter( value -> value != theNumber ).toArray();
            //System.out.println(Arrays.toString(tempR));
            tempL = Arrays.copyOf(dest, dest.length+1);//Range(dest, 0, src.length);
            tempL[tempL.length-1] = theNumber;
            //*/System.arraycopy(dest, 0, tempL, 1, 2);*/
            //System.out.println(tempL.length+1);
            //System.out.println(Arrays.toString(tempL));
            arr1 = tempL;
            arr2 = tempR;
        }else{
            tempL= new int[src.length-1];
            tempR= new int[dest.length+1];
            tempR = Arrays.stream( src ).filter( value -> value != theNumber ).toArray();
            tempL = Arrays.copyOfRange(dest, 0, src.length);
            tempL[tempL.length-1] = num;
            arr1 = tempR;
            arr2 = tempL;
        }
        /*dest = tempL;
        src = tempR;*/
        arrMap.put("arr1", arr1);
        arrMap.put("arr2", arr2);
        //System.out.println(Arrays.toString(tempL));
        //System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
        //System.arraycopy(temp, 0, dest, 0, temp.length);
        return  arrMap;
    }
    public void printArr(int[] arr,int[] arr1,int[] arr2){
        Arrays.sort(arr1);
        Arrays.sort(arr2);

        double avgArr1 = IntStream.of(arr1).sum()/arr1.length;
        double avgArr2 = IntStream.of(arr2).sum()/arr2.length;
        while(avgArr1 != avgArr2){
            int arrAvg = (int) (avgArr1 + avgArr2)/2;
            int nearestValue = (arrAvg/2);
            System.out.println(arrAvg);
            Map<String,int[]> res;
            if(avgArr1 < avgArr2){
                res = swap(arr2,arr1,nearestValue,true);
            }else{
                res = swap(arr1,arr2,nearestValue,false);
            }
            arr1 = res.get("arr1");
            arr2 = res.get("arr2");
            avgArr1 = IntStream.of(arr1).sum()/arr1.length;
            avgArr2 = IntStream.of(arr2).sum()/arr2.length;
            Arrays.sort(arr1);
            Arrays.sort(arr2);
        }
        //System.out.println(Arrays.toString(arr1));
        //System.out.println(Arrays.toString(arr2));
    }
    public static void main(String args[]){
        int [] intarr = {1,2,5,4};
        Arrays.sort(intarr);
        //ArrayAvg.printArr(intarr);
        arr1 = Arrays.copyOfRange(intarr, 0, intarr.length/2);
        //System.out.println(Arrays.toString(arr));
        arr2 = Arrays.copyOfRange(intarr, (intarr.length/2), intarr.length);
        new ArrayAvg().printArr(intarr,arr1,arr2);
        //System.out.println(intarr);
    }
}

A: This problem might be solved with dynamic programming. Make a table with size OverallSum. Fill it with all possible subsets sums, recording also number of items and the last item used to make every sum.
Let average of whole array is A = P/Q(rational value, GCD(P,Q)=1). Now check whether sums P, 2P, 3P... kP  might be created from Q, 2Q, 3Q...kQ items. If yes, unwind sum to get items composing this sum
For example  [1, 2, 5, 6]  A = 3.5 = 7/2 so check if sum 7 might be composed from two items

A: If you are only interested in solutions where the average in both parts is identical, that means both parts must have either (1) only the target average as a member(s) or (2) both a set of lower than average and a set of higher than average numbers.
Furthermore, if
a / b = c / d

then
a / b = (a + c) / (b + d)

So what you are looking for is a partition, where each part's sum is a multiple of the average of the whole list. We can divide and conquer to at least split our subset sum search to those made from either exclusively elements smaller than or exclusively elements greater than the average of the whole list.
Let A be the average of the whole list. If there are any elements in the list equal to A, splitting off any number of these into one part would constitute a valid solution.
Otherwise, let sh and sl be the sum of a subset of elements all higher than A and the sum of a subset of elements all less than A, respectively; and kh and kl these subsets' respective cardinalities. Then:
(sh + sl) / (kh + kl) = A

So given any sum and cardinality for a subset of elements lower than A, (sl, kl), a matching tuple of elements higher than A would have to equal a constant:
sh = A * (kh + kl) - sl

sh - A * kh = A * kl - sl

We can store and look up sh - A * kh (and similarly for the lower tuples).
Example:
[1,2,4,5]
A = 3

Either of [1,5] or [2,4] would inform us that a solution exists. We only need to find one of them.
sh - A * kh  =  A * kl - sl

5  - 3 * 1   =  3 * 1  - 1
4  - 3 * 1   =  3 * 1  - 2


text:
Q: does querying mysql by using function takes more time to load? I was wondering if using function to query specific row from a table each time the function is being called will be less sufficient than just querying once by a normal mysql query.
here's a clearer picture of what I mean.
function userinfo($table, $row, $data, $where){
global $db;
$users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
$users_row = $db->fetch_assoc($users_sql);
return $users_row[$row];
}

echo userinfo('users', 'firstname', $_SESSION['username'],'username');
echo userinfo('users', 'avatar', $_SESSION['username'],'username');

or just doing this without a function
$users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
$users_row = $db->fetch_assoc($users_sql);
echo $users_row['firstname'];
echo $users_row['avatar'];

I'm guessing the second way will be better, but I just gotta double check.

A: Change the first to:
function userinfo($table, $row, $data, $where){
    global $db;
    $users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
    $users_row = $db->fetch_assoc($users_sql);
    return $users_row;
}
$row = userinfo('users', 'firstname, avatar', $_SESSION['username'],'username');
echo $row['firstname'];
echo $row['avatar'];

will make it more meaningful and avoid an additional database query; but your second "without a function" equivalent isn't equivalent at all because you're assuming that $users_row will return both firstname and avatar, while your first example doesn't (unless you use the logic I've shown above)
Even more generic would be
function userinfo($table, $data, $where){
    global $db;
    $users_sql = $db->query("SELECT * FROM $table WHERE $where = '$data'");
    $users_row = $db->fetch_assoc($users_sql);
    return $users_row;
}
$row = userinfo('users', $_SESSION['username'],'username');
echo $row['firstname'];
echo $row['avatar'];

But your approach to this isn't good; you really should be using prepared statements and bind variables; and building your queries accordingly


text:
Q: Scale9Grid doesn't work in MovieClip I have a couple of MovieClips in swf files loaded with Loader.loadBytes. They are 10-th version, as3-enabled and have scale9Grid defined (I can see the tag DefineScaleGrid in them with SWiX). But when loaded, loader.content has scale9Grid == null (maybe it is normal?) and scaling is not 9-slice. I can't even set scale9Grid myself - any attempt is met with exception "One of the parameters is invalid". How to make 9-slice grid work?

A: I finally found this article to explain it all. So, in short, scale9Grid works only on DisplayObjects without children. I dug down to Shape in my clip and managed to set that grid.


text:
Q: I want to write log file for AngularJS project. How can I do it? I tried this method :

var fs = require("fs");
//or try
//var fs = require("file-system");
var cont = " selamm \n";
fs.writeFileSync("read2.txt", cont, { flag: 'a' },
    err => {

    });

Not working for Angular JS project.
System err : "fs is not a function".
System err "fs.existsSync is not a function" if I try "file system" library.
What alternatives can I use? Help?


text:
Q: Резервное копирование СУБД PostgreSQL Есть сервер (linux suse) на котором установлена СУБД PostgreSQL, подключиться к БД возможно только с использованием ssh. Возникла необходимость автоматического резервного копирования базы данных на другой удаленный сервер (linux centOS). Каким образом лучше всего организовать автоматическое копирование?

A: В вопросе бекапа potgresql есть две принципиальные возможности:
Логический бекап
Штатными утилитами pg_dump и pg_dumpall. Логический бекап - это текст запросов, которые воссоздадут вашу базу данных. Из чего следует, что это:

*

*медленное восстановление. Данные будут скопированы довольно быстро, но вот индексы и прочие ограничения будут строиться ничего не зная о том что это бекап и будут проверять действительность ограничений

*восстановление возможно только на момент начала копирования каждой из баз через pg_dump (pg_dumpall вызывает pg_dump для каждой из баз кластера)

*компактно. Обычно заметную часть объёма базы данных занимают индексы. Которые в логическом дампе представлены только командами создания этих индексов. А так же текст хорошо сжимается. Поэтому логический дамп может быть спокойно в 10 раз меньше объёма базы

*можно сохранять только некоторые базы данных, можно не сохранять некоторые таблицы

*текстовый формат plain - просто текст запросов, из него данные можно достать хоть текстовым редактором.

*форматы custom и directory с другой стороны можно восстанавливать параллельно в несколько потоков (а directory и снимать в несколько потоков) - что позволяет сократить время восстановления. А так же из этих форматов можно восстанавливать отдельные объекты базы, например, только одну таблицу.

pg_dump и pg_dumpall могут работать по сети. Единственное что необходимо - версия утилиты на бекап-машине должна быть такая же или новее чем на самой СУБД. При том нет ограничения по major версии. pg_dump версии 11.4 может корректно снимать бекап с версии условно 9.3.12 (и вообще до 7.0 релиза)
Восстанавливать можно так же на разный версиях postgresql.
Физический бекап
Другая возможность - использовать физическую копию базы. pg_basebackup либо другие её реализации.

*

*есть возможность выбрать момент, на который восстанавливать базу с точностью до конкретной транзакции. Для этого необходим basebackup снятый до необходимой точки восстановления и непрерывный архив WAL

*такой бекап занимает много места. Если заинтересованы в восстановлении на произвольную точку времени (PitR) - то архив WAL тем более занимает сложно предсказуемый объём

*это копия только всего экземпляра postgresql. Строго все базы с этого экземпляра, ничего исключить нельзя. И объём точно равный объёму базы.

*восстановление представляет собой простое файловое копирование и затем запуск базы. По объёму данных копировать много, но операция простая, в большинстве своём крупными файлами

*однако восстановление в произвольный момент времени требует обработать все WAL от начала basebackup до необходимой точки. И это может быть весьма не быстро

*восстановление возможно только используя ту же самую major версию базы и не ниже того же самого minor релиза

Работать так же может по сети без проблем. Вообще помимо бекапов так ещё реплики поднимают.

Затем владелец базы думает, необходимо ли ему восстановление в произвольную точку времени и готов ли он к такому большому объёму данных в бекапе либо достаточно например ежесуточных логических дампов. Затем определяетесь сколько копий хранить.
Можно использовать оба подхода, например, делать архив WAL глубиной в неделю со снятием basebackup в понедельник/четверг, в субботу делать pg_dump и хранить логический дамп ещё полгода.
Непосредственно по настройке выбранного плана резервного копирования:

*

*pg_dump обычно удобно делать просто из крона с отправкой оповещения о ошибках на почту.

*для basebackup вручную собирать корректную процедуру ведения архива не так просто, имеет смысл использовать специализированные системы вроде wal-g (крайне прост, если бекапить надо на S3), pgbackrest, barman


text:
Q: Tapestry5 @Persist default value I have a page with a form, which uses @Persist fields for the form controls (text boxes, radio buttons, etc), so that if the form is submitted the data is retained in the form if custom validation fails.
From the docs, "Fields marked with @Persist may not have default values (whether set inline, or inside a constructor)". However, I need to set default values for some form elements (including some @Validate("required") select boxes).
What is the method to achieve this?
Thanks

A: First off I don't think you need to @persist your form values, as tapestry will keep them across your validation failed submit. If you so want to set default values you could do so in the @SetupRender like:
@Porperty
@Persist
private String myValue;

@SetupRender
private void setup() {
    if(myValue == null) {
        myValue = "defaultVal";
    }
}

Or you could do it in a null check getter (which is a useful thing when using events as @SetupRender is not called there):
@Persist
private String myValue;

public String getMyValue() {
    if(myValue == null) {
        myValue = "defaultVal";
    }
    return myValue;
}


text:
Q: HTML textarea min-width ignored when width is set The min-width seems to be ignored, I cannot scale less than 200px;
Any workaround?
<textarea style='width:200px; max-width:400px; min-width:100px'>
    text
</textarea>

A: That's how it's suppose to work! The min-width and max-width properties should be used together to define a range of value for the element to resize to given the user's conditions (eg. monitor size). Explicitly giving the same element a width simply defeats this purpose.
See http://reference.sitepoint.com/css/min-width for more information
If you want a resizable textarea that grows with the amount of content the user adds you can have a look at this jQuery plugin: http://james.padolsey.com/javascript/jquery-plugin-autoresize/


text:
Q: Streaming from iDS to OpenCV Is it possible, to take images from iDS camera and convert them to OpenCV recognizable format?
I have followed code for stream data over rtsp:// from iDS:
/* allocate image buffer */
char *pMemoryBuffer;
int nMemoryId;
nRet = is_AllocImageMem(hCam, rectAoi.s32Width, rectAoi.s32Height, 24, &pMemoryBuffer, &nMemoryId);
abortOnError(nRet, "Allocating image memory failed with error code: ");

/* set allocated image buffer active */
nRet = is_SetImageMem(hCam, pMemoryBuffer, nMemoryId);
abortOnError(nRet, "Setting image memory active failed with error code: ");
/* capture a single frame */
nRet = is_FreezeVideo(hCam, IS_WAIT);

/* Step 4: Submit frame data to the stream */
IS_STREAM_PAYLOAD_DATA data;
data.cbSizeOfStruct = sizeof(IS_STREAM_PAYLOAD_DATA);
data.pData = reinterpret_cast<unsigned char*>(pMemoryBuffer);
data.cbSizeOfData = rectAoi.s32Width * rectAoi.s32Height * 3;
data.idSession = sessionInfo.idSession;
data.idStream = streamInfo.idStream;

But I need to get OpenCV (IplImage/Mat) image directly, or image in any other known format.

A: OK, so it is possible to do it via File System:
memset(&ImageFileParams, 0, sizeof(ImageFileParams));
ImageFileParams.pwchFileName = myString;
ImageFileParams.pnImageID = NULL;
ImageFileParams.ppcImageMem = NULL;
ImageFileParams.nQuality = 0;

nRet = is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, (void*)&ImageFileParams, sizeof(ImageFileParams));


text:
Q: maven configuration tag value's set null in java code if "plugin" tag add inside "pluginManagement" (look following code) pom.xml
<pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.example.groupid</groupId>
                <artifactId>artifact-example-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>

                <executions>
                    <execution>
                        <id>mojo-plugin-id</id>
                        <goals>
                            <goal>example-gole</goal>
                        </goals>
                        <phase>integration-test</phase>
                        <configuration>
                            <employee>
                                <firstName>MyFirstName</firstName>
                                <middleName>MyMiddleName</middleName>
                                <lastName>MyLastName</lastName>
                            </employee>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>

above configuration tag value set as null in java class (java class as follow), But if I removed "pluginManagement" tag everything works fine
ExampleMojo.java
@Mojo(name = "example-gole")

public class ExampleMojo extends AbstractMojo {
@Parameter(property = "employee")
private Employee employee;

@Override
public void execute() throws MojoExecutionException {
    getLog().info(employee);
}

}
execute method show null output to all properties
Employee.java
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;

private String firstName;
private String middleName;
private String lastName;

// consider constructor, getter and setter, hashcode, eqauls, toString is available

}
More Info
Creating customized maven plugin, above java classes are from maven plugin but the above pom.xml configuration from its caller.

A: It's working for me now. Used "plugin" "configuration" tag instead of "execution" "configuration" tag
<pluginManagement>
<plugins>
    <plugin>
        <groupId>com.example.groupid</groupId>
        <artifactId>artifact-example-maven-plugin</artifactId>
        <version>1.0-SNAPSHOT</version>

        <executions>
            <execution>
                <id>mojo-plugin-id</id>
                <goals>
                    <goal>example-gole</goal>
                </goals>
                <phase>integration-test</phase>
            </execution>
        </executions>

        <configuration>
            <employee>
                <firstName>MyFirstName</firstName>
                <middleName>MyMiddleName</middleName>
                <lastName>MyLastName</lastName>
            </employee>
        </configuration>

    </plugin>
</plugins>