text:
Q: Why don't @State parameter changes cause a view update? I am trying to follow the guidance in a WWDC video to use a @State struct to configure and present a child view. I would expect the struct to be able to present the view, however the config.show boolean value does not get updated when set by the button.
The code below has two buttons, each toggling a different boolean to show an overlay. Toggling showWelcome shows the overlay but toggling config.show does nothing. This seems to be working as intended, I just don't understand why SwiftUI behaves this way. Can someone explain why it's not functioning like I expect, and/or suggest a workaround?
https://developer.apple.com/videos/play/wwdc2020/10040/   @ 5:14
struct InformationOverlayConfig {
    @State var show = false
    @State var title: String?
}

struct InformationOverlay: View {

    @Binding var config: InformationOverlayConfig

    var body: some View {

        if config.title != nil {
            Text(config.title!)
                .padding()
                .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 15))
        }
    }
}

struct TestView: View {

    @State private var configWelcome = InformationOverlayConfig(title: "Title is here")
    @State private var showWelcome = false

    var body: some View {
        VStack {
            Text("hello world")
            Spacer()
            Button("Toggle struct parameter", action: {
                configWelcome.show.toggle()
            })
            Button("Toggle boolean state", action: {
                showWelcome.toggle()

            })
        }
            .overlay(
                VStack {
                    InformationOverlay(config: $configWelcome).opacity(configWelcome.show ? 1 : 0)
                    InformationOverlay(config: $configWelcome).opacity(showWelcome ? 1 : 0)
                })
    }

A: You "Config" is not a View. State variables only go in Views.
Also, do not use force unwrapping for config.title. Optional binding or map are the non-redundant solutions.
Lastly, there is no need for config to be a Binding if it actually functions as a constant for a particular view.
struct InformationOverlay: View {
  struct Config {
    var show = false
    var title: String?
  }

  let config: Config

  var body: some View {
    VStack {
      if let title = config.title {
        Text(title)
          .padding()
          .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 15))
      }
      // or
      config.title.map {
        Text($0)
          .padding()
          .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 15))
      }
    }
  }
}

struct TestView: View {
  @State private var configWelcome = InformationOverlay.Config(title: "Title is here")
  @State private var showWelcome = false

  var body: some View {
    VStack {
      Text("hello world")
      Spacer()
      Button("Toggle struct parameter") {
        configWelcome.show.toggle()
      }
      Button("Toggle boolean state") {
        showWelcome.toggle()
      }
    }
    .overlay(
      VStack {
        InformationOverlay(config: configWelcome).opacity(configWelcome.show ? 1 : 0)
        InformationOverlay(config: configWelcome).opacity(showWelcome ? 1 : 0)
      }
    )
  }
}


text:
Q: How to view html files in browser window which is stored in an Amazon S3 bucket? I have an HTML file stored in an Amazon S3 bucket and also I have a presigned URL for that HTML document, Now I want to display that HTML file in my browser.
How can I display that file in the browser using angular js or node?

A: The answer is listed in this tutorial. If you configured you bucket as decribed in the link below, you can use this URL:
http://www.example.com
See Configuring a static website on Amazon S3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can a machine exist making more steps than the current record, which is no busy beaver? There are some machines in the busy-beaver-competition for turing machines with $5$ states and $2$ symbols for which it is not known whether they halt or not.

Is it possible that among those machines, there is a halting machine beating the current record with respect to the number of steps, but not being a busy beaver beacuse it doesn't write down more ones than the currect record  ? Or do we know that such a halting machine would also be a new record holder with respect to the number of ones ?

I tend to believe that we cannot rule out this possibility. In fact, I am not sure whether we can even rule out any final output (except trivial ones like an empty tape, if the machine contains $1RH$ forcing at least one $1$ on the tape).

A: I would say that yes, this is perfectly possible. We know that the champion as far as the number of $1$'s written at the end does not need to be the same as the champion in terms of steps taken (here are some champions for the quadruple definition Turing machines, and the champion for $1$'s is not the same machine as the champion for steps)
So, the situation you describe is can certainly be true at the beginning of our investigations, when every machine is a holdout ... so why would that change later on, assuming we still haven't found neither the $1$-champion nor the step-champion?

A: I don't know the exact machines in the competition, but in general the answer could be "we have a machine which isn't known to halt or diverge, which we've been running for years but has written down fewer 1's so far than the best-known busy-beaver candidate". In that case, exactly one of the following is true, but we don't know which:

*

*The machine halts, leaving the tape with more $1$'s than the current record holder. Then it is a busy-beaver record beater.

*The machine halts, but does not leave the tape with more $1$'s than the current record holder. Then it is not a busy-beaver.

*The machine diverges. Then it is not a busy-beaver candidate at all, let alone a record-beater.


text:
Q: Erro para executar programa em fortran Preciso calcular o Minimo divisor comum em fortran, fiz o código, porém quando ele compila e roda, fecha após o usuário digitar o valor e eu não sei o que está errado.
PROGRAM Calc
IMPLICIT NONE
REAL :: valor,contador=0, divisao
write(*,*) "Digite um valor positivo para calcular o MDC "
read(*,*) valor
do contador = 0, valor, 1

if(MOD(valor,contador)==0)then
divisao=divisao+1
endif
end do

if(divisao == 2) then
    write(*,*) "O Valor digitado possui MDC"
else
    write(*,*) "O valor digitado nao possui MDC"
endif

STOP
END PROGRAM Calc

A: Olá, embora não tenha conseguido entender bem o objetivo do programa, visto que até onde lembro calculo de MDC precisa possuir no mínimo dois valores, aqui vai um código com as correções que acredito serem cabíveis:
PROGRAM CALC
  IMPLICIT NONE
  INTEGER*4 :: valor,contador,divisao
  WRITE(*,*) "Digite um valor inteiro positivo para calcular o MDC "
  READ(*,*)  valor
  DO contador = 1, valor, 1
    IF (MOD(valor,contador).EQ.0) THEN
      divisao=divisao+1
    END IF
  END DO
  IF (divisao .EQ. 2) THEN
    WRITE(*,*) "O Valor digitado possui MDC"
  ELSE
    WRITE(*,*) "O valor digitado nao possui MDC"
  END IF
  READ(*,*)
  STOP
END PROGRAM CALC

As mudanças que acredito serem relevantes são apenas duas:
1) As variáveis devem ser inteiras, pois você as utilizou no loop do comando "DO"
2) Seu loop "DO" iniciava do zero, o que fazia com que a função "MOD" capotasse. Esse era o motivo do crash que estava acontecendo.
Caso a resposta seja satisfatória, por favor, não esqueça de marcar ela para ajudar outras pessoas que estejam pesquisando algo parecido e também não esqueça de avaliar positivamente. Um abraço.


text:
Q: How does web server know that it has to send the request to the app server and static files? I am coming from background where a website (asp.net) code was configured on IIS server.
I am now working on Flask and do not have clarity on how the following work together: Flask, WSGI, app server and web server.
Flask is just the python app. Flask makes use of the Werkzeug WSGI (web server gateway interface). that knows how to handle the HTTP protocol request/response. App server is either the development server that comes built-in or other servers for example gunicorn. Web server is something like nginx.
I have static files used in the jinja templates {{ url_for('static', filename='style.css') }}. An app server (Like flask dev server or gunicorn) can process this. But how does nginx (web server) resolve static file address?
Also, in the following sample image, when a request comes to the web server (say nginx), then how does it know that this request has to be forwarded to the app server (gunicorn)? For example it maybe a static file url or maybe an endpoint url.

A: So, in you example you have file style.css in static folder. For now the static file is serve from flask web server app not from the nginx. The question is how to serve static file in flask from nginx right ?

*

*first, you create a location block for webapp/static in nginx configuration file

location /webapp {
  proxy_pass http://127.0.0.1:6969;
}

location /webapp/static {
  alias /path/to/webapp/static;
}

*And set static_url_path for each webapp: app = Flask(name, static_url_path="/webapp")


text:
Q: stty: standard input: Invalid argument error when scping files When I try to scp a file to my remote server I get the following error:
stty: standard input: Invalid argument

This is caused by a line in my .bashrc file:
stty -ixon

If I remove that line, the error goes away.  however, if I remove that line, then when I ssh in, if I accidentally hit [CTRL]+S then the shell freezes and it takes me a while to figure out what happened.
Is there any way to resolve this?  to prevent that error without removing that line from .bashrc, or some other way to prevent [CTRL]+S from freezing the terminal?

A: I assume you using xshell.
Press Ctrl+q could unlock it.
BTW, they called Ctrl+S freeze.
You could find more info xshell's keymap.


text:
Q: How to scale UI elements for different screen sizes in Android using ConstraintLayout my goal is to design a layout using ConstraintLayout in Android that scales to different screen sizes and thus to devices. I read quite often that you should use dp and sp for designing layouts. Basically I think that using dp and sp does not make the layout scalable for different screen sizes so I don't agree on that. Here you can see how a designed layout looks on a 5' and 7' screen.

You can clearly see (the screenshots have the same zoom level) that on the 7' display the buttoms and imageviews (whose height and width was specified with dp) and the textviews (whose size was specified with sp) look smaller or the same size as in the 5' device. But on a 7' display the elemnts should be larger and scale to the display size which I do not think is possible using dp and sp.
So my question is how can I design the layout in a way that it scales to the current screen size meaning that the elements should be smaller in small devices and larger in large-screen devices.
Here you can see the XML layout file:
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="265dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:ignore="ContentDescription" />

    <ImageButton
        android:id="@+id/commentButton"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:background="@null"
        android:contentDescription="comment_Button"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.82"
        app:srcCompat="@mipmap/comment" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/comment"
        android:textSize="18dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.025"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.753" />

    <Button
        android:id="@+id/button"
        android:layout_width="163dp"
        android:layout_height="72dp"
        android:background="@drawable/custom_button"
        android:text="Button"
        android:textAllCaps="false"
        android:textColor="#121212"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.867" />

    <TextView
        android:id="@+id/textViewS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Textview"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.012"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.581" />

</androidx.constraintlayout.widget.ConstraintLayout>

I'd appreciate every comment and would be quite thankful for your advices.

A: My apps have different dimension resources, scaling all dp and sp values for smaller screens. For example in res/values/dimens.xml
<dimen name="dp20">20dp</dimen>
<dimen name="dp24">24dp</dimen>
<dimen name="dp28">28dp</dimen>
<dimen name="dp30">30dp</dimen>
<dimen name="dp32">32dp</dimen>
<dimen name="dp36">36dp</dimen>

