text:
Q: ui-sref is generating wrong url I'm working with Angularjs with Nodejs on a project. I'm using UI-router in my project for routing.
Here are configurations of the states in my app module file:
app.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider.state('booking', {
    url: '/user/booking',
    templateUrl: '/user/booking.html',
    resolve: {
        delay: function ($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 300);
            return delay.promise;
        }
    }
}).state('bookingDetails', {
    url: '/user/bookingDetails',
    templateUrl: '/user/bookingDetails.html',
    resolve: {
        delay: function ($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 300);
            return delay.promise;
        }
    }
}).state('notificationes', {
    url: '/user/notification',
    templateUrl: '/user/notification.html',
}).state('review', {
    url: '/user/review',
    templateUrl: '/user/review.html',
    resolve: {
        delay: function ($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 300);
            return delay.promise;
        }
    }
}).state('promo', {
    url: '/user/promoCode',
    templateUrl: '/user/promoCode.html'
}).state('setting', {
    url: '/user/setting',
    templateUrl: '/user/setting.html'
}).state('setting.personalInfo', {
    url: '/personalInfo',
    templateUrl: '/user/personalInfo.html',
   resolve: {
       delay: function ($q, $timeout) {
           var delay = $q.defer();
           $timeout(delay.resolve, 300);
           return delay.promise;
       }
   }
}).state('setting.changePassword', {
    url: '/changePassword',
    templateUrl: '/user/changePassword.html',
   resolve: {
       delay: function ($q, $timeout) {
           var delay = $q.defer();
           $timeout(delay.resolve, 300);
           return delay.promise;
       }
   }
}).state('setting.notificationPre', {
    url: '/notificationPreferences',
    templateUrl: '/user/notificationPreferences.html'
}).state('setting.changeAvatar', {
    url: '/changeAvatar',
    templateUrl: '/user/changeAvatar.html'
});

});
When I hitting the URL "localhost:3000/user/booking" then at the sidebar of the main page when I hover the sidebar tabs then it is showing the URLs like "/user/user/booking", "/user/user/review".
you can see in the below screenshot.

Using ui-sref in the sidebar.html file

                Review

I'm stuck into this, don't understand why it is repeating "/user". I tried a lot but couldn't found any solution to this issue. Please help me to resolve this.

A: You don't need to prepend /user at the start of the url of every state you're defining.
Instead create an abstract state (for your example, name it main or whatever suites you) and give it the /user url and have all other user states extend it
e.g.
$stateProvider
.state('main', {
    'abstract': true,
    url: '/user'
.state('main.booking', {
    url: '/booking',
    templateUrl: '/user/booking.html',
    resolve: {
        delay: function ($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 300);
            return delay.promise;
        }
    }
})
.state('main.bookingDetails', {
    url: '/bookingDetails',
    templateUrl: '/user/bookingDetails.html',
    resolve: {
        delay: function ($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 300);
            return delay.promise;
        }
    }

This way every state you redirect to will just take the local url value and append it to the /user defined in the abstract state.


text:
Q: Problems with the comparison of two strings using strcmp I want to compare 2 string but when I do a strcmp function, it tells me that:
'strcmp' : cannot convert parameter 1 from 'std::string'

How can I fix this?
Here is my code :
int verif_file(void)
{
    string ligne;
    string ligne_or;

    ifstream verif("rasphone");
    ifstream original("rasphone.pbk");
    while (strcmp(ligne, "[SynCommunity]") != 0 &&
        (getline(verif, ligne) && getline(original, ligne_or)));
    while (getline(verif, ligne) && getline(original, ligne_or))
    {
        if (strcmp(ligne, ligne_or) != 0)
            return (-1);
    }

    return (0);
}

A: Your compiler gives you an error because strcmp is a C-style function that expects arguments of type const char* and there is no implicit conversion from std::string to const char*.
And although you might retrieve a pointer of this type using std::string's c_str() method, since you are working with std::string objects, you should use the operator == instead:
if (ligne == ligne_or) ...

or comparison with const char*:
if (ligne == "[Syn****]") ...

A: Just use std::string's operator==:
if (ligne == "[SynCommunity]") ...

if (ligne == ligne_or) ...

A: Change
if (strcmp(ligne, ligne_or) != 0)

to
if (ligne != ligne_or)

A: If you want to use strcmp, then try
if (strcmp(ligne.c_str(), ligne_or.c_str()) != 0)
   ...

A: I like the boost algorithm library.
#include <boost/algorithm/string.hpp>

std::string s1("This is string 1");
std::string s2("this is string 2");

namespace balg = boost::algorithm;

// comparing them with equals
if( balg::equals( s1, s2 ) )
     std::cout << "equal" << std::endl;
else
     std::cout << "not equal" << std::endl;

// case insensitive  version
if( balg::iequals( s1, s2 ) )
     std::cout << "case insensitive equal" << std::endl;
else
     std::cout << "not equal" << std::endl;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scaling out with 200+ Kafka topics I'm trying to understand how to dynamically scale out application which consumes a huge number of topics (unfortunately I can't reduce their number - by design each topic is for particular type of data).

I want my application cluster to share the load from all 200+ topics. E.g when a new app node added to the cluster, it should "steal" some topics subscriptions from old nodes, so the load become evenly distributed again.
As far as I understand, Kafka partinions/consumer groups help to parallelize a topic, not to share a load between multiple topics.

A: You need to make sure that all your App instances use the same Kafka Consumer Group (via group.id). In this case you actually have an even distribution you want. When a new App instance is added, consumer group is going to rebalance and make sure the load is distributed.
Also, when a new topic/partition is created it'll take consumer up to "metadata.max.age.ms" (default is 5 minutes) to start consuming from it. Make sure to set "auto.offset.reset" to "earliest" to not miss any data.
Finally, you might want to use a regex to subscribe to all those topics (if possible).

A: A Kafka Topic is a grouping of messages of a similar type, so you probably have 200+ types of messages that have be consumed by 200+ types of consumers (even if one consumer may be able to handle several types, logically you have 200+ different handlings).
Kafka Partitions is a way to parallelize the consumption of the messages from one Topic. Each Partition will be fully consumed by one consumer in a consumer group bound to the topic, therefore the total number of partitions for a topic needs to be at least the same as the number of consumers in a consumer group to make sense of the partitioning feature.
So here you would have 200+ Topics, each having N partitions (where N greater or equal to your expected Max number of applications) and each application should consume from all 200+ Topics. Consumers have to label themselves with a consumer group name, each record published to a topic is delivered to one consumer instance within each subscribing consumer group. All consumers can use the same consumer group.
See Kafka documentation for an even better explanation...


text:
Q: Spectral triples which are not $\theta$-summable I would like to see an example of a spectral triple $(A,H,D)$ such that the underlying algebra $A$ is commutative but this spectral triple is not $\theta$-summable in the sense that $e^{-tD^2}$ is never traceclass operator.
EDIT: Spectral triple is defined as a unital $*$-algebra $A$ represented faithfully on some Hilbert space $H$ together with the (usual unbounded) self adjoint operator $D$ with the property that $D$ has compact resolvent and such that for all $a$ in $A$ the commutator $[D,a]$ is (extends to) a bounded operator

A: So, under this generality, it seems to me that we can choose $A$ in a clever way: if we make $A$ smaller, then it gets "easier" to satisfy the condition.  So why not take $A$ to be the scalar multiples of the identity-- then $D$ commutes with all of $A$ on the nose.
Now let $H=\ell^2$ and let $D$ be multiplication by a sequence of real numbers $(d_n)$.  If $z\in\mathbb C$ not an accumulation point of the $(d_n)$ then $(zI-D)^{-1}$ exists and is the multiplication operator by the sequence $(z-d_n)^{-1}$.  If $d_n\rightarrow\infty$ then $(z-d_n)^{-1}\rightarrow 0$ and so $(zI-D)^{-1}$ is compact and so $D$ has compact resolvant.
Similarly, $e^{-tD^2}$ is the multiplication operator by the sequence $(\exp(-td_n^2))$.  This will be trace class if and only if
$$ \sum_n \exp(-td_n^2) < \infty $$
So you just need to let $(d_n)$ grow very slowly.  For example, set
$$ d_n = \big( \log(1/e_n) \big)^{1/2} \implies \exp(-td_n^2)
= e_n^{t} $$
where we now just need that $e_n\rightarrow 0$.  Let $e_n = 1/2$ for the first $N_2$ terms, then $e_n=1/3$ for next $N_3$ terms, and so on.  Then
$$ \sum_n \exp(-td_n^2) = \sum_{k\geq 2} \frac{N_k}{k^t}. $$
Pick $N_k \geq k^k$ so that for any $t>0$ if $K>t$ then
$$ \sum_n \exp(-td_n^2) \geq \sum_{k\geq K} \frac{N_k}{k^t}
\geq \sum_{k\geq K} 1 = \infty. $$
In this example, you could also take $A=c_0$ for a less trivial algebra.

A: One can produce an operator in a less artificial way.  Consider the Sturm-Liouville operator $Du=-u''+V(x)u$, where $V(x)$ grows at infinity as $\log\log|x|$.
The eigenvalues grow very slowly, also as $\log\log$, and therefore the exponent of the operator is not trace class (the details on the asymptotics of eigenvalues can be found, eg, in the book by S.Levendorskii, 'Asymptotic distribution of eigenvalues of differential operators. Kluwer Academic Publishers Group, Dordrecht, 1990.)


text:
Q: placeholder is not working with ajax I make ajax request to my function and when i am echo  it , placeholder is not working see this div is in loop
php:
$info=NULL;
//loop-start
$info.='
<textarea name="commentq'.$post_id.'" id="commentq'.$post_id.'" class="textarea-style1" placeholder="Comment.."  onkeydown="return runScript1(event,\''.$post_id.'\',\''.$cmt_id.'\')"> </textarea>

';
echo $info;

//loop-end

js:
$('#data').append(html);

A: You have a space between <textarea> tags, so it is inserted into textarea. If you remove it, you will be able to see a placeholder.
$info.='
<textarea name="commentq'.$post_id.'" id="commentq'.$post_id.'" class="textarea-style1" placeholder="Comment.."  onkeydown="return runScript1(event,\''.$post_id.'\',\''.$cmt_id.'\')"></textarea>

';

A: Try this: problem with your code is you have space between "textarea" tags and at the end you added two close div but you have only one open div
$info.='

<textarea  name="commentq'.$post_id.'" id="commentq'.$post_id.'" class="textarea-style1" placeholder="Describe yourself here..." onkeydown="return runScript1(event,\''.$post_id.'\',\''.$cmt_id.'\')"></textarea>
';


text:
Q: Polling Batchwise a Database Table with Reactive extensions I am trying to figure out ways to Poll a single DB Table using Reactive Extensions.
I have a Method GetEmployees()which returns  all Records from Employee table.
    var query = "SELECT emp_no, first_name, last_name FROM Employees" ;
    while (reader.Read())
      { :
        :
        yield return employee;
     }

Next , I have a Extension method which takes the above Employee Source ( AsObservable ) and Periodically polls the observable and returns Actual  results.
 public static IObservable<T> Poll<T>(this IObservable<T> source, TimeSpan period, IScheduler scheduler)
        {
            return Observable.Timer(period, scheduler)
                        .SelectMany(_ => source)
                        .Retry()
                        .Repeat();  //Loop
        }

However when I try to call the above Poll from my client code after periodic interval , I see it repeats the same result over and over again. It doesnt progress to the next batch of records from table .
Client code looks like this :-
private static void StreamDBDataWithThrottling()
        {
            var r = GetEmployees().ToObservable();

            r.Poll(TimeSpan.FromSeconds(2), Scheduler.Default)
                //.Take(20)
                // .Concat(Observable.Interval(TimeSpan.FromSeconds(0.01)).Take(100))
                .Buffer(20, 20)
                .TakeUntil(DateTimeOffset.Now.AddSeconds(15))
                .Subscribe((data) =>
                {
                    foreach (var item in data)
                    {
                        Console.WriteLine(item.FirstName);
                        // Todo: - Real Business Logic with Task.Factory.StartNew( _ => { // intensive task here } )
                    }
                });
        }

The table will Not have new data coming in once processing has started.
I am learning the caveats of Push based collections and Concurrent Collections .
Thanks in advance if you can guide me with -  How to batchwise process all records of the table until the last record.


text:
Q: React Hooks and Redux - trouble getting value from action creator so I am making a small project learning about hooks, and it is a little nightmare :)
I have a login form component that calls to action creator to login, after that I want to use value that has been changed in this action, ex. isLoggedIn. I can see the value in store has been changed in chrome react dev tools, but it's not working in code. Below is the code sample.
Reducer (reducer.js):
const initialState = {
  user: {},
  isFetching: false,
  isLoggedIn: false,
  error: false
};

export default function loginReducer(state = initialState, action) {
  switch (action.type) {
    case types.LOGIN_SUCCESS:
      return {
        ...state,
        isFetching: false,
        isLoggedIn: true,
        error: false,
        user: action.user
      };
    default:
      return state;
  }
}

Action Creator (actions.js)
export function loginToApi(credentials) {
  return function(dispatch) {
        axios
          .post("https://localhost:44320/Login", {
            email: credentials.email,
            password: credentials.password
          })
          .then(response => {
            dispatch(loginSuccess(response.data));
          })
      })
  };
}

