text:
Q: How to reset a counter that depends of actionsButtons - Shiny? I have an app that looks like this
library(shiny)
library(DT)

ui <- fluidPage(
  sidebarPanel(numericInput("c1","Example", NA),
           tags$p(actionButton("update", "Update")),
           tags$p(actionButton("reset", "Clear")),
           tags$p(actionButton("restart", "Restart")),
           textOutput("count"),
           htmlOutput("display")
 ),

  mainPanel(  DT::dataTableOutput("example")
           )
)

server <- function(input, output, session) {

  # stores the current data frame
  values <- reactiveVal(data.frame(A=1, B=2, C=3))

  # update values table on button click
  observeEvent(input$update,{

    old_values <- values()

    A_new <- input$c1
    B_new <- A_new + 2
    C_new <- A_new + B_new

  new_values <- data.frame(A=A_new, B=B_new, C=C_new)

    # attach the new line to the old data frame here:
    new_df <- rbind(old_values, new_values)

    #store the result in values variable
    values(new_df)

    #reset the numeric input to NA
    updateNumericInput(session, "c1", "Example", NA)

  })

#Delete last row
   deleteEntry <- observeEvent(input$reset,{
           values( values()[-nrow(values()),])
   })

        updateCounter <- reactiveValues(i = 0)

    ##This output value must be reset to 0
       output$count <- renderText({
         paste0("Iteractions: ", updateCounter$i)
       })

       observe({
         input$update
         isolate({
           updateCounter$i <- updateCounter$i + 1
         })
       })

       observe({
         input$reset
         isolate(updateCounter$i <- updateCounter$i - 1)
       })

      #Restart
       defaultvalues <- observeEvent(input$restart, {
         isolate(updateCounter$i == 0)
         values( values()[1,])
         updateCounter <<- reactiveValues(i = 0)
       })

    Total <- reactive({ colSums(values()[3]) })

      output$display  <- renderText({
        partialsum <-Total()
        if(updateCounter$i==3) {
          value3 <<- partialsum
          return(paste("Partial result", value3))
        }
        if(updateCounter$i<3){
          return()
        }
        if(updateCounter$i==0){
          return()
        }
        if(updateCounter$i>3) {
        display1 <- paste("Partial result", value3)
        display2 <- paste("Total result", partialsum)
        twolinesdisplay<<- HTML(paste(display1, display2, sep = '
'))
        return(twolinesdisplay)

        }
      })
  # # Print the table on mail panel
  output$example <- DT::renderDataTable({  return(values())  })
}

shinyApp(ui = ui, server = server)

When interactions equals 3 is displayed the sum of column 3, more than 3 displays the partial sum and the current total sum. Each time that the restart button is clicked, table is reset to default values and process starts again. But the interaction counter does not reset to zero.
I have tried to use the idea of this post but without success. Any suggestion?

A: Is this what you are looking for?
library(shiny)
library(DT)

ui <- fluidPage(
  sidebarPanel(numericInput("c1", "Example", NA),
               tags$p(actionButton("update", "Update")),
               tags$p(actionButton("reset", "Clear")),
               tags$p(actionButton("restart", "Restart")),
               textOutput("count"),
               htmlOutput("display")
  ),
  mainPanel(  DT::dataTableOutput("example"))
)

server <- function(input, output, session) {

  # stores the current data frame
  values <- reactiveVal(data.frame(A = 1, B = 2, C = 3))

  # update values table on button click
  observeEvent(input$update,{

    old_values <- values()

    A_new <- input$c1
    B_new <- A_new + 2
    C_new <- A_new + B_new

    new_values <- data.frame(A = A_new, B = B_new, C = C_new)

    # attach the new line to the old data frame here:
    new_df <- rbind(old_values, new_values)

    #store the result in values variable
    values(new_df)

    #reset the numeric input to NA
    updateNumericInput(session, "c1", "Example", NA)

  })

  #Delete last row
  deleteEntry <- observeEvent(input$reset,{
    values( values()[-nrow(values()),])
  })

  updateCounter <- reactiveValues(i = 0)

  ##This output value must be reset to 0
  output$count <- renderText({
    paste0("Iteractions: ", updateCounter$i)
  })

  observe({
    input$update
    isolate({
      updateCounter$i <- updateCounter$i + 1
    })
  })

  observe({
    input$reset
    isolate(updateCounter$i <- updateCounter$i - 1)
  })

  #Restart
  defaultvalues <- observeEvent(input$restart, {
    isolate(updateCounter$i == 0)
    values( values()[1,])
    updateCounter$i <- 0
  })

  Total <- reactive({ colSums(values()[3]) })

  output$display  <- renderText({
    partialsum <-Total()
    if(updateCounter$i==3) {
      value3 <<- partialsum
      return(paste("Partial result", value3))
    }
    if (updateCounter$i < 3){
      return()
    }
    if (updateCounter$i == 0){
      return()
    }
    if(updateCounter$i > 3) {
      display1 <- paste("Partial result", value3)
      display2 <- paste("Total result", partialsum)
      twolinesdisplay<<- HTML(paste(display1, display2, sep = '
'))
      return(twolinesdisplay)

    }
  })
  # # Print the table on mail panel
  output$example <- DT::renderDataTable({ values() })
}

shinyApp(ui, server)

It seems like
updateCounter$i <- 0

works while
updateCounter <- reactiveValues(i = 0)

does not.


text:
Q: Is it possible to bind a DropDownList on OnLoad method? I have a dynamic table with many DropDownLists which have dynamic 'ids'. I need to bind them when they are selected but the method OnLoad doesn't work. It works with OnClick but it's not the better way to do that.
This is my DropDown:
@Html.DropDownList("reagB-" + const.Id, new SelectList(new List<Reagente>(), "Id ", "Nome"), Resources.Geral.Selecione, new { onchange = "SelecionaReagente($(this));", onclick = "OnClickReagente($(this), " + (resultado != null ? resultado.ReagenteId : 0) + ");", onLoad = "OnLoadReagente($(this));" })

And this is my jquery code:
function OnClickReagente(cbo, ReagenteId) {
var gcId = cbo.attr("id").split('-')[1];

$("#reagB-" + gcId + " option").remove();

$.ajax({
    url: "/Grupo/ComboReagentes",
    dataType: 'json',
    type: "POST",
    data: {
        grupoConstituinteId: gcId,
        equipamentoId: cbo.val()
    },
    success: function (data) {
        var cboReagente = $("#reagB-" + gcId);

        $.each(data, function (i, item) {
            if (item.Id == ReagenteId && ReagenteId > 0) {
                cboReagente.append("<option value='" + item.Id + " selected='selected''>" + item.Nome + "</option>");
            } else {
                cboReagente.append("<option value='" + item.Id + "'>" + item.Nome + "</option>");
            }
        });
    }
})

}
When I select the dropdown the OnClick is called but it occurs every time I select the dropdown. What I need is to load de dropdown only in the first click. Today it's working in another way but I need to improve the performance.
Any idea?
Thanks!

A: You can use jquery.one for your purpose,
$(function(){
       $(".dropdown-class").one("click",function(){//call the method you specified in onclick here})
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Жизненный цикл активности Android У меня в программе есть отдельная активность, внутри нее 3 кнопки. При нажатии кнопки данные отправляются в firebase. Но после отправки(setValue) активность перезагружается, как при recreate(), хотя от нее этого не требуется. Поведение активности при нажатии на любую кнопку примерно такое в моем случае, как я выяснил из отладочных выводов в консоль: onCreate -> onStart -> onResume -> нажатие на кнопку -> onPause -> onCreate -> onStart -> onResume -> onStop и дальше по кругу после каждого нажатия. Слушатели на кнопки я установил в onCreate. Еще больше меня запутывает то, что если не обращаться к firebase, нажатия на кнопки не вызывают никаких действий у активности самостоятельно, как и должно быть. Ниже привел практически весь код, речь идет о кнопках типа RadioButton.
public class WorkerCabinetActivity extends AppCompatActivity {
FirebaseUser dbuser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference db2 = FirebaseDatabase.getInstance().getReference();
public static final String APP_PREFERENCES = "mysettings";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worker_cabinet);
    Button btnSignOut = findViewById(R.id.sign_out_button);
    RadioButton btnOnlineFree = findViewById(R.id.online_free_button);
    RadioButton btnOnlineBusy = findViewById(R.id.online_busy_button);
    RadioButton btnOffline = findViewById(R.id.offline_button);

    btnOnlineBusy.setOnClickListener(v -> db2.child("Users/" + dbuser.getUid() + "/status").setValue("online busy"));
    btnOnlineFree.setOnClickListener(v -> db2.child("Users/" + dbuser.getUid() + "/status").setValue("online"));
    btnOffline.setOnClickListener(v -> db2.child("Users/" + dbuser.getUid() + "/status").setValue("offline"));

    btnSignOut.setOnClickListener(v -> {
        SharedPreferences loginPref = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = loginPref.edit();
        editor.clear();
        editor.commit();
        startActivity(new Intent(WorkerCabinetActivity.this, MainActivity.class));
        finish();
    });
}

@Override
protected void onStart() {
    super.onStart();
    System.out.println("----------------------------onStart--------------------------------");
}

@Override
protected void onResume() {

    System.out.println("----------------------------onResume--------------------------------");
    super.onResume();
}

@Override
protected void onPause() {
    System.out.println("----------------------------onPause--------------------------------");
    super.onPause();
}

@Override
protected void onStop() {
    super.onStop();
    System.out.println("----------------------------onStop--------------------------------");
}

@Override
protected void onRestart() {
    super.onRestart();
    System.out.println("----------------------------onRestart-------------------------------");
}
}

Вывод в консоли после нажатия кнопки с this.hashCode():
I/System.out: ----------------------------onPause--------------------------------79732252
V/FA: Recording user engagement, ms: 24281
V/FA: Connecting to remote service
V/FA: Activity paused, time: 27905355
V/FA: onActivityCreated
I/System.out: ----------------------------onStart--------------------------------41611463
----------------------------onResume--------------------------------41611463
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 27905395
V/FA: Connection attempt already in progress
Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 4
I/System.out: ----------------------------onStop--------------------------------79732252
V/FA: Inactivity, disconnecting from the service

Запуск активности из MainActivity:
startActivity(new Intent(MainActivity.this, WorkerCabinetActivity.class));
finish();


text:
Q: Regex only match with set of numbers I have set of numbers have ID number here. Digit in center -01- must be match with 01,21,22,23,24,02. Currently, it just accept whatever value as long it's 2 digit. It just need to accept these set of numbers 01,21,22,23,24,02. Any idea?
[0-9]{2}(([0-0]{1}[1-9]{1})|([1-1]{1}[0-2]{1}))(([0-0]{1}[1-9]{1})|([1-2]{1}[0-9]{1})|[3-3]{1}[0-1]{1})-[01|21|23|24|01]{2}-[0-9]{4}

ID format
880101-01-5332

Here is link for my sample regex: https://regex101.com/r/GYJ6by/2

A: Use parentheses for those limited options. [] is for a character set, but for specific options, you can use (foo|bar|baz).
[0-9]{2}(([0-0]{1}[1-9]{1})|([1-1]{1}[0-2]{1}))(([0-0]{1}[1-9]{1})|([1-2]{1}[0-9]{1})|[3-3]{1}[0-1]{1})-(01|21|23|24|01)-[0-9]{4}


text:
Q: Are Vue 3 third-party components retro-compatible with Vue 2? I have built some components that are meant to be used as third-party components (installed via npm then imported in a parent project) with Vue 2.
Since I plan to upgrade to Vue 3, I will need to upgrade my Vue 2 third-party components to Vue 3. I will provide .esm and .cjs in the build dist/ output (using main and module properties from package.json).
However, when my third-party components will be updated for Vue 3, will they still be able to be used in Vue 2 projects? Is there some kind of retro-compatibility between the 2 versions when building third-party libraries/components?
I am building my SFC third-party components with rollup.js (as recommended by the Vue team) and some plugins such as rollup-plugin-vue, rollup-plugin-postcss, @rollup/plugin-commonjs, etc.


text:
Q: Variable is incremented by 2 threads without synchronization In an interview, I was asked a question that a variable is incremented 200 times by 2 threads without synchronization, what s the maximum and minimum value of variable?
Please could someone help me with the answer.
Type of variable int.
Each increment is of 1.
Initial value is not told to me.

A: The interesting problem here is that this interview question is open-ended.
The only sensible way to answer this question in an interview is to narrow down the unknowns.

*

*Do you know the type of variable to begin with?  It'd be awkward to increment a short by a long.

*Do we know what the variable starts at?  It could start at Integer.MIN_VALUE for all we know, and thus the "max" could be a very very small number.

*Do you know how much the variable is being incremented by?  Incrementation assumes +1, but that may not be the case.
This is how you would answer the question without getting into implementation details; be sure that you narrow down the requirements and get specific details of scope and starting expectations before you attempt an answer.
To the actual coding part of this, consider that either thread could see stale data.  There's no guarantee that the variable will increment anything beyond the number of times you're invoking it (multiplied by your increment value), so there is a hard ceiling and floor.  Both depend on you disambiguating the unknowns.

A: Considering the no of increments of 200 and assuming each increment is of 1 and type of variable int my guess is:-

*

*Max= variable current value+ 400,
Considering worst case scenario where 1st thread incremented the value 200 times and then 2nd thread incremented it by 200 times.

*Min= variable current value+2

*

*Thread1 & Thread2 copy variable.

*Thread1 increments 199 times. so variable
becomes variable + 199

*Thread2 increments once. so variable becomes variable +
1

*Thread1 copies variable (value = variable + 1)

*Thread2 increments 199
times. so variable becomes variable + 200

*Thread1 increments once. so variable
becomes variable + 2

The max and min will is dependent on variable current value and each increment size, here assumed it be 1.


text:
Q: CurrencyWidget app run time errors I am new to android programming, just got the code from http://www.droiddraw.org/tut4.html and trying to make a currency converter application. I am planning to get the currency conversion rates from the Internet and using JSON in the app. The problem is that  I cannot run the applications and I have tried every possible thing and solutions available on the Internet to solve this issue e.g. clean project, build, refresh, re-importing, etc . Please help me and point out that where I am missing anything which is causing Fatal Exception and the app displays that "CurrencyWidget has stopped unexpectedly ".
I am attaching my full project code and LogCat errors here, please help me.
CurrencyWidget.java

package com.kwantlen.android.currencywidget;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class CurrencyWidget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // To prevent any ANR timeouts, we perform the update in a service
        context.startService(new Intent(context, UpdateService.class));
    }

    public static double getRate() {
        // In a real app, you might want to cache this object for performance.
        HttpClient http = new DefaultHttpClient();
        // In reality this would be a dynamic service.
        HttpGet get = new HttpGet("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=");

        double rate = 0.00;
        try {
            HttpResponse response = http.execute(get);
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            response.getEntity().writeTo(outstream);
            outstream.flush();
            outstream.close();
            String data = new String(outstream.toByteArray(), "UTF-8");
            JSONObject obj = new JSONObject(new JSONTokener(data));
            rate = obj.getDouble("rate");
        } catch (IOException ex) {
            Log.e("CurrencyWidget", "IO Error", ex);
        } catch (JSONException ex) {
            Log.e("CurrencyWidget", "Parse error", ex);
        }
        return rate;
    }

    /**
     * Reads the current rate from droiddraw.org.
     */
    public static class UpdateService extends Service {
        @Override
        public void onStart(Intent intent, int startId) {
            // Build the widget update for today
            RemoteViews updateViews = buildUpdate(this, getRate());

            // Push update for this widget to the home screen
            ComponentName thisWidget = new ComponentName(this, CurrencyWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }

        public RemoteViews buildUpdate(Context context, double rate) {
            // Build an update that holds the updated widget contents
            RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);

            // Build the text for the widget
            DecimalFormat format = new DecimalFormat("##.##");
            String euroToDollar = format.format(rate);
            String dollarToEuro = format.format(1 / rate);
            updateViews.setTextViewText(R.id.etod, "Euros to Dollars: " + euroToDollar);
            updateViews.setTextViewText(R.id.dtoe, "Dollars to Euros: " + dollarToEuro);

            // Set up the button click handler
            PendingIntent pendingIntent;
            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
            launchIntent.setClass(context, CurrencyWidget.class);

            pendingIntent = PendingIntent.getActivity(context, 0,
                    launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            updateViews.setOnClickPendingIntent(R.id.converter, pendingIntent);

            return updateViews;
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kwantlen.android.currencywidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".CurrencyWidget" >
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <!-- Service to perform web API queries -->
        <service android:name=".CurrencyWidget$UpdateService" />

        <receiver
            android:label="@string/app_name"
            android:name=".CurrencyWidget" >
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_description" />
        </receiver>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

res/layout/widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget30"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appwidget_bg" >
       <Button
        android:id="@+id/converter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="Converter" >
    </Button>

    <TextView
        android:id="@+id/dtoe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="""" >
    </TextView>

    <TextView
        android:id="@+id/etod "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Loading" >
    </TextView>

</RelativeLayout>

/res/xml/widget_description.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dip"
    android:minHeight="72dip"
    android:initialLayout="@layout/widget"
    android:updatePeriodMillis="60000"
    />

LogCat Error

11-25 03:35:06.923: D/AndroidRuntime(351): Shutting down VM
11-25 03:35:06.923: W/dalvikvm(351): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-25 03:35:06.962: E/AndroidRuntime(351): FATAL EXCEPTION: main
11-25 03:35:06.962: E/AndroidRuntime(351): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kwantlen.android.currencywidget/com.kwantlen.android.currencywidget.CurrencyWidget}: java.lang.ClassCastException: com.kwantlen.android.currencywidget.CurrencyWidget
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.os.Looper.loop(Looper.java:123)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-25 03:35:06.962: E/AndroidRuntime(351):  at java.lang.reflect.Method.invokeNative(Native Method)
11-25 03:35:06.962: E/AndroidRuntime(351):  at java.lang.reflect.Method.invoke(Method.java:507)
11-25 03:35:06.962: E/AndroidRuntime(351):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-25 03:35:06.962: E/AndroidRuntime(351):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-25 03:35:06.962: E/AndroidRuntime(351):  at dalvik.system.NativeStart.main(Native Method)
11-25 03:35:06.962: E/AndroidRuntime(351): Caused by: java.lang.ClassCastException: com.kwantlen.android.currencywidget.CurrencyWidget
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
11-25 03:35:06.962: E/AndroidRuntime(351):  ... 11 more

A: CurrencyWidget is an AppWidgetProvider, not an Activity. You are creating a getActivity() PendingIntent to try to start up CurrencyWidget as an Activity. This will not work.


text:
Q: How can I download completed document field data with Docusignapi for all documents I've yet to find the answer to this question after hours of searching, but I'm using the docusign api to pull information about certain envelopes from our account.
I've used the api example here: http://iodocs.docusign.com/APIWalkthrough/getEnvelopeDocuments
What I'm actually looking to do is download the field data within each of the completed documents.
Any guidance on how I could download the field data from all completed documents would be greatly appreciated.
Thanks!
Al

A: Some options:
1) DocuSign connect can send you an XML payload with all of the tab data for all recipients
2) You can use the API (REST in this example) to query the tab details on a per recipient basis: https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST%20API%20References/Get%20Tab%20Information%20for%20a%20Recipient.htm%3FTocPath%3DREST%2520API%2520References%7C_____87

A: As @LuisScott said, you don't need DocuSign API to do this. You would be better suited using DocuSign Connect. Much easier, you do not need to get code approval from DocuSign either.
DocuSign API is for modifying how DocuSign displays or modifies documents. In other words,  pre-processing the envelope.
DocuSign Connect is for post-processing the envelope - which is what you want to do by your own account.
I had a similar question not too long ago that was answered here:
DocuSign Custom Connect - How to make a listener in php example?
Sample listener code:
https://github.com/docusign/docusign-soap-sdk/blob/master/PHP/Connect/index.php
My sample code to pull out form data:
// Figure out the URL of this server
// NOTE: DocuSign only pushes status to HTTPS!
$postBackPath = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
$postBackPath .= ($_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'] );
$postedXml = @file_get_contents('php://input');

if(!empty($postedXml)) {
    // see if this is a post to this page if it is then we have to save it.
    $xml = simplexml_load_string($postedXml);
    $post = $xml;
    print 'Got Envelope ID: ' . $xml->EnvelopeStatus->EnvelopeID . '<br />';
}

foreach($post->EnvelopeStatus->RecipientStatuses->RecipientStatus->FormData->xfdf->fields->children() as $element) {
        foreach($element->attributes() as $a) {
            $fieldArray[(string)$a] = (string)$element->value;
        }
    }

From there, you can do whatever you want with the data.
However, you do have to play around with some settings in DocuSign to get this to work. In particular, in the settings menu there is a DocuSign connect menu, where you can specify where your listener script is, what information you want passed (field data in your case), and when do you want data sent to the script (when envelope is completed).
Also, you have to have DocuSign Connect enabled for your account. If you have API access, you will have access to it as well but sometimes they need to turn it on for you.


text:
Q: Oracle Database can't connect in C# with error ORA-12514 I am trying to connect an Oracle database to my C# project, but I am getting the following error:

ORA-12514 TNS:listener does not currently know of service requested in
  connect descriptor

Screenshot:

I tested with the same values in Sql Developer and it was successful:

The only difference is that I am using SID instead of Service Name, so I tried to create two different connection strings to test it with SID and without it, and was still not able to connect:
string dt = "Data Source = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = <IP>)(PORT = 1521))(CONNECT_DATA = (SID = DB2DEV))); User Id = OMP; Password = <PW>; ";

OracleConnection conn = new OracleConnection(dt1);

if (conn.State != ConnectionState.Open)
{
  labelteste.Text = "Not Opened";
}
else
{
  labelteste.Text = "Open";
}

I used the if condition above to validate if the connection was opened, and it always returned Not Opened.
Does anyone have any idea why is this happening?

A: SID and SERVICE_NAME are entirely different. On the DB server, use the "lsnrctl status" command or "lsnrctl services" to get a listing of all registered service names for the database, then use one of those in your connect string.


text:
Q: Cannot figure this out C programming The program is supposed to remove everything but the letters and create a new string which will have only the letters in upper-case.
However, it is not printing the results.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *remove_up(char input[])
{
    char *new_str = (char *) malloc(strlen(input) + 1);
    int i=0;
    int j=0;
    while (i < strlen(input))
    {
        if (((input[i]) >= 65 && (input[i]<=90)) || ((input[i]>=97) && (input[i]<=122)))
        {
            new_str[j]= toupper(input[i]);
            i++;
            j++;
        }
        else i++;
    }
    return new_str;
}

int main()
{
    char str_1[100];
    char str_2[100];
    printf("Enter first word: ");
    fgets(str_1, sizeof(str_1), stdin);
    printf("Enter second word: ");
    fgets(str_2, sizeof(str_2), stdin);

    char *up_str_1 =(char *) malloc(strlen(str_1) + 1);
    char *up_str_2 =(char *) malloc(strlen(str_2) + 1);

    up_str_1= remove_up(str_1);
    up_str_2= remove_up(str_2);
    printf("%s", up_str_1);
    printf("\n");
    printf("%s", up_str_2);
    return 0;
}

A: There are a few problems, but because this is tagged homework, I'll point them out but not give you the answer.
First of all, this doesn't do what you think:
int i, j = 0;

j will be initialized, but i probably won't start at 0. You need to initialize i to 0 as well.
Next, there's a typo - you missed a closing ] at (input[i<=122).
Finally, based on your answers to the questions, you probably aren't printing the result anyway: look up printf() or cout or whatever you prefer to use for outputting values.

A: It doesn't print results because you haven't used any print statements to show what comes back from your calls to remove_up.
To understand what is going on in your remove_up function, you need to understand this:
http://www.asciitable.com/
This code:
if (((input[i]) >= 65 && (input[i]<=90)) || ((input[i]>=97) && (input[i<=122)))

Is checking to see if a character is an alphabetic character in the ascii character set between these two ranges.  Look at the link above.  If it is in this set it's converting it to upper (redundant for half the data) and saving the result in your newly malloc'd string.
Problems:
 1. You never set a null terminator in "new_str"
 2. You never seem to free anything (though in this code it is trivial, in real code you could create problems, i.e. memory leaks).
 3. "i" is redundant in the while loop.  It's in both the if and else...
 4. Rethink how you're using malloc (you probably don't want to use it this way in your custom functions unless you're going to cleanup after yourself)
There is probably more I'm missing, but that should help you see some problems.

A: Double check your use of parenths - you have more than needed.  You are also missing a ']' in that if statement.  Surprised it compiles.

A: change int i, j = 0; to int i = 0, j = 0;. Your i was initialized with a garbage value greater than strlen(input), and hence never entered the while loop.


text:
Q: Minimal Postfix master.cf I'm currently deploying yet another Postfix MTA and this time I'd like to thin down the master.cf and disable unneeded services to reduce the potential attack surface, and get a better understanding of it in the process.
The MTA should receive emails to virtual users, deliver them to the appropriate maildir and finally relay mail from authenticated users.
Switching to OpenSMTPd (with which my entire configuration can be expressed in a single 15-line file) isn't possible as of right now (no milter support) so I'm stuck with Postfix.
The horror in question :
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
#submission inet n       -       n       -       -       smtpd
pickup    unix  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache

There isn't any man page that describes a minimal configuration, and the man pages of each service don't really tell whether a module is required or not (for some it's easy enough to figure it out, for others it's next to impossible without endless trial and error).
My current failed attempt is the following (submission port omitted, for now I'm only trying to get the mail delivery working) :
smtp inet n - - - - smtpd
cleanup unix n - - - 0 cleanup
qmgr unix - - - 300 1 qmgr
rewrite unix - - - - - trivial-rewrite
proxymap unix - - - - - proxymap
virtual unix - n - - - virtual
anvil unix - - - - 1 anvil
local unix - n - - - local

This kinda works, except all received mail is only delivered (to maildir) on restarting Postfix, and I'm pretty sure it's incomplete and can't handle bounces, so I'm still looking for an answer.

A: I wouln't recommend you to remove service from the default master.cf. You have been bitten by it when you tried minimalist config.
One reason why postfix has many service is security. One of advantage is postfix  run by separate daemon/service to do specific task. So, postfix master can adjust permission and privilege per postfix service. For example qmgr(8) daemon does not talk to the outside world, and it can be run at fixed  low  privilege in a chrooted environment.
Anyway I don't have time to do endless trial and error in order to know what's postfix service that can be disabled. So I give you some info about some service and grouping it by several groups.
# INPUT SERVICE
smtp      inet  n       -       n       -       -       smtpd
#submission inet n       -       n       -       -       smtpd
pickup    unix  n       -       n       60      1       pickup

# PROCESSING SERVICE
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite

# OUTPUT SERVICE
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp

# HELPER
# Generate bounce
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce

# For postfix recipient/sender verification See www.postfix.org/ADDRESS_VERIFICATION_README.html
verify    unix  -       -       n       -       1       verify

# Outgoing Connection manager
scache    unix  -       -       n       -       1       scache

# TLS Cache Manager
tlsmgr    unix  -       -       n       1000?   1       tlsmgr

# maintains statistics about client connection counts or client request rates
anvil     unix  -       -       n       -       1       anvil

# Needed by mailq command
showq     unix  n       -       n       -       -       showq

# Needed by postqueue -f
flush     unix  n       -       n       1000?   0       flush

# Proxymap
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap


text:
Q: how to perform a conditional query on rtl languages in SQl I want to perform conditional query on a table that holds right to left language.
I have used stored procedure to query database from my win form.
code:
CREATE PROCEDURE filerPROC
@Person nchar(50),
@email nvarchar(100)
AS
BEGIN
    select lastname,DOB from Employee where name = @Person
END

when i get the result. it is all ??? instead of person name. how to configure table to work right? i have alreadt tried using N keword, but it gives me syntax error.
insert into Employee (N'rtl lang'......)

A: usually if your database default collation is not set to your purpose language this problem may happen.
simply write the following code based on your selected language :
ALTER database 'database name' collate SQL_Latin1_General_CP1_CI_AS

after the word 'collate' you can replace any language you want. see here :
http://technet.microsoft.com/en-us/library/ms184391.aspx

A: It could be that your application code is not passing the value to @Person in unicode. I see this a lot.  You may need to code it as UTF-8.


text:
Q: complexity of time constructible function In field of computational complexity there is a definition of time constructible function.
As example, in any reasonable and general model, functions like $t_1(n) = n^2, t_2(n) = 2^n$, and $t_3(n) = 2^{2^n}$ are computable in $poly(\log t_i (n))$ steps.
I would to know why it's exactly $poly(\log t_i (n))$ steps?
How can I show it?


text:
Q: What is the web URL to replace an HP drive? (no phone / chat) I have a failed HP drive and would like to replace it using HP's web form (online) process.
Does anyone know what that URL is? I can't find it anywhere.

A: The method is hard to find, just like a lot of things on the HP web-site. The method I use to get there:

*

*Log in to the Business Support Center.

*Click "Edit your profile".

*Click "View or modify my support cases".

That gets me to one spot to do it. There may be others. They do tend to change things around and not fix dead links.


text:
Q: change default character set of PHP functions like "htmlspecialchars" I am using PHP 5.2.6 and my app's character set is UTF-8.
Now, how should I change PHP's default character set?
NOT the one which specifies output's mime time and character set.
But which will change for all the PHP function like htmlspecialchars, htmlentities, etc.
I know, there is a parameter in those functions which takes the character set of the input string. But I don't want to specify for all the functions I use. And if somewhere I forget, it will be mess.
I also know, that I can wrap those functions and create my own wrapper like:
function myHtmlize($str)
{
  return htmlspecialchars($str, ENT_COMPAT, 'UTF-8');
}

I also, don't like this solution.
I really want to tell PHP, that by default take 'UTF-8' as the character set. Not 'iso-8859-1'.
Is it possible?

A: Like this one ? http://us2.php.net/manual/en/function.setlocale.php
* LC_ALL for all of the below
* LC_COLLATE for string comparison, see strcoll()
* LC_CTYPE for character classification and conversion, for example strtoupper()
* LC_MONETARY for localeconv()
* LC_NUMERIC for decimal separator (See also localeconv())
* LC_TIME for date and time formatting with strftime()
* LC_MESSAGES for system responses (available if PHP was compiled with libintl)

A: There is a C-function determine_charset(char *charset_hint ...) which is used to find the "right" charset based on

*

*what has been passed as charset_hint

*the setting of mb_internal_encoding

*default_charset

*compile-time CODESET

*last but not least: LC_CTYPE locale
in that order and depending on whether some extensions are built-in or not.
The "problem" is, when you call htmlentities('xyz') this determine_charset() is called with charset_hint=NULL and the first this function does is:
/* Guarantee default behaviour for backwards compatibility */
if (charset_hint == NULL)
    return cs_8859_1;

You have to call at least htmlentities('xyz', ENT_QUOTES, '')

A: I'm not entirely sure, but I think mbstring.func_overload works with htmlentities.
htmlspecialchars is charset-neutral btw. (At least as long as the charset supports the ascii subset, which utf-8 does).

A: From php.net:

5.4.0     The default value for the encoding parameter was changed to UTF-8.

In modern times you need just update your version of PHP to 5.4 or better and set the default_charset directive in php.ini to UTF-8 (which is already the default). You may also be able to do it programatially like this:
ini_set('default_charset', 'UTF-8');

Sources:

*

*https://www.php.net/manual/en/function.htmlspecialchars.php

*https://www.php.net/manual/en/function.htmlentities.php


text:
Q: Protractor getting stale element reference in page object I am verifying the filter options in a page. Every time I select an option I submit the filters then the page refreshes with the new result. Again I click on the filter button and need to select next radio button. But I am getting stale element reference error.
filterButton.click().then(function () {
  filteroptions.count().then(function (totalradios) {
    console.log("before start" + totalradios);
    filteroptions.each(function (radiooption, index) {
      radiooption.getText()  //getting error at this place on the second iteration
       .then(function (radioName) {
        console.log(radioName, index);
      })
      radiooption.click().then(() => {
        filterSubmit.click().then(function () {
          console.log(totalradios, ' ', index)
          if (index <= totalradios) {
            filterButton.click();
          }
        })
      })
    })
  })
})

Updated from each(function) to For loop
 var filteroptions = element.all(by.css("md-radio-group.ng-pristine.ng-untouched.ng-valid._md.layout-row.ng-not-empty md-radio-button"));

filterButton.click().then(function () {
  filteroptions.count().then(function (totalradios, async) {
   console.log("before start" + totalradios);
   for (var i = 0; i < totalradios; i++) {
   console.log("recalulated true " + totalradios);
   (function (index) {
    console.log("select filter option");
    filteroptions.get(index).click();
    console.log("click submit button");
    filterSubmit.click();
    console.log("click filter button");
    filterButton.click();
    console.log("get new totalcounts");
    let setradios = filteroptions.count().then((value) => {
    return value;
   })
   console.log("recalulated totalradios" + setradios);
   totalradios = setradios;
   })(i);
  }
  })
})

Tried to read the list in a separate function
var getfiltercount = function () {
  filteroptions = element.all(by.css("md-radio-group.ng-pristine.ng-untouched.ng-valid._md.layout-row.ng-not-empty md-radio-button")); // filtertext
  return filteroptions.count().then(function (addradios) {
  console.log("addradios is " + addradios);
 })
  return addradios;
}

A: Because selenium will also treat below situation as entering new page:

*

*Page whole refresh, even the page url not change

*Page partial refresh, even the page url not change

Once selenium detect entering new page, the reference of elements found on previous page are invalid, if you still use them in script, selenium will report
StaleReferenceException.
To resolve this problem is simple to find the element again on new page to get the new reference for later using.
// function to test when choose yes radio button
function testYesRaidoButton() {
    // click `yes` radio button
    element(<locator of `yes` raido button>).click();
    // find how many new radio buttons will appear after choose `yes`
    element.all(<locator of sub radio buttons of `yes`>).count()

    .then(function (totalradios) {
        console.log("before start " + totalradios);

        for(var i=0;i<totalradios;i++) {

            (function(index) {

                // click one of new radio button of `yes`
                element.all(<locator of sub radio buttons of `yes`>).get(index).click();

                // click `submit` button
                element(<locator of filterSubmit>).click();

                // click `yes` radio button on `new page` again
                element(<locator of `yes` raido button>).click();

            })(i);

        }
    });
}

// function to test when choose no radio button
function testNoRadioButton() {
    // click `no` radio button
    element(<locator of `no` raido button>).click();
    // find how many new radio buttons will appear after choose `no`
    element.all(<locator of sub radio buttons of `yes`>).count()

    .then(function (totalradios) {
        console.log("before start " + totalradios);

        for(var i=0;i<totalradios;i++) {

            (function(index) {

                // click one of new radio button of `no`
                element.all(<locator of sub radio buttons of `no`>).get(index).click();

                // click `submit` button
                element(<locator of filterSubmit>).click();

                // click `no` radio button on `new page` again
                element(<locator of `no` raido button>).click();

            })(i);

        }
    });
}

Actually, the two function has many similar code lines,
you can optimize and merge into one function to accept different parameter value to archive same purpose.
Alternative solution to archive some goal by using two loop, but not recommend to do as that, because code is hard to read and understand, pretty not friendly.
// iterate `yes` and 'no'
for (var j = 0; j < 2; j++) {

  (function(__index) {

    element.all(<locator of `yes` and `no` radio button>).get(__index).click();

    element.all(<locator of new radio buttons>).count()

    .then(function(totalradios) {
      console.log("before start " + totalradios);

      // iterate new radio buttons
      for (var i = 0; i < totalradios; i++) {

        (function(index) {

          // click one of new radio buttons
          element.all(<locator of new radio buttons>).get(index).click();

          // click `submit` button
          element(<locator of filterSubmit> ).click();

          // click `yes` or `no` radio button on `new page` again
          element.all(<locator of `yes` and `no` radio button>).get(__index).click();

        })(i);

      }
    });

  })(j)

}


text:
Q: Azure ML: how to access logs of a failed Model deployment I'm deploying a Keras model that is failing with the error below. The exception says that I can retrieve the logs by running "print(service.get_logs())", but that's giving me empty results. I am deploying the model from my AzureNotebook and I'm using the same "service" var to retrieve the logs.
Also, how can i retrieve the logs from the container instance? I'm deploying to an AKS compute cluster I created. Sadly, the docs link in the exception also doesnt detail how to retrieve these logs.
More information can be found using '.get_logs()' Error:

{   "code":
"KubernetesDeploymentFailed",   "statusCode": 400,   "message":
"Kubernetes Deployment failed",   "details": [
    {
      "code": "CrashLoopBackOff",
      "message": "Your container application crashed. This may be caused by errors in your scoring file's init() function.\nPlease check
the logs for your container instance: my-model-service. From
the AML SDK, you can run print(service.get_logs()) if you have service
object to fetch the logs. \nYou can also try to run image
mlwks.azurecr.io/azureml/azureml_3c0c34b65cf18c8644e8d745943ab7d2:latest
locally. Please refer to http://aka.ms/debugimage#service-launch-fails
for more information."
    }   ] }

UPDATE
Here's my code to deploy the model:
environment = Environment('my-environment')
environment.python.conda_dependencies = CondaDependencies.create(pip_packages=["azureml-defaults","azureml-dataprep[pandas,fuse]","tensorflow", "keras", "matplotlib"])
service_name = 'my-model-service'

# Remove any existing service under the same name.
try:
    Webservice(ws, service_name).delete()
except WebserviceException:
    pass

inference_config = InferenceConfig(entry_script='score.py', environment=environment)
comp = ComputeTarget(workspace=ws, name="ml-inference-dev")
service = Model.deploy(workspace=ws,
                       name=service_name,
                       models=[model],
                       inference_config=inference_config,
                       deployment_target=comp
                      )
service.wait_for_deployment(show_output=True)

And my score.py
import joblib
import numpy as np
import os

import keras

from keras.models import load_model
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType

def init():
    global model

    model_path = Model.get_model_path('model.h5')
    model = load_model(model_path)
    model = keras.models.load_model(model_path)

# The run() method is called each time a request is made to the scoring API.
#
# Shown here are the optional input_schema and output_schema decorators
# from the inference-schema pip package. Using these decorators on your
# run() method parses and validates the incoming payload against
# the example input you provide here. This will also generate a Swagger
# API document for your web service.
@input_schema('data', NumpyParameterType(np.array([[0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.0]])))
@output_schema(NumpyParameterType(np.array([4429.929236457418])))
def run(data):

    return [123] #test

Update 2:
Here is a screencap of the endpoint page. Is it normal for the CPU to be .1? Also, when i hit the swagger url in the browser, i get the error: "No ready replicas for service doc-classify-env-service"

Update 3
After finally getting to the container logs, it turns out that it was choking  with this error on my score.py

ModuleNotFoundError: No module named 'inference_schema'

I then ran a test that commented out the refs for "input_schema" and "output_schema" and also simplified my pip_packages and the REST endpoint come up! I was also able to get a prediction out of the model.
pip_packages=["azureml-defaults","tensorflow", "keras"])

So my question is, how should I have my pip_packages for the scoring file to utilize the inference_schema decorators? I'm assuming I need to include azureml-sdk[auotml] pip package, but when i do so, the image creation fails and I see several dependency conflicts.

A: Try retrieving your service from the workspace directly
ws.webservices[service_name].get_logs()

Also, I found deploying an image as an endpoint to be easier than inference+deploy model (depending on your use case)
my_image = Image(ws, name='test', version='26')
service = AksWebservice.deploy_from_image(ws, "test1", my_image, deployment_config, aks_target)


text:
Q: Order of $10$ in $\mathbb{Z}_{25}$ From Prof. Pinter's "A Book of Abstract Algebra":

What is the order of $10$ in $\mathbb{Z}_{25}$?

I know from the chapter, "Order of Group Elements," that the order is defined as:

If there exists a nonzero integer $m$ such at $a_{m}=e$, then the order of the element $a$ is defined to be the least positive integer $n$ such that $a^{n}=e$. (where $e$ is the neutral element).

What binary operation must I use to figure out the order of $10$ in $\mathbb{Z}_{25}?$

A: When you are looking at the group of the integers mod $n$, it is (usually) implied that the binary operation is integer addition mod $n$. Working it out, this would mean that $10$ has order $5$ in $\mathbb{Z}_{25}$.

A: You are in search for the smallest positive integer $j$ such that $10j \equiv 0 \ (\textrm{mod} \ 25)$.
$10$
$10 \cdot 2= 20$
$10 \cdot 3 = 30 = 25+ 5 \equiv 5 \ (\textrm{mod} \ 25)$
$10 \cdot 4 = 40 = 25+15 \equiv 15 \ (\textrm{mod} \ 25)$
$10 \cdot 5 = 50 = 25+25 \equiv 0 \ (\textrm{mod} \ 25)$


text:
Q: How Can I Set an Environment Variable Equal to a Different Environment Variable in a package.json Script? So I want to do something like this:
"scripts": {
    "build": "DB_URL=DB_MIGRATION_URL prisma migrate deploy"
}

Where before I run a command, I set an enviornment variable equal to the value of another env variable. I got it working by manually adding the value like: "DB_URL="postgres..." prisma migrate deploy" but cannot figure out how to do it dynamically.
I have seen things about cross-env or dotenv, just need pointed in right direction!
The reason I want to do something like this is on my Database, there are different values for DB_MIGRATION_URL depending on what branch we are deploying from, so hard-coding only works for either staging or production, and I want it to work from both.
Thank you.

A: Use dotenv.
Example:
npm install dotenv

Code wise:
# Will load .env (which contains all the values for your different environment variables),
# from your root directory.
# There are means to provide another specific .env file....

require('dotenv').config();

#You can then use it in your code this way...

# Will print the value of your S3_BUCKENT environment variable.
# console.log(process.env.S3_BUCKET)

.env (in your root folder):
VAR1="..."
VAR2="..."
...

More information are available here:

*

*https://www.npmjs.com/package/dotenv

*https://www.twilio.com/blog/working-with-environment-variables-in-node-js-html


text:
Q: python - pip install mysqlclient on Arch Linux I need to use MySQLdb in Python 3.7:
import MySQLdb

this should install through the command pip install mysqlclient which however gives me an error on Arch Linux. It seems prerequisites are missing.
I see that on other distributions, like Ubuntu, these can be installed via the command:
sudo apt-get install python-dev default-libmysqlclient-dev

Solutions are available for other distro, but I could not find them for Arch Linux.

A: In the end the solution was to install gcc and mysql
pacman -S gcc

pacman -S mysql

and just later run
pip install mysqlclient

A: Does it work through pacman? pacman -S python-mysqlclient

A: If you install 'python-mysqlclient' with pacman  then you can install it without any problem.

*

*pacman -S python-mysqlclient

*pip install mysqlclient


text:
Q: Отвалился eth0 - OpenWRT и HummingBoard Здравствуйте. На столе лежит HummingBoard  i.MX6 Solo. Решил установить на него OpenWRT, оставил u-boot и kernel от прошлой ОС Cubox-i. Система запустилась. Одна проблема, она не видит сетевую карту. Прошу специалистов помочь решить эту проблему.

A: вы пишете, что «оставили загрузчик и программу linux» от какой-то «прошлой» операционной системы.
если программа linux в этой «прошлой» системе была скомпилирована с использованием модулей, то скопировать надо было также и скомпилированные модули.


text:
Q: How do I bring an Oracle BLOB into SQL Server? I have two databases: Oracle 10G and SQL Server 2000.
Inside the Oracle database, I have several MS Word documents stored as BLOBs. What I need to do is extract the files from Oracle and place them into SQL Server. I am curious as to how I do this?
I have heard something about DTS but not sure if that is something to look into.

A: In sql server 2000, your choices for blob storages is either binary/varbinary or image.
binary/varbinary can be used if the blob is <=8000bytes and image should be use when blob is larger than 8000 bytes.
Personally I would use perl DBI to extract the files from oracle and insert them into sql server since I'm comfortable with perl.
You can also use oracle's hsodbc to make a link between oracle and the sql server and attempt to insert data from one to the other.
If you are more comfortable in sql server then DTS is a option.  I'm not sql server person so I would favor a different approach.


text:
Q: Recursive fibonacci algorithm correctnes? [proof by induction] im studying for the computer science GRE, as an exercise i need to provide a recursive fibonacci algorithm and show its correctness by mathematical induction.
here is my recursive version of fibonacci algorithm:
Fibonacci(n):
    IF n = 0 then    // a stopping case
        return 0
    elseif n = 1 then    // another stopping case
        return 1
    else
        return Fibonacci(n-1) + Fibonacci(n-2)  // closer to stopping case
    endif

How can i proof the previous algorithm by induction?

A: There's not actually very much to do, since the algorithm so closely follows the recursive definition of the Fibonacci numbers.
Clearly $\operatorname{Fibonacci}(0)=0=F_0$ and $\operatorname{Fibonacci}(1)=1=F_1$; that gets the induction off the ground. Now suppose that $m>1$, and your algorithm returns the correct value for all non-negative integers $n<m$. Then on the input $m$ it returns $$\operatorname{Fibonacci}(m-1)+\operatorname{Fibonacci}(m-2)\;,$$ which by the induction hypothesis is $F_{m-1}+F_{m-2}=F_m$, so it returns the correct value for all non-negative integers $n\le m$.


text:
Q: FlexSlider Images appearing in different location for IE and Chrome I have some flexslider images on my page(s), and I can't seem to figure out why the images are displaying in a different location in IE vs. Chrome.  Does anyone have any advice how I can make the location consistent regardless of browser?  Chrome is showing in the correct location, and IE has the images pushed over to the right....'off of the boundaries of my page.
#main {
   margin-left: 575px;
   margin-top: 175px;
   margin-right: 0px;
   overflow: hidden;}

...


text:
Q: Magento: display all level2 categories I have categories with 4 levels.
Example :
level0category --> level1category --> level2category -->lastlevel_level3cateogory
is it possible on lastlevel to display the categories that are in level2 and only? (on a block that i load a custom left.phtml)
I was thinking something with automatic category detection and not have to set cat_id=
Edit: this is what i was looking for, after mix of code from different sources.
<?php
    $currentCat = Mage::registry('current_category');

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
    {
        // current category is a toplevel category
        $loadCategory = $currentCat;
    }
    else
    {
        // current category is a sub-(or subsub-, etc...)category of a toplevel category
        // load the parent category of the current category
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
        // @TODO enhance for more nested category levels to display sub-categories
    }
    $subCategories = explode(',', $loadCategory->getChildren());

    foreach ( $subCategories as $subCategoryId )
    {
        $cat = Mage::getModel('catalog/category')->load($subCategoryId);

if ($cat->getIsActive())
{
    if ($currentCat->getEntityId() == $subCategoryId)
    {
        echo '
'.$cat->getName().'
';
    }
    else
    {

  echo 'getURL().'">'.$cat->getName().'
';    }
}

    }
?>

A: $categories = Mage::getModel('catalog/category')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->addIsActiveFilter()
                    ->addAttributeToFilter('level',2)
                    ->addOrderField('name');

make sure this line is there
apply ->addAttributeToFilter('level',2)


text:
Q: make a flask query more efficient I am using this query to get users on bases of status and type of school. Like If I have 5 type of school and 5 type of users I have to query 25 times . Is there any good solution or I am doing it right ?
   all_users = (
            session.query(User)
            .join(School)
            .filter(
                School.type == 1,
                User.status == 2,
            )
            .all()
        )

A: This is a pretty common situation with a well understood answer: is in_ on the filter like so:
all_users = (
        session.query(User)
        .join(School)
        .filter(
            School.type.in_(my_list_of_school_ids),
            User.status.in_(my_list_of_user_status),
        )
        .all()
    )


text:
Q: How to use logcat How do I use logcat in Eclipse? I know where it is, but it is always blank and nothing shows up in it. What could the problem be?

A: did you try to print something on the logcat like.
 Log.d("tagname","string you want to execute");

in your code?
then check on the logcat environment in the left side, if you have selected a filter, to be safe choose "All message(no filter)" button.

A: Look at your left panel where you will found symbol of device, click on it, and select your appropriate device or emulator, hope it will provide you info into your logcat.

If you are still not getting anything then restart your adb


text:
Q: Authorize a Credit Card returns empty refTransId on Sandbox environment I use the NodeJS SDK to authorize the credit card for later capturing and get successful response but with empty refTransId, so I can't capture the transaction.
I wonder why and if the Sandbox environment should return the refTransId?
The request is as follow:
CreateTransactionRequest {
  merchantAuthentication: MerchantAuthenticationType {
    name: 'xxxxx',
    transactionKey: 'xxxxxxxx',
    sessionToken: null,
    password: null,
    impersonationAuthentication: null,
    fingerPrint: null,
    clientKey: null,
    accessToken: null,
    mobileDeviceId: null
  },
  clientId: null,
  refId: '2MFSJPT0XC0KJ60NS1P1',
  transactionRequest: TransactionRequestType {
    transactionType: 'authOnlyTransaction',
    amount: 100,
    currencyCode: 'USD',
    payment: PaymentType {
      creditCard: null,
      bankAccount: null,
      trackData: null,
      encryptedTrackData: null,
      payPal: null,
      opaqueData: [OpaqueDataType],
      emv: null,
      dataSource: null
    },
    profile: null,
    solution: null,
    callId: null,
    terminalNumber: null,
    authCode: null,
    refTransId: null,
    splitTenderId: null,
    order: OrderType {
          invoiceNumber: '82',
          description: 'Authorize Client CC',
          discountAmount: null,
          taxIsAfterDiscount: null,
          totalTaxTypeCode: null,
          purchaserVATRegistrationNumber: null,
          merchantVATRegistrationNumber: null,
          vatInvoiceReferenceNumber: null,
          purchaserCode: null,
          summaryCommodityCode: null,
          purchaseOrderDateUTC: null,
          supplierOrderReference: null,
          authorizedContactName: null,
          cardAcceptorRefNumber: null,
          amexDataTAA1: null,
          amexDataTAA2: null,
          amexDataTAA3: null,
          amexDataTAA4: null
    },
    lineItems: ArrayOfLineItem { lineItem: [Array] },
    tax: null,
    duty: null,
    shipping: null,
    taxExempt: null,
    poNumber: null,
    customer: CustomerType {
          type: 'individual',
          id: '627d08cfc5c631872d9',
          email: 'shayzalm234an@gmail.com',
          phoneNumber: null,
          faxNumber: null,
          driversLicense: null,
          taxId: null
    },
    billTo: CustomerAddressType {
          firstName: 'adas',
          lastName: '',
          company: '',
          address: 'Southwest 1st Avenue 3298',
          city: 'Miami-Dade County',
          state: 'Florida',
          zip: undefined,
          country: 'USA',
          phoneNumber: null,
          faxNumber: null,
          email: null
    },
    shipTo: null,
    customerIP: null,
    cardholderAuthentication: null,
    retail: null,
    employeeId: null,
    transactionSettings: null,
    userFields: null,
    surcharge: null,
    merchantDescriptor: null,
    subMerchant: null,
    tip: null,
    processingOptions: null,
    subsequentAuthInformation: null,
    otherTax: null,
    shipFrom: null,
    authorizationIndicatorType: null
  }
}

The response is as follow:
{
"messages": {
  "resultCode": "Ok",
  "message": [
    {
      "code": "I00001",
      "text": "Successful."
    }
  ]
},
"transactionResponse": {
  "responseCode": "1",
  "authCode": "000000",
  "avsResultCode": "P",
  "cvvResultCode": "",
  "cavvResultCode": "",
  "transId": "0",
  "refTransID": "",
  "transHash": "",
  "testRequest": "1",
  "accountNumber": "XXXX0000",
  "accountType": "Visa",
  "messages": {
    "message": [
      {
        "code": "1",
        "description": "This transaction has been approved."
      }
    ]
  },
  "transHashSha2": ""
}

This is the documentation reference I use:
https://developer.authorize.net/api/reference/index.html#payment-transactions-authorize-a-credit-card.

A: I found out that my test account was on test mode and had to be switched to "live" in order to simulate transactions.


text:
Q: intellj IDEA doesnt build jar properly I followed this "tutorial" to build a jar from a project in intellj. The project includes a small spring application, that works running from intellij itself.
If I build the jar and run it from the command line, it says "Error: Could not find or load main class". If I run the main.class file using java .\main.class, the same Message shows up.
I specified the Main class in Intellij-IDEA before building the Jar, and the Main.java file looks something like this:
@SpringBootApplication
@RestController
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @GetMapping("/index")
    public String index() {
           . . . .
    }
}

A: I performed some test
So I created a new project

I left the default options

test with the intellij build

not work

not work

test with the build provided in spring boot

it works

A: I forgot to tell you that
you can create an order in intellij

Change configuration and launch the command from Intellij by pressing the play button


text:
Q: Kafka Streams parallel processing not working I'm learning Kafka Stream and I want to build a simple application that reads lines of text from one topic and puts number of letter occurrences to InfluxDB. My second goal is to run it in parallel. I would like to have two running instances of Kafka Stream both of them processing input at the same time but from different partitions. Unfortunately, after I launch both instances only one of them is working second one is waiting.
My configuration is as follows:
* input topic has 4 partitions
* Stream application has a property num.stream.threads set to 2
Here is the source code:
public class LineStatisticsStream {

  static Pattern letterPattern = Pattern.compile("[a-z]");
  InfluxDB influxDB;

  public static void main(String[] args) {
    new LineStatisticsStream().start();
  }

  Properties getStreamProperties() {
    Properties properties = new Properties();
    properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
    properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"lineStatistics4");
    properties.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
    properties.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG,2);
    return properties;
  }

  Topology getStreamTopology(ForeachAction<String,Long> action) {
    StreamsBuilder builder = new StreamsBuilder();
    KStream<String,String> linesStream = builder.stream("lines", Consumed.with(Serdes.String(),Serdes.String()));
    linesStream.flatMapValues(this::findAllLetters)
        .map((k,v)-> KeyValue.pair(v,v))
        .groupByKey(Grouped.with(Serdes.String(),Serdes.String()))
        .count()
        .toStream()
        .to("letterCount",Produced.with(Serdes.String(),Serdes.Long()));

    KStream<String,Long> countStream = builder.stream("letterCount", Consumed.with(Serdes.String(),Serdes.Long()));
    countStream.peek(action);
    return builder.build();
  }

  private void insertToInfluxDB(String letter, Long count) {
    influxDB.write(Point.measurement("lettersCount")
        .tag("letter",letter)
        .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
        .addField("count", count)
        .build()
       );
  }

  private List<String> findAllLetters(String s) {
    List<String> letters = new ArrayList<>();
    Matcher matcher=    letterPattern.matcher(s.toLowerCase());
    while(matcher.find()) {
      letters.add(matcher.group(0));
    }
    return letters;
  }

  private void start() {
    influxDB = InfluxDBFactory.connect("http://127.0.0.1:8086");
    influxDB.setDatabase("letters");
    influxDB.enableBatch(BatchOptions.DEFAULTS);

    final KafkaStreams streams = new KafkaStreams(getStreamTopology(this::insertToInfluxDB), getStreamProperties());
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(()->{streams.close();influxDB.close();}));

  }
}

And last few lines of a log from "waiting" application:
2019-11-18 21:27:16 INFO  ConsumerCoordinator:982 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-consumer, groupId=lineStatistics4] Found no committed offset for partition lines4-2
2019-11-18 21:27:16 INFO  ConsumerCoordinator:982 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-consumer, groupId=lineStatistics4] Found no committed offset for partition lines4-1
2019-11-18 21:27:16 INFO  RocksDBTimestampedStore:82 - Opening store KSTREAM-AGGREGATE-STATE-STORE-0000000003 in regular mode
2019-11-18 21:27:16 INFO  RocksDBTimestampedStore:82 - Opening store KSTREAM-AGGREGATE-STATE-STORE-0000000003 in regular mode
2019-11-18 21:27:16 INFO  KafkaConsumer:1068 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2019-11-18 21:27:16 INFO  KafkaConsumer:1068 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2019-11-18 21:27:16 INFO  StreamThread:212 - stream-thread [lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2] State transition from PARTITIONS_ASSIGNED to RUNNING
2019-11-18 21:27:16 INFO  KafkaConsumer:1068 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2019-11-18 21:27:16 INFO  KafkaConsumer:1068 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2019-11-18 21:27:16 INFO  StreamThread:212 - stream-thread [lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1] State transition from PARTITIONS_ASSIGNED to RUNNING
2019-11-18 21:27:16 INFO  KafkaStreams:263 - stream-client [lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099] State transition from REBALANCING to RUNNING
2019-11-18 21:27:16 INFO  ConsumerCoordinator:982 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-consumer, groupId=lineStatistics4] Found no committed offset for partition lines4-1
2019-11-18 21:27:16 INFO  ConsumerCoordinator:982 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-consumer, groupId=lineStatistics4] Found no committed offset for partition lines4-2
2019-11-18 21:27:16 INFO  ConsumerCoordinator:525 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-consumer, groupId=lineStatistics4] Setting offset for partition lineStatistics4-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition-0 to the committed offset FetchPosition{offset=73, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=localhost:9092 (id: 1 rack: null), epoch=0}}
2019-11-18 21:27:16 INFO  ConsumerCoordinator:525 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-consumer, groupId=lineStatistics4] Setting offset for partition lines4-0 to the committed offset FetchPosition{offset=63, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=localhost:9092 (id: 1 rack: null), epoch=0}}
2019-11-18 21:27:16 INFO  ConsumerCoordinator:525 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-consumer, groupId=lineStatistics4] Setting offset for partition lineStatistics4-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition-3 to the committed offset FetchPosition{offset=40, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=localhost:9092 (id: 1 rack: null), epoch=0}}
2019-11-18 21:27:17 INFO  SubscriptionState:348 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-2-consumer, groupId=lineStatistics4] Resetting offset for partition lines4-1 to offset 0.
2019-11-18 21:27:17 INFO  SubscriptionState:348 - [Consumer clientId=lineStatistics4-5e5e2a71-2a3b-4e51-9d4c-4e470a8a8099-StreamThread-1-consumer, groupId=lineStatistics4] Resetting offset for partition lines4-2 to offset 0.


text:
Q: Parent's scrolling cannot working from iframe - Flutter Web App I created a web app with Flutter for web, and embed to a Wordpress website with iframe. But when I want to scroll iframe to show full web app, it's not working. I just want a performance like the attached gif.
I tried with some css like 'overflow: scroll', 'overflow-scroll:true',...
Many thanks!


text:
Q: Microsoft Endpoint Protection Windows Azure 2.0 I've been running Azure 1.7 for .Net in production for some time and we are using Microsoft Endpoint Protection (MEP). I've recently started the upgrade to 2.0 for Azure and as far as I can tell, the MEP plugin hasn't been upgraded for use with Azure 2.0. It only installs directly to the 1.7 sdk, not to 2.0.
It seems like I might have to wait until they upgrade it, but I'm wondering if anyone knows of any plans for this to happen? Is it no longer supported/necessary?
Also posted to MSDN at http://social.msdn.microsoft.com/Forums/windowsazure/en-US/506b3405-b9f9-461c-b0f3-3dfce791beda/microsoft-endpoint-protection-windows-azure-20

A: As of today there are no publicly announced plans on working with this plugin.
However there is very fresh announcement about cooperation between Microsoft and Barracuda software on providing internet security for Windows Azure Services. You may want to check more on the following links:

*

*Barracuda on Windows Azure

*Deploying Barracude Web Application Firewall on Azure

*Security-as-a-Service provided by Barracuda


text:
Q: Want to run a program on some unknown system I have been working on a VS 2005 project and have successfully generated an exe file which works fine on my system. However when I tried to run it on some other pc it didnt run. It throws up the error message "the system cannot run the specified program". Can someone tell me how to make my code immune to such message i.e. system independent?
platform used: Windows XP, VS 2005
the extension of all my code files is cpp but I know only c and thats what I wrote inside them.

A: I have seen before exe created on Windows Sp1 not working on SP2 and problems such as that.
This should help you perhaps.

A: I've seen this when you run on a different version of Windows that doesn't have some DLL you depend on.  The easiest thing to do is statically link the C runtime (that's the usual culprit) and use depends.exe to see if there are any others.

A: You will almost certainly need to create an installer that installs your executable and any non-OS-included DLL's it relies upon.  It is not always possible or desirable to statically link all dependencies.  You can in many cases simply copy the DLL's to the same folder as the executable.
By default, even the C/C++ standard library is provided by a DLL.  While the MSVCRT.DLL used by VC++ 6 is included with the OS since later editions Win95, the MSVCRT required by VS2005 is not included with XP installations (other versions I do not know).  The run-time support is included VC redistributes package.  You may need to arrange for your installer to include that installation, or you could be more selective is you know your dependencies.
Some Win32 API calls if you are using them are dependent on the OS version (check the documentation), but if you built and rin it on XP, it should normally work of any subsequent version of Windows. You need to define various API version macros if you want to extend support to earlier versions of Windows (which seems unlikley).

A: You might need to install the VS 2005 redistributables on the other machines, depending on how you have compiled your program.


text:
Q: PHP DOMDocument how to get element? I am trying to read a website's content but i have a problem i want to get images, links these elements but i want to get elements them selves not the element content for instance i want to get that:  i want to get that entire element.
How can i do this..
<?php

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "http://www.link.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $output = curl_exec($ch);

    $dom = new DOMDocument;
    @$dom->loadHTML($output);

    $items = $dom->getElementsByTagName('a');

    for($i = 0; $i < $items->length; $i++) {
        echo $items->item($i)->nodeValue . "
";
    }

    curl_close($ch);;
?>

A: You appear to be asking for the serialized html of a DOMElement? E.g. you want a string containing link text? (Please make your question clearer.)
$url = 'http://example.com';
$dom = new DOMDocument();
$dom->loadHTMLFile($url);

$anchors = $dom->getElementsByTagName('a');

foreach ($anchors as $a) {
    // Best solution, but only works with PHP >= 5.3.6
    $htmlstring = $dom->saveHTML($a);

    // Otherwise you need to serialize to XML and then fix the self-closing elements
    $htmlstring = saveHTMLFragment($a);
    echo $htmlstring, "\n";
}

function saveHTMLFragment(DOMElement $e) {
    $selfclosingelements = array('></area>', '></base>', '></basefont>',
        '>
', '></col>', '></frame>', '>
', '>', '></input>',
        '></isindex>', '></link>', '></meta>', '></param>', '></source>',
    );
    // This is not 100% reliable because it may output namespace declarations.
    // But otherwise it is extra-paranoid to work down to at least PHP 5.1
    $html = $e->ownerDocument->saveXML($e, LIBXML_NOEMPTYTAG);
    // in case any empty elements are expanded, collapse them again:
    $html = str_ireplace($selfclosingelements, '>', $html);
    return $html;
}

However, note that what you are doing is dangerous because it could potentially mix encodings. It is better to have your output as another DOMDocument and use importNode() to copy the nodes you want.  Alternatively, use an XSL stylesheet.

A: I'm assuming you just copy-pasted some example code and didn't bother trying to learn how it actually works...
Anyway, the ->nodeValue part takes the element and returns the text content (because the element has a single text node child - if it had anything else, I don't know what nodeValue would give).
So, just remove the ->nodeValue and you have your element.


text:
Q: Write txt to Oculus Quest 2 and read it out on PC I have developed a Unity game that will be used for research purposes. The time that the player needs per level is written in a txt file. On PC it works fine. But I can't find it anywhere when I read the Oculus files with sidequest or android file transfer on my PC. I changed the permission in Unity under Project Settings -> Write Permission to External(SD) and added the lines in the Android Manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I have also tried all possible paths (Application.dataPath, Application.persistentDataPath and /sdcard/filename, /mnt/sdcard/filename,...)
I have also restarted the Oculus several times.
This is the code I'm creating and saving the txt:
if (SceneManager.GetActiveScene().name == "Level1")
        {
            //Path of the file
            string path = Application.dataPath + "/SteamingAssets/CoordinateTimeLog" + ".txt";
            //Create file if it doesn't exist
            if(!File.Exists(path)){
                File.WriteAllText(path, "Path the Player walked (x,y,z) + Time in seconds\n\n");
            }
            //Content of the file
            string content = "Level 1: " + transform.position +"   "+ System.DateTime.Now + "\n\n";
            //Add coordinates to it
            File.AppendAllText(path, content);
        }

In the AndroidManifest.xml I've added the following under </application>:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: How to create wiremock extension with encrypt and decrypt text I want to create decrypt or encrypt function from python and it can call in wiremock function.
For example
https://i.stack.imgur.com/SjHpP.png
From above picture , I expect Wiremock that can decrypt data (I already have decrypt code from Python) and check my condition. After that it will get JSON result (No encrypt data) and Wiremock have to able to encrypt JSON result (It can't I will send encrypt data directly lol )
so May anyone suggest how to create wiremock extension like this from Python?
I find the solution just write from Java...
Thanks m (_ _) m


text:
Q: Странное поведение windows Я не знаю, как точно охарактеризовать мою проблему в заголовке, но windows ведет себя немного странно.По порядку: У меня стоит 2 системы: основная kUbuntu, a вторая windown.Сначала устанавливался windows, а потом я заинтересовался linux'ом. В windows было 2 раздела на жестком диске: C и D.Я от диска D оттяпал несколько десятков гигов, распилил на  части (/, swap, /home) и благополучно поставил linux. Когда в /home стало мало места, я оттяпал от диска D еще десяток. 4 раза я повторял данную процедуру, и все было нормально. На 5-й раз, я оттяпал еще. После чего у меня слетел диск D (windows предлагал форматнуть диск). Информация была частично восстановлена. Но, самое интересное то, что у меня пропал в наушниках звук. Именно в наушниках. Потому что через колонки ноутбука звук идет, а стоит только подключить наушники/колонки в гнездо, так звука нет. Хотя realtek пишет что-то типа "подключен разъем". С гнездом все замечательно, так как на kUbuntu все работает. Переустановка драйвера не помогла. Танцы с бубном и перешаривание гугла так же оказались бесполезными. Помогите, пожалуйста!Вот ноутбук, драйверы качал с официального сайта
A: Надо бы диск проверить на бэды через mhdd или victoria.
A: Звук, кроме как в Windows настройках, так же можно настраивать в тулзе драйвера, так называемых Audio Deсk'ах.Возможно что-то там разведать возможно будет.
A: попробуйте выполнить команду sfc /scannow от имени администратора.


text:
Q: Read word document in C# I want to read a word document in the server (both doc and docx). The server does not have
office installed, therefore i can't use com objects and also no commercial softwares.
Is there a way that I can use office tools alone and read the word docs (2003 and 2007)

A: Unfortunately there are no good free options for reading .doc and .docx files.  Even commercial options are sparse at reasonable prices, but there are good extremely expensive options.
For reading .doc files the only free option I'm aware of is POI for Java which you can run in .NET using IKVM.  However, Word support in an experimental branch of POI's SVN repository, so I don't know how well it works.
http://poi.apache.org/
http://www.ikvm.net/
If you just want the text out of the .doc file and don't care about formatting, you can use the IFilter Win32 interface through pinvoke.
For reading .docx files you can use Microsoft Office Open XML SDK.  Don't let "SDK" fool you though, this is a very light abstraction over the dealing with the XML directly.  It's almost as painful to use.
http://www.microsoft.com/downloads/en/details.aspx?FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&displaylang=en

A: For .docx your free option is DocX. Very advanced and easy to use. For doc I've not seen free alternative.

A: Another free option for only .docx files is OpenXML SDK.
For both .doc and .docx files you can use free version of GemBox.Document if the files have relatively smaller size, otherwise you'll need their pro version.
You can open and read any Word format with it in the same way, for example:
var docxFile = DocumentModel.Load("Sample.docx");
var docFile = DocumentModel.Load("Sample.doc");
var rtfFile = DocumentModel.Load("Sample.rtf");

var docxText = docxFile.Content.ToString();
// ...


text:
Q: EF6/Code First: Super slow during the 1st query, but only in Debug I'm using EF6 rc1 with Code First strategy, without precompiled views and the problem is:
If I compile and run the exe application it takes like 15 seconds to run the first query (that's okay, since I'm still working on the pre-generated views). But if I use Visual Studio 2013 Preview to Debug the exact same application it takes almost 2 minutes BEFORE running the first query:
Dim Context = New MyEntities()
Dim Query = From I in Context.Itens '' <--- The debug takes 2 minutes in here
Dim Item = Query.FirstOrDefault()

Is there a way to remove this extra time? Am I doing something wrong here?
Ps.: The context itself is not complicated, its just full with 200+ tables.
Edit: Found out that the problem is that during debug time the EF appears to be generating the Views ignoring the pre-generated ones.
Using the source code from EF I discovered that the property:
IQueryProvider IQueryable.Provider
    {
        get
        {
            return _provider ?? (_provider = new DbQueryProvider(
                                                 GetInternalQueryWithCheck("IQueryable.Provider").InternalContext,
                                                 GetInternalQueryWithCheck("IQueryable.Provider").ObjectQueryProvider));
        }
    }

is where the time is being consumed. But this is strange since it only takes time in debug. Am I missing something here?
Edit: Found more info related to the question:
Using the Process Monitor (by Sysinternals) I found out that there its the 'desenv.exe' process that is consuming tons of time. To be more specific its consuming time with an 'Thread Exit'. It repeats the Thread Exit stack 36 times. I don't know if this info is very useful, but I saved a '.cvs' with the stack, here is his body: [...] (edit: removed the '.cvs' body, I can post it again by the comments if someone really think its going to be useful, but it was confusing and too big.)
Edit: Installed VS2013 Ultimate and Entity Framework 6 RTM. Installed the Entity Framework Power Tools Beta 4 and used it to generate the Views. Nothing changed... If I run the exe it takes 20 seconds, if I 'Start' debugging it takes 120 seconds.
Edit: Created a small project to simulate the error: http://sdrv.ms/16pH9Vm
Just run the project inside the environment and directly through the .exe, click the button and compare the loading time.

A: This is a known performance issue in Lazy (which EF is using) when the debugger is attached. We are currently working on a fix (the current approach we are looking at is removing the use of Lazy). We hope to ship this fix in a patch release soon. You can track progress of this issue on our CodePlex site - http://entityframework.codeplex.com/workitem/1778.
More details on the coming 6.0.2 patch release that will include a fix are here - http://blogs.msdn.com/b/adonet/archive/2013/10/31/ef6-performance-issues.aspx

A: I don't know if you have found the solution. But in my case, I had similar issue which wasted me close to a week after trying different suggestions. Finally, I found a solution by changing my web.config to optimizeCompilations="true" and performance improved dramatically from 15-30 seconds to about 2 seconds.


text:
Q: Not getting response after submitting form with ajax to php also part of script is not executed I have problem submitting form with ajax, or to be more accurate it submits the form and data is saved in db in another file but nothing works after that. Another gile (php) returns short html but it does not come out here? Also loading form is not faded in and after that nothing is faded in or out.
Here is my script:
<script>
$(function(){
  $('form').submit(function(e){
    var thisForm = $(this);
    e.preventDefault();
    $(this).fadeOut(function(){
      $("#loading").fadeIn(function(){
        $.ajax({
          type: 'POST',
          url: thisForm.attr("action"),
          data: thisForm.serialize(),
          success: function(data){
            $("#loading").fadeOut(function(){
              $("#success").text(data).fadeIn();
            });
          }
        });
      });
    });
  })
});
</script>

Here is form starting:
<form action="regit.php" method="post">

I don't put complete form here cause script submits form as should to php file that inserts it in db. Also php file gives html response back but then my script hangs. It works perfectly that (excluding fadein of loading div) far it submits data but everything after that is left undone. So there must be flow.. I got it working in another instance where it returns html but also prints html directly to screen, i wonder if there is way to display html as html so it looks ok and links etc. works? Another instance has identical code, different file and different form but identical script and it works...
This form that submits data is inside div.
So where have i gone to forest with this...?


text:
Q: Unable to send Watch Connectivity messages from a Dynamic Notification Controller I writing up this message because we encounter a weird issue while mixing Dynamic Notification Controller and Watch Connectivity calls.
You can find our sample project where we reproduced the problem here : https://gitlab.6minutecanoe.com/baptiste.leguelvouit/watch-connectivity-issue
The issue seems to be related to the didReceiveRemoteNotification method of the NotificationController class. If we override this method, and if we try to send a Watch Connectivity message in the handleActionWithIdentifier through the ExtensionDelegate class, the Watch app gets stuck unless we press the Digital Crown button.
This is really strange because if we don't override this method, everything works just fine. We also try to directly return WKUserNotificationInterfaceTypeDefault in this method but nothing changed.
Does anyone get this problem?
Thanks.
Steps to Reproduce:
Launch the sample project on a real device (iPhone + Watch) and send a remote notification with a custom category to its specific device token. When clicking on the custom action button, the problem appears.
Version:
Apple Watch 38mm on watchOS 2.0.1 (13S428) + iPhone 5S on iOS 9.1 (13B143)
Configuration:
The problem occurred especially when we try to use a Dynamic Notification Controller that returns WKUserNotificationInterfaceTypeCustom in its didReceiveRemoteNotification method.

A: My understanding after seeing your code is , what you are trying to do is that on receiving of push notification on watch....you are sending a message back to your iPhone app when user tap on notification action? right?Instead of handling action notification action in ExtensionDelegate class,implement the
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler

method in your AppDelegate and then test it.


text:
Q: How to select two tables in one query when second is empty (harder, not order task) I have two tables in MySQL: t1 AND t2.
The structure is something like that:
t1.aa    t2.az
t1.bb    t2.zz
t1.cc    t2.aa
         t2.dz

Now, I need to get something like:
result: t1.aa = 'value', t2.dz = 'value';

BUT:
1) second table (t2) is possibly just empty
2) In my query "WHERE" statement like this:
WHERE t1.aa=t2.aa AND t2.zz=345

So, if second table is really empty I need get something like this:
result: t1.aa = 'value', t2.dz = null;

Thanks.
P.S. we have other answers like Select multiple tables when one table is empty in MySQL , but my problem is in "WHERE" statement..
My tables are:
Table t1
CREATE TABLE IF NOT EXISTS `t1` (
  `aa` int(5) NOT NULL AUTO_INCREMENT,
  `bb` varchar(56) NOT NULL,
  `cc` varchar(56) NOT NULL,
  PRIMARY KEY (`aa`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

Table t1 Data
INSERT INTO `t1` (`aa`, `bb`, `cc`) VALUES
(1, 'varchar in bb', 'cc varchar');

Table t2
CREATE TABLE IF NOT EXISTS `t2` (
  `az` int(5) NOT NULL AUTO_INCREMENT,
  `zz` int(5) NOT NULL,
  `aa` int(5) NOT NULL,
  `dz` int(10) NOT NULL,
  PRIMARY KEY (`az`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Table t2 Data is null

A: I am not a genius, but I read mysql documentacion
http://dev.mysql.com/doc/#manual
Use JOIN ( I did not Test it) you need to prove it.
SELECT * FROM t1 LEFT JOIN t2 ON t1.aa == t2.aa WHERE t2.zz = 345

A: Lea Tano, we were close.
The right query is:
SELECT * FROM t1 LEFT JOIN t2 ON t1.aa=t2.aa AND zz=345

As you can see, there is no need in "WHERE" statement. This role has inherited by "ON ... AND ...".
Thank all for any help.
And Lea Tano, mostly.


text:
Q: I can't successfully install postgreSQL. 'Problem running post-install step' error message pops up I have successfully installed postgreSQL previously, but I am struggling to install it in one particular machine (Windows 8.1 Pro). Everytime I try to install it I get the following message:
Warning
Problem running post-install step. Installation may not complete correctly. The database cluster initialisation failed.

After the above message pops up the installation completes, but there's no postgreSQL service at all on the services list in the task manager.
I know that an older version of postgreSQL used to run without problems in this machine. Maybe uninstallation was not done properly? Has anyone seen this message before?


text:
Q: hashcode and ## result differ for Double,Float why ## of Double,Float result different from hashCode
Double example
scala> var x = 130d
x: Double = 130.0

scala> x.##
res24: Int = 130

scala> x.hashCode
res25: Int = 1080049664

Float
scala> var x = 130f
x: Float = 130.0

scala> x.##
res28: Int = 130

scala> x.hashCode
res29: Int = 1124204544

Integer Result Same value
scala> x.##
res30: Int = 130

scala> x.hashCode
res31: Int = 130

String result same value
scala> var x = "demo"
x: String = demo

 scala> x.##
 res32: Int = 3079651

 scala> x.hashCode
 res33: Int = 3079651


text:
Q: Throw exception without halting execution? I've dug myself into a bit of a hole with the project I'm working on. I've got this massive project (100s of thousands of lines), and there are MySQL errors everywhere. I'm in the process of cleaning them up now.
I've got this database class which all the queries go through, so what I've done is whenever there is an SQL error, I throw an exception now. The problem is that I can't have the execution stop. It has to continue as it always had, and just log the exception so I can track them down and fix them one at a time.
I was hoping set_exception_handler would do what I want, but the docs specifically say it will halt execution after calling my handler. So how do I get around this?
The exception can halt the current function, but then I want it to drop out of the function, perhaps returning null or false, and then continue as normal, but I need it to call my global exception handler.

To clarify:
I want to throw an exception from my database class (whenever there is an SQL error). I then want to log this error and/or display a message on screen until I can either fix the SQL error, or wrap the offending line in a try/catch. I don't want it to halt execution. If I simply call some error_handler() function rather than throwing an exception, then I can't catch it. If I catch it immediately (also within the DB class), then I can't catch it further down the stack (unless I re-throw it, but then we're back to halting execution).

A: If I have understood you correctly:
function myFunction($params) {

    try {

        //your code which throws Exception

    } catch (Exception $e) {

        myErrorFunction($e);
        return false;
    }

}

A: I think I found a workaround. Instead of throwing an exception, I can call my handler directly with the exception:
global_exception_handler(new MySqlException($error_message));

That way my handler still gets called, but execution continues.
And then that same exception handler can still be used to catch all the other exceptions that actually are thrown:
function _global_exception_handler($e) {
    // log error here
}

set_exception_handler('global_exception_handler');

A: Old post I know but I asked this question too and found out the answer was to add this line at the top where you're using try catch(Exception):

use Exception;