and in res/values-w320dp/dimens.xml:
<dimen name="dp16">12dp</dimen>
<dimen name="dp18">14dp</dimen>
<dimen name="dp20">15dp</dimen>
<dimen name="dp24">18dp</dimen>
<dimen name="dp28">21dp</dimen>
<dimen name="dp30">23dp</dimen>
<dimen name="dp32">24dp</dimen>
<dimen name="dp36">27dp</dimen>

Then, when setting sizes with @dimen/dp16 instead od 16dp, the screen scales better. You can add more qualified resources for more types of screens.

A: There is one third-party library that can manage your issue easily.
check this for the different size for the component: https://github.com/intuit/sdp
And this is for text size: https://github.com/intuit/ssp


text:
Q: How can I send a POST form with curl that contains hidden form fields? I want to submit a html form with curl on this site.
http://pickupline.be/bekijk
When you click on "Stem", it sends a post form to http://pickupline.be/submitVote.
The form requires this fields:
<input type="text" id="num" name="num" class="required center_text">
<input type="text" id="firstname" name="fname" class="fname required" >
<input type="text" id="lastname" name="lname" class="lname required" >
<input type="text" id="mail" name="email" class="required email" >
<select name="birthday_day" class="required birthday_day">
<option selected value="">DD</option>
<option value="1">1</option>
<select name="birthday_month" class="required birthday_month">
<option selected value="">MM</option>
<option value="1">1</option>
<select name="birthday_year" class="required birthday_year">
<option selected value="">JJ</option>
<option value="2000">2000</option>
<input type="checkbox" id="chkOpdehoogte" name="newsletter">Ik wil op de hoogte blijven van nieuwe inzendingen
<input type="checkbox" id="chkAgreeConditions" name="agree" class="required">Ik ga akkoord met het reglement
<input type="hidden" id="pickupline_id" name="id">
<input type="submit" value="STEM">

Please notice, the id is hidden.
This is what I've tried so far:
curl -v --data 'num=${nummer}&fname=${voornaam}&lname=${achternaam}&email=${mail}&birthday_day=${dag}&birthday_month=${maand}&birthday_year=${jaar}&agree="yes"&id=100' http://pickupline.be/submitVote --referer http://pickupline.be/bekijk

But I don't get a response from the server.
I've also tried to save the cookies and use them with curl, no difference.

A: Hidden is just a property for the browser to not show the field to the user. It is still sent the same way as any other form field in the actual HTTP POST request.


text:
Q: python.exe has stopped working when opened via cmd About two days ago Python stopped responding after I tried to open it in cmd. I tried reinstalling Python and searched the Internet for a possible solution, but found no answers. This problem is still going on.

A: Try doing this download/open the python installer (corresponding to the version of your python). Once opened click Repair. This will repair Python.
If you are still experiencing trouble, try doing this:
1. Open the installer
2. Click on Modify
3. Check the button that says Add Python to environmental variables.


text:
Q: Display 3 divs, 2 together and the third one under the first Well, I want to display 3 divs like this:
[ DIV 1 ] [       ]
[       ] [ DIV 2 ]
[ DIV 3 ] [       ]

But, for some reason this happens:
[ DIV 1 ] [       ]
[       ] [ DIV 2 ]
          [       ]
[ DIV 3 ]

There is a JSFiddle showing what I mean: https://jsfiddle.net/4mmdamak/

And there is a possible solution using position relative and negative margin top: https://jsfiddle.net/4mmdamak/1/

I don't want to use margin tops because I don't know the height of the second div, so, I don't know how many pixels I have to rise the third div.
Also, I tried using vertical-align: top; on the third div, but this is useless.
PD: I can't put the third div inside the first div.
PD2: Also, I can't create an table with two td tags with rowspan 2.
So, if you have any other solution... Thanks!

A: You can do this with Flexbox

.content {
  min-height: 100vh;
  display: flex;
  flex-direction: row;
  color: white;
}

.left {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.div-1 {
  background: red;
  flex: 4;
}

.div-2 {
  background: blue;
  flex: 1;
}

.right {
  background: green;
  flex: 1;
}

DIv 1

Div 2

Div 3

A: you need to add a wrapper div to the left hand side like so

        <meta charset="utf-8">
        <title>JS Bin</title>

 Left Upper

Left Lower

Right

and css as follows
body{
    height:700px;
}
#left_container{
    width: 65%;
    height:700px;
    background-color:black;
    float:left;
}
#one{
    width:100%;
    height:70%;
    background-color:blue;
    float:left;
}

#two{
    width:100%;
    height:30%;
    background-color:green;
    float:left;
}
#right_column{
    width:35%;
    height:100%;
    background-color:red;
    float:left;
}

A: you can use float in styles, but:
width of container is 140px and width of every inside div is 64px
64 + 64 = 128 and 140 - 128 = 12, if width of container is 128px float will works!
jsfiddle


text:
Q: MS Visual Studio 2010 Database connection to MS Access 2007 I'm trying to put this code in a textbox, it seems correct. However, the "OldDbConnection" and ".Open"  are underlined red. Am I missing something or doing something wrong?
OleDbConnection conn = new
    OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;
Persist Security Info=False;");

    try
    {
        conn.Open();
        MessageBox.Show("Connected");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

A: Add a using System.Data.OleDb to the top of your file.

A: Imports System.Data.OleDb
Imports System.Data.OleDb.OleDbDataReader

Public Class Form1
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        provider = "Provider =Microsoft.ACE.OLEDB.12.0;Data Source="
        dataFile = "C:\Users\ANNALIZA\Desktop\New folder (4)\JABOYY1.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        myConnection.Open()

        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [ADMIN] WHERE [userName] = '" & TextBox1.Text & "' AND [userPassword] = '" & TextBox2.Text & "'", myConnection)
        Dim userFound As Boolean = False
        Dim FirstName As String = ""
        Dim LastName As String = ""
        Dim dr As OleDbDataReader = cmd.ExecuteReader

        While dr.Read
            userFound = True
            FirstName = dr("FirstName").ToString
            LastName = dr("LastName").ToString

        End While
        If userFound = True Then
            Form2.Show()
            Form2.Label1.Text = "Welcome" & FirstName & " " & LastName
        ElseIf TextBox1.Text = "" And TextBox2.Text = "" Then
            MsgBox("No such username and password found! Input first before you click LOG IN!", MsgBoxStyle.Critical, "Warning")
            Me.Show()

        ElseIf MsgBox("Sorry username and password not found!LOGIN FAILED", MsgBoxStyle.Exclamation, "Invalid Log in") Then
            TextBox1.Text = ""
            TextBox2.Text = ""
            Me.Show()

        End If

    End Sub


text:
Q: DCOS Upgrade docker version on agent nodes We are running DC/OS 11.1 on Azure cloud and have Docker engine version 17.09 on our agent nodes. We would like to upgrade Docker engine to 17.12.1 on each agent node.
Has anyone had experience with such procedure and would it cause any instability / side effects with the rest of the DC/OS components?

A: I have not done the upgrade myself in the exact environment you are running in, but I would not be terribly concerned. It goes without saying that test this out in non-production environment before you do it in production.
I would suggest draining the agent node before doing the docker upgrade. What I mean by draining is that you stop all the containers(tasks) running on the node, this will ensure that Mesos agents will stop the tasks and then inform the framework that the tasks are no longer running and the frameworks would take appropriate action.
To drain nodes run
sudo sh -c 'systemctl kill -s SIGUSR1 dcos-mesos-slave && systemctl stop dcos-mesos-slave'

for a private agent
sudo sh -c 'systemctl kill -s SIGUSR1 dcos-mesos-slave-public && systemctl stop dcos-mesos-slave-public'

for public agent
You would observe the agent disappear from the Nodes section of the UI and all tasks running on the agent marked as TASK_LOST. Ideally it should have been TASK_KILLED but that is a topic for another time.
Now perform your docker upgrade
After you have upgraded docker start the agent service back up
sudo systemctl start dcos-mesos-slave

for a private agent
sudo systemctl start dcos-mesos-slave-public

for public agent
The nodes should now start showing up in the UI and start accepting tasks.
To be safe

*

*Verify this in non-prod environment before you do it in prod, to
iron out any operational issues you might encounter

*Do 1 or a subset of agents at a time so that you are not left with a
cluster without any nodes while you are performing the upgrade


text:
Q: Why is the constructor and the destructor called when assigning a value to an object I have the following code:
#include <iostream>

using namespace std;

class A{
    int x;
public:
    A(int x =1) : x(x) {cout << "A() ";}
    A(const A& a) {x =a.x; cout << "A(const A&) ";}
    A& operator=(const A& a){cout << "op= "; x=a.x; return *this;}
    ~A(){cout << "~A()";}
    int getX() {return x;}
    void setX(int x){this->x = x;}
};

A g(A a){
    //a = 2;
    cout << "g() ";
    a.setX(3);
    return a;
}

int main()
{
    A a;
    a = 2;

}

I expected to have the following output: A() op= ~A(), but instead the output isA() A() op= ~A() ~A(). It seems a constructor and a destructor are called when I'm assigning the value 2 to the object a. Why are those two called? Is the compiler effectively creating a new A object that has x = 2 and then uses the assignment operator to assign the value to a?

A: This is because you didn't declare an assignment operator for your class that would take an int as an argument. Because no such operator exists the compiler needs to use a workaround: It creates a temporary object using the constructor A(int). You can avoid this behavior by making the constructor explicit:
explicit A(int x_ = 1) : x(x_) { }

After the temporary is constructed it gets copied to 'a' using the provided copy constructor for A. Immediately after that, the temporary gets destroyed and invokes its destructor.
This approach is inefficient. To make it better, you should define an assignment operator for A taking an int as an argument:
A& operator= (int x_) {
    x = x_;
    return *this;
}


text:
Q: Gradle create a empty folder `build/kotlin/sessions`, why? When i delete it comes back, how to fix it? I have a multi module project in Kotlin/Springboot with Gradle build.
I have a folder build/kotlin/sessions that always appear even if i delete it.
What is the folder and why is it there? Can i remove it completely so it does not come back?

My root settings.gradle.kts:
pluginManagement {
    repositories {
        maven(url = "https://repo.spring.io/snapshot")

        maven(url = "https://repo.spring.io/milestone")

        gradlePluginPortal()
    }
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "org.springframework.boot") {
                useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}")
            }
        }
    }
}