function loginSuccess(user) {
  return { type: types.LOGIN_SUCCESS, user };
}

Login form component (form.js)
import React, { useState } from "react";
import { Redirect } from "react-router-dom";
import useForm from "./useForm";
import validate from "./LoginFormValidationRules";
import { loginToApi } from "../../redux/actions/loginActions";
import { connect } from "react-redux";

export function Form({ loginToApi, isLoggedIn }) {
  // custom form hook
  const { values, errors, handleChange, handleSubmit } = useForm(
    { accountType: "1", email: "", password: "" },
    login,
    validate
  );

  const [loginFailed, setLoginFailed] = useState(false);

  function redirect() {
    if (isLoggedIn) { // I want to use those variables here
      return <Redirect to="/home" />;
    }
  }

  function login() {
    loginToApi(values);
  }

  return (

      {redirect()}
      // form, I want to use error variable here for valdiations as well

  );
}

function mapStateToProps(state) {
  console.log(state); // I can see change here
  return {
    user: state.user,
    isLoggedIn: state.isLoggedIn,
    error: state.error
  };
}

const mapDispatchToProps = {
  loginToApi
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form);

So I want to use in this component values like error or isLoggedIn, but I don't know how to get them. All I get is undefined.
Help appreciated.
@edit
As requested my usage of Form component:
index.js:
const store = configureStore();

render(
  <ReduxProvider store={store}>
    <Router>
      <App />
    </Router>
  </ReduxProvider>,
  document.getElementById("app")
);

App.js:
function App() {
  return (

      <Switch>
        <Route path="/login" component={LoginPage} />
      </Switch>

  );
}

LoginPage.js:
const LoginPage = () => (

     <LoginForm />

);

export default LoginPage;

configureStore.js:
export default function configureStore(initialState) {
  const composeEnhancers =
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools

  return createStore(
    rootReducer,
    initialState,
    composeEnhancers(applyMiddleware(thunk, reduxImmutableStateInvariant()))
  );
}

rootReducer:
const rootReducer = combineReducers({
  reducer: reducer
});

export default rootReducer;

Hope this helps you see the problem, because I still have not resolved the issue.. thanks!

A: I believe in your Login form component (form.js),
values in mapStateToProps function should be like this:
function mapStateToProps(state) {
  console.log(state.reducer); // I can see change here
  return {
    user: state.reducer.user,
    isLoggedIn: state.reducer.isLoggedIn,
    error: state.reducer.error
  };
}

A: In form.js file:
  can you please try using this:
function redirect() {
    if (this.props.isLoggedIn || this.props.isLoggedIn.loginReducer.isLoggedIn) {
      return <Redirect to="/home" />;
    }
  }


text:
Q: jQuery - Nesting another each() loop inside existing each() event not working I'm trying to create a table from JSON data with multiple options, where I'm splitting the data and using .each() to loop through each option.
Below is the JSON data I'm using:
var StatJSON = {
        "Volvo": {
            "Options": "Option1-Black,car/Option2-Blue,car&bus"
        },
        "Mercedes": {
            "Options": "Option1-Blue,car/Option2-Blue,car&bus"
        },
    };

The challenge I'm facing is where I need to create another loop within each 'Option' to select each 'vehicle type' (i.e. car,bus in ths above JSON) using '&' as a seperator. The jQuery I'm using to loop through the data is as below (Placed comments against relavent statements below):
jQuery('.divResult table tbody tr td').each(function ($) {
    if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function () {
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) {
            var html = '
';
            jQuery.each(Options, function(index, value){
                var OptionNumber = value.split('-')[0];
                var OptionData = value.split('-')[1];
                var OptionColor = OptionData.split(',')[0];
                var OptionTransport = OptionData.split(',')[1];
                var OptionTransportArray = OptionTransport.split('&'); // <-- Splitting the transport options

                for (i=0; i<OptionTransportArray.length; i++){
                  var OptionTransportEach = OptionTransport.split('&')[i]; // <-- Looping the options
                }

                html += '
'+ OptionNumber +'
'
                html += '
Color:'+ OptionColor +'	'
                html += '
' //  <-- Adding each option
            });
            html += '
'
            return html;
        }
        jQuery(this).empty().append(HowToReach(data));
    });
 });

Unfortunately, it doesn't loop through both the elements and only shows the nth element in the array i.e only the 'bus' in case of 'Option2' and not the 'car'.

Where am I going wrong and how do I correct my code to ensure that loops through and displays each element seperated with the '&' sign.
Below is the entire working code:

jQuery(document).ready(function($) {

  var StatJSON = {
    "Volvo": {
      "Options": "Option1-Black,car/Option2-Blue,car&bus"
    },
    "Mercedes": {
      "Options": "Option1-Blue,car/Option2-Blue,car&bus"
    },
  };

  jQuery('#btnSubmit').click(function() {
    var data = [];
    jQuery("#selection").find(':selected').each(function(e) {
      var this_input = jQuery(this);
      if (this_input.is(':selected')) {
        data.push(this_input.val());
      }
    });

    $('#divResult').empty().append(PrintTable(data));

    jQuery('.divResult table tbody tr td').each(function($) {
      if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function() {
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) {
          var html = '
';
          jQuery.each(Options, function(index, value) {
            var OptionNumber = value.split('-')[0];
            var OptionData = value.split('-')[1];
            var OptionColor = OptionData.split(',')[0];
            var OptionTransport = OptionData.split(',')[1];
            var OptionTransportArray = OptionTransport.split('&');

            for (i = 0; i < OptionTransportArray.length; i++) {
              var OptionTransportEach = OptionTransport.split('&')[i];
            }

            html += '
' + OptionNumber + '
'
            html += '
Color:' + OptionColor + '	'
            html += '
'
          });
          html += '
'
          return html;
        }
        jQuery(this).empty().append(HowToReach(data));
      });
    });

    function PrintTable(data) {
      var html = '

';
      if (data && data.length) {
        html += '	';
        jQuery.each(data, function(k, v) {
          html += '' + v + '	';
        });
        html += '
';
        html += '
';
        jQuery.each(StatJSON[data[0]], function(k, v) {
          html += '
' + k + '	';
          jQuery.each(data, function(k2, v2) {
            html += '' + StatJSON[data[k2]][k] + '	';
          });
          html += '
';
        });
      } else {
        html += 'No results found
';
      }
      html += '

';
      return html;
    }

  });

});
body {
  font-family: montserratbold, montserratregular, sans-serif;
}

