text:
Q: How to update libpango and install Cairo in Ubuntu? I want to install "php gtk", but I get the following error message:
`libgtk2.0-dev : Depends: libpango1.0-dev (>= 1.20) but it is not going to be installed

I downloaded the latest pango from here.
When I ran the command: ./configure, it gave me the following error message:
checking for HARFBUZZ... no no
checking for CoreText availability... no
checking for CAIRO... no no
configure: error: Could not enable any backends. Must have at least one backend to build Pango

I tried to install php_cairo, but it gives an error too:
checking for Cario... not found
configure: error: Oops! No Cairo detected in the system

How can I update libpango, and install Cairo? Thanks.

A: You can install cairo by typing:
sudo apt-get install cairo-dock

For other part I am working myself. Just read INSTALL. I have found pango-1.34.1 package from web and I try to install myself.


text:
Q: What's the equivalent to Unwrap for a ConfiguredTaskAwaitable? I'm creating a (well adapting an existing) helper class to allow me to run async methods synchronously.  So far I've got the task factory and a static method that lets me run async methods synchronously as long as I don't configure them with .ConfigureAwait, because .ConfigureAwait turns the return value of the method from a System.Threading.Tasks.Task<T> to a System.Runtime.CompilerServices.ConfiguredTaskAwaitable<T>.  The code looks like this:
public static class AsyncUtils {
    private static readonly TaskFactory _taskFactory =
        new TaskFactory(
            CancellationToken.None,
            TaskCreationOptions.None,
            TaskContinuationOptions.None,
            TaskScheduler.Default
        );

    public static TResult RunSync<TResult>(Func<Task<TResult>> func) {
        return _taskFactory
            .StartNew<Task<TResult>>(func)
            .Unwrap<TResult>()
            .GetAwaiter()
            .GetResult();
    }
}

If I try to add a method to deal with ConfiguredTaskAwaitable<T>, it might look like this:
    public static TResult RunSync<TResult>(Func<ConfiguredTaskAwaitable<TResult>> func) {
        return _taskFactory
            .StartNew<ConfiguredTaskAwaitable<TResult>>(func)
            .Unwrap<TResult>() // Doesn't exist!
            .GetAwaiter()
            .GetResult();
    }

The trouble is, as can be seen from the comment, StartNew<ConfiguredTaskAwaitable> returns a Task<ConfiguredTaskAwaitable<TResult>> instead of a Task<Task<TResult>> meaning that the Unwrap method doesn't exist for it.  Is there an equivalent?  How can I create an equivalent method for ConfiguredTaskAwaitable?

A: ConfigureAwait() only controls how the context is resumed after an await. If you're getting the result synchronously, it will have no effect because there is no "resume".
Additionally, one would typically run async methods synchronously by just doing this:
TResult RunSync<TResult>(Func<Task<TResult>> func) {
    return func().Result;
}

Or this, if you want to force it to run on the thread pool:
TResult RunSync<TResult>(Func<Task<TResult>> func) {
    return Task.Run(func).Result;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change url and reload page in angularjs I would like after getting credentials from another website, to change the url in my angularJS application.
I am setting my app like this
angular.module('demoApp', [])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  })
  .when('/example', {
    templateUrl: 'views/example.html',
    controller: 'ExampleCtrl'
  })
  .otherwise({
    redirectTo: '/'
  });

$locationProvider.html5Mode(true);
})

In my MainCtrl controller I change url like this :
$location.url($location.path()); // to remove url query params
$location.path('/example'); // to change the url

But this cause Cannot GET /example when I refresh the page.
Is there a solution for this ?
Thanks for your help.

A: It seams you didn"t handle URL rewriting needed when you activate the HTML5 mode (actually, the /example url doesn't exists, right now the only angular existing url is index.html)
So you'll have to handle URL rewriting server side.. For example for apache in a .htaccess file :
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule !\.\w+$ index.html [L]
</IfModule>

Or if you're using grunt-connect :
connect: {
    dev: {
        options: {
            port: 9002,
            hostname: '*',
            middleware: function(connect) {
                return [
                    //modRewrite is used to handle properly angularjs' html5 mode
                    modRewrite(['^[^\\.]*$ /index.html [L]']),
                    lrSnippet,
                    folderMount(connect, '/app')
                ];
            }
        }
    }
}

One more thing, be carefull, you're doing a double location change. If you want to remove query params, I sugest you to do this :
$location.path(url);

// clear any query params
$location.$$search = {};
$location.$$compose();


text:
Q: How to use Picasso library with Androidx? I have an One year old code, which I worked so hard on, this code uses picasso library in some places to download images and use them. Today I try to improve my code, migrate to androidx and upgrade Gradle to the latest version, but it doesn't seem to sync gradle file anymore, when I comment the implementation for picasso library, the sync goes smoothly again.
Google recommends migrating to androidx to be able to serve the latest android versions, the latest play services and jetpack libraries. What is the problem? and how it can be solved?
This is my Gradle app level file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.ramikabbani.sheikhsouk"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // Picasso
    implementation 'com.squareup.picasso:picasso:2.71828'

    // Glide
    implementation 'com.github.bumptech.glide:glide:4.9.0'

    implementation 'com.google.android.material:material:1.1.0'
//

}

and this is my top level project gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is the old project app level gradle file:
apply plugin: 'com.android.application'
    android {
        compileSdkVersion 29
        defaultConfig {
            applicationId "com.dalilukom.dalilukom"
            minSdkVersion 19
            targetSdkVersion 29
            versionCode 21
            versionName "1.21"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.16'
        implementation 'com.squareup.picasso:picasso:2.71828'
        implementation 'com.github.bumptech.glide:glide:3.8.0'
        //implementation 'com.android.volley:volley:1.1.1'
        implementation 'com.android.support:design:26.1.0'
        implementation 'com.android.support:support-v4:26.1.0'
    //    implementation 'com.amitshekhar.android:android-networking:1.0.2'
    //    implementation 'com.android.support:design:26.1.0'
    //    implementation 'com.android.support:appcompat-v7:27.1.1'
    //    implementation 'com.android.support:design:27.1.1'
    //implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

and this is the top level gradle file for the old project too:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Just migrate to androidx and get the Picasso dependency for androidx on your grade file. You should be fine

A: Just found a workaround.
In build.gradle (project:..), of the project Gradle file, downgrade the plugin to 7.2.1 and recompile.
plugins {
    id 'com.android.application' version '7.2.1' apply false
    id 'com.android.library' version '7.2.1' apply false
}

It works. It seems like it's unsupported on later versions.
But I think you should change the file gradle.properties (Project properties)  under android.useAndroidX=true.
Put:
android.enableJetifier=true

Putting whole file content of gradle.properties (Project properties):
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.enableJetifier=true
android.nonTransitiveRClass=true


text:
Q: How to start a video when clicking an image I want to make a video start when clicking on an image. Is there any way I can do this using javascript/jQuery?

A: You should do this with HTML.
<video controls poster="/images/the-image-to-show.png">
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

This will do the job just fine. Remember, "controls" gives you the default video controls. Play/pause/sound etc


text:
Q: Facebooks sharer rejects goo.gl link I'm developing an Android html5 app and I wanted to share on Facebook a long URL like:

http://api.myserver.com/share.php?key=[MD5 HASH]

So I first tried:

https://m.facebook.com/sharer.php?u=http://api.myserver.com/share.php?key=[MD5 HASH]

(With the long link URL encoded as parameter) But it didn't work, it says: Link was not found.
I thought it may have something to do with the long MD5 hash that contains the link so I used goo.gl API to shorten it. It returns a string like:

http://goo.gl/xxxxx

I've tested the shorten links that the Google API returns, and they exists.
So I tried again with Facebook:

http://m.facebook.com/sharer.php?u=http://goo.gl/xxxxx

But same thing happens again.
Why does it happen? I've tried to shorten some Instagram url (for example) with goo.gl and... guess what? It works with facebook!
I don't really understand what's wrong with my URL.

A: all you have to do is to encode the url you want to pass as an argument.
In javascript you can do this with encodeURIComponent.
In fact what happens with your first try is that the hash is considered as a parameter for the facebook's sharer url, due to URL / URI specification.
One has to "url encode" the differents data passed in an url.


text:
Q: obd2 battery level on electric vehicle I'm looking for a way to get the battery level in EV using OBD2 dongle,
I manage to get the fuel level in Toyota and Ford but I need to get data from the battery management systems (BMS) on EV.
I'm using python obd libraries and I have both comma.ai panda and OBDLink-LX dongles.
thanks,
Avi

A: Some cars will report battery level on PID 0x5B of mode 1.

A: UPDATED
You can only get the emission related data from the OBD II.
List of all supported PIDs are available in ISO 15031-5 which is Communication between vehicle and external equipment for emissions-related diagnostics.
This Iso protocol includes all the possible PIDs but does not mean that all the cars are going to support them.
To see which PIDs are supported for a car, you have to firstly check all the available PIDs within each car by querying the pid 0x00, 0x20, 0x40 .... you can find more detail on Wikipedia.
Please remember the wiki is the not reliable for the complex PIDs (You have to read the ISO)!!!

I need to get data from the battery management systems (BMS) on EV.

Here is the answer from Bolav: Some cars will report battery level on PID 0x5B of mode 1.


text:
Q: Illustrator script: Selecting objects in layer So I have a script that should select the objects of a layer and deselect it afterwards. (adobe Illustrator)
But for some reason after it deselects, it automaticly selects an object that doesn't appear anywhere in my layers together with the next selected object.
What could this be?
myDoc = app.activeDocument;
myLayers = myDoc.layers;

for (var a=0; a<myLayers.length; a++)
{
    //Select objects in layer
    myLayers[a].hasSelectedArtwork = true;

    //Do action here

    //Deselect objects in layer
    myLayers[a].hasSelectedArtwork = false;
}

A: Fixed it by adding this to the beginning of the loop.
 app.activeDocument.selection = null;


text:
Q: RecyclerView in React Native: notifyItemInserted() and notifyDataSetChanged() have no effect I am experimenting with integrating a Firebase-backed RecyclerView in a React Native app. With hardcoded data it works well, but upon inserting rows loaded dynamically and calling either notifyItemInserted() or notifyDataSetChanged() on the RecyclerView.Adapter, the RecyclerView itself does not reflect the change. This manifests as an initial blank view until the app's refresh button is tapped, which has the sole effect of re-rendering the RecyclerView from the React Native side, or until scrolling or a screen orientation change.
After reading through a dozen or more questions on this site about similar issues not involving React Native and having tried most of the common solutions, I suspect this issue is related specifically to React Native.
Finding a solution to this could be helpful to many, given the ongoing performance issues with React Native's list view implementations.
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> {

    ArrayList<Post> mDataset;

    public PostsAdapter(ArrayList<Post> list){
        mDataset = list;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout mPostView;
        public ViewHolder(LinearLayout v) {
            super(v);
            mPostView = v;
        }
    }

    @Override
    public PostsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.post, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        TextView tv = (TextView) holder.mPostView.findViewById(R.id.title);
        tv.setText(mDataset.get(position).title);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

 public class RNPostsViewManager extends SimpleViewManager{
    private ArrayList<Post> mDataset = new ArrayList<>();
    public static final String REACT_CLASS = "AndroidPostsView";
    private RecyclerView mRecyclerView;
    private PostsAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private DatabaseReference mDatabase;
    private Query initialDataQuery;
    private ChildEventListener initialDataListener;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @UiThread
    public void addPost (Post p){
        mDataset.add(p);
        mAdapter.notifyItemInserted(mDataset.size()-1);
    }

    @Override
    public RecyclerView createViewInstance( ThemedReactContext context) {

        mAdapter = new PostsAdapter(mDataset);

        mRecyclerView = new RecyclerView(context){
            @Override
            protected void onAttachedToWindow() {
                super.onAttachedToWindow();
                initialDataQuery.addChildEventListener(initialDataListener);
            }
        };

        mLayoutManager = new LinearLayoutManager(context.getCurrentActivity(), LinearLayoutManager.VERTICAL, false);
        DividerItemDecoration mDecoration = new DividerItemDecoration(context, 1);
        mDecoration.setDrawable(ContextCompat.getDrawable(context.getCurrentActivity(), R.drawable.sep));
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(mDecoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        initialDataQuery = mDatabase.child("wp-posts").orderByChild("unixPostDate").limitToFirst(100);
        initialDataListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                Post p = dataSnapshot.getValue(Post.class);
                addPost(p);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
            }
            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }
            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        };

        return mRecyclerView;
    }

}

// layout file post.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:background="@android:color/background_light"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp"
    android:weightSum="1">

    <Button
        android:id="@+id/button"
        style="@style/Widget.AppCompat.Button.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:background="@android:drawable/ic_menu_more"
        android:gravity="center_vertical" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_vertical"
        android:orientation="horizontal"
        android:weightSum="1">

        <TextView
            android:id="@+id/title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="fill_vertical"
            android:layout_weight="1"
            android:gravity="top"
            android:text="TextView"
            android:textColor="@color/title"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

A: The problem is that requestLayout does not work well when the RecyclerView is a native UI component.
The following hack made all those issues go away:
I now overwrite the requestLayout method inside my RecyclerView.
Then before any notify* method, or even scrollToPosition calls or any method that invokes a re-layout, I allow my custom requestLayout method to force a re-layout.
The end result looks like this:
private boolean mRequestedLayout = false;

public void aMethodThatUpdatesStuff(int indexToUpdate, ReadableMap updatedChild) {
    final SPAdapter adapter = (SPAdapter) getAdapter();
    mRequestedLayout = false;
    adapter.updateDataAtIndex(indexToUpdate, updatedChild); // <-- this runs notifyItemChanged inside
}

@Override
public void requestLayout() {
    super.requestLayout();
    // We need to intercept this method because if we don't our children will never update
    // Check https://stackoverflow.com/questions/49371866/recyclerview-wont-update-child-until-i-scroll
    if (!mRequestedLayout) {
        mRequestedLayout = true;
        this.post(new Runnable() {
            @SuppressLint("WrongCall")
            @Override
            public void run() {
                mRequestedLayout = false;
                layout(getLeft(), getTop(), getRight(), getBottom());
                onLayout(false, getLeft(), getTop(), getRight(), getBottom());
            }
        });
    }
}

A: The root view in ReactNative is ReactRootView which onlayout is an empty method.
when call notifyDatasetChanged in RecyclerView, it's actually request layout to relayout its children. And the layout method will call super.layout to travel the whole view tree first. So that't a problem when the root view is ReactRootView.
You can manually call RecyclerView.onlayout(boolean changed, int l, int t, int r, int b) to trigger its children relayout to make notifyDatasetChanged work.


text:
Q: What would be the most efficient way to log a raspberry pi's data over ssh? I currently have a python script on a raspberry pi that creates a log file in the same directory while running, with important data that I would like to view in real time on my laptop (that I can ssh into the pi with).
Obviously I can view the log file on my laptop while ssh'd using a text editor, but it's not a real-time data stream.
Unfortunately while I have a decent amount of python experience, I don't know much about networking stuff, except that I could scp/rsync the file onto my computer but of course, that's not giving me a real time view of my log file either.

A: Two ideas spring to mind...
The Unix syslog facility allows distributed/remote logging. You would probably find a Python module, or you could just create a socket and send messages to the syslogd on your laptop. You could even send messages with netcat at a pinch. Related article
You could set up Redis on your laptop and use the Python Redis module to send time-tagged messages either to a queue or a sorted hash and write a small script to wait on the queue on your laptop. Messages could also be given a "time to live" or expiry time so the memory demands don't get too excessive. Related article

A simpler option might be to write your log to a file on your Raspberry Pi and then depending on the OS of your laptop, to share that directory via NFS or Samba with your laptop. You can then use the follow (-f) option of tail to see last few lines continuously updated:
tail -f output.log

A: tail is commonly used for this, tail -f yourlogfile.log will show the ten latest lines of the file and update on file change.

A: Netcat.
On local PC
nc -l 2000

On remote
tail -f filename | nc hostip 2000


text:
Q: Null When Passing String I got this output "Hospital (null)  ΓÇô Report for COVIC19 ΓÇô Community Visit"
I'm trying to printout the name of the hospital from the function readHospital() but all I got for the output is these weird looking text. So sorry I'm very new to coding.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>

char readHospital();
void intro(char a);

int main() {

char hospital_name;

hospital_name = readHospital();
intro(hospital_name);

}

char readHospital() {

char a[100];
printf("Enter Hospital Name: ");
fgets(a, 100, stdin);
return a;
}

void intro(char hospital_name) {
printf("Hospital %s  – Report for COVIC19 – Community Visit", hospital_name);
}

A: I've changed your code, The readHospital function that you are using in your code is not a correct function for reading the input string from the user and returning it.
Instead, you can use the readNewString function that I've written.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>

char * readNewString();
void intro(char a[100]);

int main() {

char * hospital_name;

hospital_name = readNewString();
intro(hospital_name);

}

char *readNewString(void) {
char buffer[1024];
if (!fgets(buffer, sizeof buffer, stdin)) {
    return NULL; // read failed, e.g., EOF
}
int len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
    buffer[--len] = '\0'; // remove the newline
    // You may also wish to remove trailing and/or leading whitespace
} else {
    // Invalid input
    //
    // Depending on the context you may wish to e.g.,
    // consume input until newline/EOF or abort.
}
char *str = malloc(len + 1);
if (!str) {
    return NULL; // out of memory (unlikely)
}
return strcpy(str, buffer); // or use `memcpy` but then be careful with length
}

void intro(char hospital_name[100]) {
printf("Hospital %s  – Report for COVIC19 – Community Visit", hospital_name);
}

A: Please note that hospital_name is of char type and you return a string, char list char*


text:
Q: Deleting a node in double linked list by an index position I am trying to delete a node from a doubly-linked list, but I get a NullPointerException when I try to delete the 2nd item. I was able to delete the first item and the last item.
Below is my code:
@Override
public T removeElement(int index) {
    // TODO Auto-generated method stub
    T result = null;

    if (IsEmpty()) {
        throw new NoSuchElementException();
    }

    if (count == 1 && index == 0) {
        result = head.getData();
        head = null;
        tail = null;
    }
    if (index == 0) {
        result = head.getData();
        head = head.getNext();
    }
    if (count == index) {
        result = tail.getData();
        tail = tail.getPrev();
        tail.setNext(null);
    }
    int i = 1;
    for (Node<T> current = head; current != null; current = current.getNext()) {
        if (i == index){
            result = current.getData();
            Node<T> previous = current.getPrev();
            Node<T> next = current.getNext();
            previous.setNext(next);
            next.setPrev(previous); //getting null pointer exception here
        }
        i++;
    }

    count--;
    return result;
}

@Override
public void addElement(T data)//add elements in the list
{
    Node<T> newNode = new Node<T>(data);
    if (IsEmpty()) {
        head = newNode;
        tail = newNode;
    }
    else {
        newNode.setPrev(tail);
        tail.setNext(newNode);
        tail = newNode;
    }
    count++;
}

Here is my test program:
public class Test {

public static void main(String[] args) {
    DoubleListImpl<Integer> test = new DoubleListImpl<Integer>();

    test.addElement(10);
    test.addElement(20);
    test.addElement(40);
    test.addElement(50);
    test.display();
    System.out.println(test.getCount());
    test.removeElement(4);
    System.out.println();
    //test.removeElement(3);
    test.display();
    System.out.println(test.getCount());
}
}

UPDATE:
I noticed something interesting a minute ago. If i made i=0 i get a null pointer error when i pass index ==3 as an argument in the removeElement function. or when i make i=1 i get a null pointer when i pass i==2 as an argument.

A: I wrote in comments that I didn't think the erroneous if(count==index) was the cause of the NPE.  I see now that it isn't directly the problem, but it does contribute to the problem by not catching the case where you request to delete the actual last node (index count - 1).
Of course, your addElement() method does not set or increment count when a node is added and IsEmpty() initially returns true, so the count will also be wrong.  In fact, if IsEmpty() depends on count to determine whether the list is empty then addElement() will never expand your list past one element -- new elements "added" will instead replace the previous one.
Also contributing is the fact that execution falls through to the loop at the end of your method even when deletion has already been accomplished via one of the earlier special cases, as I also observed already.  Consider, then, what happens when index is exactly the right value for the loop to iterate up to, but not beyond, the last element in your list.  Control enters the block conditioned on i == index, and the current element's previous and next elements are retrieved.  But the element in question is the last one, so its next is null.  When you attempt to invoke setPrev() on that null reference, an NPE results.
I reiterate my suggestion in comments that you add internal Node objects to serve as head and tail, so that the Nodes containing real data are all internal, and you don't need all the special cases.  For example,
class DoubleListImpl<T> implements DoubleList<T> {

    private final Node<T> head = new Node<T>(null);

    {   // better to put this in a constructor, but this way I avoid writing any
        head.setNext(head);
        head.setPrev(head);
    }

    // ...

    @Override
    public T removeElement(int index) {
        int i = 0;

        // negative indexes are always invalid
        if (index < 0) {
            throw new IndexOutOfBoundsException();
        }

        for (Node<T> current = head.getNext(); current != head;
                current = current.getNext()) {
            if (i == index){
                Node<T> previous = current.getPrev();
                Node<T> next = current.getNext();

                previous.setNext(next);
                next.setPrev(previous);
                // maybe you need count for something else, but not for this
                // count -= 1;
                return current.getData();
            }

            i += 1;
        }

        // If control reaches here then the given index is invalid
        throw new IndexOutOfBoundsException();
    }
}

A: Hello guys thanks for the input. I actually figured out my error and this works. Below is my solution to the problem. Thanks a lot guys for the help:
@Override
public T removeElement(int index) {
    // TODO Auto-generated method stub

    T result = null;
    assert(index>=1&&index<=count);

    if(index==1){
        if(count==1){
            result = head.getData();
            head = null;
            tail = null;
        }
        else{
            result = head.getData();
            head = head.getNext();
            head.setPrev(null);
        }
    }
    else if(index==count){
        result = tail.getData();
        tail = tail.getPrev();
        tail.setNext(null);
    }
    else{
        Node<T> current = head;
        int i=1;
        while(current!=null){
            if(i==index){
                Node<T> prev = current.getPrev();
                Node<T> next = current.getNext();
                prev.setNext(next);
                next.setPrev(prev);
                break;
                //current = null;
            }
            current = current.getNext();
            i++;
        }
    }
    count--;
    return result;
}


text:
Q: how to display mongodb data to yii2 table? I want to display MongoDB User collection data into yii2 tablle. When i run, it doesn't show any data output, only show 5 empty rows (i have 5 rows in User collection)
Im new in mongodb. I have tried displaying it using the usual format as I display data from mysql (only the query I changed).It doesn't seem to work well, but doesn't display any error message
Here my code :
Model/User.php
class User extends ActiveRecord implements IdentityInterface
{
  public $_id;
  public $username;
  public $password;

  public static function collectionName()
  { return ['latihan', 'User']; }

  public function attributes()
  {
    return [
       '_id',
       'id',
       'username',
       'password',
       'role',
    ];
  }

   public function fields()
   {
     return [
        '_id' => function() { return (string)$this->_id; },
        'id',
        'username',
        'password',
        'role',
      ];
  }

  public function rules()
  {
  return [
      ['role', 'default', 'value' => 10],
      [['_id', 'username', 'password'], 'safe'],
    ];
   }

  public static function findOne($condition)
  {
    $query = new Query();
    $data = $query->from(static::collectionName())->where($condition)->one();
    $user = new User();
    $user->id = $data['id'];
    $user->username = $data['username'];
    $user->password = $data['password'];
    $user->role = $data['role'];

    return $user;
}

HomeController.php
public function actionAbout()
{
    $user = User::find()->all();
    return $this->render('about', ['model' => $user]);
    }
}

About.php

        #
        Username
        Password
        Aksi

<?php $i = 1; foreach($model as $field){ ?>

    <?php $username =$field->username; ?>
        <?php echo $i++; ?>
            <?= $field->username; ?>
            <?= $field->password; ?>

            <a href="<?php echo Url::to(['/home/editabout']).'?id='.$field->id;?>"> Update |
            <a href="<?php echo Url::to(['/home/deleteabout']).'?id='.$field->id; ?>"> Delete

    <?php } ?>

A: from this question
first you must add
yii2-mongodb in your composer.json file and update composer with this command composer update
then you can edit main-local.php file and overwrite the db component.
return [
    //....
    'components' => [
        'db' => [
            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://@localhost:27017/mydatabase',
            'options' => [
                "username" => "Username",
                "password" => "Password"
            ]
        ],
    ],
];

+ if you want to use both mysql (deafult connection) and mongodb you must  dont overwrite db component and just add mongodb.
return [
    //....
    'components' => [
        'db' => [
            .... mysql db config (default)
        ],
        'mongodb' => [
            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://@localhost:27017/mydatabase',
            'options' => [
                "username" => "Username",
                "password" => "Password"
            ]
        ],
    ],
];


text:
Q: Integrate $f(x)=\frac{1}{1+(x-1/x)^2}$ I came across this rather simple looking function
$$
f(x)=\frac{1}{1+\left(x-\frac{1}{x}\right)^2}
$$
which has a nice looking plot with two peaks symmetric around the vertical axis, whereas each peak is not symmetric by itself. It also turns out to be difficult to integrate by hand, so I have two questions about it:

*

*What kind of function is it? does it have a name?

*How to actually integrate it? For example, if I know how the function behaves for small and large $x$, i.e.:

for very large $x$:
$$
\int\frac{1}{1+x^2} dx = \arctan(x) + C
$$
and for $x\sim 0$:
$$
\int\frac{1}{1+1/x^2} dx = x-\arctan(x) + C
$$
would it be possible to use this information to somehow get to them (at least one-sided) integral of the original function?

A: To integrate it, if you add and substract $\frac{1}{x^2}$ in the numerator, you can split into an $\arctan$ integral and a rational one.
More precisely
$$\int\frac{1}{1+(x-1/x)^2}\,dx = \int\frac{1+1/x^2}{1+(x-1/x)^2}\,dx-\int\frac{1/x^2}{1+(x-1/x)^2}\,dx
$$
The first one is equal to $\arctan(x-1/x)$.
The second one is
$$\int\frac{1}{x^2+(x^2-1)^2}\,dx
$$
and probably Hermite could herlp you to solve it.

A: $$I=\int \frac{dx}{1+(x-1/x)^2}=\int\frac{x^2}{x^4-x^2+1}dx =\frac{1}{2} \int \left( \frac{1-\frac{1}{x^2}}{x^2+1/x^2-1} + \frac{1+\frac{1}{x^2}}{x^2+1/x^2-1}\right)dx$$
$$\implies I(x)=\frac{1}{2} \int \left( \frac{1-\frac{1}{x^2}}{(x+1/x)^2-3} + \frac{1+\frac{1}{x^2}}{(x-1/x)^2+1}\right)dx$$
Let $x+1/x=u$ and $x-1/x=v$ in the first and second integrals, respectivelt, then
$$I(x)=\frac{1}{2}\left (\int \frac{du}{u^2-3}+ \int \frac{dv}{v^2+1}\right).$$
$$I(x)=\frac{1}{2} \left( \frac{1}{2\sqrt{3}} \ln \frac{u-\sqrt{3}}{u+\sqrt{3}}+ \tan^{-1}v \right) +C.$$


text:
Q: Resulting certificate on Signature has "
" how to remove them? I'm using xades4j to sing an xml, everything works fine.
But on the resulting XML the X509Certificate looks something like this:
<ds:X509Certificate>  MIIDUjCCAjqgAwIBAgIIYFxFM0GPYwowDQYJKoZIhvcNAQELBQAwKTEMMAoGA1UEAwwDRkVMMQww
    CgYDVQQKDANTQVQxCzAJBgNVBAYTAkdUMB4XDTE4MTIxMDE1MTQyOFoXDTIwMTIwOTE1MTQyOFow
    KDERMA8GA1UEAwwIODI1NzYyNTQxEzARBgNVBAoMCnNhdC5nb2IuZ3QwggEiMA0GCSqGSIb3DQEB
    AQUAA4IBDwAwggEKAoIBAQC6QTYY7yGtmikBaV6pNVee6WzNBToIr3jlFikbvZI4JD+4p0LJqten
</ds:X509Certificate>

How can I remove the "& #13;" from it?
The method that executes the signature is this one:
@Override
    public DOMSource generarFirmaDigitalParaXML(Document xml, KeyingDataProvider keyingDataProvider, String nombreArchivoXmlOriginal) {
    final Element rootElement = xml.getDocumentElement();
    Element elementoAFirmar = null;
    NodeList nodeList = xml.getElementsByTagName("dte:DatosEmision");

    DOMSource source = null;
    int lenght = nodeList.getLength();
    for (int i = 0; i < lenght; i++) {
        Node nNode = nodeList.item(i);
        elementoAFirmar = (Element) nNode;
    }

    XadesBesSigningProfile profile = new XadesBesSigningProfile(keyingDataProvider);
    try {
        XadesSigner signer = profile.newSigner();
        String atributoUtilizado = seleccionarAttributoComoId(elementoAFirmar, "ID");

        if (atributoUtilizado != null) {
            DataObjectDesc obj = new DataObjectReference("#" + elementoAFirmar.getAttribute(atributoUtilizado))
                    .withTransform(new EnvelopedSignatureTransform());
            SignedDataObjects dataObjs = new SignedDataObjects().withSignedDataObject(obj);
            signer.sign(dataObjs, rootElement);
            xml.setXmlStandalone(true);
            source = new DOMSource(xml);
        } else {
            throw new Exception("Atributo no encontrado en el XML");
        }
    } catch (Exception e) {
        bitacora.log(Level.SEVERE, LOGGER, bitacora.obtenerStackTrace(e), true);
    }
    return source;
}

A: It took me a few hours to resolve it, but I've finally found the solution here: https://bugs.openjdk.java.net/browse/JDK-8264194
static {
    System.setProperty("com.sun.org.apache.xml.internal.security.ignoreLineBreaks", "true");
}


text:
Q: How to display a binary number on LEDs (Raspberry Pi GPIO) Python I have some LEDs wired to my Pi's GPIO pins and I want to display, lets say an 8 bit binary number, on the LEDs. So if the number is 11110000 then I want the first four LEDs to be on and the last four to be off.
I converted a decimal number to binary and I want to be able to display this binary number using simple LEDs.

A: You can probably start by converting the binary number into a usable list of values, for deciding which of the 8 LEDs to keep turned on.
state = 0b11110000

expanded = []
for x in range(8):
    val = state & 0x01
    state = state >> 1
    expanded.append(val)
expanded = list(reversed(expanded))
print(expanded)    # [1, 1, 1, 1, 0, 0, 0, 0]

Using expanded you can decide which LEDs should remain ON.

A: I figured it out but might be a bit complicated in this approach.
So my number is represented as 0b1000101
temp = 0b1000101
binF = temp[2:].zfill(7) #prints 1000101
binF1 = temp[3:].zfill(6) #prints 000101
binF2 = temp[4:].zfill(5) #prints 00101
binF3 = temp[5:].zfill(4) #prints 0101
binF4 = temp[6:].zfill(3) #prints 101
binF5 = temp[7:].zfill(2) #prints 01
binF6 = temp[8:].zfill(1) #prints 1

#Now we want the most significant bit
binFA = binF[1:].zfill(1) #prints 1
binF1A = binF1[1:].zfill(1) #prints 0
binF2A = binF2[1:].zfill(1) #prints 0
binF3A = binF3[1:].zfill(1) #prints 0
binF4A = binF4[1:].zfill(1) #prints 1
binF5A = binF5[1:].zfill(1) #prints 0
binF6A = binF6[1:].zfill(1) #prints 1

And from here we can assign the values to certain GPIO pins
if binFA == '1':
    GPIO.output(21, 1)
else:
    GPIO.output(21, 0)

Set all GPIO pins as necessary for how many bits there are


text:
Q: Listed folder cannot be deleted I have a server with an app on it which uses themes (mollify) however after looking at the website this morning no CSS was being displayed so I had a look at the themes as my first port of call.
What had happened was the theme 'basic' had disappeared from my listing in FileZilla, so the first thing I did was attempt to re-upload it (server is 775 for this folder 755 for all others), when that failed I went to check my user settings etc.
When I did ls /path/to/themes/ the two listed themes were 'basic' and 'charcoal' and when I did  ls -l /path/to/themes/ charcoal, which displays in FileZilla, came back as expected - but basic returned:
d????????? ? ? ? ? ? basic

This to me looks like there is no owner etc of this file any more, but I have personally changed nothing on this server (The physical server crashed and was fixed at the weekend).
I uploaded a backup of this folder under a new name and pointed the index file at this CSS instead, so that users are not effected, but that doesn't help the issue with this file.
I have tried using rm -r and rm -rf to delete the folder but it returns that it does not exist. I have also then tried using mv to rename / move the files but it obviously just returns that it already exists. I'm not using the root user directly, but my own account with sudo privileges, could this be an issue as to why it will not delete?
Is there a way that I can delete, or restore, this folder when it appears to have no owner?

A: Try this: first, do ls -li to list all files with their inodes. The inode is the number on the left. Note the inode number of your problem directory. Then: find . -inum xxx -delete replacing xxx with the inode number.


text:
Q: DirectShow Filter Graph Editor doesn't show remote graphs I have a problem with connecting to remote graph from DirectShow Filter Graph Editor. When I run application that creates a direct show graph, on my Windows XP machine graph is shown in the list of remote graphs, but on the Windows 7 (x64) machine list of remote graphs is empty.  I have registered proppage.dll and also registered directshowspy.dll ... but still no results. Any ideas?

A: There's a proppage.dll and an x64/proppage.dll and you'll need to register both to ensure that both x64 and x86 apps work.
The DLL files should be available with the Windows SDK. In case of the Windows 10 SDK, for example, the files will typically reside in the x64 and x86 folders in the %ProgramFiles(x86)%\Windows Kits\10\bin\%version% folder, with %version% being the installed version of the SDK (e.g. 10.0.18362.0).

A: I ran into this issue when I first moved to Windows 7.  A DirectShow is composed of filters that are either built for x86 or x64 architecture.
If you're registering the x64 version of DirectShowSpy.dll, don't expect to be able to spy on a graph that uses x86 filters.
Get the x86 version of DirectShowSpy.dll, unregister your installed version and then install the x86 version.
I keep both versions of DirectShowSpy.dll on my machine and register the appropriate one for working on specific graphs.
I also recommend RadScorpion's GraphStudio ;)
Hope this helps!

A: Is this the same application that works in XP but not in Windows 7?  The app needs to manually expose its graph to the Running Object Table so that GraphEdit will see it.
Example here: http://forum.inmatrix.com/index.php?showtopic=4439&view=findpost&p=19994

A: Well, I got same problem and figure out that GraphEdit must be run at the Admin level.
Otherwise, I can not see any remote graph.


text:
Q: Error during sass installation for Windows I am trying to install sass after installing ruby, but I'm getting the following error:
C:\Users\HEDi-PC>gem install sass
ERROR:  Loading command: install (ArgumentError)
    unknown encoding name - CP720
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

A: Well, first things first: use virtual machine with Ubuntu in it, otherwise you will have many more wierd errors with various packages. Ruby and Rails have some quick-start procedures for Windows users, but after I used Windows with Rails for about a year, I found that it's best to stop doing that.
This particular error should go after you change encoding in your terminal:
chcp 1252

This happens because Ruby doesn't know how to handle CP720 terminal encoding.


text:
Q: digital dashboard - running multiple setInterval, permanently I'm currently working on a digital dashboard, where I e.g. display the weather, my calendar, a random cite, some crypto rates, etc.
All these elements are refreshed with ajax. Some (for example the time) are refreshed every second, the weather now is refreshed every 10 minutes, the weather for the upcoming hours every 30 minutes and the weather for the next days every 6 hours. The cite is refreshed every 24 hours and the crypto rates are refreshed every 60 seconds.
My point is: I have about 10 setIntervals on my dashboard, most of them doing AJAX requests to my server, with timings between 1000 ms and 86400000 ms. Is there any problem with that or will JavaScript be easily able to handle this? Not worried about my server getting the requests, this will work fine, but is JavaScript able to handle these mutliple setIntervals, especially considering that the web page won't be refreshed usually (I mean, not at all, for months, if everything works fine at least)...
Does anybody have experience with this or (if that's an issue) suggest a better way to do it?
EDIT: what I forgot to mention, might be important as well, in case of performance, the dashboard is running on a Raspberry PI 3B+..


text:
Q: Compile error: libicui18n.so.54 needed by libQt5Core.so.5 not found #include <opencv2/opencv.hpp> //头文件
using namespace cv; //包含cv命名空间

int main()
{
    Mat img=imread("cornea.jpg");
    imshow("src",img);
    waitKey(0);
    return 0;
}

And I compile it with:
g++ test.cpp -o test pkg-config opencv --cflags --libs opencv

Which gives me:
/usr/bin/ld: warning: libicui18n.so.54, needed by //home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5, not found (try using -rpath or -rpath-link)

/usr/bin/ld: warning: libicuuc.so.54, needed by //home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5, not found (try using -rpath or -rpath-link)

/usr/bin/ld: warning: libicudata.so.54, needed by //home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5, not found (try using -rpath or -rpath-link)

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_clone_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'uenum_next_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'u_strToLower_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_getStandardName_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucol_setAttribute_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_setMillis_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucol_strcoll_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_setSubstChars_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_getTimeZoneDisplayName_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_openCountryTimeZones_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_fromUnicode_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_open_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_getDefaultName_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucol_open_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucol_close_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_inDaylightTime_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucol_getSortKey_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_getAvailableName_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_close_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_get_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_openTimeZoneIDEnumeration_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_getDSTSavings_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_open_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_openTimeZones_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_toUnicode_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'u_strToUpper_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'u_errorName_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_close_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'uenum_close_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_countAvailable_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_getMaxCharSize_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_getAlias_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucal_getDefaultTimeZone_54'未定义的引用

//home/lmk/Qt5.5.0/5.5/gcc/lib/libQt5Core.so.5:对'ucnv_compareNames_54'未定义的引用

collect2: error: ld returned 1 exit status

The backticks in command line pkg-config opencv --cflags --libs opencv is invisible. I have not got the reason now.
Indeed,in early days, I have installed Qt. But now, I do not want my program have something to do with Qt. In order that my program is not affected by the Qt library function, I shielded the path variables of Qt in the /etc/bash.bashrc file and installed a new gcc of 5.3.0. But the same error is still existing!
I'm using Ubuntu 14.04

A: Download ICU-54.1 from here
http://www.linuxfromscratch.org/blfs/view/7.7/general/icu.html
and install manually.
For me this solved the problem.


text:
Q: Git : Unable to access configured jar file in git I was trying to integrate checkstyle jar to my java git project repository to ensure the coding standards. I configured the checkstyle jar and xml file(didn't configured java.command as it taken as default path) as
git config --add checkstyle.jar d:/checkstyle-5.6.jar
git config --add checkstyle.checkfile d:/checkstyle_checks.xml

Then added the perl script from here as pre-commit hook.
Then changed the java file and add it. While trying to commit the change, the error message showing as Unable to access jarfile d:/checkstyle-5.6.jar commit abort
Is there any problem with configuring the jar and xml file.

A: Its due to the path syntax problem. Thanks to @bluefeet for mentioning the issue.


text:
Q: Calculating line segment lengths within polygon using ArcGIS Desktop? I have a layer with line segments and a layer of polygons (in this case, buffers around points). I need to create a new field for each polygon that contains the total length of all line segments contained within that polygon, including portions of the line segments with the polygon that straddle the borders.

A: A slight modification of the answer linked in the comments would be to do a Summary Statistics to get the SUM of the Shape.Length field of the intersect feature class, using the FID field of the polygons a case field, and then Join Field that back to the polygon feature class.
In the ArcMap 10.1 Python window, these commands worked for me:
intersection = arcpy.Intersect_analysis("RoadCenterline;SchoolTaxDistrict", r"in_memory\intersect")
arcpy.CalculateField_management(intersection, "SHAPE_Leng", "!shape.length!", "PYTHON_9.3")
summary = arcpy.Statistics_analysis(intersection, r"in_memory\statistics", "SHAPE_Leng SUM", "FID_SchoolTaxDistrict")
arcpy.JoinField_management("SchoolTaxDistrict", "FID", summary, "FID_SchoolTaxDistrict")


text:
Q: Find a function satisfying this condition
Be a continuous function $f: \mathbb{R} \to \mathbb{R}$ such that $f(x)f(f(x)) = 1$ and $f(2020) = 2019$. What is the value of $f(2018)$?

I am having a problem with this question.
I already tried, through various attempts, to find the function explicitly which satisfy this condition and $f(0)$ different from $0$. But it leads me to nothing. I am really thinking there is no way to find an explicit function, so I would appreciate any solution to this problem (normally I would prefer a tip, but my ideas are exhausted).


text:
Q: Upgraded to Angular 4.1.2 from 2.4 and now why does it requires absolute Urls? I am using the Microsoft.AspNetCore.Spatemplates and am now running on angular 4.1.2. When I was using the previous version of the Spatemplates that was using angular 2.4 I was able to do a http.get to my .NET controller with an angular service with the code you see below using a relative url.
export class MyService {
private url = 'api/myController';

constructor(private _http: Http) {
}
public getAll = (): Observable<any> => {
    return this._http.get(this.url)
        .map(data => data.json());
};

Now that I am using the new Spatemplates it is requiring an absolute URL. Does anyone know why this is?
Also I know have noticed in my app.module.client.ts I see an ORIGIN_URL
imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ...sharedConfig.imports
],
providers: [
    { provide: 'ORIGIN_URL', useValue: location.origin }
]

I'm assuming that I need to use the ORIGIN_URL in my service, but not quite sure how to inject it in there. I just didn't think I should have to use this url:
 "http://localhost:{port#}/api/myController" in my service. Am I correct in thinking this way?

A: If you want to inject, and use that provider 'ORIGIN_URL', you do it with constructor injection like this.
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

...
export class MyService {
    private url = '/api/myController';

    constructor(private _http: Http, @Inject('ORIGIN_URL') private originUrl: string) {
    }
    public getAll = (): Observable<any> => {
        return this._http.get(this.originUrl + this.url)
            .map(data => data.json());
    };
}

I can't say for sure why the relative URL no longer works.


text:
Q: Can a bot in a group conversation know when a user is talking to it I'm writing a BotFramework bot, and have integrated it with Slack and Teams and in 1-to-1 chats it's working quite nicely.
I'd like to have it work in a group channel as well, but I don't want it to respond to every comment (as most responses would be "I didn't understand the question") - I'm using a Luis Dialog along with a FormFlow form and some Prompts.
I initially tried the following setup within my MessagesController Post method:
if (questionIsToMe(activity))
{
  await Conversation.SendAsync(activity, () => new OctopusLuisDialog());
}

with the questionIsToMe defined as:
private bool questionIsToMe(Activity activity)
{
  // IsGroup is null => 1-1 conversation with non-group capable client
  // IsGroup is False => 1-1 conversation within group capable client
  // IsGroup is True AND message starts with OctoBot => group conversation with question
  // to me
  return !activity.Conversation.IsGroup.HasValue ||
         !activity.Conversation.IsGroup.Value ||
         (activity.Conversation.IsGroup.Value &&
         activity.Text.StartsWith("OctoBot", StringComparison.InvariantCultureIgnoreCase));
    }

Which works for most of the intents fairly well, but causes problems when the user is responding to the FormFlow or Prompts - as I need to include "Octobot" in the response to send the value, which I can strip out of my FormFlow, but the prompts all fail with my fallback text.
How can I distinguish between normal channel chatter and responses to my bots questions?

A: If the bot is @mentioned it will show up in the Entities field of the Activity.
activity.Entities.Items[0] =
    {{
      "mentioned": {
        "id": "{your bot slack id}",
        "name": "{your bot name}"
      },
      "text": "@{your bot name}"
    }}

A: There is no way of knowing when a message is directed to your bot. You can try to:

*

*only respond to messages when it knows the answer

*respond only when the message includes the name of the bot


text:
Q: How to remove kubuntu desktop environment and change to default unity desktop environment? I am new to Ubuntu 14.04. I have installed KDE recently.I don't know how to uninstall/remove it.
It displays an error message and I want to switch back to default Unity Desktop Environment. How to change to default through terminal?
I want to definitely know because I could not open any application (including my files/folders) other than terminal (for which I know the shortcut). I want to switch back to Unity badly.
In the xsessions command in terminal it displays ubuntu.desktop and kubuntu-plasma.desktop; But when I try to remove it shows: no such package is there.

A: First logout of your KDE desktop and login to Unity desktop.
Then open terminal (Ctrl-Alt-T).
Then run this command:
sudo apt-get remove akonadi-facebook akregator amarok amarok-common amarok-utils apport-kde apturl-kde ark audiocd-kio bluedevil calligra-data calligra-libs colord-kde cryptsetup dolphin dragonplayer freespacenotifier gnupg-agent gnupg2 gpgsm gstreamer0.10-qapt gtk2-engines-oxygen gtk3-engines-oxygen gwenview ibus-qt4 kaccessible kaddressbook kamera kamoso kate kcalc kde-base-artwork kde-baseapps-bin kde-baseapps-data kde-config-gtk-style kde-config-tablet kde-config-telepathy-accounts kde-config-touchpad kde-style-oxygen kde-telepathy kde-telepathy-approver kde-telepathy-auth-handler kde-telepathy-contact-list kde-telepathy-data kde-telepathy-filetransfer-handler kde-telepathy-integration-module kde-telepathy-minimal kde-telepathy-send-file kde-telepathy-text-ui kde-wallpapers-default kde-window-manager kde-window-manager-common kde-workspace kde-workspace-bin kde-workspace-data kde-workspace-kgreet-plugins kde-zeroconf kdegames-card-data kdegames-data kdegraphics-strigi-analyzer kdemultimedia-kio-plugins kdenetwork-filesharing kdepasswd kdepim-kresources kdepim-strigi-plugins kdesudo kexi khelpcenter4 kinfocenter klipper kmag kmail kmenuedit kmix kmousetool knotes konsole kontact korganizer kpat kppp krdc krita krita-data ksnapshot ksysguard ksysguardd ksystemlog ktorrent ktorrent-data kubuntu-default-settings kubuntu-desktop kubuntu-docs kubuntu-firefox-installer kubuntu-netbook-default-settings kubuntu-notification-helper kubuntu-web-shortcuts kvkbd kwalletmanager libassuan0 libaudiocdplugins4 libbluedevil1 libcalendarsupport4 libchm1 libcln6 libdebconf-kde0 libepub0 libeventviews4 libfftw3-3 libgpgme++2 libgps20 libgrantlee-core0 libgtlcore0.8 libgtlfragment0.8 libibus-qt1 libincidenceeditorsng4 libindicate-qt1 libkateinterfaces4 libkblog4 libkcompactdisc4 libkdcraw-data libkdcraw21 libkdecorations4abi1 libkdegames6 libkdepim4 libkdepimdbusinterfaces4 libkdgantt2 libkephal4abi1 libkexiv2-11 libkexiv2-data libkipi-data libkipi9 libkleo4 libkmanagesieve4 libkonq-common libkonq5-templates libkonq5abi1 libkontactinterface4 libkpgp4 libkrossui4 libksane-data libksane0 libksba8 libkscreensaver5 libksgrd4 libksieve4 libksieveui4 libksignalplotter4 libktnef4 libktorrent-l10n libktorrent4 libktpchat0 libktpcommoninternalsprivate3 libkunitconversion4 libkwineffects1abi4 libkwinglutils1abi1 libkwinnvidiahack4 libkworkspace4abi2 liblastfm1 liblightdm-qt-2-0 libllvm3.0 libloudmouth1-0 libmailcommon4 libmailimporter4 libmessagecomposer4 libmessagecore4 libmessagelist4 libmessageviewer4 libmuonprivate1 libmygpo-qt1 libokularcore1abi1 libopenal-data libopenal1 libopenconnect2 libopenctl0.8 libopenjpeg2 libopenshiva0.8 libplasma-geolocation-interface4 libplasmaclock4abi3 libplasmagenericshell4 libpoppler-qt4-4 libprocesscore4abi1 libprocessui4a libqalculate5 libqalculate5-data libqca2-plugin-ossl libqgpgme1 libqimageblitz4 libqoauth1 libqtglib-2.0-0 libqtgstreamer-0.10-0 libqtgstreamerui-0.10-0 libqtscript4-core libqtscript4-gui libqtscript4-network libqtscript4-sql libqtscript4-uitools libqtscript4-xml libqtshiva0.1 libreoffice-kde libreoffice-style-oxygen libruby1.9.1 libsolidcontrol4abi2 libsolidcontrolifaces4abi2 libspnav0 libsyndication4 libtag-extras1 libtaskmanager4abi3 libtelepathy-logger-qt4-1 libtelepathy-qt4-2 libtemplateparser4 libweather-ion6 libyaml-0-2 libzip2 lightdm-kde-greeter muon muon-installer muon-notifier muon-updater okular okular-extra-backends oxygen-cursor-theme partitionmanager pinentry-gtk2 pinentry-qt4 plasma-dataengines-addons plasma-dataengines-workspace plasma-desktop plasma-netbook plasma-scriptengine-python plasma-widget-facebook plasma-widget-folderview plasma-widget-kimpanel plasma-widget-menubar plasma-widget-message-indicator plasma-widget-networkmanagement plasma-widget-telepathy-chat plasma-widget-telepathy-presence plasma-widgets-addons plasma-widgets-workspace plymouth-theme-kubuntu-logo plymouth-theme-kubuntu-text print-manager python-pyudev python3-pykde4 python3-pyqt4 python3-sip qapt-deb-installer quassel quassel-data rdesktop rekonq ruby ruby1.9.1 skanlite software-properties-kde systemsettings tasks-icons ubuntu-release-upgrader-qt usb-creator-kde userconfig

This will remove KDE completely and then you might want to run:
sudo apt-get autoremove

Thanks to: Psychocats Eliah Kagan for pointing it out.


text:
Q: Verificar si existe un campo dentro de un Json tengo un problema con mi Json, verán, hago una consulta a la base de datos para verificar si un Paciente tiene alguna derivación o no. En caso de que la tenga, deberá devolverme los datos del paciente y además los datos de la derivación. Y, si por el contrario no cuenta con una derivación, solo me devolverá los datos de mi paciente.
Esto me lo devuelve como un Json.
Lo que quiero hacer es verificar si ese Json tiene un campo llamado, por ejemplo nameDoctor ya que si lo tiene, mostrara una tarjeta de datos diferente, que incluirá obviamente los datos de la derivación.
let patientData =  JSON.parse(this.responseText);

if(isset(patientData.nameDoctor)){
    alert('Si tiene Medico');
}else{
    alert('No tiene Medico');
}

Algo así. Obviamente el isset es de PHP, lo que quiero es traducir eso a JS

A: Puedes preguntar si un objeto tiene una propiedad específica con el método hasOwnProperty('propiedad') que devuelve true o false dependiendo si el objeto tiene o no la propiedad.

const obj1 = {nameDoctor: "Juan Antonio"}
const obj2 = {name: "Alberto"}

console.log(obj1.hasOwnProperty('nameDoctor'))
console.log(obj2.hasOwnProperty('nameDoctor'))

A: Para validar si el campo existe o si es un string vacío (es decir:
nameDoctor = "")
puedes usar:
if(patientData.nameDoctor) {
   alert('Si tiene Medico');
}

por otro lado si quieres algo más estructurado puedes usar isEmpty() de lodash
https://lodash.com/docs/4.17.15#isEmpty
esta librería es bastante útil al momento de trabajar con objetos Json complejos

A: Se puede usar .hasOwnProperty como han dicho, o el operador in, pero cada método tiene sus cosas. .hasOwnProperty no verifica las propiedades heredadas, lo que lo hace en general mas seguro, pero al mismo tiempo pueden pasar cosas como que lo siguiente sea true:

[1,2,3].hasOwnProperty("length");

Por otro lado, el operador in solo funciona con objetos literales. Si controlamos la definición del objeto podemos usar tranquilamente in, sino, como en el caso de trabajar con objetos del dom por ejemplo, u objetos que no sabemos de que heredan, es preferible .hasOwnProperty. Ejemplo de in:

const json = '{"prop":"val","nameDoctor":"Algo"}';

if ("nameDoctor" in JSON.parse(json)) {

  console.log("tiene la propiedad");

} else {

  console.log("no tiene la propiedad");

}

Como curiosidad, el método JSON.parse puede recibir una especie de callback, que se llama "reviver" en verdad, dentro del "reviver" podemeos también verificar si existe la propiedad, aunque es muy poco práctico:

const json = '{"prop":"val","nameDoctor":"Algo"}';

JSON.parse(json, (k) => {

  if (k === "nameDoctor") {

    console.log("tiene la propiedad");

  }

});


text:
Q: MFC - Why the pop up message box of DDV_MinMaxUInt only modal for main frame? we know the pop up message box of DDV_MinMaxUInt is modal. But this message box is only modal for the main frame, NOT for the parent dialog which derived this message box. Where I went wrong?
example:
Main Frame->Dialog A-> Dialog B -> Dialog C-> DDV_MinMaxUInt(...)
The pop-up message box of DDV_MinMaxUInt is only modal for main frame. But I want this message box modal for all dialog.


text:
Q: Strategies for uploading big files in REST service Below is simple code from my application and it uploads files, Java web app.
@POST
    @Path("/uploadDocument")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadDocument(
           @FormDataParam("file") InputStream fileInputStream,
           @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

As you see it is jersey code (I also have CXF services on other application with the same issue) and it is one POST for file.
What would happen if file is too big and when it is too big for such service? Every server has some timeout settings so it would throw RequestTimeoutException. Does HTTP protocol (when REST service is used) do some chunking behind? Does this annotation means chunking in case of REST service?
@Consumes(MediaType.MULTIPART_FORM_DATA)

would be enough for this?
Or maybe REST provides something like MTOM in webSerives?

A: In these kind of scenario's i would be limiting the file upload size example here


text:
Q: How and Who calling the ConfigureServices and Configure method of startup class in .net core As everyone know that Main method of Program.cs is the entry point of application. As you can see in the .net core default code created when we create any project.
public static void Main(string[] args)
{
   CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
       .UseStartup<Startup>();

And in startup class we have two In-build method i.e ConfigureServices and Configure as shown below.
public void ConfigureServices(IServiceCollection services)
{
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}

I just want to know that how these methods is invoked. As we know that to invoked any method we have to create a object of the class and using that object we can execute the method, then how these(ConfigureServices and Configure) methods execute without creating any object.
Please help me out to understand in deep.

A: As an overly simplified explanation,
WebHost.CreateDefaultBuilder(args)

method call returns an object for default webhost builder which implements IWebHostBuilder. Then UseStartup() extension method configures created webhost builder using the Startup class you provide. UseStartup() method can identify your startup class since you specify as the generic argument. UseStartup() cantains the implementation to invoke ConfigureServices and  Configure methods which you provide by using the reflection. Note that to invoke a method one can use reflection also other than creating an instance of a class.

A: Those methods are called by the ASP.NET Core framework. Note that in your Main method you have this call:
.UseStartup<Startup>()

Where you specify the class to use for the startup, in this case Startup. The ConfigureServices and Configure methods are called by convention. If those methods are found in the class specified in the UseStartup extension, they will be called.

A: Lets take a step back and try to understand what are we trying to do here -
We are setting Up the Host and Host originates the request pipeline. Now both Configure and Configure services are like the rooms where the requests are configured through middleware or services.
Now as you built the Host and Ran it from Program.cs and injected StartUp as already said, using reflection, stitches up the Request Pipleline origin and configured with these two methods so that it can handle all the requests

A: Try to comment out both of these methods and you'll get exceptions as a result:

*

*"System.InvalidOperationException: A public method named 'ConfigureDevelopment' or 'Configure' could not be found in the 'Your_WebApplication.Startup' type".

*System.InvalidOperationException: 'Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAuthorization' inside the call to 'ConfigureServices(...)' in the application startup code.'
Configure -  This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
ConfigureServices - This method gets called by the runtime. Use this method to add services to the container.


text:
Q: Why am I getting an std::bad_alloc error I'm having an issue when running the code below. Every time I set the while loop to reach the .eof() it returns a std::bad_alloc
inFile.open(fileName, std::ios::in | std::ios::binary);

        if (inFile.is_open())
        {
            while (!inFile.eof())
            {
                read(inFile, readIn);
                vecMenu.push_back(readIn);
                menu.push_back(readIn);
                //count++;
            }

            std::cout << "File was loaded succesfully..." << std::endl;

            inFile.close();
        }

It runs fine if I set a predetermined number of iterations, but fails when I use the EOF funtion. Here's the code for the read function:
void read(std::fstream& file, std::string& str)
{
    if (file.is_open())
    {
        unsigned len;
        char *buf = nullptr;

        file.read(reinterpret_cast<char *>(&len), sizeof(unsigned));

        buf = new char[len + 1];

        file.read(buf, len);

        buf[len] = '\0';

        str = buf;

        std::cout << "Test: " << str << std::endl;

        delete[] buf;
    }
    else
    {
        std::cout << "File was not accessible" << std::endl;
    }
}

Any help you can provide is greatly appreciated.
NOTE: I failed to mention that vecMenu is of type std::vector
      and menu is of type std::list

A: The main problems I see are:

*

*You are using while (!inFile.eof()) to end the loop. See Why is iostream::eof inside a loop condition considered wrong?.

*You are not checking whether calls to ifstream::read succeeded before using the variables that were read into.
I suggest:

*

*Changing your version of read to return a reference to ifstream. It should return the ifstream it takes as input. That makes it possible to use the call to read in the conditional of a loop.

*Checking whether calls to ifstream::read succeed before using them.

*Putting the call to read in the conditional of the while statement.
std::ifstream& read(std::fstream& file, std::string& str)
{
   if (file.is_open())
   {
      unsigned len;
      char *buf = nullptr;

      if !(file.read(reinterpret_cast<char *>(&len), sizeof(unsigned)))
      {
         return file;
      }

      buf = new char[len + 1];

      if ( !file.read(buf, len) )
      {
         delete [] buf;
         return file;
      }

      buf[len] = '\0';

      str = buf;

      std::cout << "Test: " << str << std::endl;

      delete[] buf;
   }
   else
   {
      std::cout << "File was not accessible" << std::endl;
   }

   return file;
}

and
inFile.open(fileName, std::ios::in | std::ios::binary);

if (inFile.is_open())
{
   std::cout << "File was loaded succesfully..." << std::endl;

   while (read(inFile, readIn))
   {
      vecMenu.push_back(readIn);
      menu.push_back(readIn);
      //count++;
   }

   inFile.close();
}


text:
Q: Calculating similarity -> python code to php code - Whats wrong? I am trying to convert the following python code to a PHP code. Can you please explain me what is wrong in my PHP code, because I do not get the same results. If you need example data please let me know.
# Returns a distance-based similarity score for person1 and person2

def sim_distance(prefs,person1,person2):
    # Get the list of shared_items
    si={}
    for item in prefs[person1]:
        if item in prefs[person2]: si[item]=1
    # if they have no ratings in common, return 0
    if len(si)==0: return 0

    # Add up the squares of all the differences

    sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
        for item in prefs[person1] if item in prefs[person2]])

    return 1/(1+sum_of_squares)

My PHP code:
$sum  = 0.0;

foreach($arr[$person1] as $item => $val)
{
    if(array_key_exists($item, $arr[$person2]))
    {
        $p = sqrt(pow($arr[$person1][$item] - $arr[$person2][$item], 2));
        $sum = $sum + $p;
    }
}

$sum = 1 / (1 + $sum);

echo $sum;

Thanks for helping!

A: The main difference is that you've added sqrt to the PHP code. The PHP also doesn't handle the special case of no prefs in common, which gives 0 in the python version and 1 in the PHP version.
I tested both versions and those are the only differences I found.

A: this is close as i could make a direct translation... (untested)
function sim_distance($prefs, $person1, $person2) {
    $si = array();
    foreach($prefs[$person1] as $item) {
        if($item in $prefs[$person2]) $si[$item]=1;
    }
    if(count($si)==0) return 0;

    $squares = array();
    foreach($prefs[$person1] as $item) {
        if(array_key_exists($item,$prefs[$person2])) {
            $squares[] = pow($prefs[$person1][$item]-$prefs[$person2][$item],2);
        }
    }
    $sum_of_squares = array_sum($squares);
    return 1/(1+$sum_of_squares);
}

I don't really know what you're trying to do, or if I've interpreted the indentation correctly...but maybe this'll help. I'm assuming your data structures have the same layout as in the python script.
oh...and i'm interpreting the python as this:
def sim_distance(prefs,person1,person2):
    # Get the list of shared_items
    si={}
    for item in prefs[person1]:
        if item in prefs[person2]: si[item]=1

    # if they have no ratings in common, return 0
    if len(si)==0: return 0

    # Add up the squares of all the differences
    sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]])

    return 1/(1+sum_of_squares)


text:
Q: How to get a linux command output to chef attribute I want to get a command output into a chef attribute. Can some one help me how to set that in execute resource or bash resource.
ruby_block "something" do
    block do
        #tricky way to load this Chef::Mixin::ShellOut utilities
        Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)
        command = 'cat #{fileName}'
        command_out = shell_out(command)
        node.set['my_attribute'] = command_out.stdout
    end
    action :create
end

How to use attributes in the above code..

A: The answer to your question is pretty mich given in How can I put the output of a Chef 'execute resource' into a variable. With tiny modification, if I understand the question right, your problem can be solved like this:
ruby_block "something" do
    block do
        #tricky way to load this Chef::Mixin::ShellOut utilities
        Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)
        command = 'cat /etc/hostname'
        command_out = shell_out(command)
        node.set['my_attribute'] = command_out.stdout
    end
    action :create
end

Replace the content of command with the command that you want to run and my_attribute with the attribute that you want to set.


text:
Q: Workbook not opening at startup (splash screen frozen) I use Excel 2016. The file I am using runs some code in workbook Open event handler.
Depending on what the code does the workbook may never get opened (visible).
in Workbook_Open the event handler establishes a connection with a data base and load some data eventually warn the user if an error occurs for instance.
Establishing the connection with a data base and load some data works most of the time. Some times it does not and the Excel splash screen remains on the screen for ever. After closing the splash screen clicking on the close cross, the Excel process continues running in the background.
If an error occurs I don't see the pop up form which is opened to warn the user as long as the workbook is not visible.
when I kill the process an reopen Excel (not the workbook), Excel suggest to retrieve the file which was opened earlier proving somehow that it has in deed been opened.
The second process just does not work unless the workbook is visible. If I run Excel and then open the workbook it s ok (in case an error occurs the warning pop up form is opened).
If Excel is closed and i open the workbook it does not work (splash screen frozen).
what is the proper way to start a VBA application where It is necessary to manage some cosmetics tasks (show some sheets, hide some other) and run a connection to a data base?
Here is a simplified version of the code  (can't provide it all - too complex - too long)
In this code the function bConnectToTheDatabase is forced to return False which make the bLogin function useless (the code is not provided for this reason).
Private mLoginForm As frmLgn ' a form to login the application (see image)
Private mCustomMsgBox As frmMsgBox ' a form to display custom messages (see image)

Public Const gsPFU_VBA_PWD as String = "my secret password"
Public Const gsBLANK_WKS_NAME As String = "Blank"
Private Sub Workbook_Open()
'
    Call HidShowSomeSheets()
    ' start the application up
    Call LoginIntoTheApplication()
End Sub
' hide all sheets but the one named gsBLANK_WKS_NAME
' protect/unprotect to chnage visibility
Sub HidShowSomeSheets()
    With Application.Workbooks(ThisWorkbook.Name())
        .Unprotect (gsPFU_VBA_PWD)
        .Sheets(gsBLANK_WKS_NAME).Visible = xlSheetVisible
        For Each wks In .Sheets
        With wks
            .Unprotect (gsPFU_VBA_PWD)
        End With
        Next wks
        For Each wks In .Sheets
        With wks
            If (StrComp(gsBLANK_WKS_NAME, .Name) <> 0) Then
                .Unprotect (gsPFU_VBA_PWD)
                On Error Resume Next
                .Visible = xlSheetVeryHidden
            Else
                .Protect (gsPFU_VBA_PWD)
                .Activate
            End If
        End With
        Next wks
        .Protect (gsPFU_VBA_PWD)
    End With
End Sub
Sub LoginIntoTheApplication()
    if( bConnectToTheDatabase() ) then
        call bLogin
    else
        'create a custom form (it has it own even handler - block the execution flow)
        'set mCustomMsgBox= new frmMsgBox
        'mCustomMsgBox.Show vbModeless    'this does not work
        MsgBox  "something went wrong" 'this works
    end if
end Sub
Function bLogin() as Boolean
'login into the application

End Function
Function bConnectToTheDatabase() as Boolean
    'do the connection
    'get the data
    'etc ....
    bConnectToTheDatabase= False 'fore it to False for the purpose of the explanation
End Function

The login form

The custom message box


text:
Q: search a text in a svn repository across all releases I need to search a text in a SVN repository, inside all revisions.
I am trying this software, which indexes all repositories and then you can search:
http://www.supose.org/projects/supose/wiki
#create the index
./bin/supose  sc -U "svn://..." --username ... -p ... --fromrev 0 --create

#search
./bin/supose  se -Q "+contents:class"

if i understood correctly, this should search across all files for the text "class".
this should return a lot of matches, as there a lot of java files.
however, it only returns maches in some .xml; it is ignoring java files.
why?
and what is the "search --fields" option? what is a field?


text:
Q: onResume() only if Resume Activity I need callback if application resume from background but onResume() is called always Activity start.
I open a Activity with:
Intent i = new Intent(this, Spedizione.class);
i.putExtra("codice", result.getText());
 startActivity(i);

onResume code:
    @Override
    protected void onResume() {
    super.onResume();
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();
    }

When open Activity onResume() always call AlertDialog, not only if app is resume from background, why?
I just need callback only if application is reopen from background.

A: OnResume() is an activity lifecycle method which gets called every time. You can handle your condition by putting your call on onRestart() or maintain a boolean to check firstTimeCall or not.


text:
Q: Validationsummary not showing onclick of button I am using ASP.NET 1.1 and I'm having problems with my validationsummary and validationcontrols working. On button click, required field validations, etc are not fired. How do I fix this?
Here's the code:
<asp:ValidationSummary id="EsppDataInputValidationSummary" runat="server" Font-Names="Arial" Font-Size="8pt" HeaderText="Please Correct the following error(s):" DisplayMode="List" ShowSummary="True"></asp:ValidationSummary></TD>

<asp:RequiredFieldValidator id="Validator1" runat="server" Font-Size="8pt" Font-Names="Arial"
ControlToValidate="txtPrice" Display="None" ErrorMessage="Please enter the Price"></asp:RequiredFieldValidator>

<asp:textbox onblur="return ValidateLength(this)" style="Z-INDEX: 0; TEXT-ALIGN: right" id="txtPurchasePrice" onkeypress="return IsValidChar(event);" onkeyup="return ValidateLength(this)" runat="server" Width="160px" MaxLength="10"></asp:textbox>

<asp:button id="btnAdd" runat="server" Text="Add"></asp:button>"

A: I think the problem may be you're not testing the Page.IsValid property in you codebehind, but as you don't show it I couldn't be sure. You need to test it before doing anything, else your form will be submitted and you'll never get to actually see your validation summary...
So, in your onClick event handler, where you do all your stuff for now I presume :
if(Page.IsValid)
{
//do the actions you wish here
}


text:
Q: JavaScript: Can you add images to an array? I have an array, and each item within the array contains a title and a description, I would also like to add an image to each item as well. How can I do this?
var myArray = [
    {title: "my title", description: "my description."},
    {title: "my title", description: "my description."},
    {title: "my title", description: "my description."},
];

I've already tried {title: "my title", description: "my description.", image: src="my file path here"}, but that didn't work for me.

A: Of course? Just add actual image elements =)
var myArray = [{
  title: "my title",
  description: "my description.",
  image: buildImage("http://example.org/thing.png");
}, {
  title: ...
  ...
});

With a simple builder function like:
function buildImage(url) {
  var img = new Image();
  img.onerror = function() {
    console.log("could not load image on URL " + url);
  };
  img.src = url;
  return img;
}


text:
Q: Why Nodemailer does not securely connect to my server running on a shared host I need to secure the connexion between my node app and my mail server (running on a shared hosting).
I use Nodemailer configured like this :
{
   transport: {
     // Is this where I am not sure
      key: [ readFileSync(__dirname + '/../../../../cert.pem') ],
      host: mail.my.domain,
      auth: {
        user: USER,
        pass: PWD
     }
  }
}

When I try to send an email I end up with this error:
Hostname/IP does not match certificate's altnames: Host: mail.my.domain. is not in the cert's altnames: DNS:xxx.planethoster.net, DNS:xxx.xxx.planethoster.net

I read everywhere that I should use rejectUnauthorized: true to by pass this issue and it works. But it is not an option to let this connexion ensecure.
The cert.pem loaded was the private ~/ssl/keys/XXXX.key of my mail server renamed with the .pem extension. I am not very confortable with certificate/keys stuff but I know that the running SSL certificate on my server is a valid one.
So, I have doubt about the files I renamed and gave to Nodemailer.

A: Planethoster support helped me to understand what was going wrong. I wan't to let this here as I think I won't be the only one to use share hosting for mailing.
In fact, my mail server is on a shared hosting at Planethoster. Thus, the certificate is only for the hosting machine name. Here it is world-346.fr.planethoster.net
So I resolved the problem by setting my configuration like this:
{
   transport: {
      // Removed the unecessary cert loading
      // key: [ readFileSync(__dirname + '/../../../../cert.pem') ],
      host: world-346.fr.planethoster.net, // The host is now the shared machine
      auth: {
        user: USER,
        pass: PWD
     }
  }
}

The host machine is now OK with the given hostname as it is included in its certificate.


text:
Q: PHP cURL getting plaintext I'm using cURL in PHP to get webpage content and it's working great. But my program now requires me to get only plain-text from the target site, instead of HTML. I've looked extensively for this but no one seems to have the answer.  I've also tried setting CURLOPT_TRANSFERTEXT=1 in my cURL options, but this seems to have no effect on the results.
Any idea why this is happening?

A: Make sure you have the following:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

The return value of curl_exec should then be the data.

A: I think it is what you are looking for:
<?
$address = file_get_contents('http://www.thesite.com/file.html');
echo $address;

$file = file_get_contents('./file.txt', true);

 or

$file = file_get_contents('./file.txt', FILE_USE_INCLUDE_PATH);

?>

A: Actually I do like this to get the content of another page.
<?php
function curl_get_file_contents($URL)
    {
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
            else return FALSE;
    }

echo curl_get_file_contents("http://www.php.net");
?>

But it returns to me the whole content.

A: Do you mean that you  want to strip off all the HTML tags on the page?
Simply use the strip_tags() function.


text:
Q: run console.log commands through protractor after some research I've found that can I make some assertions using 'console.log' (in Chrome) when testing a three.js page.
for example:
console.log(scene)
console.log(camera)

when running those commands I'm getting a JSON array and can check the parameters.
my question is - can I do this through protractor? meaning running the commands and check the response?
EDIT:
I know that  I can use console.log for logging the test. but - I can for example going to browser console (chrome for example) and enter:
console.log(window)

when doing that, I get:
 {top: Window, window: Window, location: Location, external: Object, chrome: Object…}Infinity: Infinity$: function (a,b){return new e.fn.init(a,b,h)}AnalyserNode: ...

and so on.
I can also enter
console.log(document.URL)

and get
http://stackoverflow.com/posts/28690960/edit

when trying to put the same line in protractor:
  console.log(window);

I'm getting this error:
 ReferenceError: window is not defined

thanks!

A: If your question is whether you can use console.log in protractor to log simple objects/variables, then yes, protractor is just javascript.
If your question is how to use console.log properly for promises (i.e. element(by.xyz).getText(), just keep in mind that everything protractor returns are promises, so you'll need to resolve the promise before doing console.log (see Protractor console log)
EDIT: okay, so you want to log objects from your browser. Protractors runs in a different process from your browser, so you would need to retrieve it first before doing console.log
browser.driver.executeScript(function() {
    return window;
}).then(function(result) {
    console.log('result is: ', result);
});


text:
Q: Substituting JavaScript values based on Grunt task, best approach? I do not have any specific code to share as I believe the Grunt configuration of tasks is fairly straightforward.
What I would like to ask is for recommendations on replacing JavaScript variables (contained within a JavaScript /src folder) with new values based on the chosen Grunt task.
Specifically, I have a Shared.js (AngularJS Factory) that contains information critical to the application working (ex. locations of Web Services, Whether authentication is enabled, etc.).
Would it make more sense to "build" a new Shared.js depending on the task (i.e. swap in dev-Shared.js if the task is "dev") or should I use Grunt's "string-replace" to crawl through each JavasSript file and replace these values?
I would appreciate your recommendations and comments and any code snippets that you have time to provide. :)


text:
Q: PDF of $U,V$ where $U=|X-Y|$ and $V=\operatorname{min}(X,Y)$ Let $X\perp Y$ two random variables with uniform distribution on $[0,1]$. I found that $f_U(u)=2-2u$ and $f_V(v)=2-2v$. Now I have to apply the formula for a joint density of a transformation when $X\perp Y$, that is $f_{UV}(u,v)=f_X(u)f_Y(v)|J|$.
So I should solve the system of equations $u=|x-y|$ and $v=\min(x,y)$ in order to calculate $|J|$ (I do apologize but I can't insert systems of equations and matrices in Latex: everything appears on the same row and I don't know why), but I'm stuck. Could you help me to solve it?
Thnaks in advance.


text:
Q: SBJson won't go as deep in NSDictionary I've been banging my head on the wall all day because of this.
I'm trying to parse this JSON blob here.
This is what I'm using:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSDictionary *results = [responseString JSONValue];

NSArray *allTweets = [[results objectForKey:@"response"] objectForKey:@"posts"];

However, when I try to do this:
NSURL *url = [NSURL URLWithString:[[[[aTweet objectForKey:@"posts"] objectForKey:@"photos"] objectForKey:@"original_size"] objectForKey:@"url"]];

It gives me no error but the *url is set as "null".
I've used CFShow for the NSDictionary but everything after the "photos" key comes out as a regular string and not JSON formatted.
Can anyone tell me why?
Thanks in advance for all your help.

A: try this.
    for (int i = 0; i < [[[results objectForKey:@"response"] objectForKey:@"posts"] count]; i++) {
        NSLog(@"url data = %@",[[[[[[[results objectForKey:@"response"]
        objectForKey:@"posts"] objectAtIndex:i] objectForKey:@"photos"]
        objectAtIndex:0] objectForKey:@"original_size"] objectForKey:@"url"]);
    }


text:
Q: Make script terminate when background zenity dialog is closed I have written a fairly simple script here that is meant to display a text info dialog using zenity and continuously read data from a remote TCP connection and display it in the dialog. This works... However I would like for the entire script to terminate if I close the zenity dialog.
Is there a way to do this? I don't think I can check for anything in the while loop, because the script could be stalled on reading the data from the remote TCP connection.
#!/bin/bash

on_exit() {
        zenity --display=:0 --error --text="Script has exited." &
}

# Options
while getopts "a:p:t:" OPTION; do case "$OPTION" in
        a) address="$OPTARG";;
        p) port="$OPTARG";;
        t) title="$OPTARG";;
esac; done

exec &> >(zenity --display=:0 --text-info --title=$title || exit)
                               # doesn't make a difference?  ↑
                               # also tried &&
trap "on_exit" EXIT

while read data < /dev/tcp/$address/$port; do
        echo $data
        # ...
        # do some other stuff with the information
        # ...
done

Note: This is going to be run on IGEL Linux. I don't have the option of installing additional packages. So, ideally the solution I'm looking for is native to Bash.

Update
I only had to make this modification to continue using exec. Or @BachLien's answer using named pipes also works.
PID=$$
exec &> >(zenity --display=:0 --text-info --title=$title; kill $PID)

A: I do not have zenity installed, so I tried this script to illustrate the idea.
The program terminal+cat (emmulating zenity) is executed by the function _dspMsg which runs in background (child process); cat continuously displays messages from a file ($m) which is a named pipe; the parent process is killed when terminal+cat exits.
In the mean while, another cat proccess writes messsages into pipe $m (emmulating TPC infomation feeds); it would be killed when when _dspMsg exits.
#!/bin/bash
                              # 1) named pipe
m=`mktemp -u /tmp/msg-XXXX=`  #    get a temporary filename (for named pipe)
mkfifo "$m"                   #    create that named pipe
trap "echo END; rm $m" EXIT   #    remove that file when exit
                              # 2) zenity
_dspMsg(){                    #    continuously display messages
  urxvt -e bash -c "cat <$m"  #    terminal+cat is used in place of zenity
  kill $1                     #    kill parent pid
}                             #    to be run in background
_dspMsg $$ &                  #    $$ = proccess id
                              # 3) TCP info feeds
cat >>"$m"                    #    feeding messages using cat
                              #    cat is used in placed of TCP data feed

Note:

*

*A named pipe is used as a way of communicating between parent and child processes.

*To test that script, you may need to change urxvt to xterm, iTerm, or any other terminal emmulator available in your computer.

So, maybe it is what you need (untested):
#!/bin/bash

while getopts "a:p:t:" OPTION; do case "$OPTION" in
  a) address="$OPTARG";;
  p) port="$OPTARG";;
  t) title="$OPTARG";;
esac; done

m=`mktemp -u /tmp/msg-XXXX=`
mkfifo "$m"
trap "zenity --display=:0 --error --text='Script has exited.' & rm $m" EXIT

_dspMsg(){
  zenity --display=:0 --text-info --title="$title" <"$m"
  kill $1
}

_dspMsg $$ &

while read data < /dev/tcp/$address/$port; do
  echo $data >>"$m"
done

A: You can pipe all of the output of the while loop into zenity, getting rid of the need for exec &>.
while read data < "/dev/tcp/$address/$port"; do
        echo "$data"
done | zenity --display=:0 --text-info --title="$title"


text:
Q: how to specific rails version? i have different versions in different project yulong@ubuntu:~$ rails -v

Rails 3.1.0

yulong@ubuntu:~$ cd four

yulong@ubuntu:~/four$ rails -v

Rails 3.1.0.rc8

yulong@ubuntu:~/four$ cd ..

yulong@ubuntu:~$ cd z

yulong@ubuntu:~/z$ rails -v

Rails 3.1.0.rc6

A: Use rvm on Linux/OSX and DevKit on Windows
For every project(folder) you can customize ruby and rails versions. Then rvm automatically will set all gems(libraries) for every folder accordingly to your settings.

A: If you just need to set Rails versions and not Ruby versions per project add the rails version to the Gemfile in each project folder
gem 'rails', '3.1.0'

and run
bundle install


text:
Q: Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException I am trying to inject the FortuneService interface to the TennisCoach class but I am getting the error and If I am trying to inject it using new keyword then it is working fine. I tried it by using creating the object of HappyFortuneService. I have tried like below in TennisCoach class
FortuneService fortuneService = new HappyFortuneService(); but if I am trying to inject it using constructor injection it is giving me below error.
I am getting the error like Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
package com.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.annotation.coach.Coach;
import com.annotation.coach.FortuneService;
import com.annotation.coach.HappyFortuneService;
import com.annotation.coach.TennisCoach;

@SpringBootApplication
public class Luv2CodeAnnotationApplication {

    private static final Logger logger = LoggerFactory.getLogger(Luv2CodeAnnotationApplication.class);

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

        Coach coach = new TennisCoach();
        logger.info(coach.getDailyWorkout());
        logger.info(coach.getDailyFortune());

    }

}

package com.annotation.coach;

public interface Coach {

    public String getDailyWorkout();
    public String getDailyFortune();
}

    package com.annotation.coach;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;

    import com.annotation.Luv2CodeAnnotationApplication;

    @Component
    public class TennisCoach implements Coach {

        private static final Logger logger = LoggerFactory.getLogger(Luv2CodeAnnotationApplication.class);

        private FortuneService fortuneService;

        public TennisCoach(FortuneService fortuneService) {
            this.fortuneService = fortuneService;
        }
        public TennisCoach() {
        }

        @Override
        public String getDailyWorkout() {
            return "*************Tennis Coach Daily Workout*************";
        }

        @Override
        public String getDailyFortune() {
            logger.info("*********INVOKED***************");
            return fortuneService.getFortune();
        }

    }

    package com.annotation.coach;

    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Component;

    @Component
    public class HappyFortuneService implements FortuneService {

        @Override
        public String getFortune() {
            return "*************Happy Fortune Service*************";
        }

    }

package com.annotation.coach;

public interface FortuneService {

    public String getFortune();
}

A: If you create any bean using new keyword that bean will not added to Spring Application Context,so Coach coach = new TennisCoach(); not added to Application context. So class TennisCoach not recognizing the Autowired FortuneService.
you can do Autowired using Constructor, the instance of Coach is injected as an argument to the constructor when Luv2CodeAnnotationApplication is created.
Please find modified code below
@SpringBootApplication
public class Luv2CodeAnnotationApplication {
private static Coach coach;
private static final Logger logger = LoggerFactory.getLogger(Luv2CodeAnnotationApplication.class);

@Autowired
public Luv2CodeAnnotationApplication(Coach coach) {
    Luv2CodeAnnotationApplication.coach = coach;
}

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

  //Coach coach = new TennisCoach();
    logger.info(coach.getDailyWorkout());
    logger.info(coach.getDailyFortune());

}

}