rootProject.name = "ris_2.0_backend"
include("workflow")
include("messaging")
include("project")
include("restapi")

My root build.gradle.kts:
plugins {
    id("io.spring.dependency-management") version "1.0.8.RELEASE"
    kotlin("jvm") version "1.3.61" apply false
    kotlin("plugin.spring") version "1.3.61"
    kotlin("plugin.jpa") version "1.3.61"
}

subprojects {

    apply(plugin = "io.spring.dependency-management")

    repositories {
        jcenter()
    }

    dependencyManagement {
        imports {
            mavenBom("org.springframework.boot:spring-boot-dependencies:2.1.8.RELEASE") {
                bomProperty("kotlin.version", "1.3.61")
            }
        }
    }

}

And all build.gradle.kts in each module:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("com.adarshr.test-logger").version("1.7.0") // pretty log printing
    kotlin("jvm")
    kotlin("plugin.spring")
    jacoco
}

group = "no.inmeta.ris.workflow"
version = "0.0.1-SNAPSHOT"
val junit5Version = "5.5.1"

val developmentOnly = configurations.create("developmentOnly")

configurations.runtimeClasspath.get().extendsFrom(developmentOnly)

configurations {
    developmentOnly
    testCompile {
        exclude(group = "junit", module = "junit") // force junit5
        exclude(group = "mocito-core", module = "mockito-core")
    }
}

repositories {
    mavenCentral()
}

dependencies {

    // Spring
    implementation("org.springframework.boot:spring-boot-starter")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")

    // Swagger
    implementation("io.springfox:springfox-swagger2:2.9.2")

    // Testing
    implementation(enforcedPlatform("org.junit:junit-bom:$junit5Version"))
    testImplementation("org.springframework.boot:spring-boot-starter-test:2.1.9.RELEASE")
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
    testImplementation("org.assertj:assertj-core:3.11.1")

    // Kotlin testing library
    testImplementation("com.ninja-squad:springmockk:1.1.3")
    testImplementation("io.mockk:mockk:1.9.3")

    // Kotlin
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.10.0")
}

configure<JacocoPluginExtension> {
    toolVersion = "0.8.4"
}

tasks.withType<JacocoReport> {
    reports {
        xml.isEnabled = true
        csv.isEnabled = false
        xml.destination = file("${buildDir}/jacoco/reports/test.xml")
        html.destination = file("${buildDir}/jacoco/reports/test.html")
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
    testLogging {
        events("passed", "skipped", "failed")
    }
    finalizedBy("jacocoTestReport")
}

val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
    jvmTarget = "1.8"
}
val compileTestKotlin: KotlinCompile by tasks
compileTestKotlin.kotlinOptions {
    jvmTarget = "1.8"
}

Is it anything in my configuration which is making this empty build folder appear?
Thank for the help!

A: Gradle automatically adds build directory in every project (it is normal, every Gradle project has such directories).
If you look in folders of your subprojects (messaging, restapi, etc), you'll probably see similar build folder there. Later you may add more gradle plugins that will store their data in these directories.
IntelliJ IDEA automatically signs these directories as excluded, so IDE does not process any files in them. If you are using Git, add these directories in your .gitignore file (just add "build" line in it, it will remove all build folders for all subprojects from VCS). And if you are VERY annoyed seeing this folders, you can hide excluded folders in IDEA.

A: You can run ./gradlew clean assemble --debug and find such entry:
[org.jetbrains.kotlin.gradle.plugin.KotlinGradleFinishBuildHandler] [KOTLIN] Deleted session-is-alive flag file: build/kotlin/sessions/...

source:
https://github.com/JetBrains/kotlin/blob/master/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinGradleFinishBuildHandler.kt
Perhaps, this are the culprit's lines, which don't take folder into account:
            for (file in sessionFiles) {
                file.delete()
                log.kotlinDebug { DELETED_SESSION_FILE_PREFIX + file.relativeToRoot(rootProject) }
            }


text:
Q: How to correctly embed a Perl interpreter in a C++ application on Windows I have a Perl script of about 15,000 lines that I want to execute with a PerlInterpreter from a Windows executable compiled with C++.
I tried, following these directions
I downloaded Perl 5.18 source and included the core (install) directory, for perl.h, and EXTERN.h, as well as core/win32 and core/win32/include
Then I tried compiling the simple C++ project in Visual Studio 2013
#include <EXTERN.h>               /* from the Perl distribution     */
#include <perl.h>                 /* from the Perl distribution     */

static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/

int main(int argc, char **argv, char **env)
{
  PERL_SYS_INIT3(&argc,&argv,&env);
  my_perl = perl_alloc();
  perl_construct(my_perl);
  PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
  perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
  perl_run(my_perl);
  perl_destruct(my_perl);
  perl_free(my_perl);
  PERL_SYS_TERM();
}

The project did not compile, giving hundreds of errors, but most prevalent error was
missing config.h file included by perl.h

So I added a #define PERL_MICRO statement to perl.h
This reduced the number of errors to 20
However all of the errors originate from Windows SDK files string.h and guidedef.h
so I am clueless as to what is the origin of these errors
Can anyone provide me with any information on how to create and build a C++ interpreter for Perl scripts?

The remaining errors are
Error   10  error C3861: 'my_memcmp': identifier not found  c:\program files (x86)\windows kits\8.1\include\shared\guiddef.h    161 1

Error   3   error C2733: 'memmove_s' : second C linkage of overloaded function not allowed  c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 136 1

Error   4   error C2733: 'memmove' : second C linkage of overloaded function not allowed    c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 139 1

Error   2   error C2733: 'memcpy_s' : second C linkage of overloaded function not allowed   c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 57  1

Error   1   error C2733: 'memcpy' : second C linkage of overloaded function not allowed c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 55  1

Error   8   error C2732: linkage specification contradicts earlier specification for 'strstr'   c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 228 1

Error   7   error C2732: linkage specification contradicts earlier specification for 'strrchr'  c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 226 1

Error   6   error C2732: linkage specification contradicts earlier specification for 'strpbrk'  c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 224 1

Error   5   error C2732: linkage specification contradicts earlier specification for 'strchr'   c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 222 1

Error   9   error C2732: linkage specification contradicts earlier specification for 'memchr'   c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h 233 1

A: I'll describe some things I know on the subject. I hope this will help.
First you should specify which Perl you're using on Windows.
There are at least 2 I know of on Windows:

*

*Strawberry Perl

*Activestate Perl
Second, what you're trying to achieve is Embedding a Perl interpreter in a C/C++ application. I mention this so you can refer to it when you search for documentation about it.
The perlembed documentation provides general information about this.
If you want to do this on Windows with ActivePerl you can have a look at the Embedding Perl Under WIN32.
For Strawberry Perl, someone on Perlmonks has a working example of embedding Perl on Windows here.
At the same time, notice that it may be useful to follow the perlwin32 perl documentation page in order to set up the MSVC compiler with the appropriate paths.
Finally, there's also a book on the topic called Extending and Embedding Perl which you may want to look at for some details on the topic. In this book, chapter 8 discusses embedding Perl in C in general, and chapter 9 deals with an embedding case study.
UPDATE:
Reading through ExtUtils::MakeMaker documentation I've found this part which looked interesting:
If you are running experiments with embedding perl as a library into other applications, you might find MakeMaker is not sufficient. You'd better have a look at ExtUtils::Embed which is a collection of utilities for embedding.
And in particular ExtUtils::Embed is concerned with Utilities for embedding Perl in C/C++ applications.
I haven't tried it myself but I'm thinking it could help. I'll come back with more details once I get some time to look into this.
UPDATE:
A list of applications that feature an embedded Perl interpretor:

*

*Pidgin - in particular offers you the possibility to write plugins that run via its embedded Perl interpretor. This is an interesting example as it's also known to work under Windows. Of interest here, seems to be libpurple/plugins/perl and in particular the Makefile.mingw which should contain information on how to build on Windows