.divResult {
  overflow: scroll;
  position: relative;
}

.compTable {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;
}

.InnerTable {
  margin: 1px;
  border: 1px solid #222;
  text-align: center;
}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/brands.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/fontawesome.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/regular.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">

<select id="selection" multiple="multiple">
  <option value="Volvo">Volvo</option>
  <option value="Mercedes">Mercedes</option>

  <input id="btnSubmit" class="button" type="submit" value="submit" />
</select>

A: You need to move your loop down and build the html based on it

jQuery(document).ready(function($) {

  var StatJSON = {
    "Volvo": {
      "Options": "Option1-Black,car/Option2-Blue,car&bus"
    },
    "Mercedes": {
      "Options": "Option1-Blue,car/Option2-Blue,car&bus"
    },
  };

  jQuery('#btnSubmit').click(function() {
    var data = [];
    jQuery("#selection").find(':selected').each(function(e) {
      var this_input = jQuery(this);
      if (this_input.is(':selected')) {
        data.push(this_input.val());
      }
    });

    $('#divResult').empty().append(PrintTable(data));

    jQuery('.divResult table tbody tr td').each(function($) {
      if (jQuery(this).text() == 'Options') jQuery(this).nextAll("td").each(function() {
        var data = jQuery(this).text();
        var Options = data.split('/');

        function HowToReach(data) {
          var html = '
';
          jQuery.each(Options, function(index, value) {
            var OptionNumber = value.split('-')[0];
            var OptionData = value.split('-')[1];
            var OptionColor = OptionData.split(',')[0];
            var OptionTransport = OptionData.split(',')[1];
            var OptionTransportArray = OptionTransport.split('&');
            console.log(OptionTransportArray);

            html += '
' + OptionNumber + '
'
            html += '
Color:' + OptionColor + '	'
            html += ''
            for (i = 0; i < OptionTransportArray.length; i++) {
              html+= ''
              }
            html+='
';
          });
          html += '
'
          return html;
        }
        jQuery(this).empty().append(HowToReach(data));
      });
    });

    function PrintTable(data) {
      var html = '

';
      if (data && data.length) {
        html += '	';
        jQuery.each(data, function(k, v) {
          html += '' + v + '	';
        });
        html += '
';
        html += '
';
        jQuery.each(StatJSON[data[0]], function(k, v) {
          html += '
' + k + '	';
          jQuery.each(data, function(k2, v2) {
            html += '' + StatJSON[data[k2]][k] + '	';
          });
          html += '
';
        });
      } else {
        html += 'No results found
';
      }
      html += '

';
      return html;
    }

  });

});
body {
  font-family: montserratbold, montserratregular, sans-serif;
}

.divResult {
  overflow: scroll;
  position: relative;
}

.compTable {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  margin: 10px;
  border: 1px solid #222;
  text-align: center;
}

.InnerTable {
  margin: 1px;
  border: 1px solid #222;
  text-align: center;
}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/brands.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/fontawesome.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/regular.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">

<select id="selection" multiple="multiple">
  <option value="Volvo">Volvo</option>
  <option value="Mercedes">Mercedes</option>

  <input id="btnSubmit" class="button" type="submit" value="submit" />
</select>


text:
Q: Многопоточность в PHP Здравствуйте. Необходимо реализовать кроссплатформенную многопоточность на PHP. Задача следующая, допустим, есть метод для каких либо вычислений, числа пи, число Фибоначчи и т.п., необходимо запустить этот метод в несколько потоков. Каким образом можно реализовать подобную задачу?
Нагуглил, что можно реализовать используя cURL, но не совсем понимаю логику данного метода.
Попробую конкретизировать задачу. Есть функция, которая высчитывает определенное значение. Задается стартовое значение (точность вычислений), которое указывает количество выполнений. Допустим, мы хотим произвести вычисления с точностью 300, это можно было бы разбить на 3 потока:

*

*вычислял бы значение от 1 до 100

*от 101 до 200

*от 201 до 300
В конце достаточно сложить результаты выполнения этих потоков и вывести результат. Но каким образом их запустить синхронно, понятия не имею.


