text:
Q: Display JSON response from POST request I have to send a POST request containing the parameters 'username' and 'password'.
I believe I did this below:
public static void execute() {
    Map<String, String> comment = new HashMap<String, String>();
    comment.put("username", login.getText().toString());
    comment.put("password", password.getText().toString());
    String json = new GsonBuilder().create().toJson(comment, Map.class);
    makeRequest("http://www.example.com", json);
}

public static HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        Log.d("Result", httpPost.toString());
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

The next step says that I will receive a JSON response with an 'id' and a 'verification'. How do I display/parse this JSON response? I tried doing `            Log.d("Result", httpPost.toString()); but that clearly doesn't work and I have no idea what I am doing here.
Can someone please help?

A: Read response from server after calling DefaultHttpClient().execute :
HttpResponse  response=makeRequest("http://www.example.com", json);
BufferedReader reader = new BufferedReader(
          new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line);
}

Log.d("Result","Response :: "+ builder.toString());

if server returning JSON response then convert builder.toString() to JSONObject and get all values from it using keys


text:
Q: Better to add CSS timed transition to link selector (a) or to the hover state (a:hover)? When using the CSS transitions for creating rollovers that fade in/out, is it better to place it under the a selector or the a:hover selector?
My instinct is to place it on the a:hover selector because that's the active portion of the rollover but looking at examples, people seem to declare them after the a instead.
Both seem to work perfectly but I'd really like to know which is considered "correct", and if possible, why.
So, this:
a { color:blue; transition:.5s; }

a:hover { color:red; }

Or this (my instinct):
a { color:blue; }

a:hover { color:red; transition:.5s; }

Thanks.
(Vendor prefixes intentionally omitted)

A: It depends on your needs, using the transition property below in a
a { color:blue; transition:.5s; }

Will transit the element when you mouseover/hover the element, as well as when you mouseout
Where this
a:hover { color:red; transition:.5s; }

Will transit the element only on hover, it will get back to normal the moment you take out the mouse.
Demo (Too and fro transition)
Demo 2 (Will transit only on hover and will be back to normal once the mouse is off the element)

Note: I've increased the transition time to show how it actually
  matters.

Conclusion: Generally speaking, transition shouldn't be used on :hover as it won't transit when the mouse is taken out of the element. But as I said again, it depends on the needs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sitefinity 4.3 A/B Testing I am using Sitefinity 4.3 for my organisation's site.
We have a home page and on it we are showing our Portfolio slider and it has Image, Text and Description.
The portfolio details are in the database. How should I go about doing A/B testing for this section as if we create another page the source will also be in the database.
Please guide how to approach A/B testing in this situation.

A: Google Experiments are an easy way to do this. There is a blog post on Telerik's site that highlights it (although, the blog is using 5.x)
http://www.sitefinity.com/blogs/grisha-karanikolovs-blog/2013/04/12/a-b-and-multivariate-testing-with-sitefinity-cms-and-google-experiments


text:
Q: What is the safe way to update production data if data found inconsistent I am in a small company and require to fix a bunch of data in production which are inconsistent.  I have written the script to handle the fix.
I understand that writing sql to fix data is way more risky than working on fixes normal front end or backend code. For front end or back end, we can write thousands of test code to automatically test result or even little bug the affect might not be as dramatic.
How do you guys fix the data in production normally if many data was inconsistent? Are there any method or strategy which can reduce the risk

A:
How do you guys fix the data in production

Very very carefully!
This may be too general a question: there are many variables involved regarding data size, error severity, how active that data is, what service level agreements you have with the client, ...
Some tips:

*

*Test the scripts in your dev/test environments as extensively as time allows.

*If you can, take a copy of the production system to test the scripts on. You probably need to do this on production services if your application handles PPI or other sensitive data.

*If you have an upcoming maintenance window when you can offline the production environment to test and apply the change (and rollback the DB if something goes wrong).

*If there is time in that window take a fresh copy of production database to retest before applying to production proper.

*Take a backup of production, so you can rollback if the update fails and makes more mess.

*Apply the change to production and test that the result is as desired.

*If all is well, drop the extra test copies and turn production back on, if not rollback to your backups and try again...

Of course if the data fix needs to be made more urgently, you may need to be much less cautious than the above list.


text:
Q: HP Code Wars Check digit algorithm error QUESTION:
http://www.hpcodewars.org/past/cw17/problems/Prob02--CheckDigit.pdf
Here's my code:
    int checkdigit(){

    int n,i,j,sum1,sum2,k;

    char ch;
    printf("Enter the number of lines.Then enter ther the codes!");
    scanf("%d",&n);
    char *codes[n];
    int msum[n];
    int fsum[n];
    for(i=0;i<n;++i){
        scanf("%s",codes[i]);
    }
    for(i=0;i<n;++i){
            for(j=0,k=3;j<21;j+=3,k+=3){
        char *num;
        num=codes[i];
        ch=num[j];
        sum1+=atoi(ch);
        if(k<21)
        ch=num[k];
        sum2+=atoi(ch);
    }
    msum[i]=sum1*3;
    fsum[i]=((msum[i]+sum2)%10);
    if(fsum[i]!=0)
        fsum[i]-=10;
 }
       for(k=0;k<sizeof(fsum);k++){
          printf("%s %d",codes[k],fsum[k]);
      }

return 0;
}

The Code now crashes after taking the first UPC code as input.

A: Change
fsum[i]=((msum+sum2)%10);

to
fsum[i]=((msum[i]+sum2)%10);

That is because msum is an array of integers, and msum[i] is an integer. As msum is an array, it is of type int* and is not compatible with int for the binary operator %

A: Here
char *codes[n];

is array of n pointers and you don't allocate memory for these pointers and try to scan values to this location so you see a crash

A: #include <stdio.h>

int checkdigit(int data[12]){
    int i, even, odd, result;

    even = odd = 0;
    for(i = 0; i < 11; ++i){
        if(i & 1)
            even += data[i];
        else
            odd += data[i];
    }
    result = (odd * 3 + even) % 10;
    if(result)
        result = 10 - result;
    return data[11] = result;
}

int main(){
    int n;
    scanf("%d", &n);
    int codes[n][12];
    int i, j;
    for(i = 0; i < n; ++i){
        for(j = 0; j < 11; ++j){
            scanf("%d", &codes[i][j]);
        }
        checkdigit(codes[i]);
    }
    for(i = 0; i < n; ++i){
        for(j = 0; j < 12; ++j){
            if(j) putchar(' ');
            printf("%d", codes[i][j]);
        }
        putchar('\n');
    }
    return 0;
}


text:
Q: Jq contains query with a variable containing spaces I've been having an issue with searching a json field that has spaces it in it with a variable containing the search term that also has spaces in it. I've been using the contains search but I'm not sure how to make it search the entire phrase.
COUNTRY="United States"
CITY='"New York"'

cat testdata | jq --arg COUNTRY "$COUNTRY" --arg CITY "$CITY" -r \
'.wireguard[] | select(.country == $COUNTRY) | select(.city|contains('$CITY'))'

When attempting to run the jq command, it has this error:
jq: error: syntax error, unexpected $end, expecting QQSTRING_TEXT or QQSTRING_INTERP_START or QQSTRING_END (Unix shell quoting issues?) at <top-level>, line 1:
.wireguard[] | select(.country == $COUNTRY) | select(.city|contains("New
jq: 1 compile error

It appears that despite the variable containing the qoutes, the space in the variable is stopping the query.
I have also tried select(.city|contains($CITY)), but that returns no results (no error).
But, select(.city|contains("New York")) query runs perfect fine. Even though the content of the CITY variable is "New York".
How do I use a variable with spaces in it with the 'contains' query?
Json I'm testing against:
{
  "wireguard": [
    {
      "gateway": "us-ga.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Atlanta, GA",
      "isp": "Datapacket"
    },
    {
      "gateway": "us-ca.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Los Angeles, CA",
      "isp": "Datapacket"
    },
    {
      "gateway": "us-ny.wg",
      "country_code": "US",
      "country": "United States",
      "city": "New York, NY",
      "isp": "M247"
    },
    {
      "gateway": "us-ut.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Salt Lake City, UT",
      "isp": "100TB"
    },
    {
      "gateway": "us-fl.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Miami, FL",
      "isp": "Quadranet"
    },
    {
      "gateway": "us-nj.wg",
      "country_code": "US",
      "country": "United States",
      "city": "New Jersey, NJ",
      "isp": "Quadranet"
    },
    {
      "gateway": "us-nv.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Las Vegas, NV",
      "isp": "M247"
    }
  ]
}

A: Your shell definition of CITY means that it's actually got double quotes in the text. That's going to fail to match anything.
Your use of $CITY is as a shell variable not a jq parameter. Furthermore, because you've come out of quotes where you use it, the shell can parse it - and the JSON gets split at the space between "New and York".
Try this instead. I've swapped the case of the shell variables to make it clearer which is a shell variable and which is for jq
country='United States'
city='New York'

jq --arg COUNTRY "$country" --arg CITY "$city" -r \
'.wireguard[] | select(.country == $COUNTRY) | select(.city|contains($CITY))' testdata

Output
{
  "gateway": "us-ny.wg",
  "country_code": "US",
  "country": "United States",
  "city": "New York, NY",
  "isp": "M247"
}


text:
Q: Control loop simulation of a LM5117 buck converter, CM mode, using LTspice I am trying to perform a control loop simulation of a buck converter based on a LM5117 chip.
It will be used for battery charging, hence the output voltage and output current should be regulated. The input voltage is 63 V, regulated by a pre-regulator. Note that the input voltage does not have much margin to the maximum input voltage of 65 V.
As per the datasheet, a TL431 stage has to be introduced after the usual voltage divider.
I read the following resources:

*

*One about the TL431 use in a power supply control loop.

*Power Tips: Using a simple SPICE model to simulate a buck control loop

*The LM5117 datasheet.

If I understand the challenge well, I'll have to make at least two simulation models:
One with a R_load high enough so that output current flowing through it is not clamped, and one with a low R_load that will make the current flowing through it constant.
I could also step R_load.
The simulation fixture will model the following stages:

*

*the voltage divider

*the TL431 stage

*the type 1 or 2 compensation network (between FB and COMP pins)

*the CM pin (current monitor voltage output) through the formula in the datasheet in section 7.3.10. It is dependent on I_peak and I_valley going through the inductor, I believe. This (the CM voltage) will be modeled through an algebraic expression in LTspice

*The error amplifier stage, using datasheet parameters. I could model it with an ideal op-amp and plug in the DC gain, and use the bandwidth to derive its output capacitance

*The load, a crude model of a battery as a diode to prevent feedback, a resistor for the battery internal resistance at a defined state of charge, and a voltage source, plus the output capacitors.

I find the rest of the power stage tricky to model, that is the power stage gain.
Since my stability problems occurs when the output current is clamped, is it safe to assume that the power stage DC gain is simply a linear function? That is, the output voltage supplied to the load (which is V_drop + R_batt*I_clamp + V_batt, V_drop being the voltage drop of the diode in front of the battery model, which is the simplest possible) divided by the error amplifier output voltage.
That would give quite a crude model in my opinion. I believe that it would be better to at least model the PWM and ramp signal comparator operation.
In the power-tips-using-a-simple-spice-model-to-simulate-a-buck-control-loop page, there is another compensation network between the error amplifier and the power stage, maybe this accounts for the rest of the power stage?
This is my first attempt at modelling a SMPS control loop, so bear with me.
Included us an image of the schematic for transient analysis. I have not yet started to design the control loop schematic.


text:
Q: How to get the count of similar records along with the number of results in select statement using T-SQL? Given the following T-SQL query and the result below,
select
    Tag
from
    [dbo].[_StanwellAlarms_U3]
where
    [TimeStamp] >= CONVERT(NVARCHAR(19), '2013-06-06 00:00:00')
    and [TimeStamp] < CONVERT(NVARCHAR(19), '2018-06-16 00:10:00')
    and T = 'A' and RG = 'R'

Result

I'm struggling to create a select statement that will return the number of result and a count of similar (group) tag.
For example:
Based on the 35 records, I expect the result would yield the following result:
Tag                     TagCount  TotalRows
-------------------------------------------------
T3HYY10EW100-H.ZV02.OUT    8        35
T3LFN40AA008..COM          2        35
...                        ..       ..

I know this is a noob SQL related question, sorry for I'm just starting to learn T-SQL, so please bear with me.
I really appreciate any help.

A: It isn't entirely clear what the logic is which would lead to only two unique tags in your result set, but a simple count aggregation query might be what you have in mind:
WITH cte AS (
    SELECT COUNT(*) AS cnt
    FROM [dbo].[_StanwellAlarms_U3]
    WHERE
        [TimeStamp] BETWEEN '2013-06-06 00:00:00' AND '2018-06-16 00:10:00' AND
        T = 'A' and RG = 'R'
)

SELECT
    Tag,
    COUNT(*) AS TagCount,
    (SELECT cnt FROM cte) AS TotalRows
FROM [dbo].[_StanwellAlarms_U3]
WHERE
    [TimeStamp] BETWEEN '2013-06-06 00:00:00' AND '2018-06-16 00:10:00' AND
    T = 'A' and RG = 'R'
GROUP BY Tag


text:
Q: Const reference qualifier on a member function I have seen in an anwser there:
Is returning by rvalue reference more efficient?
The member function definition:
Beta_ab const& getAB() const& { return ab; }

I am familiar with the cv-qualifier (const) on member functions, but not const&.
What does the last const& mean?

A: The & is a ref-qualifier. Ref-qualifiers are new in C++11 and not yet supported in all compilers, so you don't see them that often currently. It specifies that this function can only be called on lvalues (and not on rvalues):
#include <iostream>

class kitten
{
private:
    int mood = 0;

public:
    void pet() &
    {
        mood += 1;
    }
};

int main()
{
    kitten cat{};
    cat.pet(); // ok

    kitten{}.pet(); // not ok: cannot pet a temporary kitten
}

Combined with the cv-qualifier const, it means that you can only call this member function on lvalues, and those may be const.

A: We know that in this code...
Beta_ab const& getAB() const { return ab; }
                       ^^^^^

The highlighted const means that the member function may be called upon a const object. A member function can always be called upon a non-const object regardless of the function's cv-qualification.
So in this code...
Beta_ab const& getAB() const & { return ab; }
                             ^

We should expect that the highlighted & also says something about what kinds of objects this member function is allowed to be called upon. We would be correct; in C++11, this says that the member function may only be called upon lvalues.
Beta_ab const& getAB() const& { return ab; }
Beta_ab &&     getAB() &&     { return ab; }

In the above example, the first overload is invoked on lvalues, and the second overload is invoked on non-const rvalues. Similar to the following more familiar example, with qualifiers applied to ordinary function parameters:
void setAB(AB const& _ab) { ab = _ab; }
void setAB(AB &&     _ab) { ab = std::move(_ab); }

It works slightly differently for ordinary parameters though, as in this example, the first overload would accept an rvalue if the second overload were removed.


text:
Q: How to sync branches on git i'm trying to add changes in a personal project. So i was create a new Branch with GitBash, but i can't see it on Github and viceversa (if i create a new Branch on GitHub, i can't see it on my computer console). Also, a friend of mine made a request in this project, but I can't see the changes to the files on my computer no matter if I merge on GitHub. I'm new at this so thanks if u can help me!
i try to see the same Branches on GitHub and GitBash, also to merge the pull request correctly.


text:
Q: geometry line intersection with polygon returns null I'm trying to set a column based on the result of a line midpoint intersection with a polygon. I know I can call the line midpoint with something like
  X_Coord = SHAPE.STPointN(SHAPE.STNumPoints()/2).STX ,
  Y_Coord = SHAPE.STPointN(SHAPE.STNumPoints()/2).STY

but how to pass that to
update GRSM_ROADS
set QuadName = USGS_24K_TOPOMAP_BOUNDARIES.NAME
from  GRSM_ROADS
inner join USGS_24K_TOPOMAP_BOUNDARIES
on dbo.GRSM_ROADS.Location_ID = GRSM_ROADS.Location_ID
where (USGS_24K_TOPOMAP_BOUNDARIES.SHAPE.STIntersects(dbo.GRSM_ROADS.shape) = 1);

is a mystery. I've tried stcontains and stintersects, which runs, but the output is null, indicating that I'm not correctly determining when or where the line midpoint intersects the polygon.
SQL 2008 R2

A: where (USGS_24K_TOPOMAP_BOUNDARIES.SHAPE.STIntersection(dbo.GRSM_ROADS.shape).STDimension() = 1);

Stdimension solved it!


text:
Q: ASP.NET Core - Post requests using [HttpPost] not working for objects I am trying to do a simple POST request but it seems like [FromBody] cannot seem to understand more than 2 parameters.
The request:
 [HttpPost]
 public IEnumerable<EnergyMarket> addEnergy([FromBody] EnergyMarket energyMarket)
 {
     _energyMarketService.addEnergy(energyMarket.Name, energyMarket.StockIPO, energyMarket.EnergyPrice);
     return _energyMarketService.Energies;
 }

The object:
public class EnergyMarket
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("stockipo")]
    public string StockIPO { get; set; }
    [JsonProperty("price")]
    public double EnergyPrice { get; set; }

    public EnergyMarket() { }

    public EnergyMarket(string name, string stockIPO, double val)
    {
        this.Name = name;
        this.StockIPO = stockIPO;
        this.EnergyPrice = val;
    }
}

Request (Content-type is application/json)
{
   "name": "Air Canada",
   "stockipo": "AC.TO",
   "price": 13.12
}

When I go on POSTMAN and put the following request, it works fine for the first two parameters, but the price is always 0. When I changed the price from a double to string, the string was always null.

A: Default ASP.NET Core model binder does not use Newtonsoft.Json property attributes. Therefore, we should implement it ourselves.
Firstly, create implementation of IModelBinder that would read request body and deserialize it using Newtonsoft JsonConvert.DeserializeObject method
public class NewtonsoftModelBinder : IModelBinder
{
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {

        string valueFromBody = string.Empty;
        using (var sr = new StreamReader(bindingContext.HttpContext.Request.Body))
        {
            valueFromBody = await sr.ReadToEndAsync();
        }

        if (string.IsNullOrEmpty(valueFromBody))
        {
            return;
        }

        try
        {
            var model = JsonConvert.DeserializeObject(valueFromBody, bindingContext.ModelType);

            bindingContext.Result = ModelBindingResult.Success(model);
        }
        catch
        {
            bindingContext.ModelState.TryAddModelError(
                "", "Model can not be deserialized.");

        }

        return;
    }
}

Then there are multiple ways how we can apply it to our code, but the easiest one is to put it as attribute on your EnergyMarket class
[ModelBinder(BinderType = typeof(NewtonsoftModelBinder))]
public class EnergyMarket
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("stockipo")]
    public string StockIPO { get; set; }
    [JsonProperty("price")]
    public double EnergyPrice { get; set; }

    public EnergyMarket() { }

    public EnergyMarket(string name, string stockIPO, double val)
    {
        this.Name = name;
        this.StockIPO = stockIPO;
        this.EnergyPrice = val;
    }
}

Finally, we can see correct data in controller after Postman request


text:
Q: Angular 1.3 error: Argument 'PageNavController' is not a function, got undefined I have a question about my Angular 1.3 and Django Project.
Background:  I am writing a web application using Django Frameworks and Angular 1.3 for the front end.  The short term goal is to simply use angular to be able to change views using a controller.  I'll show the code for the angular application I am using in my project:
(function () {
  'use strict';

  angular
    .module('viex', [
      'viex.config',
      'viex.routes',
      'viex.authentication',
      'viex.layout',
      etc...

    ]);

  angular
    .module('viex.config', []);

  angular
    .module('viex.routes', ['ngRoute']);

  angular
  .module('viex')
  .run(run);

run.$inject = ['$http'];

function run($http) {
  $http.defaults.xsrfHeaderName = 'X-CSRFToken';
  $http.defaults.xsrfCookieName = 'csrftoken';
}
})();

Here are some of my routes.  Ignore the ones that render templates...those work just fine.  I am attempting to use a URL with an action, so when someone types /welcome, an action of welcome.view will occur.  Here is the code:
(function () {
  'use strict';

  angular.module('viex.routes').config(config);

  config.$inject = ['$routeProvider'];

  function config($routeProvider) {
    $routeProvider.when('/', {
      controller: 'PageNavController',
      controllerAs: 'vm'
    }).when('/welcome', {
      action: 'welcome.view'
    }).when('/faq', {
      action: 'faq.view'
    }).when('/browse', {
      templateUrl: 'static/templates/layout/browse.html'
    }).when('/termsandconditions', {
      controller: '',
      controllerAs: '',
      templateUrl: 'static/templates/toc/termsandconditions.html'
    .otherwise('/');
  }

})();

Next, I define a module for my layout which in turn contain my controllers:
(function () {
  'use strict';

  angular
    .module('viex.layout', [
      'viex.layout.controllers'
    ]);

  angular
    .module('viex.layout.controllers', []);
})();

Lastly, the controller I want to use to change my views (not serve templates, but simply hide and show certain elements).
/**
* PageNavController
* @namespace viex.layout.controllers
*/
(function () {
  'use strict';

  angular
    .module('viex.layout.controllers')
    .controller('PageNavController', PageNavController);

  PageNavController.$inject = ['$scope', '$route', '$routeParams'];

  /**
  * @namespace PageNavController
  */
  function PageNavController( $scope, $route, $routeParams ) {

        render = function(){

            var renderAction = $route.current.action;

            console.log(renderAction);
            var renderPath = renderAction.split(".");

            var username = ($routeParams.username || "");

            var isWelcome = (renderPath[ 0 ] == "welcome");
            var isFaq = (renderPath[ 0 ] == "faq");

            $scope.renderAction = renderAction;
            $scope.renderPath = renderPath;

            $scope.username = username;

            $scope.isWelcome = isWelcome;
            $scope.isFaq = isFaq;

        };

        $scope.$on("$routeChangeSuccess",
            function( $currentRoute, $previousRoute ){
                render();
            }
        );

  }

})();

All I want to do is Switch from one view to another using the controller above.  When A view is rendered, only one will show, and the others will hide for this simplistic example.   Here is the HTML:

            {% include 'navbar.html' %}

                            {% include 'welcome.html'%}

                            {% include 'faq.html' %}

        {% include 'footer.html'%}

When I load my page, I get the error "Error: [ng:areq] Argument 'PageNavController' is not a function, got undefined".  My line of thinking was that I made my function PageNavController in my controller.  Evidently, my application doesn't recognize it, or my syntax is messed up.
I am using Angular 1.3+, Python 3.X, and Django 1.8+.
Thanks again to anyone who can offer some help or point me in the right direction where to start looking!
-DJ

A: Angular doesn't support namespace even you name the modules in that style. You have to inject viex.layout.controllers into your viex.routes module.
angular
.module('viex.routes', ['ngRoute',  'viex.layout.controllers']);


text:
Q: Crash while releasing in implementation of NSCoding Protocol methods Below is the code I use for unarchiving the data:
- (id)initWithCoder:(NSCoder *)decoder
{
    if((self = [super init]))
    {
        NSString *resoureItemClassName = NSStringFromClass([ResourceItem class]);
        self.selectedItemClassName=[decoder decodeObjectForKey:@"selectedItemClassName"];
        Class class = NSClassFromString(selectedItemClassName);
        id temp = nil;

        if(class)
        {
            temp = [[class alloc] init];
        }

        if(temp)
        {
            if([temp isKindOfClass:[NSString class]])
            {
                self.selectedString = [decoder decodeObjectForKey:@"selectedString"];;
                self.ID = selectedString;
            }
            else if([selectedItemClassName isEqualToString:resoureItemClassName])
            {
                DLog(@"Resource item")
            }

            [temp release];
        }
        else
        {
            self.ID = nil;
        }
    }

    return self;
}

When I release the tempObject, the app crashes. If I do not do it, it is a leak. I tried using the autorelease method. Still then it crashed? What is the solution?
UPDATE:
The encoded data in selectedItemClassName is either __NSCFConstantString or __NSCFString. The crash occurs only with __NSCFString and  not with __NSCFConstantString as the class name,
What could be the reason?

A: How about:
- (id)initWithCoder:(NSCoder *)decoder
{
    if((self = [super init]))
    {
        NSString *resourceItemClassName = NSStringFromClass([ResourceItem class]);
        self.selectedItemClassName=[decoder decodeObjectForKey:@"selectedItemClassName"];
        Class class = NSClassFromString(selectedItemClassName);

        if(class)
        {
            NSString *stringClassName = NSStringFromClass([NSString class]);
            if([stringClassName isEqualToString:self.selectedItemClassName])
            {
                self.selectedString = [decoder decodeObjectForKey:@"selectedString"];;
                self.ID = selectedString;
            }
            else if([self.selectedItemClassName isEqualToString:resourceItemClassName])
            {
                DLog(@"Resource item")
            }
        }
        else
        {
            self.ID = nil;
        }
    }

    return self;
}


text:
Q: IOUtils copy method is not working properly The copy method gives me this error:
"The method copy(InputStream, OutputStream) in the type IOUtils is not applicable for the arguments (FileInputStream, StringWriter, String)"
... even though I have 3 parameters and that IOUtils does have the
copy(InputStream, Writer, String) method.
Here is my code:
import java.awt.BorderLayout;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.StringWriter;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;

import org.apache.poi.util.IOUtils;

@SuppressWarnings("serial")
public class AboutDialog extends JFrame {
    private final String fileLocation = "resources/Contents.html";
    private FileInputStream htmlStream;
    private JLabel lblMessage;

    public AboutDialog() {
        String message;
        setType(Type.POPUP);
        setTitle("About");
        setResizable(false);
        setEnabled(false);
        getContentPane().setLayout(new BorderLayout(0, 0));
        try {
            htmlStream = new FileInputStream(fileLocation);
            StringWriter writer = new StringWriter();
            IOUtils.copy(htmlStream, writer, "UTF-8");
            message = writer.toString();
            lblMessage = new JLabel(message);
            lblMessage.setHorizontalAlignment(SwingConstants.CENTER);
            getContentPane().add(lblMessage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void display() {
        JOptionPane.showMessageDialog(null, lblMessage);
    }
}

A: I guess you mean to import org.apache.commons.io.IOUtils instead of org.apache.poi.util.IOUtils.
The former has a lot of copy() methods the latter only has copy(InputStream, OutputStream).

A: IOUtils from apache POI contains only the 2 params method. https://poi.apache.org/apidocs/org/apache/poi/util/IOUtils.html


text:
Q: How to compile kscope on windows system? kscope is a very nice gui tool on unix to analysis of sorce code i am using it for a while on my linux box.
is there is any port of kscope on windows availbale?
I know cygwin support kde env. but i am not able to compile kde on it.

A: May be release 1.9.x are better prepared to be installed on Windows as it is Qt based. (No KDE required).
Farouk


text:
Q: Java Split issue User will be entering the email ids in the text box with semicolon as separator. Before storing into db, i want to validate whether entered email id are valid. So i started using split. But the problem is, when user enter the value like 'xxxx@gmail.com;;;', in this case i want to validate to remove the unwanted characters.
I thought split will return the length will be  4 and then i can check for empty or null. But split returning length as only one. So along with extra characters it stores in the DB. Any help to resolve this ?

A: The split method by default discards trailing empty strings when splitting the text.  If you really want the trailing empty strings, then use the overloaded version of split that takes two arguments -- the second argument limit can be negative, and it tells split not to discard trailing empty strings.
But I don't see why you would want the trailing empty strings.  The split method normally discards them for you.

A: After you use split(), you will have all the supposed email ids in an array and can validate them.  After validation, instead of using the original string, rebuild the string using the array.  That eliminates any duplicate semicolons you had.  Use StringBuffer for the building, it is slightly more efficient for concatenating a number of strings.

A: Do it this way to validate and get a length
 String values = textBox1.getText();
        String[] split = values.split(";");
        System.out.println(split.length);
        for(String s : split) {
            if(null != s)
                //do junk
        }

A: Would something like this help:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

public class Test{
 public static void main(String args[]){
  String line = "'xxxx@gmail.com;;;',";
    if(line.contains("@")){
        int x=0;
       for (String valueBetweenCommas: line.split("'", 2)){
           x++;
          if(x==2){
             Pattern p = Pattern.compile("[\\w]*([.+]??[\\w]+?)+?[\\w]@[\\w]+[.][a-zA-Z]{2,5}+$");
             Matcher m = p.matcher(valueBetweenCommas);
             boolean result = m.matches();
             if(result){
                 //add to database
             }else{
                 break;
             }
          }

          }
          }

 }

A: Firstly, using a JTextField for what is essentially a list seems to be impractical. What you should do instead is have a JList<String> with each item representing an email and then add/remove buttons that will modify the list through your DefaultListModel<String>. After that, to retrieve all of the elements (email addresses), you may then call the .elements() method and traverse through them.
So, it would look something like this:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class EmailList extends JPanel implements ActionListener{

private final JList<String> list;
private final DefaultListModel<String> model;
private final JScrollPane scroll;

private final JButton addButton;
private final JButton removeButton;
private final JPanel buttonPanel;

public EmailList(){
    super(new BorderLayout());

    addButton = new JButton("Add");
    addButton.addActionListener(this);

    removeButton = new JButton("Remove");
    removeButton.addActionListener(this);

    buttonPanel = new JPanel(new GridLayout(1, 2, 5, 0));
    buttonPanel.add(addButton);
    buttonPanel.add(removeButton);

    model = new DefaultListModel<>();

    list = new JList<>();
    list.setModel(model);

    scroll = new JScrollPane(list);

    add(buttonPanel, BorderLayout.NORTH);
    add(scroll, BorderLayout.CENTER);
}

private boolean valid(final String email){
    //see if email is valid in here
    return true;
}

public List<String> emails(){
    final List<String> emails = new LinkedList<>();
    final Enumeration<String> elements = model.elements();
    while(elements.hasMoreElements())
        emails.add(elements.nextElement());
    return emails;
}

public void actionPerformed(final ActionEvent e){
    final Object source = e.getSource();
    if(source.equals(addButton)){
        final String input = JOptionPane.showInputDialog(null, "Enter an email address");
        if(input == null || input.trim().isEmpty())
            return;
        final String email = input.trim();
        if(!valid(email)){
            JOptionPane.showMessageDialog(null, "That email is not valid");
            return;
        }
        model.addElement(email);
        list.repaint();
    }else if(source.equals(removeButton)){
        final int i = list.getSelectedIndex();
        if(i < 0)
            return;
        model.removeElementAt(i);
        list.repaint();
    }
}
}

Just a minor note, I wrote this in Java 8 so you may need to make some minor changes (only change seems to be putting String in the empty <>


text:
Q: counting odd numbers in a list python This is a part of my homework assignment and  im close to the final answer but not quite yet. I need to write a function that counts odd numbers in a list.
Create a recursive function count_odd(l) which takes as its only argument a list of integers. The function will return a count of the number of list elements that are odd, i.e., not evenly divisible by 2.\
>>> print count_odd([])
0
>>> print count_odd([1, 3, 5])
3
>>> print count_odd([2, 4, 6])
0
>>> print count_odd([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144])
8

Here is what i have so far:
    #- recursive function count_odd -#
def count_odd(l):
    """returns a count of the odd integers in l.
    PRE: l is a list of integers.
    POST: l is unchanged."""
    count_odd=0

    while count_odd<len(l):
        if l[count_odd]%2==0:
            count_odd=count_odd
        else:
            l[count_odd]%2!=0
            count_odd=count_odd+1
    return count_odd

#- test harness
print count_odd([])
print count_odd([1, 3, 5])
print count_odd([2, 4, 6])
print count_odd([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144])

Can u help explain what im missing. The first two test harness works fine but i cant get the final two. Thanks!

A: Since this is homework, consider this pseudo-code that just counts a list:
function count (LIST)
    if LIST has more items
        // recursive case.
        // Add one for the current item we are counting,
        // and call count() again to process the *remaining* items.
        remaining = everything in LIST except the first item
        return 1 + count(remaining)
    else
        // base case -- what "ends" the recursion
        // If an item is removed each time, the list will eventually be empty.
        return 0

This is very similar to what the homework is asking for, but it needs to be translate to Python and you must work out the correct recursive case logic.
Happy coding.

A: def count_odd(L):
    return (L[0]%2) + count_odd(L[1:]) if L else 0

A: Are slices ok?  Doesn't feel recursive to me, but I guess the whole thing is kind of against usual idioms (i.e. - recursion of this sort in Python):
def countOdd(l):
    if l == list(): return 0           # base case, empty list means we're done
    return l[0] % 2 + countOdd(l[1:])  # add 1 (or don't) depending on odd/even of element 0.  recurse on the rest

x%2 is 1 for odds, 0 for evens. If you are uncomfortable with it or just don't understand it, use the following in place of the last line above:
   thisElement = l[0]
   restOfList = l[1:]
   if thisElement % 2 == 0: currentElementOdd = 0
   else: currentElementOdd = 1
   return currentElementOdd + countOdd(restOfList)

PS - this is pretty recursive, see what your teacher says if you turn this in  =P
>>> def countOdd(l):
...     return fold(lambda x,y: x+(y&1),l,0)
...
>>> def fold(f,l,a):
...     if l == list(): return a
...     return fold(f,l[1:],f(a,l[0]))

A: All of the prior answers are subdividing the problem into subproblems of size 1 and size n-1.  Several people noted that the recursive stack might easily blow out.  This solution should keep the recursive stack size at O(log n):
def count_odd(series):
    l = len(series) >> 1
    if l < 1:
        return series[0] & 1 if series else 0
    else:
        return count_odd(series[:l]) + count_odd(series[l:])

A: The goal of recursion is to divide the problem into smaller pieces, and apply the solution to the smaller pieces. In this case, we can check if the first number of the list (l[0]) is odd, then call the function again (this is the "recursion") with the rest of the list (l[1:]), adding our current result to the result of the recursion.

A: def count_odd(series):
    if not series:
        return 0
    else:
        left, right = series[0], series[1:]
        return count_odd(right) + (1 if (left & 1) else 0)

A: Tail recursion
def count_odd(integers):
    def iter_(lst, count):
        return iter_(rest(lst), count + is_odd(first(lst))) if lst else count
    return iter_(integers, 0)

def is_odd(integer):
    """Whether the `integer` is odd."""
    return integer % 2 != 0 # or `return integer & 1`

def first(lst):
    """Get the first element from the `lst` list.

    Return `None` if there are no elements.
    """
    return lst[0] if lst else None

def rest(lst):
    """Return `lst` list without the first element."""
    return lst[1:]

There is no tail-call optimization in Python, so the above version is purely educational.
The call could be visualize as:
count_odd([1,2,3])    # returns
iter_([1,2,3], 0)      # could be replaced by; depth=1
iter_([2,3], 0 + is_odd(1)) if [1,2,3] else 0 # `bool([1,2,3])` is True in Python
iter_([2,3], 0 + True) # `True == 1` in Python
iter_([2,3], 1)        # depth=2
iter_([3], 1 + is_odd(2)) if [2,3] else 1
iter_([3], 1 + False)  # `False == 0` in Python
iter_([3], 1)          # depth=3
iter_([], 1 + is_odd(3)) if [3] else 1
iter_([], 2)           # depth=4
iter_(rest([]), 2 + is_odd(first([])) if [] else 2 # bool([]) is False in Python
2 # the answer

Simple trampolining
To avoid 'max recursion depth exceeded' errors for large arrays all tail calls in recursive functions can be wrapped in lambda: expressions; and special trampoline() function can be used to unwrap such expressions. It effectively converts recursion into iterating over a simple loop:
import functools

def trampoline(function):
    """Resolve delayed calls."""
    @functools.wraps(function)
    def wrapper(*args):
        f = function(*args)
        while callable(f):
            f = f()
        return f
    return wrapper

def iter_(lst, count):
    #NOTE: added `lambda:` before the tail call
    return (lambda:iter_(rest(lst), count+is_odd(first(lst)))) if lst else count

@trampoline
def count_odd(integers):
    return iter_(integers, 0)

Example:
count_odd([1,2,3])
iter_([1,2,3], 0)         # returns callable
lambda:iter_(rest(lst), count+is_odd(first(lst))) # f = f()
iter_([2,3], 0+is_odd(1)) # returns callable
lambda:iter_(rest(lst), count+is_odd(first(lst))) # f = f()
iter_([3], 1+is_odd(2))   # returns callable
lambda:iter_(rest(lst), count+is_odd(first(lst))) # f = f()
iter_([], 1+is_odd(3))
2                         # callable(2) is False

A: I would write it like this:
def countOddNumbers(numbers):
    sum = 0
    for num in numbers:
        if num%2!=0:
            sum += numbers.count(num)
    return sum

A: not sure if i got your question , but as above something similar:
def countOddNumbers(numbers):
    count=0
    for i in numbers:
        if i%2!=0:
            count+=1
    return count

A: Generator can give quick result in one line code:
sum((x%2 for x in nums))


text:
Q: Installing docker on WSL 2 Windows - Ubuntu 20.04.4 LTS(focal) Getting the following error when trying to start docker on WSL Windows 11
"System has not been booted with systemd as init system"

A: Follow all these steps from the original Docker docs:
https://docs.docker.com/engine/install/ubuntu/#installation-methods
However, because in WSL we may run into something like this when trying to start Docker:

"System has not been booted with systemd as init system"

Here's the reason why: https://www.partitionwizard.com/partitionmanager/system-not-booted-with-systemd-as-init.html
Use the following command
sudo service docker start


text:
Q: ASP.NET application hangs after a call I'm having a simple ASP.NET application hosted on my local IIS6, under Vista.
It contains a button that when I click I execute a piece of code for recognizing the text in a WAV file (using the System.Speach.Recognition.SpeechRecognition class) and display the text in a label.
The code works great on a desktop application, and it almost works on the web one... I say almost, because if I debug, I can see that the recognizer returns the correct text from the WAV, I can see that I am finishing the handler for the button click with no error, but nothing gets displayed in my page, and the page appears like loading... it's hanging, or something... No errors, no timeout, nothing. Just loading...
I don't know if this detail helps, but in order to make the piece of code that was already working on the desktop application work on the web application, I had to set the identity of the ApplicationPool of my application to LocalSystem (security breach, I know). Otherwise, I would have received a Access Denied error (0x80070005(E_ACCESSDENIED)).
Do you have any ideea why the call hangs like that? I'm fighting with this for more than two days, time pressures me, and I have no clue... Any help is really welcomed!
Thanks!

A: After another one week of stuglles, I found an overcome to the problem. I'm posting this just so other that might have this problem find the solution faster.
The solution was to call the method for making the speech recognition on a different thread. I think this forced the release of all resources in that thread after the recognition ended.
I cannot make any sense why this even happened on the first place (I used using blocks and I closed and disposed all the object in all the imagining ways), but I suspected to be a memory release problem...
Anyway, a very simple call on another thread fix it!


text:
Q: Persistent Auth cookie in .net core 2.0 Recently I created my new website in .net core 2.0 and I'm using a persistent cookie in authentication. I'm also using persistent culture cookie for language.
my website hosted in azure shared pool and I didn't specify any machine key.
Problem.
When I re-open my website after few hours of inactivity (new browser) I lost my auth cookie and I need to log in again but culture cookie works as per the last session.
I also setup Application Insights availability to keep warm up my application (ping website in every 10 min from 2 different location).
LoginController
if (this.accountService.ValidateOTP(phoneNumber, otp))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.MobilePhone, phoneNumber),
                new Claim(ClaimTypes.Name, phoneNumber)
            };
            var userIdentity = new ClaimsIdentity("Custom");
            userIdentity.AddClaims(claims);
            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

            //await HttpContext.SignOutAsync("AnimalHubInstance");
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                userPrincipal,
                new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.Now.AddYears(1),
                });
}

Startup
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(option =>
            {
                option.LoginPath = new PathString("/Account/Unauthorized");
                option.LogoutPath = new PathString("/Account/Logout");
                option.Cookie.Name = ".myAuth";
                option.ExpireTimeSpan = TimeSpan.FromDays(365);
                option.Cookie.Expiration = TimeSpan.FromDays(365);
            });

A: You need to use the data protection to persist your session encryption keys.
When hosting apps in Azure App Service or IIS in general (in VM or on-premises), IIS will recycle apps and app pools on inactivity. So if your app doesn't get hit for a specific amount of time, it will be shut down and started again on next connection.
When this happens, new encryption keys will be generated for session and your previous session will be invalid.

A:
When I re-open my website after few hours of inactivity (new browser) I lost my auth cookie and I need to log in again but culture cookie works as per the last session.

The value of your culture cookie is just urlencoded. As Tseng said that the machine key for hashing and encryption may automatically re-generate at some points. I assumed that this issue caused by the pricing tier you chose. For Free and Shared tier, you application would run on shared infrastructure and you only have the limited resources(e.g. CPU time, RAM, disk space) and no SLA.
App Service limits:

Moreover, I tried to restart the website and recycle the application pool on my local side, the authentication cookie could still work as expected. For my web app hosting under the basic pricing tier, I do not encounter this issue until now.


text:
Q: How to have the user input alternate between uppercase and lowercase in Ruby? I have Ruby ask the user five times to enter a name, and want the answers to be spat out with each line to alternate with uppercase and lowercase. Below is what I have done and it prints out each name twice, one uppercase one lowercase. But I just want each line to alternate between uppercase and lowercase. I hope I'm making sense here...
Football_team = []

5.times do
    puts "Please enter a UK football team:"
    Football_team << gets.chomp
end

Football_team.each do |Football_team|
    puts team.upcase
    puts team.downcase
end

A: football_team = []

5.times do
  puts "Please enter a UK football team:"
  football_team << gets.chomp
end

football_team.each_with_index do |team, index|
  if index.even?
    puts team.upcase
  else
    puts team.downcase
  end
end

Note that you should use identifiers starting with capitals only for constants. While Football_team might be a constant, it is generally not a good idea. Also note that your loop variable was wrong.

A: You don't really need two loops. You can do it all in one. See below
football_team = []

5.times do |i|
    puts "Please enter a UK football team:"
    team = gets.chomp

    if i.even?
        football_team << team.upcase
    else
        football_team << team.downcase
    end
end

puts football_team

Alternatively, same solution but in shorthand:
football_team = []

5.times do |i|
    puts "Please enter a UK football team:"
    i.even? ? football_team << gets.chomp.upcase : football_team << gets.chomp.downcase
end

puts football_team


text:
Q: String thread safety because of immutability? Hi was reading about that a string is thread safe because it is immutable.
For example i do:
String a = "test";

One thread uses this variable.
But another thread could still also use this variable and change it:
a = a + "something";

So it would change or not?
If it would be volatile, i would get it, that it can just be used by one thread at a time. But immutabilty doesnt guarantee me this!?

A: You're not changing the object pointed by a, but where a points to:
String a = "test";

here a points to a string "test"
a = a + "something";

here a new string is created as the result of the concatenation of "test" and "something", which "testsomething" where a points to. It's a different instance.
So there is no problem of thread safety, as both threads will have their own a referring to the same "test" string object, but once one of those thread will modify the string to be referring the "testsomething" object, the other Thread will still be referring the original "test" object.

A: The String itself isn't changing, the reference is. It sounds like you need the reference to be final. Immutability guarantees that the Object does not change, not that the reference cannot change. Just mark it like this:
final String a = "test";

A: You can make the code thread safe trivially by having each thread copy the reference a. In fact, that's normally what happens anyway, since you usually pass the string to the thread via a parameter.
So both threads hold a reference to the original string, here "test". If thread 1 now modifies a it only modifies this reference. Thread 2 still retains an intact reference to "test" because the string itself (rather than the reference) is immutable.

A: Strings objects are thread-safe. If your String a is a local variable then this code is still thread-safe. If it is a field of your class than it is your responsibility to guarantee its thread-safety. Thread-safety of String won't magically make your own code thread-safe. You should take care about it.
You can make field volatile then you get visibility among threads. So any thread will see up-to-date value of your field. But you won't get atomicity in this way. Imagine the following. Let a = "test". Thread 1 updates a and thread 2 updates a. They both see current value which is "test". They read it, make new strings by concatenation and update value of a. And what will be that value? It is unknown. It can be "testsomethingsomething" if threads perform their operations strictly one after another. But it can be just "testsomething". For instance:

*

*thread 1 read "test" from a

*thread 2 read "test" from a

*thread 2 updates a with "testsomething"

*thread 1 updates a (remember, it read a as "test" before) with the same "testsomething"
Voila, you've lost an update to your field. To avoid this kind of problem, you should guard all accesses and modifications to your field with synchronization on single lock object.

A: A lot of confusion here...
What thread safety of some class means is that concurrent use of it's instance
will not destroy it's internal structure.
In our case it is just a warranty that we finally get a "testsomething", but not a mess like
"tsomethingest" or "tesomethingst" or "tseosmtething" or "somethingtest".
Here a "quick and dirty" illustration:
public class Test2 {

    private volatile String tstStr = "";

    Test2(){
    }

    void impl(int par){
        Thread wrk = new Thread(new MyRun(par));
        wrk.start();
    }

    static public void main(String[] args) throws Exception {
       Test2 tst2 = new Test2();
       long startTime = System.currentTimeMillis();
       Thread wrk;
       for (int i = 0; i < 9; i=i+1) {
           tst2.impl(i);
       }
       long endTime = System.currentTimeMillis();
       System.out.println("The process took " + (endTime - startTime) + " milliseconds");
    }

    class MyRun implements Runnable {
        int no;
        MyRun(int var){
            no = var;
        }
        public void run(){
            tstStr = tstStr + " " + no;
            for (int i = 0; i < 3; i=i+1) {
                System.out.println("Message from "+no+", tested string ="+tstStr);
            }
        }
    }

}

The output:
Message from 1, tested string = 0
Message from 1, tested string = 0 2 3
Message from 1, tested string = 0 2 3
Message from 4, tested string = 0 2 3 4
Message from 4, tested string = 0 2 3 4
Message from 0, tested string = 0 2
Message from 8, tested string = 0 2 3 4 7 8
Message from 5, tested string = 0 2 3 4 7 8 5
Message from 0, tested string = 0 2 3 4 7 8 5
Message from 0, tested string = 0 2 3 4 7 8 5
The process took 0 milliseconds
Message from 7, tested string = 0 2 3 4 7
Message from 7, tested string = 0 2 3 4 7 8 5 6
Message from 4, tested string = 0 2 3 4
Message from 3, tested string = 0 2 3
Message from 2, tested string = 0 2
Message from 3, tested string = 0 2 3 4 7 8 5 6
Message from 7, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 5, tested string = 0 2 3 4 7 8 5
Message from 8, tested string = 0 2 3 4 7 8 5
Message from 5, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 3, tested string = 0 2 3 4 7 8 5 6
Message from 2, tested string = 0 2 3 4 7 8 5 6
Message from 6, tested string = 0 2 3 4 7 8 5 6
Message from 8, tested string = 0 2 3 4 7 8 5 6
Message from 2, tested string = 0 2 3 4 7 8 5 6


text:
Q: How to load multiple assembies
*

*In C# programming, I am trying to load multiple assemblies with same features in their namespaces, for reflection. For example, load all assemblies with the same prefix in namespaces
ABC..
ABC.*
ABC...*
How to realize it?

*Similar question is how to load multiple assemblies with same features in their names?
Thanks,
Ken

A: You can use Reflection.Assembly.ReflectionOnlyLoadFrom(filepath)

A: For question number 2 - if you have the files of these assemblies, you can use Assembly.LoadFrom(String) or Assembly.ReflectionOnlyLoadFrom(String) and pass the names of those files that match your desired pattern.


text:
Q: Recursively add fields on a nested object I need to add uuid on an object recursively,
How could I do that with javascript?
My idea is that BFS/DFS are both working.
My idea
function addIdRecursively(root){
  if(root is a Object){
    ITERATE_EACH_ATTR_IN
    root.id = 'UUID'
  }
  else if(root is a array){
    root.map(item=>addIdRecursively(item))
  }
}

input
{
  "viewType": "List View",
  "sections": [
    {
      fields:[
      'Id',
      'Name'
      ]
    },
    {
      "children": [
        {
          "name": "no"
        }
      ]
    }
  ]
}

Expect result
{
  "id": "ef910f30-fe25-0134-8f50-745c898f0819",
  "viewType": "List View",

  "sections": [
    {
      "id": "ef910f30-fe25-0134-8f50-745c898f0819",
      fields:[
      'Id',
      'Name'
      ]
    },
    {
      "id": "ef910f30-fe25-0134-8f50-745c898f0819",
      "children": [
        {
          "id": "ef910f30-fe25-0134-8f50-745c898f0819",
          "name": "no"
        }
      ]
    }
  ]
}

A:

let uuid = "ef910f30-fe25-0134-8f50-745c898f0819";

function addRecursively(obj) {
  if(Array.isArray(obj))                                    // if obj is an array
    obj.forEach(addRecursively);                            // then call addRecursively on all its items
  else if(obj && typeof obj === "object") {                 // otherwise if it's an object (the "obj &&" part is needed because typeof null === "object")
    obj.id = uuid;                                          // add the id property to it
    Object.keys(obj).forEach(k => addRecursively(obj[k]));  // and then call add recursively on all its items
  }
}

let obj = {"viewType":"List View","sections":[{"fields":["Id","Name"]},{"children":[{"name":"no"}]}]};

addRecursively(obj);
console.log(obj);

A:     // Generate a v4 UUID (random)
    import stringMatching = jasmine.stringMatching;
    import {log} from "../Util";
    const uuidV4 = require('uuid');
    // uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

    export default class UUIDGenerator {
        structure = null
        constructor(structure) {
            this.structure =     {
                "viewType": "List View",
                "sections": [
                    {
                        fields:[
                            'Id',
                            'Name'
                        ]
                    },
                    {
                        "children": [
                            {
                                "name": "no"
                            }
                        ]
                    }
                ]
            }
        }
        process(){
            this.addIdRecursively(this.structure)
            log(this.structure)
            debugger
            return this.structure
        }

        addIdRecursively(structure){
            switch (typeof  structure){
                case 'array':
                    return structure.map(item => this.addIdRecursively(item))
                case 'object':
                    for (var key in structure) {
                        this.addIdRecursively(structure[key])
                    }
                    structure.id = uuidV4()
                    return structure
            }
        }
    }


text:
Q: Angular multiple api call issue In my controller, I am calling a service that is making an http request to an api that returns a JSON file with my analytics data.
This is my service:
.factory('getData', ['$http', function($http) {
return {
    getFacebookData: getFacebookData,
};

function getFacebookData(clientName) {
   return $http.get('/blah.com/'+clientName)
    .then(getDataComplete)
    .catch(getDataFailed);

   function getDataComplete(response) {
    return response.data[0].facebook;
   }

   function getDataFailed(error) {
     console.log(error);
   }
}

Then my controller calls the service like this:
.controller('HomeCtrl', function ($scope, $http, getData) {
var clientName = "blah"
getData.getFacebookData(clientName)
    .then(function(data) {
    console.log("facebook:", data)
});

The problem I am having is that in the console, it is making the request and logging the data 6 times.  This may be a dumb question, but any advice on why its doing this and how to only make the request once would be awesome.


text:
Q: Comparing two text files and counting the differences I have been trying to compare two text files in Python, essentially I want to open them and compare a single character at a time if the characters are different add 1 to a counter and then display this value.
Here is what I have so far:
#!/usr/bin/env python

diff = 0

import random
import string
import sys

file_A = sys.argv[1]
file_B = sys.argv[2]

read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()

for a in read_A:
    for b in read_B:
        if a != b:
            diff = diff + 1
    return diff
break

print "No of Differences ",diff

Right now it does count but the value it returns does not seem correct.

A: The simplest way to do this is to use difflib. It doesn't require any additional eggs for python and gives really good results for tracking various kinds of diff checks. The result of a diff check would be what you'd look toward to check for equality as well as close matches. That can be important as well if you allow for weighting of results.

A: Looping isn't certainly the pythonic way to do it. Without using any external library, you can use simple list comprehension to find the instances of differences between two files:
If the order is significant:
x=[i for i, j in zip(read_A, read_B) if i != j]
print len(x)

If the order is not significant:
x=[i in read_B for i in read_A]
#Now count the instances where the comparison resulted in False
i = x.count(False)

A: If you have two strings which you want to compare character by character, it seems best to zip them.
So, once you've doe this:
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()

you do:
for char_a, char_b in zip(read_A, read_B):
    if char_a != char_b:
        # something

If your files are very big, you may wish to only read character by character and use izip instead of zip...
BTW...
You are not closing your files. It is a good idea to always access files this way:
with open(file_A, 'r') as f1:
    read_A = f1.read()

with open(file_B, 'r') as f2:
    read_B = f2.read()


text:
Q: How to do conditional variable assignment with cmake? I would like to give a default value DEF to a variable VAR if I do not give the flag -DVAR=VAL. Have you any idea?
Thank you.

A: The following seems to work. Thanks to Kamil Cuk which leads me to one solution.
if(not defined VAR)
                set(VAR VAL)
 endif()

A: You can just use set(... CACHE ...) command:
set(VAR "DEF" CACHE STRING "My VAR for doing xyz")

If the variable is already set in the cache - e.g. via command line switch -D - it's not overwritten. And the user could change it with cmake-gui or ccmake.
Or if you have boolean values take the option() definitions command.
References

*

*What's the CMake syntax to set and use variables?

*What is the difference between "option" and "set CACHE BOOL" for a CMake variable?


text:
Q: SharePoint CSOM Copy - RoleAssignment hope you can help me out.
I'm working on a powershell script performing serveral modifications on a sharepoint environment.
I want to copy the RoleAssignments from on web to an other in the same site collection. Basicly it works when i run my commands manual in the console but it doesent work while running the script.
What I do is this.
    $RoleAssignmentMember =  $RoomWebRoleAssignment.Member
    $RoleBindings =  $RoomWebRoleAssignment.RoleDefinitionBindings
    $ctx.Load($RoleAssignmentMember)
    $ctx.Load($RoleBindings)
    $ctx.ExecuteQuery()

    $Web.RoleAssignments.Add($RoleAssignmentMember, $RoleBindings)
    $ctx.ExecuteQuery()

Running $Web.RoleAssignments.Add($RoleAssignmentMember, $RoleBindings) in console works.. not in the script .. I got an error that the collection is not ready .. but acutally it is^^..
Any Ideas ? Hope you can help
Greetz

A: Sorry, silly me.
for the people who are interested:
# Load it
$ctx.Load($Web.RoleAssignments.Add($RoleAssignmentMember, $RoleBindings));
$ctx.ExecuteQuery();


text:
Q: Show that the number of partitions of $n$ into $k$ parts that are all $m$ or less is Full problem: Show that the number of partitions of $n$ into $k$ parts that are all $m$ or less is the number of partitions of $km-n$ into fewer than $m$ parts that are all $k$ or less.
I'm a little confused about how to show this, I tried drawing a Ferrer's diagram, because it's reminding me a little but of identifying self-conjugate partitions but I'm not sure... Can anyone help with this?

A: Hint:  Consider the $k \times m$ rectangle into which the partition diagrams of both types fit and find a bijection between the two types:
$$\begin{matrix} {\color{red} \bullet} &{\color{red} \bullet} & {\color{red} \bullet} & {\color{blue} \bullet} \\ {\color{red} \bullet} &{\color{red} \bullet} & {\color{blue} \bullet}&{\color{blue} \bullet} \\ {\color{red} \bullet} & {\color{red} \bullet} &{\color{blue} \bullet} &{\color{blue} \bullet} \\ {\color{red} \bullet}& {\color{blue} \bullet}& {\color{blue} \bullet} &{\color{blue} \bullet}\end{matrix}$$


text:
Q: Why id from Redux is undefined? I have Redux state:
import phones from "./../API/phone.json"

const initialState = {
   data: phones
};

I have component and it's containter componenet:
const Iphone = ({phones}) => {

  const filterIphone = phones.map((p, index) =>
    (

      <NavLink to={'/CurrentIphone/' + phones.id}>{p.body.model}</NavLink>

  ))

  return (

      {filterIphone}

  );
};

export default Iphone;

export class CurrentIphoneContainer extends React.Component {

    render() {
        return (
            <CurrentIphone {...this.props} />
        )
    }
}

const mapStateToProps = (state) => ({
    phones: state.phoneReducer.data
})

export default compose(connect(mapStateToProps, {getPhones})(CurrentIphoneContainer))

So the problem is in this string:
<NavLink to={'/CurrentIphone/' + phones.id}>{p.body.model}</NavLink>

My id is undefined, although when I put id to 'p.body.id' It shows. (When i use debugger id brings with props)

A: <NavLink to={'/CurrentIphone/' + p.id}>{p.body.model}</NavLink>


text:
Q: Bug visual usando LongListSelector (grouped) e Checkbox Windows Phone 8 Estou desenvolvendo um aplicativo que possui uma lista agrupada, e dentro de cada item da lista existe um checkbox. O problema que vem ocorrendo acontece quando o checkbox do primeiro item do grupo 1 é selecionado, o checkbox do primeiro item do grupo 2 também é selecionado. Mas isso só ocorre visualmente, em nenhum momento o evento de check é chamado para o 2 checkbox. Gostaria de saber se alguém já passou por isso, e se sim como fazer para resolver, obrigado.
EDIT: ----
No meu xml tenho o LongListSelector:
<phone:LongListSelector
                x:Name="llsAlunosTurmas"
                Background="Transparent"
                ItemTemplate="{StaticResource AddrBookItemTemplate}"
                LayoutMode="List" />

e o data template dos itens:
<DataTemplate x:Key="AddrBookItemTemplate" x:Name="dte" >
            <StackPanel VerticalAlignment="Top"
                    Margin="0,3,0,0"
                    Background="White"
                    HorizontalAlignment="Stretch"
                    Orientation="Horizontal">
                <StackPanel Orientation="Vertical"
                        Margin="12,0,0,0"
                        VerticalAlignment="Center">
                    <TextBlock Foreground="{StaticResource CorTxtPagina}"
                           VerticalAlignment="Center"
                           Text="{Binding matricula}"
                           Width="385"
                           FontSize="16"
                           TextTrimming="WordEllipsis"
                           FontStretch="SemiCondensed"/>
                    <TextBlock Foreground="{StaticResource CorTxtPagina}"
                           Text="{Binding nomAlu}"
                           Width="385"
                           FontSize="16"
                           HorizontalAlignment="Left"
                           TextTrimming="WordEllipsis" />
                </StackPanel>
                <CheckBox x:Name="cbxAlunos"
                      Background="{StaticResource CorBotoes}"
                      Click="cbxAlunos_Click"
                      IsChecked="{Binding selecionado, Mode=OneWay}"
                      Tag="{Binding idtAlu}"/>
            </StackPanel>
    </DataTemplate>

e no c#, depois de receber os dados por webservice, organizo como os dados serão exibidos(o agrupamento) e coloco como dataset da lista:
 if (lista.Count != 0)
        {
            int cont = 0;

            string turmaAtual = lista.First().idtTurma;
            foreach (var item in lista)
            {
                if (turmaAtual != item.idtTurma)
                {
                    cont++;
                    turmaAtual = item.idtTurma;
                }
                item.ordem = cont + "";
            }
            List<string> headers = lista.GroupBy(aluno => aluno.idtTurma).Select(grp => grp.First().turma).ToList();

            lista = lista.OrderBy(aluno => aluno.nomAlu).ToList();
            alunos = lista;

            llsAlunosTurmas.ItemsSource = AlphaKeyGroup<Aluno>.CreateGroups(lista, headers,
                                            System.Threading.Thread.CurrentThread.CurrentUICulture,
                                            (Aluno a) => { return a.ordem; }, false);
        }


text:
Q: Error using packet 1 could not find function "sp.polygon" I'm trying to add shp or rds file into my raster plot in R, but after that I get some error in a plot with this.

My script:
library(rasterVis)
levelplot(cape_bulanan, col.regions=colorRampPalette(c("Red","Yellow","Blue"))) +
    latticeExtra::layer(sp.polygon(indo.rds, col = "black", fill = "transprent"))


text:
Q: next Image component doesn't load images I have a problem with next Image component as it doesn't seem to be loading the images. The component is set up like
<Image  className={styles.imgHomeBlock}
                        src={testImg}
                        alt='Commercial'
                        width='500'
                        height='500'
                />

where testImg is imported like
import testImg from '../../public/google-map-fake.jpg';

When I bring it up it doesn't load as it is looking for the image on "localhost:3000/_next/image/google-map-fake.jpg" and that folder doesn't exist anywhere.
Serving the image in an html img works just fine. Image is placed in public folder and public folder is at the root of the project.
Putting the url directly into next Image component, passing it as a prop from its parent or putting an external url there again breaks. When for example I put an external url of an image, I still get a 404 and console indicates that it is looking for the image on "localhost:3000/_next/image/https://{image_url_here}".
Is there a way to change that "_next/image" prefix that Image component uses or else, why would the component not show the Image from the public folder directly like img tag does?
Here is the full component code:
import {useState} from 'react';
import Link from "next/link";
import Image from 'next/image'
import styles from '../../styles/T01/t01HomeBlock.module.css';

import testImg from '../../public/google-map-fake.jpg';

const T01HomeBlock = (props) => {

  return (

              <Link href={props.target}>
{props.overlay}
</Link>

              <Link href={props.target}>

                    //this works

                {/*
                <Image  className={styles.imgHomeBlock}
                        src={testImg}
                        alt='Commercial'
                        width='500'
                        height='500'
                /> //this doesn't
                */}

            </Link>

{props.text}

   );

}

export default T01HomeBlock;

A: Try to import the picture not using the module, but immediately insert it into the src
import React, {useState} from 'react';
import Link from "next/link";
import Image from 'next/image'
import styles from '../../styles/T01/t01HomeBlock.module.css';
const T01HomeBlock = (props) => {

  return (

              <Link href={props.target}>
{props.overlay}
</Link>

              <Link href={props.target}>

                    //this works

                {/*
                <Image  className={styles.imgHomeBlock}
                        src='/google-map-fake.jpg'
                        alt='Commercial'
                        width='500'
                        height='500'
                /> //this doesn't
                */}

            </Link>

{props.text}

   );

}

export default T01HomeBlock;

P.S Please note that there are no public on the way, this is how it should be


text:
Q: when apply SUPEE-6788 my home page goes blank When I apply PATCH_SUPEE-6788_CE_1.9.0.0_v1-2015-10-26-11-59-04.sh
in my magento 1.9.0.0 my home page goes blank.
My 1column.phtml shows on frontend:

when I reverse apply the patch, the website shows back.

A: Did you whitelists the blocks ?
Follow these steps to white-list it
 1.System > Permissions > Blocks

 2. Add New Block
    Block Name: cms/block
    Is Allowed : Yes

after the update you need to white-list the blocks and clear cache

A: Run the PHP script here https://github.com/rhoerr/supee-6788-toolbox and in the report WHITELIST as said above all the blocks it identifies.
You will then be good to go.
Steve


text:
Q: Как отсортировать базу данных Возможно ли отсортировать базу данных сразу по нескольким параметрам? Если да, то как? Мой код компилятор не принимает.
Мой код для сортировки:
 String selectQuery = "SELECT  date FROM " + TABLE_DATES + " WHERE " + KEY_ID + " = " + id+", WHERE month = "+my;
        Cursor cursor = db.rawQuery(selectQuery, null);

A: "SELECT  date FROM " + TABLE_DATES + " WHERE " + KEY_ID + " = " + id+" and month = '"+my+"'"
Нужно использовать оператор and.


text:
Q: Can't access attribute of Angular Promise I'm trying to write a JS function using Angular such that I can have it return a value, then set a variable on the scope equal to that value. I return a promise object that according to the chrome console has an attribute with my data in it, but when I try to access that, it says it is undefined.
Code:
   function getData($scope, $http) { //line 71
    output = $http.get('/static/json/tickets').
        success(function(data, status) {
            output.data = data;
            console.log(output.data); //Within the proper scope; displays the data array
            output.status = status;
        }).
        error(function (data, status){
            output.data = data || "Error";
            output.status = status;
        });
        console.log(output); //displays the promise object, with attribute data
        console.log(output.data); // displays 'undefined' (out of scope?)
        return output

    out = getData($scope, $http);
    console.log(out); // Displays the promise object, with attribute data
    console.log(out.data); // displays 'undefined'
    $scope.data = out.data;

Chrome console:

Is there any way I can put a return statement inside the .success(data, status) function that will make the parent function (getData) return that value? I'm fairly new to JS, and while I know that it's possible to return from a nested function, .success is a method of the promise returned by $http.get, and trying to return output.data gives an undefined object. This code:
function getData($scope, $http) {
dataout = {};
output = $http.get('/static/json/tickets').
    success(function(data, status) {
        dataout = data;
        console.log(output.data); //Within the proper scope; displays the data array
        output.status = status;
    }).
    error(function (data, status){
        output.data = data || "Error";
        output.status = status;
    });
    console.log(output); //displays the promise object, with attribute data
    console.log(output.data); // displays 'undefined' (out of scope?)
    return dataout

returns an undefined object as well, which makes me think that Angular is doing something with async that I'm not handling properly.

A: This is not how you use promises. The output variable get actually logged before the data is there. But the chrome console shows the object in its current data state.
try to log out.data.toString() it will log "undefined".
Try this:
function getData($http) {
 return $http.get('/static/json/tickets').
    success(function(data, status) {
        console.log(data); //Within the proper scope; displays the data array
        return data;
    }).
    error(function (data, status){
        return status;
    });
}

The $http will return a promise in which you attach the success and error callback and by returning a value within these callbacks, angular will wrap a promise around and return it.
And then call it like this:
getData($http).then(function(data){
  console.log(data);
});

Maybe move the method into a service and dont pass the $http as a parameter there.

A: You need to let the promise resolve before you can get the data.  Here is an example using a factory and controller:
app.factory('Tickets',function($http,$q) {
    var dataout = $q.defer();

    $http.get('/static/json/tickets/').success(function(data,status) {
            dataout.resolve(data);
    });

    return {
        getData: function() {
            return dataout.promise;
        }
    }
});

app.controller('GetData',function($scope,Tickets) {
    Tickets.getData().then(function(data) {
        $scope.out = data;
    });
});


text:
Q: Laptop only boots windows I have a Lenovo Z585 and I want to replace the hard drive and install KDE Neon on it. I have tried putting in the new drive and it will not boot from a USB. The only working way to access the bios is to go to advanced startup and enter it through there. I cannot access it on boot whatsoever. When I do get into it I disabled secure boot and enabled legacy mode, then moved the USB to highest boot priority but when I save and restart it goes straight to Windows. I have Ubuntu dual booted and it ignores that too. It used to work and now the only way to boot into Ubuntu or any USB is in the advanced startup menu. Ubuntu works fine this way but when I select the USB it shows the KDE splash screen then goes blank. I tried using another computer to install KDE on the new hard drive but when it starts it does nothing. It only boots from the drive that it came with.

A: in regards to duel booting windoze and ubuntu: have you tried to re-build the master GRUB configuration file? Windoze is well known for trying to ignore linux. To re-build grub:
1 boot any linux version, USB, HDD, Floppy, whatever.
2 In your linux, open a terminal (press Ctrl + Alt + T at the same time)
3 In the terminal type sudo update-grub , wait for the update to finish.
4 Reboot your computer.
I really hope this helps.
https://www.google.com.au/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0ahUKEwje3NnFn5_ZAhXJoZQKHXWpA9MQFgg_MAM&url=https%3A%2F%2Faskubuntu.com%2Fquestions%2F281119%2Fhow-do-you-run-update-grub&usg=AOvVaw3dbMwxS4wpt2Q4zKoN9N5i


text:
Q: Uploadify Queue Not Showing I have successfully implemented a copy of uploadify into my site. The SWF button shows, I can click on it and browse my files. However, the rubber meets the road whenever it comes to file files showing the queue.
For some reason, when I select a file, there isn't any queue, even though I have followed uploadify directions. Does anyone have any ideas on how to overcome this? Here are the relative parts of my code:
<!DOCTYPE html>
<html>
<head>
...
<link rel="stylesheet" type="text/css" href="../system/stylesheets/uploadify.css" />
<script type="text/javascript" src="../system/javascripts/swfobject.js"></script>
...
<script type="text/javascript" src="../system/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="../system/javascripts/uploadify.jquery.min.js"></script>
<script type="text/javascript">
  $(':file').uploadify({
    'uploader' : '../system/flash/uploadify.swf',
    'script' : 'index.php',
    'cancelImg' : '../system/images/common/cancel.png'
  });
</script>
</head>

<body>
...
<input type="file" name="logo" class="logo" /></td>
...
</body>
</html>

I'm sure all of the images/stylesheets/JavaScripts are properly linked, but it is still a no go.
Thank you for your time.

A: I got it! For some reason, you MUST select the input field by it's ID, and therefore, you can't select more than one at a time. (Why??? lol)
Anyway, that solved my problem. Hope that helps someone.


text:
Q: Reset a destination date column value I can already change the value of a destination DateTime field by assigning it e.g. 2000-01-01 00:00. But if either of the systems changes their timezone, this value will also change with them, so I cannot rely on it always keeping this value.
So, is there a way to clear the value of the column?
If we do not type or insert a value, Zapier assumes that we do not want to update it.


text:
Q: How to connect a custom domain to an existing subpage/subdomain? I am trying to connect a custom domain to the subpage of an existing website hosted via Firebase Hosting. Just like in website builder sites who allow users to 'connect a domain'.
Should I connect the new custom domain to Firebase's name servers, and then reroute to the specific subpage?
Or is there a separate standardized approach which lets a website publish content to custom domains?

A: You cannot map your DNS records to a subpage because it just map IP addresses to hostname.
The solution for you is to redirect requests from source page to your destination page.


text:
Q: MVC Mocking (Moq) - HttpContext.Current.Server.MapPath I have a method I am attempting to Unit Test which makes use of HttpContext.Current.Server.MapPath as well as File.ReadAllLines as follows:
public List<ProductItem> GetAllProductsFromCSV()
{
    var productFilePath = HttpContext.Current.Server.MapPath(@"~/CSV/products.csv");

    String[] csvData = File.ReadAllLines(productFilePath);

    List<ProductItem> result = new List<ProductItem>();

    foreach (string csvrow in csvData)
    {
        var fields = csvrow.Split(',');
        ProductItem prod = new ProductItem()
        {
            ID = Convert.ToInt32(fields[0]),
            Description = fields[1],
            Item = fields[2][0],
            Price = Convert.ToDecimal(fields[3]),
            ImagePath = fields[4],
            Barcode = fields[5]
        };
        result.Add(prod);
    }
    return result;
}

I have a Unit Test setup which (as expected) fails:
[TestMethod()]
public void ProductCSVfileReturnsResult()
{
    ProductsCSV productCSV = new ProductsCSV();
    List<ProductItem> result = productCSV.GetAllProductsFromCSV();
    Assert.IsNotNull(result);
}

I have since done a lot of reading on Moq and Dependancy Injection which I just dont seem to be able to implement. I have also seen a few handy answers on SO  such as: How to avoid HttpContext.Server.MapPath for Unit Testing Purposes however I am just unable to follow it for my actual example.
I am hoping someone is able to take a look at this and tell me exactly how I might go about implementing a successful test for this method. I feel I have a lot of the background required but am unable to pull it all together.

A: In its current form, the method in question is too tightly coupled to implementation concerns that are difficult to replicate when testing in isolation.
For your example, I would advise abstracting all those implementation concerns out into its own service.
public interface IProductsCsvReader {
    public string[] ReadAllLines(string virtualPath);
}

And explicitly inject that as a dependency into the class in question
public class ProductsCSV {
    private readonly IProductsCsvReader reader;

    public ProductsCSV(IProductsCsvReader reader) {
        this.reader = reader;
    }

    public List<ProductItem> GetAllProductsFromCSV() {
        var productFilePath = @"~/CSV/products.csv";
        var csvData = reader.ReadAllLines(productFilePath);
        var result = parseProducts(csvData);
        return result;
    }

    //This method could also eventually be extracted out into its own service
    private List<ProductItem> parseProducts(String[] csvData) {
        List<ProductItem> result = new List<ProductItem>();
        //The following parsing can be improved via a proper
        //3rd party csv library but that is out of scope
        //for this question.
        foreach (string csvrow in csvData) {
            var fields = csvrow.Split(',');
            ProductItem prod = new ProductItem() {
                ID = Convert.ToInt32(fields[0]),
                Description = fields[1],
                Item = fields[2][0],
                Price = Convert.ToDecimal(fields[3]),
                ImagePath = fields[4],
                Barcode = fields[5]
            };
            result.Add(prod);
        }
        return result;
    }
}

Note how the class now is not concerned with where or how it gets the data. Only that it gets the data when asked.
This could be simplified even further but that is outside of the scope of this question. (Read up on SOLID principles)
Now you have the flexibility to mock the dependency for testing at a high level, expected behavior.
[TestMethod()]
public void ProductCSVfileReturnsResult() {
    var csvData = new string[] {
        "1,description1,Item,2.50,SomePath,BARCODE",
        "2,description2,Item,2.50,SomePath,BARCODE",
        "3,description3,Item,2.50,SomePath,BARCODE",
    };
    var mock = new Mock<IProductsCsvReader>();
    mock.Setup(_ => _.ReadAllLines(It.IsAny<string>())).Returns(csvData);
    ProductsCSV productCSV = new ProductsCSV(mock.Object);
    List<ProductItem> result = productCSV.GetAllProductsFromCSV();
    Assert.IsNotNull(result);
    Assert.AreEqual(csvData.Length, result.Count);
}

For completeness here is what a production version of the dependency could look like.
public class DefaultProductsCsvReader : IProductsCsvReader {
    public string[] ReadAllLines(string virtualPath) {
        var productFilePath = HttpContext.Current.Server.MapPath(virtualPath);
        String[] csvData = File.ReadAllLines(productFilePath);
        return csvData;
    }
}

Using DI just make sure that the abstraction and the implementation are registered with the composition root.

A: The use of HttpContext.Current makes you assume that the productFilePath is runtime data, but in fact it isn't. It is configuration value, because it _will not change during the lifetime of the application. You should instead inject this value into the constructor of the component that needs it.
That will obviously be a problem in case you use HttpContext.Current, but you can call HostingEnvironment.MapPath() instead; no HttpContext is required:
public class ProductReader
{
    private readonly string path;

    public ProductReader(string path) {
        this.path = path;
    }

    public List<ProductItem> GetAllProductsFromCSV() { ... }
}

You can construct your class as follows:
string productCsvPath = HostingEnvironment.MapPath(@"~/CSV/products.csv");

var reader = new ProductReader(productCsvPath);

This doesn't solve the tight coupling with File, but I'll refer to Nkosi's excellent answer for the rest.


text:
Q: fread from data.table package can't read small numbers I am using fread() from data.table to efficiently read large rectangular CSV files into R which are all double (and only double) values -- no missing elements.
However if I have very very small numbers in scientific notation, it'll get converted to character which ruins the whole read. Here is the error message (as an example, there are multiple for each small number):

16: In fread("SomeCSVFile") :
  Bumped column 560 to type character on data row 16799, field contains '-2.1412168512924677E-308'. Coercing previously read values in this column from integer or numeric back to character which may not be lossless; e.g., if '00' and '000' occurred before they will now be just '0', and there may be inconsistencies with treatment of ',,' and ',NA,' too (if they occurred in this column before the bump). If this matters please rerun and set 'colClasses' to 'character' for this column. Please note that column type detection uses the first 5 rows, the middle 5 rows and the last 5 rows, so hopefully this message should be very rare. If reporting to datatable-help, please rerun and include the output from verbose=TRUE.

I want the function to set them to zero or truncate them at the minimum possible value (either is fine).

A: To reproduce this, I put this content in a text file:
x
1
1
1
1
1
1e-309

Then I called fread("that file.txt").

The size of the smallest positive number that R can store is
format(.Machine$double.xmin, digits = 22)
## [1] "2.2250738585072013828e-308"

Your data file includes the value -2.1412168512924677E-308, which is smaller than this limit.  To prevent R treating the value as zero, the data.table package has converted the column to be strings.  This stops the data precision being lost.
If you need to work with values of this size, then use the Rmpfr package to store the numbers with more precision.  Import them as characters (using colClasses; see that data table warning text).  Then use
library(Rmpfr)
mpfr("-2.1412168512924677E-308")
## 1 'mpfr' number of precision  70   bits
## [1] -2.1412168512924676999992e-308

As Ben Bolker siad in the comments.  If you don't care about the tiny numbers, and just want to treat them as zero, then import the column as characters, then use as.numeric.
the_data <- fread("the file.txt", colClasses = "character")
the_data$DodgyColumn <- as.numeric(the_data$DodgyColumn)


text:
Q: Ruby: change time zone issue I am trying to change the following in Ruby:
Time.now.utc
to
Time.now.pst
However, it is not working. What do you think I am missing?
Thanks!
Mel

A: You will have to use TimeWithZone:
irb(main):005:0> Time.zone = 'Pacific Time (US & Canada)'
=> "Pacific Time (US & Canada)"
irb(main):006:0> Time.zone.now
=> Mon, 11 Nov 2013 02:23:09 PST -08:00

API Reference - http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html


text:
Q: inet_ntoa problem I am declaring following variables
unsigned long   dstAddr;
unsigned long   gateWay;
unsigned long   mask;

These variables contains ipaddresses in network byte order. So when I am trying to print the dot notation using inet_ntoa function for mask variable sometimes it is printing strange values. The below code is in a while loop .. which loops for n times.
printf("%s\t%s\t%s\t",inet_ntoa(dstAddr),inet_ntoa(gateWay),inet_ntoa(mask));

  192.168.122.0         0.0.0.0    0.255.255.255

but it should be
  192.168.122.0         0.0.0.0    255.255.255.0

I printed the HEX values of the variables and it shows ..
007aa8c0    00000000      ffffff00

So is this because of inet_ntoa ??
Actually I am trying to get the values of the declared variables from 254 routing table in kernel via NETLINKS. I guess I should still use inet_ntoa function to convert the value into dot notation .. ??

A: The only thing that makes sense is that your assumption regarding all the addresses being in network byte order is incorrect.

A: Well, given that it works for your non-mask values (including the first which also has the high bit set), I'd be looking at what mask actually contains.
What is it when you print it out as a normal unsigned long? My bet is that mask is actually not the correct value:
printf ("%08x\t%08x\t%08x\n", dstAddr, gateWay, mask);

(assuming you have four-byte longs).
For example, this little program (compiled under Cygwin):
#include <stdio.h>

int main (void) {
    unsigned long dstAddr, gateWay, mask;
    dstAddr = 0x007aa8c0;
    gateWay = 0x00000000;
    mask    = 0x00ffffff;

    printf("%-15s %-15s %-15s\n",
        inet_ntoa (dstAddr),
        inet_ntoa (gateWay),
        inet_ntoa (mask));

    printf("%-15s ",  inet_ntoa (dstAddr));
    printf("%-15s ",  inet_ntoa (gateWay));
    printf("%-15s\n", inet_ntoa (mask));

    printf ("%08x%8s%08x%8s%08x\n",
        dstAddr, "",
        gateWay, "",
        mask);

    return 0;
}

outputs:
192.168.122.0   192.168.122.0   192.168.122.0
192.168.122.0   0.0.0.0         255.255.255.0
007aa8c0        00000000        00ffffff

Note that I had to separate my calls to inet_ntoa as it appears to use a static buffer. When I was doing it all within a single printf, it overwrote the contents of that buffer before any of them were printed, hence I only got the last one processed. I don't think that's happening in your case since you're getting different values.

A: I also have the same problem with you.
Use inet_ntop() and inet_pton() if you need it other way around. Do not use inet_ntoa(), inet_aton() and similar as they are deprecated and don't support ipv6.
see link: convert Ip address int to string


text:
Q: how to get to the target floor in minimum time if one can move to N + 1, N - 1 and 2 * N in one minute? This is a problem I was asked to solve during an interview, but the code I implemented during interview cannot pass all test cases, the problem is just as title said, given N and T (T >= N), which  are initial floor and target floor respectively, one can move to current floor + 1, current floor - 1 or 2 * current floor in one minute, what's the minimum time need to reach the target? I think it's a typical DP problem, this is how I did in interview
@lru_cache(None)
def solve(cur):
    if cur >= target: return cur - target
    if cur * 2 >= target:
        # if current floor * 2 < target, we can move to current floor + 1 each time or move backward to (target + 1) // 2 and move current floor * 2 next time, and if target is odd, we need extra 1 move
        return min(target - cur, cur - (target + 1) // 2 + 1 + (target % 2))
    return min(solve(cur + 1), solve(cur * 2)) + 1

I test it with some cases, it seems to work, I cannot figure out why it cannot pass all test cases during interview,
Update---------------------------------------------------------------
I tried using Dijkstra to solve this, but the code become a bit of mess, than I thought if the problem askes to find shortest distance, maybe we can use BFS, and I think it's the right solution, so below is the code
def solve():
    while(True):
        N, T = map(int, input().split())
        q = deque([N])
        vis = [False] * (T * 2)
        vis[N] = True
        steps = 0
        while q:
            for _ in range(len(q)):
                u = q.popleft()
                if u == T:
                    print(f'reach target in {steps} minutes')
                    break
                cand = [u - 1, u + 1, u * 2] if u < T else [u - 1]
                for v in cand:
                    if v > 0 and not vis[v]:
                        vis[v] = True
                        q.append(v)
            steps += 1

A: An easy way is to start from the target T and to found how many iterations we need to go down to initial value N. Here, the allowed operations are +1, -1 and division by 2.
The key point is that division by 2 is only allowed for even value of T. Moreover, if T is even effectively, then it seems clear that division by 2 is the road to take, except if T is near enough to N. This little issue is solved by comparing 1 + nsteps(N, T/2) with  T - N.
If T is odd, we must have to compare nsteps(N, T-1) with nsteps(N, T+1).
Last but not least, if T is less than N, then the number of steps is equal to N - T.
Complexity:  ??
Here is a simple C++ implementation to illustrate the algorithm. It should be easy to adapt it in any language.
#include <iostream>
#include <algorithm>

int nsteps (int n, int t) {
    if (t <= n) {
        return n - t;
    }
    if (t%2 == 0) {
        return std::min (1 + nsteps(n, t/2), t-n);
    }
    return 1 + std::min (nsteps(n, t-1), nsteps(n, t+1));
}

int main () {
    int n, t;
    std::cin >> n >> t;
    std::cout << nsteps (n, t) << std::endl;
    return 0;
}

In practice, as noted in a comment by @David Eisenstat, it is still slow, at least in some occasions. For example, for an input 1 1431655765, it needs 10891541 calls of the function. I modified the code hereafter, by using the value of T modulo 4 in order to speed it up: if T is large enough, we can decide betweens the two roads when Tis odd. In the same test case, only 46 calls are needed now.
In this case, the complexity seems indeed equal to O(log T).
int cpt2 = 0;
long long int nsteps2 (long long int n, long long int t) {
    cpt2++;
    if (t <= n) {
        return n - t;
    }
    if (t%2 == 0) {
        return std::min (1ll + nsteps2(n, t/2), t-n);
    }
    if (t/4 < n) return 1ll + std::min (nsteps2(n, t-1), nsteps2(n, t+1));
    if (t%4 == 1) return 1ll + nsteps2(n, t-1);
    else return 1ll + nsteps2(n, t+1);
}

A: As you mentioned, we can make use of normal BFS search for this question as the direction for our movement between floor is given already as floor + 1 or floor - 1 or floor / 2. As per my understanding a floor / 2 movement is only possible if we are at an even floor.
Here is my java code for the same :

int findSteps(int n, int t) {
    if (n > t) {
        return n - t;
    }
    if (n == t) {
        return 0;
    }
    Queue<Integer> queue = new LinkedList<>();
    Set<Integer> visited = new HashSet<>();
    queue.offer(n);
    visited.add(n);
    int steps = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i=0; i<size; i++) {
            int currentFloor = queue.poll();
            if (currentFloor == t)
                return steps;
            int possibleMove1 = currentFloor + 1;
            int possibleMove2 = currentFloor - 1;
            int possibleMove3 = currentFloor % 2 == 0 ? currentFloor / 2 : -1;
           // out of bound conditions or visited condition
            if (possibleMove1 < t && possibleMove1 > n && !visited(possibleMove1)) {
                queue.offer(possibleMove1);
                visited.add(possibleMove1);
            }
            if (possibleMove2 < t && possibleMove2 > n && !visited(possibleMove2)) {
                queue.offer(possibleMove2);
                visited.add(possibleMove2);
            }
            if (possibleMove3 < t && possibleMove3 > n && !visited(possibleMove3)) {
                queue.offer(possibleMove1);
                visited.add(possibleMove1);
            }
        }
        steps += 1;
    }
    return -1;
}

Note : There is some repeating codes that can be moved to a separate function and use that function instead.