*Irssi - here ExtUtils::Embed is used inside configure.in ( see git clone git://git.irssi.org/irssi for details, or svn.irssi.org )

*Vim   - (Also uses ExtUtils::Embed in its configure.in. For more details hg clone https://vim.googlecode.com/hg/ vim. Vim also allows scripting via Perl.)

*Icinga - Icinga allows scripting in Perl

*Nagios - A relevant article about Nagios in this context can be found here .

*collectd - Makefile.am and perl.c


text:
Q: Sudo mkdir fails due to permission denied error I've written a script that copies some files from one place to another and since I don't have permissions to the source folder, I tried running it with sudo.
The problem is that now the creation of the destination folders fails.
Here is a simple test case:
In my home directory the following works:
mkdir testDir

But this fails due to permission denied error
sudo mkdir testDir2

My home directory has 755 permissions and is own by me.
I ran sudo groups and found that as expected the root group is there, but strangely, the users is not. Also running groups as myself reveals that I'm not in the sudo group.
Any ideas what's going on? Why am I not able to write to my home folder when running with sudo?

A: This is due to "root squash" on the NFS server.  From the exports(5) man page (emphasis mine):

nfsd bases its access control to files on the server machine on the
  uid and gid provided in each NFS RPC request. The normal behavior a
  user would expect is that she can access her files on the server just
  as she would on a normal file system. This requires that the same uids
  and gids are used on the client and the server machine. This is not
  always true, nor is it always desirable.
Very often, it is not desirable that the root user on a client machine
  is also treated as root when accessing files on the NFS server. To
  this end, uid 0 is normally mapped to a different id: the so-called
  anonymous or nobody uid. This mode of operation (called 'root
  squashing') is the default, and can be turned off with no_root_squash.

To paraphrase, it's generally a security risk to allow root (e.g., when running sudo) on the NFS client to modify files and file attributes as if it were root on the NFS server.  This would effectively make root on the client equivalent to root on the server, and allow a rogue client to take over the server.
From the RHEL 6 security guide:

If no_root_squash is used, remote root users are able to change any
  file on the shared file system and leave applications infected by
  Trojans for other users to inadvertently execute.


text:
Q: Why do I get 'permission denied' when trying to 'cd' into a NFS share on Synology? I have two NFS shares configured the same way on my Synology NAS:
synology> sudo cat /etc/exports

/volumeUSB1/usbshare 192.168.1.10(ro,async,no_wdelay,no_root_squash,insecure_locks,sec=sys,anonuid=1025,anongid=100)
/volume1/Plex        192.168.1.10(ro,async,no_wdelay,no_root_squash,insecure_locks,sec=sys,anonuid=1025,anongid=100)

I'd like to mount these NFS shares on my Ubuntu:
ubuntu> sudo mkdir /mnt/Synology_USB
ubuntu> sudo mkdir /mnt/Synology_Plex

ubuntu> sudo mount synology:/volumeUSB1/usbshare /mnt/Synology_USB
ubuntu> sudo mount synology:/volume1/Plex /mnt/Synology_Plex

ubuntu> cd /mnt
ubuntu> ls -l
drwxrwxrwx 2 root root 4096 Dec 20 09:22 Synology_Plex
drwxr-xr-x 2 root root 4096 Dec 13 19:09 Synology_WD2000GB

ubuntu> cd /mnt/Synology_USB
# No errors up until here, I can see all my files

ubuntu> cd /mnt/Synology_Plex
-bash: cd: /mnt/Synology_Plex/: Permission denied

I think that the difference could be caused by the fact that one is a USB drive (NTFS) and the other one is Synology's built in drive (btrfs) but for the world I can't figure out what the problem is.


text:
Q: Get the value of array to use in sort? I need to get the result from K (number of students) but in case 2 ... program fills up all 30 places in the array with (if K=2) two number and other 28 are some kind of 38392839238 .. .some thing like that, here is my code:
int main()
  {
int i,n,k;
unsigned int m[30], a[30], b[30];
int ch=0, nech=0;
cout<<"Number of students (max30)";cin>>k;
for(i=0; i<k; ++i)
{
    cout<<i+1<<". Student number: ";
    do
    {
        cin>>m[i];
    }
    while(!(m[i]>=1e7 && m[i]<1e8));
    if(m[i]%2==0)
    {
        a[ch]=m[i]; ch++;
    }
    else
    {
        b[nech]=m[i]; nech++;
    }
}
cout<<endl;
cout<<"\nAll numbers: "<<endl;
for(i=0; i<k; ++i)
    cout<<m[i]<<"\t";
    loop:
cout<<endl;
cout<<"\nChoose 1 to see Even and Odd numbers: ";
cout<<"\nChoose 2 to see ascending order: ";
cout<<"\nChoose 3 to exit: ";
cout<<"\nEnter Your choise: "; cin>>n;
switch(n)
{

case 2:
    {
        {
        int e=sizeof(m) / sizeof(m[0]);
        sort(m,m+e);
        for(i=0;i<e;++i)
            cout<<"\n"<<m[i]<<' ';
        }
    }
    goto loop;

}
 }

This program wants to enter the number of students in class, after that it wants to enter their number in class and in CASE 2 i it need to make them in ascending order. For example:
Number of students in class: 2
 1. Student number: 12345678
 2. Student number: 55555555
and when you hit 2 for case2 it needs to make their ascending order, so result must be:
12345678
55555555
(from min to max).
My program makes it but on the other 28 places (my array must be max 30) it puts another number = 3435973836

A: The problem that you see has to do with reading from the elements of the arrays that have not been initialized, and therefore containing garbage values.
Your first loop assign values to the top k elements, yet inside the case '2' you have a loop that sorts and outputs the entire array. This is undefined behavior, because you are reading from unassigned elements of the array.
Using k instead of e would fix this problem:
sort(m, m+k);
for(i=0;i<k;++i)
    cout<<"\n"<<m[i]<<' ';
}


text:
Q: "Illegal Instruction (core dumped)" occuring in valgrind No matter what the program is, valgrind gives nearly the same output :

Illegal Instruction (core dumped).

Even in this underlying program it shows the same
#include<stdio.h>

void fun(int *i)
{
    printf(" %d \n",*i);
}

int main()
{
    int j=90;
    fun(&j);
    return 0;
}

A: Your valgrind is broken, or is not compatible with your C library.
To confirm this, first see if you can run the valgrind binary at all:
valgrind --help

(if that fails, maybe the binary is corrupt or is for a different architecture)
Then try within something you didn't write:
valgrind /bin/true

(if that fails, perhaps it's not compatible with your C library)
Assuming one or more of those fails, you will need to reinstall valgrind and try again.


text:
Q: Howto convert a list into a numpy array with predefined structure I have a list with ohlc data:
[(1360710000.0, 69.06, 69.67, 68.53, 69.53, 550000.0, 69.53),
(1360623600.0, 68.98, 69.05, 68.39, 68.94, 604200.0, 68.94)]

and want it to convert into a numpy array which is structured like this one:
array([ (1352934000, 63.130001068115234, 63.59000015258789, 62.900001525878906, 63.16999816894531, 816300.0, 63.16999816894531),
   (1353020400, 62.970001220703125, 63.529998779296875, 62.599998474121094, 62.61000061035156, 942000.0, 62.61000061035156),
   (1353279600, 63.0, 64.97000122070312, 63.0, 64.87999725341797, 812800.0, 64.87999725341797),
   (1353366000, 64.44999694824219, 65.27999877929688, 64.29000091552734, 65.23999786376953, 467700.0, 65.23999786376953),
   (1353452400, 65.16999816894531, 65.4000015258789, 64.58999633789062, 64.8499984741211, 417700.0, 64.8499984741211)],
  dtype=[('time', '<i4'), ('open', '<f4'), ('high', '<f4'), ('low', '<f4'), ('close', '<f4'), ('volume', '<f4'), ('amount', '<f4')])

Any attempts result in wrong structure as expected:
np.array(list, dtype=Day)

array([[1360710000.0, 69.06, 69.67, 68.53, 69.53, 550000.0, 69.53],
   [1360623600.0, 68.98, 69.05, 68.39, 68.94, 604200.0, 68.94]], dtype=object)

A: lst = [(1360710000.0, 69.06, 69.67, 68.53, 69.53, 550000.0, 69.53),
       (1360623600.0, 68.98, 69.05, 68.39, 68.94, 604200.0, 68.94)]
np.array(lst, dtype=[('time', '<i4'), ('open', '<f4'), ('high', '<f4'), ('low', '<f4'), ('close', '<f4'), ('volume', '<f4'), ('amount', '<f4')])

returns
array([ (1360710000, 69.05999755859375, 69.66999816894531, 68.52999877929688, 69.52999877929688, 550000.0, 69.52999877929688),
       (1360623600, 68.9800033569336, 69.05000305175781, 68.38999938964844, 68.94000244140625, 604200.0, 68.94000244140625)],
      dtype=[('time', '<i4'), ('open', '<f4'), ('high', '<f4'), ('low', '<f4'), ('close', '<f4'), ('volume', '<f4'), ('amount', '<f4')])

Isn't it what you wanted?


text:
Q: Docker container shows running even after exit command I am new to docker, hence may be missing a simple piece. Here is my scenario. I started a container with command 'docker run -it ubuntu:14.04'. Then with Ctrl+P+Q, I exited such that the container keeps running. I verified with docker ps, and saw the container running. Then I again entered the container with 'docker exec -it  bash. This took me inside the container again. Now on typing 'exit' command, I come out of the container, but the container is still in running mode. Normally with exit command, the container stops. Any idea why this is happening?

A: The container's running status is tied to the initial process that it was created for/with.
If you do docker run then this will create a new container with some inital process. When that process terminates, the whole container is stopped. If that initial process was bash, and you exit it, then this terminates the container itself.
docker exec starts a new process inside of the running container. When that process terminates, the container still keeps running.
Typing exit into an interactive bash shell will just exit that shell. It will not affect other processes running inside the same container (just like closing one terminal window in your host OS does not affect any other processes).

A: With the exit command in your case, the container stops only the /bin/bash/ executable. Probably some other application like NGINX or Apache is running inside the container and does not let it shut down.


text:
Q: Open new window when you click play in jwplayer 5 Old example is megavideo.com.....when you click play button once, it will open a new window to a sponsor site. then it will play the video.
Can this be done in jw player 5?
Player code:

Thanks

A: You could wrap your player object in a div, set the position to absolute i believe, then do another div inside after your player object with the position to relative and top to 0, left, 0, right 0, bottom 0 (should theoretically expand the inner div to inside, then add a click event on it to open your window and hide it div.
This is basically called an overlay ontop of your player.
Update


text:
Q: Is sequential consistency equivalent to performing memory accesses by a processes in program order and performing each memory access atomically? In Fundamentals of Parallel Multicore Architecture, by Yan Solihin,  p304 defines sequential consistency memory model:

Overall, we can express programmers' implicit expectation of memory
access ordering as: memory accesses coming out of a processor should
be performed in program order, and each of them  should be performed
atomically.  Such an expectation was formally defined as the sequential
consistency (SC) model. The following is Lamport [37]'s definition of
sequential consistency:

A multiprocessor is sequentially consistent if the result of any
execution is the same as  if the operations of all the processors were
executed in some sequential order, and the  operations of each
individual processor occur in this sequence in the order specifed by
its program.

where the atomicity of memory accesses is defined on p303 as

an expectation that each memory access occurs in an instant, without being overlapped
with other memory accesses. In the example, the expectation assumes that when process P0 writes to shared variable x, the write is instantly propagated to both processes P1 and P2.

I was wondering if  sequential consistency is equivalent to the combination of

*

*"memory accesses coming out of a processor should be performed in program order", and

*"each of them  should be performed atomically"?

I guess yes because "each of them  should be performed atomically" is required by SC and its "instant write propagation" seems to guarantee "the result of any execution is the same as if the operations of all the processors were executed in some sequential order".
But I can't prove or disprove my suspision.
Thanks.

A: No, your definition is not quite equivalent to the definition of sequential consistency but would be closer to strict consistency. There are two relevant aspects: (a) there are multiple processors/processes involved, and (b) they only have to behave as if they were being executed in a total order. The atomicity is not required in reality, only in the "as if" model. That memory accesses are performed in program order is already true pretty much by definition.
There is a consistency model called strict consistency that requires that writes take effect in the order they were executed. If a process writes to x at time t1, then all later reads at time t2 > t1 from x should return the written value. This would require atomic writes that propagate immediately to all other processes. Even on a single multicore CPU, this is impossible due to speed of light constraints unless exclusive locks are used, effectively enforcing that reads/writes actually obey a global order – no "as if".
Sequential consistency is a weaker consistency model. We do not require that writes take effect immediately/atomically, but merely that all processes observe writes in the same order, i.e. that they agree on a total order of operations.
Let's look at some processes that manipulate a shared global variable x.
I'll write W(x)a when a process writes the value a to x, and R(x)a when the process reads from x and gets a. We'll have four processes that perform a sequence of operations:

*

*process 1: W(x)a

*process 2: W(x)b

*process 3: R(x)_, R(x)_

*process 4: R(x)_, R(x)_

Here's some ASCII-Art that illustrates the different times at which the operations could be executed by the processes. The different processes are shown above each other, and the time axis increases to the right.
Here's a strictly consistent execution where all writes take effect immediately:
   -----------------------------> time
1: W(x)a
2:       W(x)b
3:             R(x)b       R(x)b
4:                   R(x)b R(x)b

But here is an execution that is sequentially consistent, yet not strictly consistent:
   -----------------------------> time
1: W(x)a
2:       W(x)b
3:             R(x)b       R(x)a
4:                   R(x)b R(x)a

Here, process 1 first performs the W(x)a operation. However, this operation does not take effect immediately.
Now, process 2 executes W(x)b and this write is observed by the other processes.
Processes 3 and 4 execute R(x)b, i.e. they get the value b that was just written by process 2.
At this point, the write from process 1 takes effect
and is observed by the next reads R(x)a of processes 3 and 4.
The important point is that although the writes were not executed atomically, all processes agreed on an order of events, in particular write events. The behaviour of all processes was as if they had been executed in a particular order, although this agreed-upon order was different from the actual temporal order. We don't care about when a write is observed, only about the order between writes.
In contrast, here's an execution where processes 3 and 4 don't agree on the order of W(x)a and W(x)b:
   -----------------------------> time
1: W(x)a
2:       W(x)b
3:             R(x)b       R(x)a
4:                   R(x)a R(x)b

Here, process 3 has observed events W(x)b, W(x)a,
whereas process 4 has observed W(x)a, W(x)b.
This is not sequentially consistent.
In practice, sequential consistency is easily achievable for single variables e.g. when using locks. The C memory model also enables sequential consistency for single memory locations when all accesses to that location use appropriate memory order.
With multiple variables things tend to get tricky, in particular because sequential consistency is a fairly strong consistency guarantee. The Jepsen.io project has developed tools for fuzzing (distributed) databases in search of consistency violations, and has a good overview of consistency models.

A: A very nice question!
Some definitions.
A memory order is the order in which loads and stores are globally performed (so either on cache/memory). It is key to understand that the actual memory order isn't relevant. There is no way to prove what the actual memory order was unless you hook up some very advanced measuring equipment to the CPU.
An execution is a single run of a program.
To determine if an execution is cache coherent, you need to find a memory order such that:

*

*there is a total order of all loads and stores per address.

*the order is consistent with the program order of each CPU

*a load needs to see the most recent store before it in the memory order.
Let have a look at sequential consistency (SC). To determine if an execution is SC, you need to find a memory order such that:

*there is a total order of all loads and stores over ALL addresses.

*the order is consistent with the program order of each CPU

*a load needs to see the most recent store before it in the memory order.
Sequential consistency is a restriction of cache coherence where by the memory order needs to have a total order of loads and stores over all addresses instead of a single address. So there are memory orders that are cache coherent, but not sequential consistent. But not the other way around because cache coherence is a relaxation of SC.
Lets have a look at your definition:
A) "memory accesses coming out of a processor should be performed in program order"
B) "each of them should be performed atomically"?
I'll assume that you mean with 'performed' that the load/store is performed in the memory order (so either loaded from memory or from cache) and not when it is actually executed.
'B' will confine the allowed memory orders such that there is a total order over all loads and stores on a single address. Because atomicity will not order loads/stores to different addresses.
'A' will confine the allowed memory orders to the ones preserving PO between all loads/stores (also the loads/stores to different addresses) issued by a single processors. Combined with B, I believe we have 4) 5).
The key part that is missing is 6), a read needs to see the most recent write before it in the memory order.
So if you would add 6) then I believe your definition is compatible with SC.
You might ask yourself the question why do I get a total order over all loads/stores if the PO between different addresses is preserved? So how do we move from a total order of a single address to a total order over multiple addresses? If different CPU's are executing loads and stores concurrently, then these loads and stores are independent because they can't be causally related. So these loads and stores do not need to not ordered with respect to each other and hence we have no total order. The nice thing is we can just pretend a total order exist because nobody can prove otherwise. In mathematical terms: you can always create a topological sort of the memory order (which is a DAG: an acyclic partial order) and create  one or more total orders.