text:
Q: Where should the CRUD operations go in an Android app with many model objects? In my app, I have many Java model objects (I believe you'd normally refer to them as POJOs?), and I have a central Database singleton class (DatabaseHelper) that extends SQLiteOpenHelper.
My problem: I am unsure where to actually put stuff. Right now I've been putting everything into the DatabaseHelper class and it's getting huge.
This leads me to rethink my approach and that maybe I need to be separating things out.
Should I be putting the database CRUD operations in a dedicated class that acts as a bridge between the model objects and the DatabaseHelper? Or should I be coupling the CRUD methods in the model objects themselves? What about where to store things like the table and column names?
What's considered accepted practice here?

A: If you have plenty of tables in your database, which I presume you do since you're asking the question, I'd suggest you put all of the CRUD logic into separate classes called Repositories (e.g. ModelRepository).
These classes should have all the things necessary and they'd best be implemented via the interface that has the C R U and D methods, so that if the implementation needs to undergo some changes, everything keeps on working because of the usage of interface. So for every model you need 2 classes, ModelRepositoryInterface which can even extend a common interface with these 4 operations and each can have some additional methods specific to the class itself; and the class that implements the interface, say ModelRepositoryImplementation.
Some basic example, let's assume your Model is called Course:
public class Course {
    //your class logic, constructor, getters, setters, etc.
}

This would be it's repository interface:
public interface CourseRepositoryInterface {
     void addCourse(Course course);
     void deleteCourse(Course course);
     void updateCourse(Course course);

     List<Course> getAllCourses();
}

Something like that, of course it can have more/less methods varying from your needs.
Finally you need a class that implements that interface like:
    public class CourseRepoWithMySqlDatabase implements CourseRepositoryInterface {
     void addCourse(Course course) { //TODO: Implement it }
     void deleteCourse(Course course) { //TODO: Implement it }
     void updateCourse(Course course) { //TODO: Implement it }

     List<Course> getAllCourses() { //TODO: Implement it }
    }

In this class you would implement the methods to do what they need to do with, for example, MySql database. In case you ever needed to switch from MySql to, let's say, another type of database or a no database implementation, you'd just use another class to implement the interface, and pass that where the interface parameter is required.

Pay attention: this is very important. You always need to require the interface in the place where you plan to use its methods.


text:
Q: Swift - ContainerView covering ViewController I have a ViewController and a containerView. The problem is that my containerView is covering my ViewController so I can't click the buttons inside my ViewController.

I know I can self.view.sendSubviewToBack(containerView) but that doesn't solve my problem because I actually want the containerView(bottomBar + settingsButton) to be visible on the foreground.
Is there any way I can have the containerView on top of my ViewController and still be able to click the buttons inside my ViewController?

A: You need to reverse the containment ,  the vc that have the addButton and the bottom bar should hold the other vc and by this you can control the visibility of the childVC ( the one the pop out when you click add ) by sending it back to what you need it visible above it


text:
Q: Custom SpEL function for use in ThymeLeaf ThymeLeaf newb question here: I would like to register a custom SpEL utility object to provide some custom formatting. The Spring EL documentation says that I should use StandardEvaluationContext.registerFunction() to do this, which is great and all, but I want this to be available for use in all SpEL functions in my ThymeLeaf templates. I figure that this is done in the servlet context XML, but I have no clue how to go about it and I can't find ThymeLeaf documentation that explains how to do it.

A: StandardEvaluationContext.registerFunction() is used to assign an identifier with a method and then use it to call that method from your SpEL expressions.
But Spring EL also allows you to call methods on any objects in the context. So if all you need is to make some helper object methods accessible for your SpringEL expressions to call, all you need to do is just put an instance of that helper class to the evaluation context.


text:
Q: No such file or directory while using os.rename This is not this question:Rename script with [Errno2] No such file or directory
I am trying to move the images from the folder images to train_images and test_images folders on the basis of corresponding xml file names in train and test folders.
But getting this error consistently:
Traceback (most recent call last):
 File "Move2.py", line 13, in <module>
 os.rename(src2,dest2)
 FileNotFoundError: [Errno 2] No such file or directory: '/home/mohit/darkflow/yes/images/DSCN8434.jpg' -> '/home/mohit/darkflow/yes/train_images/DSCN8434.jpg'

My script is:
import os

train=os.listdir("/home/mohit/darkflow/yes/train")
test=os.listdir("/home/mohit/darkflow/yes/test")

path2="/home/mohit/darkflow/yes/images/"
moveto3="/home/mohit/darkflow/yes/train_images/"
moveto4="/home/mohit/darkflow/yes/test_images/"

for f_name in train:
    f_name=f_name.replace(".xml",".jpg")
    src2=path2+f_name
    dest2=moveto3+f_name
    os.rename(src2,dest2)

for f_name2 in test:
    f_name2=f_name2.replace(".xml",".jpg")
    src2=path2+f_name2
    dest=moveto4+f_name2
    os.rename(src2,dest2)

*

*Similar thing happens even if use shutil.move

*I can see that particular image in the image folder for which error is generated.

*Strangely eog imagename does not open it when i am in the images directory

Thanks in Advance!

A: I found the mistake.

*

*Actually the image extension was .jpg for some images and .JPG for others.

Solution:

*

*I changed the less appeared .jpg to .JPG manually and changed .jpg to .JPG in the code as well.

The code did worked
Thank You!


text:
Q: Magento How to Add custom SM super categories I'm Using Magneto CMS, and I want to add a custom Super category like the following screenshot.
the screenshot shows a product in my site and its super category (Favorite and Quick view)

Actually I can disable any one of them, add another from the provided super categories allowed by the theme but I want to add my custom one

A: if you want to add your custom one just find the glyphicon icon of the category you are looking for and replace it by your own glyphicon . Just inspect the site and get to the source of the image and replace it.


text:
Q: How to avoid the class conflict using maven I use the maven-shade-plugin to build a project , However, I have encounter  a problem I could not handle it.there are two jars almost have the same class and the path is same,aspectjweaver.jar and aspectjrt.jar , when package the jar ,I get the warning "duplicate class have exist in ....". I tried to use the "relocation" property to relocate the class, but the question is , How can I recongnize the class in the two jars? Next is part of my Pom.xml.

                org.apache.maven.plugins
                maven-shade-plugin
                1.3.1
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>

                        <filters>
                            <filter>
                                <artifact>org.aspectj:aspectjrt</artifact>
                                <includes>
                                    <include>*</include>
                                </includes>
                            </filter>
                        </filters>
                        <relocations>
                            <relocation>
                                <pattern>org.aspectj</pattern>
                                <shadedPattern>hide.org.aspectj</shadedPattern>
                            </relocation>
                        </relocations>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>cm.data.DatBoostrap</mainClass>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>META-INF/spring.handlers</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>META-INF/spring.schemas</resource>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: you should just exclude the classes from one of the artifacts using some thing like this:
<configuration>
 <filters>
  <filter>
   <artifact>junit:junit</artifact>
   <includes>
    <include>junit/framework/**</include>
    <include>org/junit/**</include>
   </includes>
   <excludes>
    <exclude>org/junit/experimental/**</exclude>
    <exclude>org/junit/runners/**</exclude>
   </excludes>
  </filter>
  <filter>
   <artifact>*:*</artifact>
   <excludes>
    <exclude>META-INF/*.SF</exclude>
    <exclude>META-INF/*.DSA</exclude>
    <exclude>META-INF/*.RSA</exclude>
   </excludes>
  </filter>
 </filters>
</configuration>


text:
Q: sudo inside docker (on fedora) ask for password, on host it doesn't ask password I am testing something in docker, it requires sudo without entering password, I added required entries in /etc/sudoers. After that in host it doesn't ask for password. But in case of docker it still ask for password. BTW, I am running fedora 24 in VirtualBox VM on a Fedora 24 host.
Here is the details...
abc@webster $ sudo bash

root@webster $ cat /etc/sudoers
## Sudoers allows particular users to run various commands as
...
...
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

%users ALL=(ALL) ALL
%admin ALL=(ALL) NOPASSWD: ALL

%sudo   ALL=(ALL:ALL)   ALL
abc      ALL=(ALL) NOPASSWD: ALL
#abc      ALL=(ALL)       ALL

abc@webster $ id
uid=1000(abc) gid=1000(abc) groups=1000(abc),10(wheel),100(users),977(docker),1001(admin) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

abc@fc-docker $ sudo bash
[sudo] password for abc:

A: Adding this as an answer for more clarity.
Docker instance had its own /etc/sudoers. Which need to be updated to allow sudo without password. Login to docker instance as
" docker exec -it fc-docker bash ", you will be logged in as root. Then add
"abc      ALL=(ALL) NOPASSWD: ALL" to /etc/sudoers/. Logout & login back, we can do sudo without password.

A: Here's how I setup a non-root user with passworsdless access to the sudo group using the base image of ubuntu:18.04:
RUN \
    groupadd -g 999 foo && useradd -u 999 -g foo -G sudo -m -s /bin/bash foo && \
    sed -i /etc/sudoers -re 's/^%sudo.*/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^root.*/root ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^#includedir.*/## **Removed the include directive** ##"/g' && \
    echo "foo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
    echo "Customized the sudoers file for passwordless access to the foo user!" && \
    echo "foo user:";  su - foo -c id

What happens with the above code:

*

*The user and group foo is created.

*The user foo is added to the both the foo and sudo group.

*The uid and gid is set to the value of 999.

*The home directory is set to /home/foo.

*The shell is set to /bin/bash.

*The sed command does inline updates to the /etc/sudoers file to allow foo and root users passwordless access to the sudo group.

*The sed command disables the #includedir directive that would allow any files in subdirectories to override these inline updates.


text:
Q: How do i make a login helper for Rspec? Hello i have about 50 rspec tests i need to write. There's no gem that was used for the user model. It was created from scratch. How does someone make a login helper for rspec?
Please keep in mind this is for Rspec not capybara
Thank you.
Here is the sessions controller
class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:sessions][:email].downcase)
    if user && user.authenticate(params[:sessions][:password])
      if user.activated?
        log_in user
        params[:sessions][:remember_me] == '1' ? remember(user) : forget(user)
        redirect_back_or user
      else
        message  = "Account not activated. "
        message += "Check your email for the activation link."
        flash[:warning] = message
        redirect_to root_url
      end
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

Here is the sessions helper
module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Logs out the current user.
  def log_out
    session.delete(:user_id)
    @current_user = nil
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns true if the given user is the current user.
  def current_user?(user)
    user == current_user
  end

  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end

  # Redirects to stored location (or to the default).
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  # Stores the URL trying to be accessed.
  def store_location
    session[:forwarding_url] = request.url if request.get?
  end
end

Here is a user controller spec that i have. Problem is i don't have a login(user) helper method. Does anyone know how to write one? I have looked this up and couldn't find much information about it.
require "rails_helper"
require "test_helper"
RSpec.describe UsersController, type: :controller do
  let!(:admin) { create(:user, password: "Password123", admin: true) }
  let!(:user) { create(:user, password: "Password456", admin: false) }

  let!(:update_params) do
    { id: user.id, user_id: user.id, user: user }
  end

  let!(:users) do
    [admin, user] + 3.times.map { create(:user) }
  end

  let!(:user_params) { user_params = { username: "username#{rand(1000)}",
                                       email: "user#{rand(1000)}@factory.com",
                                       password: "Password123",
                                       password_confirmation: "Password123",
                                       admin: false,
                                       description: "Nihil eligendi ab debitis iure.",
                                      } }

  let!(:category) { create(:category, name: "Shirt") }
  let!(:category1) { create(:category, name: "Short") }

  describe "GET #index" do
    it "admin user renders template and shows users" do
      get :index, {}, { user_id: admin.id }
      expect(response).to render_template(:index)
      expect(response).to have_http_status(:success)
      expect(assigns(:users).map(&:id)).to eq users.map(&:id)
    end

    it "user renders template and shows users" do
      get :index, {}, { user_id: user.id }
      expect(response).to redirect_to(root_path)
    end

    it "redirects visitor" do
      get :index
      expect(response).to redirect_to(root_path)
    end
  end

  describe "GET #show" do
    it "user renders template and shows user" do
      get :show, id: user.id
      expect(response).to render_template(:show)
      expect(response).to have_http_status(:success)
      expect(assigns(:user)).to eq(user)
    end
  end

  describe "GET #new" do
    it "renders template" do
      get :new
      expect(response).to render_template(:new)
      expect(response).to have_http_status(:success)
    end
  end

  describe "POST #create" do
    it "user created" do
      post :create, user: user_params
      expect(assigns(:user)).to be_persisted
    end
  end

  describe "GET #edit" do
    it "user edit" do
      get :edit, {id: user.id }, { user_id: user.id }
      expect(response).to render_template(:edit)
      expect(response).to have_http_status(:success)
      expect(assigns(:user)).to eq(user)
    end
  end

  describe "POST #update" do
    it "user updated" do
      patch :update, update_params
      expect(response).to redirect_to(assigns(:user))
      expect(assigns(:user)).to eq(user)
    end
  end

  # describe "DELETE #destroy" do
  #   it "user destroy" do
  #     delete :destroy, {id: user.id }, { user_id: user.id }, user: user_params
  #     expect(response).to redirect_to(users_path)
  #   end
  # end
end

When i run the above test i receive this error
  2) UsersController POST #update user updated
     Failure/Error: expect(response).to redirect_to(assigns(:user))
       Expected response to be a redirect to <http://test.host/users/1046959425> but was a redirect to <http://test.host/login>.
       Expected "http://test.host/users/1046959425" to be === "http://test.host/login".

It is because my user isn't logged in. It would be great to have a login helper method that will login the user in a before do end.

A: I have implemented some user login related methods for my tests in my test_helper.rb, it looks like this:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Logs in a test user.
  def log_in_as(user, options = {})
    password    = options[:password]    || 'password'
    remember_me = options[:remember_me] || '1'
    if integration_test?
      post login_path, session: { email:       user.email,
                                  password:    password,
                                  remember_me: remember_me }
    else
      session[:user_id] = user.id
    end
  end

  private

  # Returns true inside an integration test.
  def integration_test?
    defined?(post_via_redirect)
  end
end

It has log_in_as method that takes an user and you can use that in your test. e.g.:
  describe "POST #update" do
    it "user updated" do
      log_in_as user # now you have log_in_as method implemented
      patch :update, update_params
      expect(response).to redirect_to(assigns(:user))
      expect(assigns(:user)).to eq(user)
    end
  end

You may need to make some modifications of the above code in order to make it work in your application but it should give you a clear idea on how to do that. I hope this helps.


text:
Q: Compare nested objects and add missing elements Have 2 or more nested objects with following structure:
Order is not guaranteed!
object 1:
{
"outer": [
            {
                "inner": [
                    {
                        "Service1": 34,
                        "title": [
                            {
                                "level1": 57
                            },
                            {
                                "level2": 75
                            }
                        ]
                    }
                ]
            }
        ]
    }

object 2:
{
"outer": [
            {
                "inner": [
                    {
                        "Service2": 23,
                        "title": [
                            {
                                "level1": 89
                            }
                        ]
                    }
                ]
            },
            {
                "inner": [
                    {
                        "title": [
                            {
                                "level1": 45
                            }
                        ],
                        "Service1": 68
                    }
                ]
            }
        ]
    }

Wanted to find a generic way to compare both objects and add missing elements from object 2 to object 1 and from object 1 to object 2.
Missing elements can be at any level.
inner.service1 can be found in both objects but elements at title level can be different. I would like to add them back to other object but with empty or value with 0 for that key
  Object 2:

{
"outer": [
            {
                "inner": [
                    {
                        "Service2": 23,
                        "title": [
                            {
                                "level1": 89
                            }
                        ]
                    }
                ]
            },
            {
                "inner": [
                    {
                        "title": [
                            {
                                "level1": 45
                            },
                             {
                                "level2":
                            }
                        ],
                        "Service1": 68
                    }
                ]
            }
        ]

Object 1:

{
"outer": [
             {
                "inner": [
                    {
                        "Service2": ,
                        "title": [
                            {
                                "level1":
                            }
                        ]
                    }
                ]
            },
            {
                "inner": [
                    {
                        "Service1": 34,
                        "title": [
                            {
                                "level1": 57
                            },
                            {
                                "level2": 75
                            }
                        ]
                    }
                ]
            }
        ]
    }

Comparing and finding difference for simple json is easy but for nested I cannot think of a way to compare and add them back to each other.
Have went through other solutions but it wasn't working for me!
Any suggestion would be greatly appreciated!


text:
Q: Play Framework + Spring: Injecting URL from application.conf I'm using Spring 4.1.x with Play 2.3.x and I'm trying to inject a property value from Play's application.conf file.
I can access properties thanks to this:
@PropertySource("classpath:application.conf")
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

I have a URL value in my application.conf:
photo.url="https://our-photo-storage.net"
Note the quotes. If I remove them, Play will throw com.typesafe.config.ConfigException$Parse.
I am injecting property value like this:
@Autowired
public PhotoToUrlMapper(@Value("${photo.url}") url) {
    // trim quotes :-/
}

Spring will inject the value with the quotes. I can obviously just trim them, but I'd like to be able to inject the url without the quotes.
Notes:

*

*I could probably create a separate .properties file, but I'd like to avoid that (more configuration)

*I could probably use horrible static Play's Play.current.configuration.getString("photo.url"), but I actually like to write unit tests ...

Is there a reasonable workaround for this?

A: I guess the only way to so is to use the properties file, i don't think that's too much configuration to do, since it provides you with a better readability for your code. quoted a sample of the code you need to include your properties file
<bean id="placeholderProperties"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/url.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="order" value="1" />
    </bean>


text:
Q: Multiply VBA InputBox value (decimal) by cell value (decimal) derived from a Json url Web Query (Updated) I'm new to VBA and have been trying various things for hours but I can't seem to figure out how to simply multiply a decimal user input of 1.1 by the cell value of C1 (71388.92). Here is what I've tried last:
Private Sub CommandButton1_Click()
Dim myValue As Variant

myValue = InputBox("Prompt", "Title")
Range("C5").Value = myValue * Range("C1")

End Sub

I get a runtime error '13'- Type mismatch perhaps because cell C1's value is derived from a json web query. I've tried Variant, Double, Single, Long and Data Types Decimal, Number and Currency.
Download link: https://www.dropbox.com/sh/tg5f2a71k9jy6xq/AACrhI9_6VG8vJkDr0QVCbSUa?dl=0

A: I think this is your solution:
myValue = InputBox("Prompt", "Title")
Range("C5").Select
ActiveCell.FormulaR1C1 = myValue * Range("C1")

A: Declare as double instead of variant
Dim myValue As Double
myValue = InputBox("Prompt", "Title")
Range("C5").Value = myValue * Range("C1")

A: Found Solution:
The error with the InputBox accepting a decimal entry lies with the "Thousands Separator" settings and whether you enter a comma or point into the InputBox. I had my "Thousands Separator" set to use a point . because I'm working with .csv file exports so it was useful. Either will work but you have to change your Windows decimal symbol settings by going to:
Control Panel > Language > Change date, time, or number formats > Additional Settings > Decimal symbol.
As for the multiplication part: The original InputBox returns a string. Using Val() converts the number string to a number and is the correct VBA script:
Private Sub CommandButton1_Click()
Dim myValue As Variant

myValue = Val(InputBox("Prompt", "Title"))
Range("C5").Value = myValue * Range("C3")

End Sub


text:
Q: Invoking an HTML page from JAVA code I am trying to invoke an HTML File stored on my desktop from inside a JAVA code as below.
I found this code snippet here
       try
        {
            Runtime r= Runtime.getRuntime();
            String url = "C:\\Users\\Rana\\Desktop\\test.html";
            String browser ="C:/Program Files/Mozilla Firefox/firefox.exe ";
            Process p = r.exec(browser);
            p.waitFor();
        }

        catch(Exception e)
        {
            e.printStackTrace();
        }

I tried using backslash and forward slashes, both. But it is throwing this error in both case....
java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
    at java.lang.Runtime.exec(Runtime.java:617)
    at java.lang.Runtime.exec(Runtime.java:450)
    at java.lang.Runtime.exec(Runtime.java:347)
    at package1.Test.main(Test.java:22)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:376)
    at java.lang.ProcessImpl.start(ProcessImpl.java:136)

The path "browser" is present.
Please suggest where I am doing wrong.

A: The issue is with the space in your path to the browser.  The system thinks you are trying to run a program called "C:/Program" with "Files/Mozilla" and "Firefox/firefox.exe" as the arguments.  Try adding quotes around the exe name:
String browser ="\"C:/Program Files/Mozilla Firefox/firefox.exe\" ";

To incorporate SnakeDoc's advice, you could use the environment variable to take care of the portion of the path down to "Program Files", but you will still need the quotes to take care of any other spaces in the path:
String browser = "\"" + System.getenv("ProgramFiles(X86)") + "Mozilla Firefox/firefox.exe\"";

A: Try using the system properties:
System.getenv("ProgramFiles");

or
System.getenv("ProgramFiles(X86)");

A: Better advice,
use AutoHotKey for such tasks.You should give it a try.I promise you would definitely find it useful.

A: if you are using the 32bit version browser should be String browser ="C:/Program Files(x86)/Mozilla Firefox/firefox.exe ";
hope this helps

A: Try
String browser ="\"C:/Program Files/Mozilla Firefox/firefox.exe\"";

There is problem with space in Program files that get treated as separator if not inside Quotes. It is briliant idea by Microsoft...

A: The best way would be to do this with java.awt.Desktop
File htmlFile = new File("C:" + File.separator + "Users" + File.separator + "theuser" + File.separator + "Desktop" + File.separator + "Test.html");
if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().open(htmlFile);
}


text:
Q: How does this circuit work? I am rusty on my circuit knowledge and looking into wiring my own regulated box mod circuit using an LM2596. I found a circuit diagram to use, and while I could just wire it up and hope it works, I'd really like to understand why it works!

*

*S1 represents a switch, right?

*What purpose does the MOSFET serve?

*I think my coil is 2.5Ohms, not 0.5 like in the circuit. Would this change anything like maybe the strength of the 15k resistor?

Circuit diagram I want to use:

A: This appears to be a standard MOSFET low-side switch circuit. An N-channel MOSFET conducts from drain to source when the gate voltage is higher than the source voltage by a certain amount. When the voltages are equal, current cannot flow from drain to source (it is an open circuit).
The 15k resistor weakly pulls the gate voltage down to source voltage, thus insuring that the transistor will be off, UNLESS the momentary switch, S1, is on. S1 is a pushbutton type of switch. When you press it, it is on, and when you let go, it turns off by spring action. In this circuit, pressing S1 will cause the MOSFET to turn on because it  will elevate the gate voltage above the source voltage.
When the MOSFET is off, there is no conductive path for the current through whatever that thing is that says ATTY. When you push the button (S1) the gate of the MOSFET will be driven high  compared to the source, and the MOSFET will conduct current from drain to source, thus completing the circuit and energizing ATTY.
The basic idea of the circuit is sound. Just need to make sure the MOSFET can handle the relevant voltages and currents.

A: Lm2596 is a step down converter that can just manage till 3 amps of current I'm not so sure that this is going to work properly for with higher voltage than 3.5 or something cause if we imagine I have a resistor of 0.5 ohms and I applied 4.5 volt the Amps that it need to work properly are 9 amps and if from the convertor you just get 3 amp max it is going to get really warm till you cannot make it anymore


text:
Q: Returning a Random nextBoolean in a user defined method accessed by switch case statement in java I am trying to get my program to work the way I want. When I go in the switch statement I want to have the user type in a value and go to that corresponding user createdmethod. When in one of the user created method I have a random boolean value returned to the main method. I want my program to only println "key is here" when the value is true and ONLY for the one method I accessed, not all of the methods. Because when I run the program it will go through all the methods in the if statements and not just the one i want. Can someone please help me? I want to keep the user created methods returning nextBoolean and have the println "key is here" to be in the main method still. Is there a way to do this? Thanks in advance. I'm a total beginner at this :)
Here is the code:
import java.util.*;
import java.util.Random;

public class JavaGameSearchHouse
{
    public static Scanner console = new Scanner(System.in);
    public static boolean keyValue;
    public static Random keyVal = new Random();
    public static void main(String[] args)
    {

        String roomValue;
        int counter;
        int keepGoing = 0;

        do{
            System.out.println("Lets search this house for the key");
            roomValue = console.next();

            switch(roomValue.toLowerCase())
            {

            case "kitchen": kitchenMethod();
            break;
            case "bedroom": bedroomMethod();
            break;
            case "familyRoom": familyRoomMethod();
            break;
            case "livingRoom": livingRoomMethod();
            break;
            case "bathroom": bathroomMethod();
            break;
            case "basement": basementMethod();
            break;
            default: System.exit(0);
            }

            if(kitchenMethod())
                System.out.println("Key is here1");

            if(bedroomMethod())
                System.out.println("Key is here2");

            if(familyRoomMethod())
                System.out.println("Key is here3");

            if(livingRoomMethod())
                System.out.println("Key is here4");

            if(bathroomMethod())
                System.out.println("Key is here5");

            if(basementMethod())
                System.out.println("Key is here6");

            System.out.println("press 1 to search again");
            keepGoing = console.nextInt();
        }while(keepGoing == 1);
    }

    public static boolean kitchenMethod()
    {
        return keyVal.nextBoolean();
    }

    public static boolean bedroomMethod()
    {
        return keyVal.nextBoolean();
    }

    public static boolean familyRoomMethod()
    {
        return keyVal.nextBoolean();
    }

    public static boolean livingRoomMethod()
    {
        return keyVal.nextBoolean();
    }

    public static boolean bathroomMethod()
    {
        return keyVal.nextBoolean();
    }

    public static boolean basementMethod()
    {
        return keyVal.nextBoolean();
    }

}

A: You could just run your methods in the switch and remove the if statements at the end :
           case "kitchen": if(kitchenMethod())
                System.out.println("Key is here1");
            break;
            case "bedroom": if(bedroomMethod())
                System.out.println("Key is here2");
            break;
            case "familyRoom": if(familyRoomMethod())
                System.out.println("Key is here3");
            break;
            case "livingRoom": if(livingRoomMethod())
                System.out.println("Key is here4");
            break;
            case "bathroom": if(bathroomMethod())
                System.out.println("Key is here");
            break;
            case "basement": if(basementMethod())
                System.out.println("Key is here6");
            break;
            default: System.exit(0);
            }

A: The method that is accessed should print the value, not the if statement.
   public static boolean kitchenMethod()
    {
        Boolean key = keyVal.nextBoolean();
        if (key)
          System.out.println("Key is here1");
        return key;
    }

do it for other methods and remove if statements.

A: Remove the switch. Your approach calls the room methods every time, even if not required.
Instead, do this:
if(roomValue.equalsIgnoreCase("kitchen") && kitchenMethod()) {
    System.out.println("Key is here1");
}

Etc.
This approach will only call the room method if required.

Alternatively, you could embed the if statements inside the switch, but it would make for some ugly code.


text:
Q: How does onUpdated work I'm currently trying to check wether there is a new update of my app before the whole app is loading, this in order to speed the loading up a bit.
So I was trying to figure out how and when the onUpdated function is called but I can't seem to find anything in the ST sources.
Ext.application({

  ...

  onUpdated: function() {
    var title, message;
    title   = 'Application Update';
    message = 'A new version of this site is available. Reload now?';
    Ext.Msg.confirm(title, message, function(buttonId) {
      if (buttonId === 'yes') {
        window.location.reload();
      }
    });
  }
});

Basically two questions :
When is the onUpdated function called in the framework ?
How can I check wether there is an update or not before the whole app is loaded and rendered ?

A: Check out the detailed explanation by Jacky Nguyen on Sencha Touch 2.x Forum post!