text:
Q: Flash message is not display on handlerbar template using node js with passport js I am trying to show message in handlebar template using connect-flash package but message is not showing and its print count when i use {{loginMessage}} in login page. but not display message.
 here is my code
file..routes/index.js
 var express =  require('express');
 var router =   express.Router();
 var mongoose = require('mongoose');
 var flash =    require('connect-flash');
 const m_db =   require('.././config/mongo_connection');
 var Site =     require('.././models/site');
 var User = require('../models/user');
 var bcrypt   = require('bcrypt-nodejs');
 var passport = require('passport');
 var LocalStrategy = require('passport-local').Strategy;
 require('.././config/passport')(passport);
 //routes start here
 router.get('/login', function(req, res, next) {
 res.render('passports/login.hbs', { message:   req.flash('loginMessage','failed login') });

})
my app.js
  app.use(require('express-session')({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false
}));
  app.use(flash());
 //
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static(path.join(__dirname, 'public')));
 // passport config

 app.use(logger('dev'));
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

 app.use('/', index);
 app.use('/users', users);
 app.use('/api', api);

 // catch 404 and forward to error handler
  app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
 });

 // error handler
  app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
 });
  module.exports = app;

Please help!
Thanks!

A: router.get('/login', function(req, res, next) {

  res.render('passports/login.hbs', { message: req.flash('loginMessage') });
     .
     .

What I want to say it:
req.flash('loginMessage','failed login')

is for setting the flash variable name loginMessage to failed login
req.flash('loginMessage')

and this is when your read the flash that your set later on. The code above return array of flash messages(if more than one flash are set) of loginMessage.


text:
Q: Does knockout.js really employ MVVM pattern? I am new to knockout.js. Few moments back I read the headline features of ko.
I could not understand is ko really MVVVM? Because all they talk about is data binding and the ease of it. But I am sure MVVM is more than data binding isn't it?

A: Yes, knockout.js does apply the MVVM pattern. It's explained in the documentation:

*

*A model: your application's stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.

*A view model: a pure-code representation of the data and operations on a UI. For example, if you're implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.
Note that this is not the UI itself: it doesn't have any concept of buttons or display styles. It's not the persisted data model either - it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.

*A view: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.
When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.

A: In addition to the answer already provided, there are a few things to keep in mind -
MVVM
Knockout is MVVM because it supports a good separation of concerns.  Unlike other JavaScript libraries, such as jQuery, it's goal is to not pollute the view with that which does not concern it.
The view model's purpose is important to understand.  It does not attempt to manipulate the DOM because only logic required to serve up data to the view is placed inside of it.
The view's purpose is only to present (render) the data.  No logic, validation, or other logic code goes here.
The model is the only place where Knockout can get a bit tricky.  It is generally a good accepted practice to place a separate model in your project for Knockout to use, but many developers have found the ease of mixing the model into the view model.  The reason for this is obvious (some models are very basic) but again this is only out of ease of implementation.
MVC vs MV*
Surely there are other answers on SO.com that attempt to answer what is MV*, but I wanted to throw my $0.02 in here - Other libraries or frameworks speak to the fact that they are MVC or MVP or MV(whatever) based but Knockout is the only one that I have found that practices what it preaches in this regard.  If you have the time and desire look at the structure of other frameworks such as Angular or Ember and you will see there is a blurred line that exists, and more or less they are simply using an MVVM based pattern but calling it something different.

A: Well I guess it can, however I am working on a project where all styling and UI layout manipulation is done in the knockout js ViewModel file, which is not good practice.


text:
Q: Google Sheet check for filter always goes to true why does this always go to true? How can i check if its acually something filtered or not?
 var list = SpreadsheetApp.openByUrl(url);
var SS = list.getSheetByName("Sheet 1");

if (SS.getFilter() !== null && SS.getFilter() != {}) {
  console.log("have populated filter..", SS.getFilter());

}

current output: have populated filter.. {}

A: Based on the documents:

getFilter() - Returns the filter in this sheet, or null if there is no filter.

This will always have value if the sheet has 1 or more filter regardless the range.
I also tried to replicate your code and it only set to false if the whole sheet has no filter.
Example:
With filter:

Output:

Without filter:

Output:

Reference:

*

*getFilter()

A: Thanks for the question.  I played around with this.  It actually takes quite a long time to run getFilter:
Here's what I did:
function messinwithmysheetsfilter() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  let f = sh.getFilter();
  console.log(typeof f)
  if (f != null && typeof f == 'object') {
    console.log('Frozen: '+Object.isFrozen(f));
    console.log('Sealed: '+Object.isSealed(f));
    console.log('Extensible: '+Object.isExtensible(f));
    console.log('OwnProperies: '+Object.getOwnPropertyNames(f));
    console.log('toString(): '+ f.toString());
    console.log('getRange: ' + f.getRange().getA1Notation());
  }
}

Console Log Results:
11:54:32 AM Notice  Execution started
11:54:33 AM Info    Frozen: false
11:54:33 AM Info    Sealed: false
11:54:33 AM Info    Extensible: true
11:54:33 AM Info    OwnProperies: toString,remove,sort,getRange,getColumnFilterCriteria,getColumnSortSpec,setColumnFilterCriteria,removeColumnFilterCriteria
11:54:33 AM Info    toString(): Filter
11:54:33 AM Info    getRange: A1:Z63
11:54:33 AM Notice  Execution completed

Perhaps you can learn something from it I did.
You can actually rewrite your conditional as I did below:
function messinwithmysheetsfilter() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  let f = sh.getFilter();
  //console.log(typeof f)
  if (f != null && f.toString()=='Filter') {//use the results of the filters toString() method which should  be 'Filter'
    console.log('Frozen: '+Object.isFrozen(f));
    console.log('Sealed: '+Object.isSealed(f));
    console.log('Extensible: '+Object.isExtensible(f));
    console.log('OwnProperies: '+Object.getOwnPropertyNames(f));
    console.log('toString(): '+ f.toString());
    console.log('getRange: ' + f.getRange().getA1Notation());
  }
}