text:
Q: negation of std::integral_constant Sorry for asking so simple question, but I cannot find the answer easily. Google says nothing interesting about "C++ negation integral_constant" and similar queries.
Is there in C++11 any trait that make std::true_type from std::false_type and vice versa? In other words, I'd like some more readeble version of
std::is_same<my_static_bool, std::false_type>

I know of course I can write it myself, but I'd like to use the existing one if there is such.

A: There is not, because it's essentially a one-liner and the <type_traits> should be as small as possible.
template <typename T> using static_not = std::integral_constant<bool, !T::value>;

Usage:
static_not<my_static_bool>

This is the correct way because the standard always says "false_type or derived from such", so you can't depend on being equal to std::false_type. I usually relax that to "having a constexpr boolean ::value property" because I don't use tag dispatching.

A: Yet another way to do it:
template <typename T>
using static_not = typename std::conditional<
    T::value,
    std::false_type,
    std::true_type
>::type;

A: The following code uses template metafunction forwarding (i.e. it inherits from std::integral_constant with a negated boolean value, this is of course inspired by the Boost.MPL that heavily uses this pattern)
#include <type_traits>

template<typename T>
struct logical_not
:
    std::integral_constant<bool, !T::value>
{};

int main()
{
   typedef logical_not<std::false_type>::type T;
   typedef logical_not<std::true_type>::type F;

   static_assert((std::is_same<T, std::true_type>::value), "");
   static_assert((std::is_same<F, std::false_type>::value), "");
}

Output on LiveWorkSpace

A: The types true_type and false_type have a nested typedef that refers to themselves, so you can write:
std::is_same<my_static_bool::type,std::false_type>::value

Depending on the context it might be simpler to just do !my_static_bool{}, which is a constexpr of value true if your type is indeed std::false_type.


text:
Q: Printing out all timezones in C I'm looking to print out the current time in a specified timezone in c. I understand that the time.h library has a few ways of displaying time but I can't figure out how to change those times depending on an inputted timezone. If anyone could point me in the right direction, I'd appreciate it.

A: Use the tzset() function. Note that this sets the time zone globally for your whole process, since it reads from the TZ environment variable (which is also process-global).
To change the TZ environment variable, you can use putenv() which takes a formatted environment variable in the form TZ=Europe/Paris for example.


text:
Q: How to Read and Parse X12 Data Elements Using PowerBuilder? Flat File content:
ST*850*12500001|
BEG*00*NE*71249364**20130103|
CUR*SE*SGD|
REF*BT*SGL169816-7191416|
P01*0000000001*4*EA*0*CP*UP*731304265511*VP*SURT1000XLIQ|
P01*0000000002*10*EA*0*CP*UP*731304265511*VP*SURT1000XLIQ|
P01*0000000003*100*EA*0*CP*UP*731304265511*VP*SURT1000XLIQ|

Question:
Anybody who can share an idea on how to parse dynamically each element. The length of each data differs from time to time like for example : 12500001, 731304265511 and SURT1000XLIQ. The problem is how can i get the data between the asterisk (*) and pipeline (|). Thanks to help....

A: Your flat file looks like an EDI file, though not an EDIFACT.
There are some converters (either open source or commercial) from EDI to XML, maybe that you can try with such a tool to be able to read the resulting xml file into a DataWindow or a datastore?
As I do not know the actual file format, I cannot be more precise.
Example of EDI -> XML converters :

*

*BOTS (the code is stored on Google Code

*libEDI

*edi-to-xml

*EDIdEv (commercial)

*Altova EDI to XML (commercial)

EDIT: I just landed on an ancient post on the PowerBuilder Developer Journal that addresses the same subject: "Converting X12 EDI to XML", it gives additional ideas.

A: That's an X12 file, an 850 Purchase Order. As eppye suggests in the comments, you will need to find out exactly what standard the file you're getting follows. To get you started there's a version of the 850 here. "Draft MEMA 4010 850" will help you understand the format. "GCommerce 4010 850V1.4.doc" is the Data Dictionary that tells you what's in each element. Please understand, though, that unless you're selling auto parts, that's probably not the exact specification of the file you're working with. The people sending you the file should provide this to you.
I would create a user object for each segment and loop, and one to represent the purchase order itself. The purchase order UO needs variables that are the data type of the segments and loops. Don't include the segments that are inside the loops, put those in the UO for the loop. The UO for a segment will have variables that are standard datatypes like string, integer, date, etc. for the Data Elements in the segment. Refer to the Data Dictionary for the datatypes.
Note that if a segment repeats, the variable that holds the segment is an array. The variables for the loops will be arrays.
Your objects that handle segments will have a method, e.g. of_importLine that splits up the line at the asterisk and stores the values.
Your objects that handle loops will have a method, e.g. of_readLoop that reads lines (segments) until it reads the last segment of the loop. For each segment, it will create the UO for that type of segment, assign it to the instance variable, or the next array slot if the segment can repeat, and call the new object's  of_importLine.
Your object that handles the purchase order is like one for a loop, except that when it sees the first segment of a loop, it creates the UO for that kind of loop, assigns it to the next array slot for the loop, and calls the new object's of_readLoop. Note that while your purchase order object is reading inside a loop it will create a new object to read and store each repeat of the loop.
Your objects that read loops should log an error and stop if a required segment is missing or a segment that doesn't belong in the loop is found. The error should include the line number and contents. I can't give you a detailed description of how to validate the purchase order itself because many of the segments are optional in the specification, but they probably aren't optional in your application. For each segment and loop the object has a variable for, it needs the sequence where the item appears and minimum and maximum occurrences. Then the PO object can check the segments and loops as it goes along.
This will get the data from the document into objects that represent the parts of the document so you can work with the data.

A: If you were using plain old PowerBuilder, the basics would be to do a bunch of Pos() and Mid()'s; nothing automagic. However, in your tags you mention PFC; you can always bring in the String Service's of_ParseToArray() function after you've read the file in, something like (the following is untested and is up to the reader to find the bugs):
long ll_Line, ll_LineCount, ll_Element, ll_ElementCount
string ls_Lines[], ls_Elements[]
n_cst_String lnv_String

ll_LineCount = lnv_String.of_ParseToArray (ls_FileContents, "|", ls_Lines)
FOR ll_Line = 1 TO ll_LineCount
   ll_ElementCount = lnv_String.of_ParseToArray (ls_Lines[ll_Line], "*", ls_Elements)
   // process the line with the elements separated out...
NEXT

Good luck,
Terry

A: Below is the method that I've derived.
ls_tranidcode = of_trimdata(is_Message, 4, '*')
ids_edihdr.SetItem(ll_hdrins,'TRANSETIDCODE',ls_tranidcode)

Function:
of_trimdata()

Return Type : String
Argument Type :
String arg_msg
Integer pos1
String  s_dlm

Long ll_pos2
String ls_ret

arg_msg = mid(arg_msg, pos1)
ll_pos2 = POS(arg_msg,s_dlm)
ls_ret = Mid(arg_msg, 1, ll_pos2 - 1)
arg_msg = Mid(arg_msg, ll_pos2 + 1)

RETURN ls_ret


text:
Q: C++ Is it possible to 'delete' element from an array? I want to make new array which has size - 1 than my 'main array'.
And there is problem I cant declare string newArray[oldArray.length()-1].
Is it this possible in C++ ?

A: No, it is not possible to delete an element from a static array.  You can, however, shift the subsequent elements down one slot and then ignore the last slot.  You can use a separate variable to keep track of how many usable elements are in the array.
Alternatively, use std::vector to create a dynamic array.


text:
Q: Update a list item in moss2007 i have a list with Column name Reported By.It is a choice field.When adding a new item to the list the current user name also should be added to the Reported By column's field.It should be the first choice of column 'Reported By'. How can i do that? Thanks in Advance

A: If I understand correctly, you want the column "Reported By" to show the user who created the list item?
Is so, why not just use the default "Created By" field? You can always rename it if you want to "Reported By"
If you want some sort of concatenation, you can use calculated fields.
Stick with out of the box functionality before goign custom Event Receivers.

A: You can create an event receiver for your list and handle ItemAdding event - there you'll be able to modify field values.


text:
Q: I am facing ClassNotFoundException in Android I'm trying to create a Chat app that uses Firebase. But suddenly I'm facing this error.
02-13 10:23:02.533446   733   733 E AndroidRuntime: FATAL EXCEPTION: main
02-13 10:23:02.533446   733   733 E AndroidRuntime: Process: com.mycompany.myapp3, PID: 733
02-13 10:23:02.533446   733   733 E AndroidRuntime: java.lang.RuntimeException: Unable to instantiate application com.mycompany.myapp3.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.mycompany.myapp3.MyApplication" on path: DexPathList[[zip file "/data/app/com.mycompany.myapp3-1/base.apk"],nativeLibraryDirectories=[/data/app/com.mycompany.myapp3-1/lib/arm, /system/lib, /vendor/lib, /system/vendor/lib]]
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.LoadedApk.makeApplication(LoadedApk.java:807)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5477)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.ActivityThread.-wrap2(ActivityThread.java)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1595)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:110)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.os.Looper.loop(Looper.java:203)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6251)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
02-13 10:23:02.533446   733   733 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.mycompany.myapp3.MyApplication" on path: DexPathList[[zip file "/data/app/com.mycompany.myapp3-1/base.apk"],nativeLibraryDirectories=[/data/app/com.mycompany.myapp3-1/lib/arm, /system/lib, /vendor/lib, /system/vendor/lib]]
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.Instrumentation.newApplication(Instrumentation.java:992)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     at android.app.LoadedApk.makeApplication(LoadedApk.java:801)
02-13 10:23:02.533446   733   733 E AndroidRuntime:     ... 9 more

build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.mycompany.myapp3"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildTypes {
        debugg {
            debuggable true
        }
    }
}

dependencies {
    implementation 'com.google.android.gms:play-services-analytics:15+'
    implementation 'com.google.firebase:firebase-storage:15+'
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.google.firebase:firebase-auth:15+'
    implementation 'com.google.firebase:firebase-database:15+'
}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.myapp3" >

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

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".StartActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity" />
        <activity
            android:name=".ResetPasswordActivity" />
        <activity
            android:name=".LoginActivity" />
        <activity
            android:name=".MainActivity" />
        <activity
            android:name="ChatActivity" />
        <activity
            android:name=".UserProfileActivity" />
        <!--<activity
            android:name=".ImageActivity" />-->
        <activity
            android:name=".DebugActivity"
            android:screenOrientation="portrait"/>
        <meta-data
            android:name="android.max_aspect"
            android:value="4.0"/>

        <uses-library android:name="org.apache.http.legacy" android:required="false" />
    </application>

</manifest>

I don't know how Do I fix it. I will apprentice if you can help.
NOTE: Please, I'm a beginner in this feild. I really need help. If I missed to share any information, please let me know, I'll add the information.
Thanks.

A: It looks like You have not registered your Application class in AndroidManifest file.
Register like this
<application
android:name=".MyApplication">