text:
Q: Can someone explain why python can't find these modules? I am trying to get the hang of modules/packages in Python 2.7. I have a file called tmp.py in /Users/me/dir
import mypackage.datamanagement.lib.models
from mypackage.datamanagement.lib.models import Order

I can run it like this
$pwd   #/Users/me/dir
$python tmp.py  #runs fine

Everything works fine.
However, if I copy tmp.py to a different location in the package...
$cp tmp.py mypackage/datamanagement/scrips/

And then try to run it with $python mypackage/datamanagement/scripts/tmp.py from /Users/me/dir I get...
File "mypackage/datamanagement/scrips/tmp.py", line 1, in <module>
import mypackage.datamanagement.lib.models
ImportError: No module named mypackage.datamanagement.lib.models

I have an init.py in all of the relevant directories. I think this has to do with pythonpath.  I am osx and if I run
echo $PYTHONPATH

I get a blank line.
Can someone explain what is going on? Is the python working directory set by the location of the python file? And not the location where python is executed?

A: If you are trying to use a local Python module, in your case, "lib" would be the directory to your "tmp.py" module:
import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

Source: https://stackoverflow.com/a/4284378/950427


text:
Q: Bypass memory corruption limitations Assuming you are security code auditing guy and you have been got into some
code like this:
if(strlen(data) < 100) {
     strcpy(buffer, data);
}

What would you do in order to corrupt the buffer?
Is that possible? if so, how? and why dont using that condition for code security?

A: One obvious answer is if buffer isn't at least 101 chars long, a specific case of which is when the programmer forgot that the null-terminator is copied as well (if the buffer is exactly 100 chars long). There are two more subtle attack vectors I can see off the top of my head:

*

*data may border on non-readable memory and not contain a null-terminator. This would cause a segmentation fault or access violation, but not memory corruption directly.

*data and buffer could overlap when treated as strings. The behavior is undefined in this case.
As an example of the second attack, take the following code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    char someImportantString[] = "Something that should not be overwritten";
    char buffer[101] = "\0goodbye cruel world";
    char data[16] = {'h', 'e', 'l', 'l', 'o',' ','w','o','r','l','d',
                     'x','x','x','x','x'};

    if(strlen(data) < 100)
    {
         printf("Probably not good\n");
         strcpy(buffer, data);
    }

    return 0;

}

The likely result of this is overwriting a lot of memory and then seg-faulting.


text:
Q: System.Threading.Tasks error when trying to call API I am new to vb.net code. I have to call external API from vb.net. I tried the code below but it is throwing an error - getting issue as