A: For android studio 4+, you need to enable Java 8 like this in your build.gradle (app):
android {
    defaultConfig {
            ...
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}


text:
Q: What opengl library should i use with an nvidia graphics card I'm trying to compile an SDL2 and OpenGL game on linux, but the error that shows up is always

/usr/bin/ld: cannot find -lGL
  collect2: error: ld returned 1 exit status

Which led me to find out which opengl version I have. But it shows this:

OpenGL version string: 4.5.0 NVIDIA 375.39

But I don't know which parameter or library to use with nvidia opengl.
Does anyone know?

A: Fixed it easily by just swapping out -lGL with -l:libGL.so.1.
But find out what library you have using

ls /usr/lib/

and then look for libGL.so.version_number_here
Works for me until I need to add it to my linker.


text:
Q: Nuget no longer able to find package versions My build server suddenly started failing all builds when running nuget restore, with errors for all packages.  These package versions exist, and have been working fine until the last week or so.
NuGet Version: 5.6.0.6591
MSBuild auto-detection: using msbuild version '16.6.0.22303' from 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
MSBuild P2P timeout [ms]: 120000
<long MSBuild output>

Restoring NuGet package NLog.4.6.2.
Restoring NuGet package FluentAssertions.3.0.107.
Restoring NuGet package Mindscape.Raygun4Net.5.0.0.
WARNING: Unable to find version '3.0.107' of package 'FluentAssertions'.
WARNING: Unable to find version '4.6.2' of package 'NLog'.
WARNING: Unable to find version '5.0.0' of package 'Mindscape.Raygun4Net'.
WARNING: Unable to find version '4.6.2' of package 'NLog'.
WARNING: Unable to find version '3.0.107' of package 'FluentAssertions'.
WARNING: Unable to find version '5.0.0' of package 'Mindscape.Raygun4Net'.

NuGet Config files used:
    C:\TeamCity\buildAgent\work\5179f1a1ebd4ddaa\src\.nuget\NuGet.Config
    C:\Users\<my name>\AppData\Roaming\NuGet\NuGet.Config

I found a Nuget blog post about removing support for TLS 1.0 and 1.1, so I updated the server to only use TLS 1.2;  this did not fix the issue.  I am not sure how else to diagnose why nuget is unable to find the package versions.

A: Had similar issue, branch code did not change at all, before build was ok(3 weeks ago), triggered it once again yesterday and failed. In my case updating NuGet to latest version helped, before had old version 3.3.0.212, now have 5.6.0.6591 and it works, maybe try to install other nuget version(older for example and check). No other changes have been made, except nuget.exe update to latest.
Old nuget version errors


text:
Q: Merge not working for insert a record when it's doesn't exist Can I use Merge to insert a record when it's doesn't exist like below,
MERGE INTO [dbo].[Test] AS [Target]
USING (SELECT DISTINCT [Name] FROM [dbo].[Test]) AS [Source]
    ON [Target].[Name] = [Source].[Name]
WHEN NOT MATCHED THEN
INSERT ([Id], [Name])
VALUES (NEWID(), 'Hello');

If the record with value Hello does not exists in table Test, insert it otherwise don't do anything. With above code record is not inserted even I don't have this record in table. And there are no errors.
I know how to accomplish this using insert ... where not exists (...) but am specifically wanting to know how to do it using a merge statement.

A: The reason your merge statement wasn't working is that you were merging the same table, dbo.Test, back onto itself, so of course there is no missing record.
You can insert a single missing record as follows, where you create a source query to contain the record(s) you wish to insert:
declare @Test table (id uniqueidentifier, [Name] nvarchar(64))

select * from @Test

-- Returns
-- id                                   |   Name
-- ----------------------------------------------

MERGE INTO @Test AS [Target]
USING (select 'Hello' [Name]) AS [Source]
ON [Target].[Name] = [Source].[Name]
WHEN NOT MATCHED THEN
INSERT ([Id], [Name])
VALUES (NEWID(), [Name]);

select * from @Test

-- Returns
-- id                                   |   Name
-- ----------------------------------------------
-- C1C87CD5-F745-436D-BD8D-55B2AF431BED |   Hello

A: I agree with the answer from Dale K. Its correct.
If I suppose you might have a source_table from where the data needs to get inserted and not to get inserted if the record already exists then you can do the following.
Instead of the MERGE you can
insert
  into dbo.Test
       (id
        ,name
        )
  select top 1
         newID()
        ,'Hello'
   from dbo.Test a
  where not exists(select 1
                     from dbo.Test b
                    where b.name='Hello')


text:
Q: removing all but one node in perl XML::Twig I've got an xml file with a number of level3 elements. I want to remove all but one such elements. My xml file:
<?xml version="1.0" encoding="UTF-8"?>
<level1 id="level1_id">
    <level2 id="level2_id">
        <level3 id="level3_id1">
            <attributes>
                <attribute>1</attribute>
                <attribute>2</attribute>
            </attributes>
        </level3>
        <level3 id="level3_id2">
            <attributes>
                <attribute>1</attribute>
                <attribute>2</attribute>
            </attributes>
        </level3>
        <level3 id="level3_id3">
            <attributes>
                <attribute>1</attribute>
                <attribute>2</attribute>
            </attributes>
        </level3>
    </level2>
</level1>

My perl script:
my $filename = 'test3.xml';
my $outfile = $filename."_after";
open my $output, '>', $outfile or die "Couldn't open output file\n";
my $twig = new XML::Twig (twig_handlers => { 'level2' => \&edit });
$twig->parsefile($filename);
#$twig->flush;
$twig->print($output);

sub edit {
    my ($twig, $element) = @_;
    my @elements= $element->children('level3');
    print $#elements."\n";
    my @elements= @elements[1..$#elements];
    print $#elements."\n";
    my $count = 0;
    foreach (@elements){
        $count++;
        $_->delete;
    }
    print $count;
    $twig->purge;

}

This however just leaves the level1 element:
<?xml version="1.0" encoding="UTF-8"?>
<level1 id="level1_id"></level1>

On the other hand, my script works just fine when the top level is level2. Example xml file and the result after processing:
<?xml version="1.0" encoding="UTF-8"?>

<level2 id="level2_id">
    <level3 id="level3_id1">
        <attributes>
            <attribute>1</attribute>
            <attribute>2</attribute>
        </attributes>
    </level3>
    <level3 id="level3_id2">
        <attributes>
            <attribute>1</attribute>
            <attribute>2</attribute>
        </attributes>
    </level3>
    <level3 id="level3_id3">
        <attributes>
            <attribute>1</attribute>
            <attribute>2</attribute>
        </attributes>
    </level3>
</level2>

Result:
<?xml version="1.0" encoding="UTF-8"?>
<level2 id="level2_id">
    <level3 id="level3_id1">
        <attributes>
            <attribute>1</attribute>
            <attribute>2</attribute>
        </attributes>
    </level3>
</level2>

This is exactly what I want, i.e. just one level3 element left. What am I doing wrong? Is it to do with how I define twig handlers?
I don't want to hard code the xml structure, e.g. my $twig = new XML::Twig (twig_handlers => { 'level1/level2' => \&edit });
I don't know how deep level2 will be in an actual xml file and the actual files might not be identical in structure, so this part should be dynamic

A: There is no need for the line $twig->purge or anything like it and I don't understand why you have written it
It will discard anything that has been parsed but not printed to the output, which is the whole of the level2 element that you have just edited
I also recommend that you write
my $twig = XML::Twig->new(
    twig_handlers => { level2 => \&edit },
    pretty_print  => 'indented',
);

as the indirect object syntax that you have used is ambiguous and prone to errors. The pretty_print option will also make the output XML more readable.

A: I would suggest that unless you're specifically wanting to do incremental parsing on a large file, twig_handers are needlessly complicated. It's a powerful tool if you want to treat XML as a stream and modify/discard parts of that, but actually usually just loading the whole XML, and working with it is simpler and clearer.
What you want to do appears to be to delete all 'level3' elements after the first.
So:
#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new->parsefile('your_xml_file.xml');
my $count;

foreach my $level3 ( $twig->get_xpath('.//level3') ) {
   #delete after the first one.
   $level3->delete if $count++;
}

#set formatting
$twig -> set_pretty_print('indented_a');
#print to stdout
$twig->print;


text:
Q: In an Azure Mobile App Services client, how do I set the userId so loginAsync works? I'm implementing custom authentication in a Xamarin.Forms app that uses a .NET backend in Azure, some of the controllers are marked with [Authorize].  I've followed instructions from a multitude of blogs and articles, but it's still unclear how to make TableController calls that are unauthorized trigger a login screen, or how to access the same authentication subsystem loginAsync does to set the userId or token information so that multiple instances of MobileServiceClient retains the latest userId and MobileServiceAuthenticationToken values.  How do I correctly trigger a login page and update the userId / token in the same authentication subsystem MobileServiceClient accesses with the other OOTB providers?

A: When your mobile app tries to access a backend that is marked with [Authorize], but an authorization header is not provided (technically, an X-ZUMO-AUTH header with a valid JWT), the service returns 401 Unauthenticated. There are a number of ways to trap this, but your operation will fail (and in a Xamarin.Forms application, that will cause a MobileServiceInvalidOperationException).  You need to handle this case, call loginAsync() and then re-try the operation.
You should not have multiple MobileServiceClients - you should have one at a global scope (use DI to inject it or just make it a static in the App context).  The MobileServiceUser will be used by all tables that are generated.


text: Q: How to get my app code registered in the App Store When I opened the project file to update the app that I released a month ago, some of the files were deleted and the codes were old. Can I see the code of the app when the app was released?I'm not sure if there's a conflict with the GitHub, but it's useless to check out because the commit wasn't done properly.


text:
Q: Ran 'git checkout HEAD .' in the wrong directory Oops, I accidentally ran 'get checkout HEAD .' in the wrong directory.
It produced the output 'Updated 2 paths from 2096756f' but I have no idea what my local changes were.
I assume that I can't find out, but I am wondering how I can protect myself in the future as this command is how I habitually discard local changes. Is there some alias I can create that for this that would protect me from such a mistake in the future?

A:
I accidentally ran 'get checkout HEAD .' in the wrong directory.

This is bad.

It produced the output 'Updated 2 paths from 2096756f' but I have no idea what my local changes were.

And unless you have local backups (zfs snapshots, macOS Time Machine, etc.), they're just gone.  Git can't help you get them back: you told Git to discard them from your working tree, and it did.

I assume that I can't find out,

If your OS keeps modification times on files, look for the two most-recently-modified files.  Those will be the two that git checkout HEAD . overwrote.

I am wondering how I can protect myself in the future as this command is how I habitually discard local changes.

Change your habits.  You can't alias a built in Git command.  You can make a git alias or git command of your own that:

*

*checks to see if you're running something "safe", or checks to see if you're using this particular command;

*if you're running something you've deemed "safe", runs the real Git command with the same arguments, but if you're running git checkout HEAD ., complains and doesn't do that.

Since you're writing this command-or-alias yourself, you get to choose what goes in the "but" section of step 2.  This will (presumably) get you to change your habits.
(I try to use git status and then git restore -- path/to/file these days, so that I know just what I'm restoring; I can cut-and-paste the file name from git status here.)

A:
Is there some alias I can create that for this that would protect me from such a mistake in the future

No. checkout is dangerous and Git will not protect you from yourself.
But an excellent protection is to abandon the use of checkout. Instead use switch and restore. They make it much harder to make a harmful mistake.


text:
Q: Changing Character Value of Active Cell in Excel VBA I am trying to write a VBA macro that takes a single letter of the alphabet from the active cell and replaces it with a letter five positions ahead (i.e. "a" becomes "f", "x" becomes "c"). This is to decode a file of encrypted text where all letters have been shifted back five positions.
So far I have tried using the ASCII value of the letter and converting from that integer back to a character, but this seems not to be working (run time error 13) and I can't help but wonder if there is a more efficient way. Here's what I have so far:
Sub DECODER()
Worksheets("Sheet1").Activate

Dim What As String
What = ActiveCell.Value

Dim dCode As String
If What = "" Then
dCode = What
Else
dCode = Chr(Asc((What) + 5))
End If

ActiveCell.Value = dCode

End Sub

A: Without VBA:
With a single lower case alphabetic character in cell A1, in B1 enter:
=CHAR(IF(CODE(A1)>117,CODE(A1)-26,CODE(A1))+5)

and With VBA:
Public Function DeCoder(Sin As String) As String
    Dim num As Long

    If Sin Like "[a-z]" Then
        num = Asc(Sin) + 5
        If num > 122 Then num = num - 26
        DeCoder = Chr(num)
    Else
        DeCoder = Sin
    End If
End Function


text:
Q: How to disable link on images google custom search engine cse? I'm using Google custom search engine cse (free version) and I want to disable link on images results, because I want to show pop-up images on click, someone can help me, how I can disable the link on images on Google custom search engine?
I tried
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
    $(document).ready(function() {
      $('.gs-image-box').bind('click', false);
    });
    </script>

but this is not working.

A: $(".gs-image-box").click(function(event){
    event.preventDefault(); // This will prevent a link from opening the URL

    // your popup code
});


text:
Q: Почему андроид приложение не запускается на моем устройстве через USB кабель? Пытаюсь протестировать свое приложение на смартфоне, который подключен через USB - выдает такую ошибку:
Installation failed due to: ''pm install-create -r -t -S 3366360' returns error 'UNSUPPORTED''

Смартфон - xiaomi redmi note 4
Как исправить?


text:
Q: Unzip a file using python caller in FME 2011 The idea is to download a zipped file from a website and unzip it using FME 2011. I have attached a screenshot of FME workbench which is not working.

A: Your code seems incorrect.  Try:
import pyfme, os, zipfile
z = zipfile.ZipFile("GoTransitDL.zip")
z.extractall()

And just as a warning (from API docs):

Warning Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".

The zip file can be made to extract files to anywhere on your hard drive, and z.extractall() will oblige.  Very dangerous if you don't know the source.

A: I just did the exact same thing. You should check the documentation on the PythonCaller. You need to create a function or class as described in the help. Use a function to process a single feature, as in this case.
Example:
from zipfile import ZipFile

def fmeUnzip(fmeFeature):
    zipFile = fmeFeature.getAttribute("_ZIPFILE_NAME")
    outDir = fmeFeature.getAttribute("_OUTPUT_DIR")
    unzip(zipFile, outDir)

def unzip(zipFile, outDir):
    z = ZipFile(zipFile)
    z.extractall(outDir)

In the PythonCaller parameters, set 'Symbol to use' to fmeUnzip and copy the code to the source code parameter. You can alternatively save it in a .py file, see the PythonCaller help for how to do this.
Note: _ZIPFILE_NAME and _OUTPUT_DIR are attributes created by ParameterFetcher transformers, which create attributes based on the values of workspace parameters.


text:
Q: Why can we substitute $dWdW$ with $dt$ in ito integral? I'm reading the stochastic process by myself, and I have some confusion about ito integral. Based on what I know: the quadratic variance of brownian motion $W(t)$ (for a single $\omega$) converges to $t$ in the $L^2 norm$ sense, which can be written:
$$\int_\Omega \bigg(\big(W(T)-W(0)\big)^2-T\bigg)^2d\mathbb P(\omega)\to0$$
But how does this relate to that we can substitute $dWdW$ with $dt$ in the Riemann integral? Is there any material that I can read to fill the gap? thanks!