System.Threading.Tasks.k`1

Public Shared Async Function GetToken_saka() As Task(Of sakaweb)
    Dim req As New HttpRequestMessage(HttpMethod.Post, "https://api.qa.se.com/token")
    '        req.Content = New FormUrlEncodedContent(New Dictionary < String, String > {
    '    {"client_id", "your client_id"},
    '    {"client_secret", "your client_secret"},
    '    {"grant_type", "client_credentials"}
    '});

    Dim dct As New Dictionary(Of String, String)
    dct.Add("client_id", "your_client_id")
    dct.Add("client_secret", "your_client_secret")
    dct.Add("grant_type", "client_credentials")

    Dim htc As New HttpClient
    req.Content = New FormUrlEncodedContent(dct)
    Dim response = Await htc.SendAsync(req)
    response.EnsureSuccessStatusCode()

    'Dim payload = JObject.Parse(Await response.Content.ReadAsStringAsync())
    Dim payload = JsonConvert.DeserializeObject(response.ToString)

    Dim token = payload.Value(Of String)("access_token")
    Dim t1 As sakaweb = Nothing
    Return t1

    'Dim t1 As New Task("K")
    'Return t1
End Function


text:
Q: circular colorTransform Is there a way to apply a colorTransform to a BitmapData in a circle rather than in a rectangle?
Instead of erasing rectangular parts of an image by reducing the alpha channel as in the code below, I'd like to do it in circles.
 _bitmap.colorTransform(new Rectangle(mouseX-d/2, mouseY-d/2, d, d),
 new ColorTransform(1, 1, 1, .5, 0, 0, 0, 1));

I do have some code which loops through the pixels, extracts the alpha value and uses setPixel but it seams significantly slower than the colorTransform function.

A: Try creating a circle using the drawing API (flash.display.Graphics) and then drawing that onto the bitmap data with BlendMode.ERASE. That might solve your problem, if I understand it correctly.
var circle : Shape = new Shape;
circle.graphics.beginFill(0xffcc00, 1);
circle.graphics.drawEllipse(-50, -50, 100, 100);

// Create a transformation matrix for the draw() operation, with
// a translation matching the mouse position.
var mtx : Matrix = new Matrix();
mtx.translate(mouseX, mouseY);

// Draw circle at mouse position with the ERASE blend mode, to
// set affected pixels to alpha=0.
myBitmap.draw(circle, mtx, null, BlendMode.ERASE);

I'm not 100% sure that the ERASE blend mode works satisfyingly with the draw() command, but I can't see why it shouldn't. Please let me know how it works out!


text:
Q: getting notification when someone comments using comments plugin So I have an iFrame app on a fan page, which includes the comments plugin. Is there a way I/any admin can receive a notification or email every time someone adds a comment?

A: You can subscribe to comment.create event and send the notification to admin in any way you prefer, once comment is created. Facebook itself doesn't provide such functionality.
This may looks like this (I assume Facebook JavaScript SDK is already loaded on page before doing this, read about it in documentation on Loading, anyway if you're using Social Comments Plugin it should be loaded already):
<script type="text/javascript">
  FB.subscribe('comment.create', function(response){
    // Here you need to do a call to some service/script/application
    // to notify your administrator about new comment.
    // I'll use jQuery ajax to call server-side script to illustrate the flow
    $.post('//hostnamne/path/to/script', {
      "action": "comment created",
      "url_of_page_comment_leaved_on": response.href,
      "id_of_comment_object": response.commentID
    });
  });
</script>

In your script located at http(s?)://hostnamne/path/to/script you can send a notification to admin, how to do it may vary on way you want it for example if you want to send an email you can use something like this php sample (aging this is just a flow sample, not real code you should use):
 <?
   $admin_email = 'root@localhost';

   $commentID = $_REQUEST['id_of_comment_object'];
   $page_href = $_REQUEST['url_of_page_comment_leaved_on'];
   $message = "comment #{$commentID} was leaved on page {$page_href}";

   mail($admin_email, "You have a new comment", $message);
 ?>

If you need to track the deletion of comments too you can use comment.remove event with similar flow...


text:
Q: Zoom In and Zoom Out for dynamic Image This is my Zoom In and Out code:
function ZoomIn() {
    var ZoomInValue =      parseInt(document.getElementById("stuff").style.zoom) + 1 + '%'
    document.getElementById("stuff").style.zoom = ZoomInValue;
    return false;
}

function ZoomOut() {
    var ZoomOutValue = parseInt(document.getElementById("stuff").style.zoom) - 1 + '%'
    document.getElementById("stuff").style.zoom = ZoomOutValue;
    return false;
}

This is not working correctly I want it to zoom in and out it makes the image larger which is not a pleasing zoom. Can anyone help in getting the proper zoom in and out code so that my problem can be solved or if there is a better alternative to do it?
The HTML:
echo'<input type="button" value="Zoom In" OnClick="return ZoomIn();" />';
echo'<input type="button" value="Zoom out" OnClick="return ZoomOut();" />';

A: This is the code that I have use in the past for getting a Zoom Effect on images.. Let me know if you can use is:
            $('#container img').hover(
                function(){
                    var $this = $(this);
                    $this.stop().animate({'opacity':'1.0','height':'200px','top':'0px','left':'0px'});
                },
                function(){
                    var $this = $(this);
                    $this.stop().animate({'opacity':'0.5','height':'500px','top':'-66.5px','left':'-150px'});
                }
            );
        });

A: I think this link is what you are looking for..
var currentZoom = 1;
$('button').click(function() {
    currentZoom += 0.1;
    $('body').css({
        zoom: currentZoom,
        '-moz-transform': 'scale(' + currentZoom + ')'
    });
});

See it on jsfiddle...

A: Please let me know if the below given sample code helps.

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

<button type="button" id="ZoomIn">Zoom-In</button>
<button type="button" id="ZoomOut">Zoom-Out</button>


text:
Q: creating summary field in yii I am new to yii and i'm looking for the best approach to solving my problem. I have a model that logs info and a view that displays all records. I need users to be able to view summary report. A typical sql script will look like this:
Select user, count(info) as info from tbl_log

My questiona are:
1) Do i create a new controller,view and search form and add a method that contains the search  criteria or should i use the same controller but create different action for this purpose?
2) Will i use createCommand() to specify my sql statement or is there a proper way of doing this?
Thanks


text:
Q: How do I call activity indicator at process time After clicking the button, the next page is taking a little time to load. This is because the next page creates many dynamic label controls to show data. How do I show activity indicator at process time.
private async void ProductTypeButton_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new ProductPage(_ViewModel));
}

A: Before PushAsync to the ProductPage, you need make the ActivityIndicator  run and after successfully navigating to ProductPage, you can set IsLoading = false. Here's the code snippet below for your reference:
Code-behind:
  private bool _isLoading;

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged("IsLoading");
            }
        }
        public MainPage()
        {
            InitializeComponent();
            BindingContext = this;
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {

            IsLoading = true;

            //set the delay time to push smoothly
            await Task.Delay(300);

            try
            {
                await Navigation.PushAsync(new ProductPage());
            }
            finally
            {
                IsLoading = false;
            }

        }

Xaml:
<ActivityIndicator IsRunning="{Binding IsLoading}" ></ActivityIndicator>


text:
Q: Get purchased product from PaymentIntent in my app i want to list past purchases for a stripe customer. So I was looking at the relevant API objects like PaymentIntents, Sessions or Charges. But they all do not seem to contain any reference to Product or Price, which I would need to list the purchased products.
Subscriptions contain a list of items that are contained in that subscription, so I was expecting PaymentIntents to have something like that too.
Does anyone has an idea how to archive my list of past purchases? Thanks!

A: I did some digging through the Stripe API docs[1] and, out of the three objects you referrenced (PaymentIntent, Session, Charges), the only one that I can see being able to trace back to a product is the Session.
Session objects have a line_items property[2] which can be followed all the way down to line_items.data.price.product[3].  To access this you'll need to inlcude the expand=["data.line_items"] parameter to your call to list Checkout Sessions.  You can read more about expanding API responses here[4]
So for all the charges to your customers that were done using Checkout Sessions, you could list them all, use the customer property to associate earch session with a customer in your application, traverse the the returned data, and then query the API for the product details.  If you have a lot of customers & products these API calls will add up fast so I would store this data in your back-end to avoid hitting rate limits[5].
Alternatively, you could just save the product ID (either Stripe or your local version) as metadata[6] for any of the above Stripe payment objects listed.  That would allow you to link any payment object you wish to a product.

*

*https://stripe.com/docs/api

*https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-line_items

*https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-line_items-data-price-product

*https://stripe.com/docs/expand

*https://stripe.com/docs/rate-limits

*https://stripe.com/docs/api/metadata

A: I had the same question I found a way to retrieve the products related to a specific PaymentIntent.
You need to get the sessions that was linked to PaymentIntent when the Checkout process was made.
I will give you the code (in PHP) that I use to to this.
        \Stripe\Stripe::setApiKey(STRIPE_API_SECRET);
        // Find the Session for that PaymentIntent
        $sessions = \Stripe\Checkout\Session::all([
            'payment_intent' => "pi_xxxxxxxxxx",
            'expand' => ['data.line_items'],
        ]);

You will then have an key line_items that contain the products linked.
Enjoy


text:
Q: Getting result only when click submit for second time I'm trying to do change password feature in angular 7,
from the backend side, if the current password not correct, it will return true.
and in angular side error message will appear.
but the problem is i have to click twice to show the error message, even i can see the response in logs printing true value, but not sure why the *ngIf not working
Template side
    <span *ngIf="hasError">
         wrong current password value
    </span>

my component side
hasError: boolean;

 submit () {
     this.apiService
    .changePassword(this.formGroup.value).subscribe(res => {
  console.log(res);
  this.hasError = res;    });

service side
  changePassword(body: any){
     return this.http.post<any>(this.url + 'changePassword', body);
  }

can someone explain why i have to click submit button twice to show the html element
thanks

A: I suspect you have passed changeDetection: ChangeDetectionStrategy.OnPush in the component decorator. In this case, the angular will not read the changes until the next change detection cycle which in your case occurs on the second click.
In order to fix this, you need to inject ChangeDetectorRef in the constructor and call the change detection cycle manually. Something like:
  constructor(private cdr: ChangeDetectorRef) {}

  hasError: boolean;

  submit () {
     this.apiService
    .changePassword(this.formGroup.value)
    .subscribe(res => {
       console.log(res);
       this.hasError = res;
       this.cdr.markForCheck();  // <<<---- detect changes
  });

Though there is no harm in using ChangeDetectorRef, another way to fix this problem is by using observables and angular async pipe.
  hasError$: new Subject();

  submit () {
    this.apiService
    .changePassword(this.formGroup.value)
    .subscribe(res => this.hasError$.next(res));

in template:
  <span *ngIf="hasError$ | async">
       wrong current password value
  </span>

A: This is the reason for your issue
hasError: boolean;
You are initiating the variable but not giving any value at the starting. So as soon as the component is loaded, the value of hasError is undefined/null. So it will load the template with that value only.
How to prevent this:
Method 1) (not preferred)
// If you dont want to initiate the value in the component.ts file, make this change in
  the HTML file,

<span *ngIf="!!hasError">
         wrong current password value
</span>

the '!!' will check for null status of the variable

Method 2) Preferred
// Initiate the value of the variable to false,

// In component.ts file

hasError: boolean = false; // IMPORTANT

and then your code remains the same.

So the initial value will now be false, and also when the service is subscribed, you can have it true or false and your HTML also remains the same.


text:
Q: pseudo-code for visiting a state machine I want to write pseudo-code for visiting a state machine using DFS. State machine can be considered as a directed graph. Following algorithm from Cormen book uses a DFS algorithm to visit a graph.
DFS-VISIT(G, u)          //G= graph, u=root vertex
    u.color = GRAY
    for each v from G.Adjacents(u)   //edge (u, v)
        if v.color == WHITE
            DFS-VISIT(G, v)

State machine however can have multiple edges between the two vertices. And above algorithm stores edges in an adjacency list. I have implemented the algorithm in Java with following classes,
class Node{
    String name;
    ....
    ArrayList<Transition> transitions;

    void addTransition(Transition tr);
}

class Transition
{
    String src;
    String dest;
}

With the above given information, I have built a state machine with node and transition objects. I want to modify the above algorithm where I don't have a graph object G. I just have access to root object.
Can I modify the above algorithm like below?
DFS-VISIT(root)                //root node
    root.color = GRAY
    for each t from root.getTransitions()  //t=transition
        v = t.getDestination()        //v=destination of t
        if v.color == WHITE
            DFS-VISIT(v)

A: The algorithm is independent of implementation. Actually, it's the other way around. The question you should be asking is this: "do your proprietary implementation has all the exact properties that are required by the algorithm?"
The algorithm has very few strict demands. You need a set of nodes and a set of edges, where each edge connects 2 nodes. That's the generic definition of graph. How you acquire, store and process these sets is irrelevant to the algorithm. For the algorithm step all you need is access to a given node from the set and access to a set of its neighbors. What you've presented seems fine (of course, for the next step you'll need to progress to the next node after root).


text:
Q: Why am I getting duplicate pages extracted from iText7 C#? I am extracting text from a PDF and have an issue with the same text being returned from sequential pages. I have written a few PDF parsers using iTextSharper and have just ported the following code from iTextSharper to iText7 on the flawed assumption this was only an iTextSharper issue:
        var pdfDocument = new PdfDocument(new PdfReader(@"C:\Temp\MyForm.pdf"));

        for (int page = 1; page <= pdfDocument.GetNumberOfPages(); page++)
        {
            var strategy = new SimpleTextExtractionStrategy();
            var pdfPage = pdfDocument.GetPage(page);
            var currentText = PdfTextExtractor.GetTextFromPage(pdfPage, strategy);

            // Process this page
            Console.WriteLine("PAGE {0}", page);
            Console.WriteLine(currentText);
        }

Is there something I'm missing here?

A: Actually it is not the same text being returned from sequential pages. Instead you get

*

*the text from page 1 when you extract page 1;

*the text from pages 1 and 2 when you extract page 2;

*the text from pages 1, 2, and 3 when you extract page 3;

*...

Often this happens for code that re-uses a text extraction strategy for multiple pages. But that's not the case in your code, you correctly create a new strategy object for each page. Thus the cause must be in the PDF itself.
And indeed, each page of your document does contain the contents of all previous pages, too, merely outside its crop box. To extract only the text in the respective page crop box you have to filter, e.g. like this:
string SRC = @"285187.pdf";

PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC));

Console.WriteLine("\n285187 Filtered\n============\n");

for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
    var strategy = new SimpleTextExtractionStrategy();
    var pdfPage = pdfDoc.GetPage(i);

    var filter = new IEventFilter[1];
    filter[0] = new TextRegionEventFilter(pdfPage.GetCropBox());
    var filteredTextEventListener = new FilteredTextEventListener(strategy, filter);

    var currentText = PdfTextExtractor.GetTextFromPage(pdfPage, filteredTextEventListener);

    Console.WriteLine("PAGE {0}", i);
    Console.WriteLine(currentText);
}

pdfDoc.Close();

It is unclear whether the PDF has been created like this by design or by error.


text:
Q: How to fetch Oracle reference cursor into table variable? I am trying to load data from reference cursor into a table variable (or array), the reference cursor works if the table variable is based on existingtable %Rowtype but my reference cursor gets
loaded by joining multiple tables so let me try to demonstrate an example what i am trying to do and some one can help me
--created table
create table SAM_TEMP(
    col1 number null,
    col2 varchar(100) null
);

--created procedure which outputs results from that table

CREATE OR REPLACE
PROCEDURE SP_OUT_RefCur_PARAM(
    C_RESULT OUT SYS_REFCURSOR
) IS
BEGIN
    OPEN C_RESULT FOR
        SELECT COL1,COL2
        FROM SAM_TEMP;
END SP_OUT_RefCur_PARAM;

--seeing the output works like this
DECLARE
    REFCUR SYS_REFCURSOR;
    outtable SAM_TEMP%rowtype ;
BEGIN
    SP_OUT_RefCur_PARAM(REFCUR);
    LOOP
        FETCH REFCUR INTO outtable;
        EXIT WHEN REFCUR%NOTFOUND;
        dbms_output.put_line(outtable.col1);
    END LOOP;
    CLOSE REFCUR;
END;

--but when i try to run below script it is giving error,i think i am missing something
DECLARE
    REFCUR SYS_REFCURSOR;
    TYPE REFTABLETYPE IS RECORD (COL1 NUMBER, COL2  VARCHAR(100));
    TYPE TABLETYPE IS TABLE OF REFTABLETYPE;
    outtable TABLETYPE;
BEGIN
    SP_OUT_RefCur_PARAM(REFCUR);
    LOOP
        FETCH REFCUR INTO outtable;
        EXIT WHEN REFCUR%NOTFOUND;
        dbms_output.put_line(outtable.col1);
    END LOOP;
    CLOSE REFCUR;
END;

Error report:
ORA-06550 line 9, column 21:
PLS-00597 expression 'OUTTABLE' in the INTO list is of wrong type
ORA-06550 line 9, column 3:
PL/SQL SQL Statement ignored
ORA-06550 line 11, column 32:
PLS-00302 component 'COL1' must be declared

Not sure what i am missing, Thanks in advance for your help

A: The name of variable in code above misleaded you. Your variable outtable is in table type. It isn't possible to fetch record data into table of records, but you can fetch it into record itself.
DECLARE
    REFCUR SYS_REFCURSOR;
    TYPE RECORDTYPE IS RECORD (COL1 NUMBER, COL2  VARCHAR(100));
    outtable RECORDTYPE;
BEGIN
    SP_OUT_RefCur_PARAM(REFCUR);
    LOOP
        FETCH REFCUR INTO outtable;
        EXIT WHEN REFCUR%NOTFOUND;
        dbms_output.put_line(outtable.col1);
    END LOOP;
    CLOSE REFCUR;
END;

Update: If you want to fetch all data for better performance your application you need to use BULK COLLECT statement:
DECLARE
    REFCUR SYS_REFCURSOR;
    TYPE RECORDTYPE IS
        RECORD (COL1 NUMBER, COL2  VARCHAR(100));
    TYPE TABLETYPE IS
        TABLE OF REFTABLETYPE
        INDEX BY PLS_INTEGER;
    outtable TABLETYPE;
BEGIN
    SP_OUT_RefCur_PARAM(REFCUR);
    LOOP
        FETCH REFCUR INTO BULK COLLECT outtable;
        EXIT WHEN outtable.COUNT = 0;

        FOR indx IN 1 .. outtable.COUNT
        LOOP
            dbms_output.put_line(outtable(indx).col1);;
        END LOOP;
    END LOOP;
    CLOSE REFCUR;
END;

Note: memory consumption with the BULK statement is much more than without.

The most important thing to remember when you learn about and start to
  take advantage of features such as BULK COLLECT is that there is no
  free lunch. There is almost always a trade-off to be made somewhere.
  The tradeoff with BULK COLLECT, like so many other
  performance-enhancing features, is "run faster but consume more
  memory." (Oracle Magazine)

But if you are just fetching and processing the rows - a row at a time there is no needs in BULK statement, just use the cursor FOR LOOP. (Ask Tom)

A: Another way to do it is this one:
DECLARE
    REFCUR SYS_REFCURSOR;
    TYPE REFTABLETYPE IS RECORD (COL1 NUMBER, COL2  VARCHAR(100));
    TYPE TABLETYPE IS TABLE OF REFTABLETYPE;
    outtable TABLETYPE;
BEGIN
    SP_OUT_RefCur_PARAM(REFCUR);
    FETCH REFCUR BULK COLLECT INTO outtable;
    FOR i in outtable.First..outtable.Last Loop
        dbms_output.put_line(outtable(i).col1);
    END LOOP;
    CLOSE REFCUR;
END;


text:
Q: Implementing Strategy pattern in rust without knowing which strategy are we using at compile time I've been trying to implement a Strategy pattern in rust, but I'm having trouble understanding how to make it work.
So let's imagine we have a trait Adder and Element:
pub trait Element {
    fn to_string(&self) -> String;
}

pub trait Adder {
    type E: Element;

    fn add (&self, a: &Self::E, b: &Self::E) -> Self::E;
}

And we have two implementations StringAdder with StringElements and UsizeAdder with UsizeElements:
// usize
pub struct UsizeElement {
    pub value: usize
}

impl Element for UsizeElement {
    fn to_string(&self) -> String {
        self.value.to_string()
    }
}

pub struct UsizeAdder {
}

impl Adder for UsizeAdder{
    type E = UsizeElement;

    fn add(&self, a: &UsizeElement, b: &UsizeElement) -> UsizeElement{
        UsizeElement { value: a.value + b.value }
    }
}

// String
pub struct StringElement {
    pub value: String
}

impl Element for StringElement {
    fn to_string(&self) -> String {
        self.value.to_string()
    }
}

pub struct StringAdder {
}

impl Adder for StringAdder {
    type E = StringElement;

    fn add(&self, a: &StringElement, b: &StringElement) -> StringElement {
        let a: usize = a.value.parse().unwrap();
        let b: usize = b.value.parse().unwrap();

        StringElement {
            value: (a + b).to_string()
        }
    }
}

And I want to write a code that uses trait methods from Adder trait and it's corresponding elements without knowing at compile time which strategy is going to be used.
fn main() {
    let policy = "usize";
    let element = "1";

    let adder = get_adder(&policy);
    let element_a = get_element(&policy, element);

    let result = adder.add(element_a, element_a);
}

To simplify I'm going to assign a string to policy and element but normally that would be read from a file.
Is the only way to implement get_adder and get_element using dynamic dispatch? And by extension should I define Adder and Element traits to use trait objects and or the Any trait?
Edit: Here is what I managed to figure out so far.
An example of possible implementation is using match to help define concrete types for the compiler.
fn main() {
    let policy = "string";
    let element = "1";
    let secret_key = "5";

    let result = cesar(policy, element, secret_key);

    dbg!(result.to_string());
}

fn cesar(policy: &str, element: &str, secret_key: &str) -> Box<dyn Element>{
    match policy {
        "usize" => {
            let adder = UsizeAdder{};
            let element = UsizeElement{ value: element.parse().unwrap() };
            let secret_key = UsizeElement{ value: secret_key.parse().unwrap() };
            Box::new(cesar_impl(&adder, &element, &secret_key))
        }
        "string" => {
            let adder = StringAdder{};
            let element = StringElement{ value: element.to_string() };
            let secret_key = StringElement{ value: secret_key.to_string() };
            Box::new(cesar_impl(&adder, &element, &secret_key))
        }
        _ => {
            panic!("Policy not supported!")
        }
    }
}

fn cesar_impl<A>(adder: &A, element: &A::E, secret_key: &A::E) -> A::E where A: Adder, A::E : Element {
    adder.add(&element, &secret_key)
}

However the issue is that I have to wrap every function I want to implement using a match function to determine the concrete type, and also case for every policy available.
It does not seem like the proper way of implementing it as it will bloat the code, make it more error prone and less maintainable unless I end up using macros.
Edit 2: Here you can find an example using dynamic dispatch. However I'm not convinced it's the proper way to implement the solution.
Example using dynamic dispatch
Thank you for your help :)


text:
Q: Need to stop a service in aws ec2 instance just before it reboots I need to write a script in python which stops a service running in EC2 instance just before it reboots.
What should be the approach here?
Suppose service name is abc.
to manually stop this service, I execute:
  service abc stop

I want to automate this before instance goes for reboot.
Help me with this

A: The cron scheduler allows you to use @reboot in place of a schedule string.  So, write your script and then crontab -e and add the following:
@reboot /path/to/python /path/to/reboot_script.py

For the reboot script, python isn't really your best choice.  I would write it using a bash script, looking something like this:
#!/bin/bash

service abc stop

If you must use python, you could use invoke:
from invoke import run
run('service abc stop', hide=True, warn=True)

Edit:
To run this BEFORE reboot, make a shell script called K99kill_service and add it to your /etc/rc6.d directory.  These scripts are executed before reboot or shutdown.  It's important that it is named as above to make sure it runs at the right time and doesn't interfere with other shutdown scripts.

A: Courtesy : https://opensource.com/life/16/11/running-commands-shutdown-linux
See the link, it explains in very much detail on, How to shutdown services in linux before shutdown for both SysVinit and Systemd ?


text:
Q: WMI Queries in C? Is it possible to issue WMI WQL queries in plain C? And if yes, how?

A: You can use any programming language that you want as long as you can call into the COM API for WMI.

A: It looks like you can do this sort of thing by using ExecQuery(), though this example is in C++.  BTW this guy couldn't get it to work, but you may check out what he's doing.
Hope this helps.
http://forums.devshed.com/c-programming-42/wmi-wql-querying-problem-in-c-215026.html
More WMI programming:
http://www.vedivi.com/blog/2008/05/how-to-enable-remote-desktop-programmatically/


text:
Q: How to change all schema location for xjc binding? I have a zip of .xsd file.
I would like to generate Java classes for each xsd using JAXB/XJC.
Each .xsd referenced schema location or import that are not part of my classpath.
Example :
schemaLocation = "http://schemas.opengis.net/gml/3.2.1/gml.xsd" is the current line in my xsd
But, I have downloaded all the schema and the location http://schemas.opengis.net is replaced by D://temp
How can I do that to generate all classes automatically, instead of editing one by one each schema location manually..
Thank you


text:
Q: Conveniently view vector's content if iterator given Is there convinient way to see vector's content if i need to debug a program in Visual Studio 2013 which uses function signatures like this:
void foo(Iterator beginA, Iterator endA);

in case i have vector<int> a i can easily see what is inside of the vector. But if i given only iterator, then, for debug purpose, i need to declare vector just to see what is inside, or there exists easier way?

A: Try something like beginA._Ptr,10 in the Watch window. This relies on an implementation detail of the iterator (that it has a member called _Ptr), and the ,10 syntax in the Watch window means "treat the pointer as an array address and show me 10 elements of the array". You can put an arbitrary number there, doesn't have to be 10, of course.
HTH


text:
Q: mp4 file upload issue in multer of node.js I'm trying to upload mp4 file by using multer in node.js
(View)VideoUploadPage.js
import React, { useState } from "react";
import Axios from "axios";

function VideoUploadPage() {

const onDrop = (files) => {
    let formData = new FormData();
    const config = {
      header: { "content-type": "multipart/form-data" },
    };
    formData.append("file", files[0]);
    console.log(files);

    Axios.post("/api/video/uploadfiles", formData, config).then((response) => {
      if (response.data.success) {
        console.log(response.data);
      } else {
        alert("비디오 업로드를 실패 했습니다.");
      }
    });
  };

}

(Server)
video.js
const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ffmpeg = require("fluent-ffmpeg");

let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}_${file.originalname}`);
  },
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    if (ext !== ".mp4") {
      return cb(res.status(400).end("only mp4 is allowed"), false);
    }
    cb(null, true);
  },
});

const upload = multer({ storage: storage }).single("file");

router.post("/uploadfiles", (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      return res.json({ success: false, err });
    }
    return res.json({
      success: true,
      url: res.req.file.path,
      fileName: res.req.file.filename,
    });
  });
});

At the video.js destination: (req, file, cb) => {
cb(null, "uploads/")
} <----- I can check which file is going to upload with console.log(response.data), but there is no mp4 file in the "uploads" folder.
When I changed "uploads/" to my local directory path, mp4 file is on the uploads folder ....
ex: "C://~~~/uploads"
Any idea?

A: use path.resolve('./uploads') to resolve a sequence of path-segments to an absolute path.
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.resolve('./uploads'); // path of the upload folder
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname);
if (ext !== ".mp4") {
  return cb(res.status(400).end("only mp4 is allowed"), false);
}
cb(null, true);
},
});

A: You can use path.resolve(process.cwd() + 'path till upload folder');
for eg:
path.resolve(process.cwd() + '/uploads');