text:
Q: Error in ipaddr.py in Python I'm trying to program an IP Lookup in python using the package "ipwhois".
The problem is that when I try to execute it it gives me an error that I can not fix. I've already search in internet and I can't find the solution.
Error:
   File
 "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/ipaddr.py",
 line 1450
     ip_int = 0L

                ^ SyntaxError: invalid syntax

Does anyone has an idea how can I solve this issue? Any help is welcome.
Thanks

A: As per the documentation use built-in ipaddress from the Python 3 standard library.
ipaddr 2.2.0 is intended for Python 2.7.X versions


text:
Q: How to decompile a .jar file?
Possible Duplicate:
How to decompile a whole Jar file?

I want to see the classes, the code and how it is designed. When I try to open a .class in Netbeans, it says that they cannot be open. Am I missing something? How to see the code behind a .jar file?

A: You must find a java decompiler to see the code. If it has been obfuscated, you won't get anything helpful.

A: Most jar files won't have source inside them.  If the jar files are for open source software, you should be able to find the source on the same website where you got the jar files.
If you can't find the source, you can try decompiling the compiled class files (described in another answer).  You may not legally have the right to do this, however.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AutoHotKey shortcuts stop working after a time I have a lot of text shortcuts in my .ahk file. These have worked well for me on all previous Windows platforms (XP, Windows 7) for me, and function correctly on Win 10 too.
Except after some unspecified amount of time, they just stop working across the board, in all applications.
Getting them going again requires me to right-click on the AutoHotKey icon in the tray and pick "Reload This Script". The shortcuts will then work again for a while.
This has happened to me on several different Windows 10 installations on different machines, so I don't think it's a local configuration issue.
Anybody know why this happens and (hopefully) what I can do about it?


text:
Q: changing django-storages backend from from s3 to cloudfiles and dealing with old files I've got a django app that I'm moving to rackspace. I have a model that uses FileFields and I'm using the django-storages library s3/boto backend. I want to use cloudfiles for storage, and I need to be able to serve up the old s3 content.
On a template page where I provide links to the files, I do this:
href="{{ static_url }}{{ article.code_archive_file}}"

static_url is set from the view and equals settings.STATIC_URL. Clearly this isn't going to work since settings.STATIC_URL is going to change when I switch from s3.
Do I need to write a script to migrate all of my s3 files by hand to cloudfiles and also go through and update all the FileFields in my tables? (ugh). I'd rather be able to change out the storages backend and leave the old material in the s3 bucket.
If I do need to migrate the files and the fields, has someone already written a script for that?
bonus question: What best-practices didn't I follow when doing this? I've only been using django for about half a year now.

A: Option A: You can use a bit different paths on old and new storages and have something to decide from where file should be served. Something could be custom storage class, I think: you create storage class inherited from CloudFilesStorage, and in overrided url method it will either call super (if file is in the new storage) or call url method from S3BotoStorage (if file is in the old storage).
Option B: You can move your files to cloudfiles. I don't think you actually need to change anything in DB after that if you keep paths similar. Maybe you even don't need a script, just download files and then upload then (s3cmd can be used for downloading, cloudfiles probably got some tool for uploading too).
About best practices: you should've used media_url and DEFAULT_FILE_STORAGE instead of static_url and static storage. It's a good idea to keep project's static files (css/js/icons) and uploaded media separated.


text:
Q: returning error response in jquery I am trying to call a controller from jquery.Here every thing works fine,but in ajax it shows error alert. What is going wrong.
$.ajax({
                         type: 'POST',
                         url:'<%=request.getContextPath()%>/billing',
                         data: ({caseId: caseId,  noteID :  noteID}),
                         cache: false,
                         success: function(data){
                                alert("Success");
                            },
                         error: function(xhr, textStatus, error){
                         alert("Error occured.");
                         }
                         });

My controller
@RequestMapping(value = "/billing", method = RequestMethod.POST)
    public String Billing(@RequestParam Long caseId,
            @RequestParam Long noteID, HttpServletRequest request)  throws Exception {
        try{

           ----Some data base updation---
            logger.debug("success ");
        return "success";
        } catch (Exception e) {
            logger.error(e,e);
            throw e;
        }}

Please help me in this.

A: //you have to left content type to send the server side ,please define content type..
 $.ajax({
                type: "POST",
                url: '@Url.Action("PerTGradeMastEdit", "Master")',
                data: "{'Request':'" + request + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    if (response != null) {

                        var strResponse = response;
                        var ProgramData = strResponse.split("/");
                        // response = ProgramData[0];programId
                        $('#txtPerGrade').val(ProgramData[0]);
                        $('#txtDesc').val(ProgramData[1]);

                    }
                },
                failure: function (msg) {
                    alert(msg);
                    window.location.href = '@Url.Action("INDEX", "AUTHORIZE")';
                }
            });`enter code here`


text:
Q: Sort an array of strings that are dates JavaScript I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.
My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
How can I grab the last and the first date in these?
I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.

A: If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates e.g. YYYY-MM-DD.
You can use localeCompare to compare strings.You can use following code to sort the dates:

dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]

dateData.sort(function(a, b){
  var A = a.split("/");
  var B = b.split("/");
  var strA = [ A[2], A[1], A[0] ].join("/");
  var strB = [ B[2], B[1], B[0] ].join("/");
  return strA.localeCompare( strB );
});

console.log( dateData );

Once sorted, you can get the min and max dates as:
var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];

A:

var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];

function dateToNum(d) {
  // Convert date "26/06/2016" to 20160626
  d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}

dateData.sort(function(a,b){
  return dateToNum(a) - dateToNum(b);
});

console.log( dateData );

To retrieve the first, last date:
var firstDate = dateData[0];
var lastDate  = dateData[dateData.length -1];

Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.
so you're basically sorting:
20140626
20140604
20140513
20140720

resulting in:
[
  "13/05/2016",
  "04/06/2016",
  "26/06/2016",
  "20/07/2016"
]

A:
The getTime() method returns the numeric value corresponding to the
  time for the specified date according to universal time. Date.getTime()

dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
.map(a=>a.split('/').reverse().join('/'))
.sort((a,b)=>new Date(a).getTime() - new Date(b).getTime());
console.log(dateData);

A: A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function. The one thing I haven't seen shared is how to get the first and last dates. This should do the trick:
//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];

//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
    var splitDate = date.split("/")
    return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})

//sort the dates
formattedDates.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(a) - new Date(b);
});

//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];

//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)

A: To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD.
This way regular sorting will get you the min and max properly, and you won't need further parsing.
Helper function to sort would be like this:
for(var i=0;i<dateData.length;++i)
{
    var split = dateData[i].split("/");
    dateData[i] = split.reverse().join("/");
}

A: One way I know to do this is using the .sort() function for a string. https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx
You would have to change your array into YYYY-MM-DD
then you could have the following code
var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"];
dateData.sort();
var first = dateData[0];
var last = dateData[dateData.length-1];
where first is the earliest date and last is the latest date

A: Roko's answer worked for me, and +1. And Jose had a similar thought to me, +1...
...There's an easier and more robust way: .valueOf()
converting date string to number:
const dateAsNumber = new Date(dateAsString).valueOf()

JS has a built in method/function for calculating the number of milliseconds that have passed since a date; that's .valueOf(), which can be called on a Date object. So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.
After that, the normal .sort() works fine.  As shown below, for your convenience:
const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];

const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());

console.log(sortedArray);

Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.


text:
Q: Return the condition in the fitler? I have the following code to filter a Seq and return the error if nothing returned.
let s = nodes
        |> Seq.filter(fun (a, _, _, _) -> if a.ToLower().Contains(key1)) // condition 1
                                          then true
                                          else false // Error message should have Key1
        |> Seq.filter(....) // condition 2
        |> Seq.filter(....) // condition 3
        .....
        |> Seq.filter(function // condition N
           | _, Some date, _, _ -> date >= StartPeriod
           | _ -> false // put StartPeriod in the final message s is not empty before this step
           )

if Seq.isEmpty s
then sprintf "Failed by condition 1 (%s) or condition 2 (%s) .... or condition N (Date > %s)"
               key1, ...., (StartPeriod.ToShortDateSTring())
else ....

The final error message sprintf will contain all the filter conditions. Is it a way to let the code just return the ones (or just the last one) make the s empty?

Based on rmunn's answer, I modified it to return all the filters that contributed to empty the list.
let rec filterSeq filterList input msgs =
    match filterList with
    | [] -> input, msgs
    | (label, filter) :: filters ->
        let result = input |> Seq.filter filter
        if result |> Seq.isEmpty then
            printfn "The \"%s\" filter emptied out the input" label
            Seq.empty, (List.append msgs [label])
        else
            filterSeq filters result (List.append msgs [label])

let intFiltersWithLabels = [
    "Odd numbers", fun x -> x % 2 <> 0
    "Not divisible by 3", fun x -> x % 3 <> 0
    "Not divisible by 5", fun x -> x % 5 <> 0
    "Even numbers", fun x -> x % 2 = 0
    "Won't reach here", fun x -> x % 7 <> 0
]

{ 1..20 } |> filterSeq intFiltersWithLabels <| List.empty

A: What I would do is make a list of filters, and a recursive function that applies them one at a time. If the filter that was just applied returns an empty sequence, then stop, print the filter that just emptied your input, and return that empty sequence. Otherwise keep looping through the recursive function, taking the next filter in the list in turn, until either you end up with no input or you have run through your entire filter list and there's still some input remaining after passing all the filters.
Here's some sample code to illustrate what I mean. Notice how I've put labels in front of each filter function, so that I don't see output like "The <fun:filtersWithLabels@4> filter emptied out the input", but instead I see a sensible human-readable label for each filter.
let rec filterSeq filterList input =
    match filterList with
    | [] -> input
    | (label, filter) :: filters ->
        let result = input |> Seq.filter filter
        if result |> Seq.isEmpty then
            printfn "The \"%s\" filter emptied out the input" label
            Seq.empty
        else
            filterSeq filters result

let intFiltersWithLabels = [
    "Odd numbers", fun x -> x % 2 <> 0
    "Not divisible by 3", fun x -> x % 3 <> 0
    "Not divisible by 5", fun x -> x % 5 <> 0
    "Even numbers", fun x -> x % 2 = 0
    "Won't reach here", fun x -> x % 7 <> 0
]

{ 1..20 } |> filterSeq filtersWithLabels
// Prints: The "Even numbers" filter emptied out the input

If you want to print all filters until the one that emptied out the input, then you'd just move that printfn call up one line, outside the if expression. The fact that the recursion stops once the input is empty means that you won't see any printfn calls after the filter that emptied out the input.
Note that the way I wrote the function assumes that your original input will not be empty. If your original input was empty, then the function will credit the first filter for emptying the input and will print the first filter's label. You could solve that easily enough by checking for empty input before you check for empty result, but I didn't bother since this is just demo code. Just be aware of this if your real input could ever be empty in your actual use case.
Update: If you need to return a list of labels, not just print them, then make that a second parameter that you pass through your filterSeq function. Something like this:
let matchingFilters filterList input =
    let rec filterSeq filterList labelsSoFar input =
        match filterList with
        | [] -> input, []  // Note NO labels returned in this case!
        | (label, filter) :: filters ->
            let result = input |> Seq.filter filter
            if result |> Seq.isEmpty then
                Seq.empty, (label :: labelsSoFar)
            else
                filterSeq filters (label :: labelsSoFar) result
    let result, labels = filterSeq filterList [] input
    result, List.rev labels

let filtersWithLabels = [
    "Odd numbers", fun x -> x % 2 <> 0
    "Not divisible by 3", fun x -> x % 3 <> 0
    "Not divisible by 5", fun x -> x % 5 <> 0
    "Even numbers", fun x -> x % 2 = 0
    "Won't reach here", fun x -> x % 7 <> 0
]

{ 1..20 } |> matchingFilters filtersWithLabels
// Returns: ["Odd numbers"; "Not divisible by 3"; "Not divisible by 5"; "Even numbers"]

A couple things to note about this version of the function: it sounds like what you want is that if the filters run all the way through without emptying out the input, then you want NO filter labels to be returned. If I've misunderstood you, then replace the | [] -> input, [] line with | [] -> input, labelsSoFar to get all the labels in the output. Second thing to note is that I've changed the "shape" of this function: instead of returning a seq, it returns a 2-tuple of (result seq, list of filter labels). The list of filter labels will be empty if the result seq is not empty, but if the result seq ended up empty, then the list of filter labels will contain all the filters that were applied, not just all the filters that reduced the size of the input.
If what you really need is to check whether the size of the input is reduced and print only the labels of filters that filtered something out, then look at Funk's answer for how to check that, but be aware that Seq.length has to run through the entire original sequence and apply all the filters up to that point, each time. So it's a slow operation. If your input data set is large, then it's best to stick with the Seq.empty logic. Play around with it and decide what best fits your needs.

A: You can separate your logging / error handling code from your business logic by using a decorator.
First, our logger.
open System.Text

type Logger() =
    let sb = StringBuilder()
    member __.log msg =
        sprintf "Element doesn't contain %s ; " msg |> sb.Append |> ignore
    member __.getMessage() =
        sb.ToString()

Now, we want to wrap Seq.filter so it logs every time we filter out some element(s).
let filterBuilder (logger:Logger) msg f seq =
    let res = Seq.filter f seq
    if Seq.length seq > Seq.length res then logger.log msg
    res

Wrapping up with an example.
let logger = Logger()
let filterLog msg f seq = filterBuilder logger msg f seq

let seq = ["foo" ; "bar"]

let r =
    seq
    |> filterLog "f"
        (fun s -> s.Contains("f"))
    |> filterLog "o"
        (fun s -> s.Contains("o"))
    |> filterLog "b"
        (fun s -> s.Contains("b"))
    |> filterLog "a"
        (fun s -> s.Contains("a"))

logger.getMessage()

val it : string = "Element doesn't contain f ; Element doesn't contain b ; "

"bar" gets filtered out immediately, producing the first message. "foo" goes out the third time around. Also note the second and last pipe in the line don't log any message.


text:
Q: The Jackass Syndrome Some years ago, I watched an episode of the show Just Shoot Me! where one of characters used the phrase "The Jackass Syndrome" to describe the situation were two people who are quite similar in some ways can really hate each other (it was followed by a short scene in which, after two people met for the first time, each of them walked away muttering "jackass" in reference to the other person).
Over the years I have noticed that sometimes people that are indeed similar in some aspects (that they may not be aware of) can not get along with one another.  Is there another word for this situation?

A: There are phrases relevant to the phenomenon, but I'm not familiar with any single word.

We hate most in others what we fear most in ourselves.*

and

The pot calling the kettle black

are both applicable in situations wherein one person finds objectionable in another an attribute that s/he, too, possesses.
The psychological concept of projection is not unrelated. People who project generally deny feelings or desires within themselves and ascribe them to others.
*Rather than fear most, you might also hear see or even can't see.


text:
Q: Ember's titleBinding on a link-to helper breaks Jasmine tests I'm currently upgrading out Ember application to Ember 1.3.0 stable. I'm encountering the following issue in our Jasmine tests:
Error: Assertion Failed: You must use Ember.set() to access this property (of [object Object])
    at new Error (native)
    at Error.Ember.Error (http://localhost:8888/assets/rake-ember.js?body=true:837:23)
    at Object.Ember.assert (http://localhost:8888/assets/rake-ember.js?body=true:79:13)
    at Object.Ember.MANDATORY_SETTER_FUNCTION [as keywords] (http://localhost:8888/assets/rake-ember.js?body=true:3446:13)
    at withHelper (http://localhost:8888/assets/rake-ember.js?body=true:27796:40)
    at Object.eval (eval at <anonymous> (http://localhost:8888/assets/rake-handlebars.js?body=true:1500:23), <anonymous>:88:28)
    at Handlebars.VM.template (http://localhost:8888/assets/rake-handlebars.js?body=true:2214:33)
    at renderPartial (http://localhost:8888/assets/rake-ember.js?body=true:29502:7)
    at partialHelper (http://localhost:8888/assets/rake-ember.js?body=true:29479:9)
    at Object.eval (eval at <anonymous> (http://localhost:8888/assets/rake-handlebars.js?body=true:1500:23), <anonymous>:54:99)

It seems that this is happening on the following bit of code:

{{#link-to 'someroute' somemodel titleBinding="view.someproperty"}} Hi! {{/linkTo}}

We've narrowed it down to the titleBinding property above, when removing it - our tests can then continue to run. Anyone have any insight here?

A: Try to use new Binding syntax title=somepropery


text:
Q: Where can I find adventureworks2012_database.zip? I am looking for adventureworks2012_database.zip the mdf file and the log file. Once downloaded I will be attaching the mdf file. Version: Microsoft SQL Server 2012 Express. I downloaded SQLEXPRADV_x64_ENU.exe.

A: As mentioned by @AlexKudryashev in the comment section, you can download the AdventureWorks2012.bak file from the below link
https://github.com/Microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorks2012.bak
These information we can easily download from Googling itself.


text:
Q: How to stop printing few particular lines in python? I have a script for minimising chi2 function.
When I run the script it prints me a long lines of "J2000.0" and then gives the value of my calculation. I know these successive lines of "J2000.0" comes because of my determination of astrophysical coordinate system.
Now, I just want to get rid of printing the lines "J2000.0".
I tried the piece of code following:
import sys, os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__

blockPrint()

But it blocks even later on outputs which I want to read.
Can anyone please help me with a code which will help not to show only the lines containing "J2000.0"?

A: Some interpreters (like jupyter notebook) do not print on the console by default. So if you call sys.stdout = sys.__stdout__ you force printing to the console instead of the browser.
The belows code works for me.
import sys, os

class HandlePrint():

    def __init__(self):
        self.initial_stout = sys.stdout

    def blockPrint(self):
        sys.stdout = open(os.devnull, 'w')

    # Restore
    def resetPrint(self):
        sys.stdout = self.initial_stout

handle = HandlePrint()
handle.blockPrint()

print 'AAAA'

handle.resetPrint()
print 'BBBB'


text:
Q: How to make a transform of return type DataFrame => DataFrame which will give product of 2 column as value and column1_column2 as name Input
+-------+-------+----+-------
| id    |    a  |  b |    c
+-------+-------+----+-------
|  1    |  1    |  0 |    1
+-------+-------+----+-------

output
+-------+-------+----+-------+-------+-------+----+-------
| id    |    a  |  b |    c  |  a_b  | a_c  | b_c
+-------+-------+----+-------+-------+-------+----+-------
|  1    |  1    |  0 |    1  |  0    |  1   | 0
+-------+-------+----+-------+-------+-------+----+-------

basically I have a sequence of pair which contains Seq((a,b),(a,c),(b,c))
and thier values will be col(a)*col(b) , col(a)*col(c) col(b)*col(c) for new column
Like I know how to add them in dataFrame but not able to make a transform of return type DataFrame => DataFrame

A: Is this what you what?
Take a look at the API page. You will save yourself sometime :)
val df = Seq((1, 1, 0, 1))
  .toDF("id", "a", "b", "c")
  .withColumn("a_b", $"a" * $"b")
  .withColumn("a_c", $"a" * $"c")
  .withColumn("b_c", $"b" * $"c")

output ============
+---+---+---+---+---+---+---+
| id|  a|  b|  c|a_b|a_c|b_c|
+---+---+---+---+---+---+---+
|  1|  1|  0|  1|  0|  1|  0|
+---+---+---+---+---+---+---+


text:
Q: How to mock nested properties and objects and their functions? I have the code below which I would like to test, but I'm not sure whether it is possible or not.
I have EF repositories and they are put together to a class as public properties. I don't know exactly whether it is bad solution or not, but it is easier to manage the code and its dependencies. Only the testability is still a question.
Purpose of my test is injecting data via

administrationRepository.ModuleScreen.GetAll()

method and catch the result. I know that it can be tested once it is deployed, but I want the tests in build time in order to have as fast feedback as possible.
I went through questions and answers here, but I cannot find answers. In my code I got to the point where the property is set up, but when I call the administrationRepoMock.Object.ModuleScreen.GetAll() ReSharper offers only the methods coming from Entitiy Framework and not the Moq related functions.
It is possible what I want? If so, how? Is my design suitable for this? If not can you give me articles, urls where I can see examples?
Repository:
public interface IModuleScreen
{
    IEnumerable<DomainModel.Administration.ModuleScreen> GetAll();
}

public interface IAdministrationRepository
{
    IModuleScreen ModuleScreen { get; }
}

public partial class AdministrationRepository : IAdministrationRepository
{
    public virtual IModuleScreen ModuleScreen { get; private set; }

    public AdministrationRepository( IModuleScreen moduleScreen )
    {
        this.ModuleScreen = moduleScreen;
    }
}

Application:
public partial class DigitalLibraryApplication : IDigitalLibraryApplication
{
    private IAdministrationRepository _administrationRepository;
    private IMapper.IMapper.IMapper _mapper;
    private IDiLibApplicationHelper _dilibApplicationHelper;

    #region Ctor
    public DigitalLibraryApplication( IAdministrationRepository administrationRepository, IMapper.IMapper.IMapper mapper, IDiLibApplicationHelper diLibApplicationHelper)
    {
        _administrationRepository = administrationRepository;
        _mapper = mapper;
        _dilibApplicationHelper = diLibApplicationHelper;
    }
    #endregion

    public IEnumerable<ModuleScreenContract> GetModuleScreens()
    {
        //inject data here
        IEnumerable<ModuleScreen> result = _administrationRepository.ModuleScreen.GetAll();

        List<ModuleScreenContract> mappedResult = _mapper.MapModuleScreenToModuleScreenContracts(result);

        return mappedResult;
    }

}

Test code:
[Test]
public void ItCalls_ModuleRepository_Get_Method()
{
    List<SayusiAndo.DiLib.DomainModel.Administration.ModuleScreen> queryResult = new List<SayusiAndo.DiLib.DomainModel.Administration.ModuleScreen>()
    {
        new DomainModel.Administration.ModuleScreen()
        {
            Id = 100,
        },
    };

    var moduleScreenMock = new Mock<IModuleScreen>();
    moduleScreenMock.Setup(c => c.GetAll()).Returns(queryResult);

    administrationRepoMock.SetupProperty(c => c.ModuleScreen, moduleScreenMock.Object);

    var mapperMock = new Mock<IMapper.IMapper.IMapper>();
    var dilibApplicationHerlperMock = new Mock<IDiLibApplicationHelper>();

    IDigitalLibraryApplication app = new DigitalLibraryApplication( administrationRepoMock.Object, mapperMock.Object, dilibApplicationHerlperMock.Object );

    app.GetModules();
    //issue is here
    administrationRepoMock.Object.ModuleScreen.GetAll() //???
}

A: Here is a refactoring of your test that passes when run. You can update the pass criteria to suit you definition of a successful test.
[Test]
public void ItCalls_ModuleRepository_Get_Method() {
    // Arrange
    List<ModuleScreen> queryResult = new List<ModuleScreen>()
    {
        new ModuleScreen()
        {
            Id = 100,
        },
    };
    //Building mapped result from query to compare results later
    List<ModuleScreenContract> expectedMappedResult = queryResult
        .Select(m => new ModuleScreenContract { Id = m.Id })
        .ToList();

    var moduleScreenMock = new Mock<IModuleScreen>();
    moduleScreenMock
        .Setup(c => c.GetAll())
        .Returns(queryResult)
        .Verifiable();

    var administrationRepoMock = new Mock<IAdministrationRepository>();
    administrationRepoMock
        .Setup(c => c.ModuleScreen)
        .Returns(moduleScreenMock.Object)
        .Verifiable();

    var mapperMock = new Mock<IMapper>();
    mapperMock.Setup(c => c.MapModuleScreenToModuleScreenContracts(queryResult))
        .Returns(expectedMappedResult)
        .Verifiable();

    //NOTE: Not seeing this guy doing anything. What's its purpose
    var dilibApplicationHerlperMock = new Mock<IDiLibApplicationHelper>();

    IDigitalLibraryApplication app = new DigitalLibraryApplication(administrationRepoMock.Object, mapperMock.Object, dilibApplicationHerlperMock.Object);

    //Act (Call the method under test)
    var actualMappedResult = app.GetModuleScreens();

    //Assert
    //Verify that configured methods were actually called. If not, test will fail.
    moduleScreenMock.Verify();
    mapperMock.Verify();
    administrationRepoMock.Verify();

    //there should actually be a result.
    Assert.IsNotNull(actualMappedResult);
    //with items
    CollectionAssert.AllItemsAreNotNull(actualMappedResult.ToList());
    //There lengths should be equal
    Assert.AreEqual(queryResult.Count, actualMappedResult.Count());
    //And there should be a mapped object with the same id (Assumption)
    var expected = queryResult.First().Id;
    var actual = actualMappedResult.First().Id;
    Assert.AreEqual(expected, actual);
}


text:
Q: Calling a UDF (Sql server) from VB Access "Undefined function  in expression" I am trying to call a udf (SQL server) from Vb code in access. Connection to DB was successful and I am able to run queries on SQL server tables. However, when I try to call the UDF, it throws me an error saying undefined function.
Please see the code below:
Private Sub cmd_Login_Click()
    ' some code here
    Set db = CurrentDb()

    sSQL = "SELECT UserID FROM TBL_User_Login WHERE UserName = '" & cbo_User & "' AND Status = 0"
    Set recset = db.OpenRecordset(sSQL)

    recset.Close
    Set rectset = Nothing

    sSQL = "SELECT fn_validate_user(" & gb_UserId & ",'" & Hash(Me.txt_Password + cbo_User) & "') AS PasswordValid"
    Set recset = db.OpenRecordset(sSQL)  ' this is where i get error for undefined function fn_validate_user
    PasswordValid = recset("PasswordValid")

Can someone see if I am missing something here.

A: When you run a standard query in Access it is first processed by the Access Database Engine, even if that query refers to ODBC linked tables. Access can recognize Access user-defined functions (created with VBA) but it is not aware of SQL Server user-defined functions.
In order to use a SQL Server user-defined function you need to use a pass-through query. As the name suggests, it bypasses the Access Database Engine and sends the query directly to the remote database (via ODBC). The VBA code to do that would look something like this:
Dim db As DAO.Database, qdf As DAO.QueryDef, recset As DAO.Recordset
Dim sSQL As String, PasswordValid As Boolean
Set db = CurrentDb
sSQL = "SELECT fn_validate_user(" & gb_UserId & ",'" & Hash(Me.txt_Password + cbo_User) & "') AS PasswordValid"
Set qdf = db.CreateQueryDef("")
' get .Connect property from existing ODBC linked table
qdf.Connect = db.TableDefs("TBL_User_Login").Connect
qdf.ReturnsRecords = True
qdf.SQL = sSQL
Set recset = qdf.OpenRecordset(dbOpenSnapshot)
PasswordValid = recset.Fields("PasswordValid").Value
recset.Close
Set recset = Nothing
Set qdf = Nothing


text:
Q: sampled_softmax_loss not decreasing while sequence_loss_by_example does I am training an LSTM and using sampled_softmax_loss to compute the loss after each epoch (so many documents). I also compute the perplexity on a held-out set at the same time with sequence_loss_by_example.
The loss decreases for the first few epochs -- radically going down from 1-2. Then it just hangs around the same value (sometimes a little less; sometimes a little more). On the other hand, the perplexity does decrease consistently.
Why would loss stop decreasing while perplexity continues to go down? I expected both of them to decrease consistently.
Code looks something like this:
total_steps = 0
total_cost = 0.
for batch in train_epoch:
  total_steps += num_steps
  loss = tf.nn.sampled_softmax_loss(...)
  cost = tf.reduce_sum(loss) / batch_size
  total_cost += cost
  ...
  optimizer.apply_gradients(tf.gradients(cost, vars),...)
print("average loss = {}".format(total_cost / total_steps))

total_steps = 0
total_xentropy = 0.
for batch in valid_epoch:
  total_steps += num_steps
  loss = tf.nn.seq2seq.sequence_loss_by_example(...)
  total_xentropy += tf.reduce_sum(loss) / batch_size
print("perplexity = {}".format(np.exp(total_xentropy / total_steps))

A: This observed behavior was resolved by reducing the learning rate. After that change, training loss and validation perplexity moved (mostly) in tandem.


text:
Q: wordpress site working locally but not from the domain My wordpress site is working locally in my wamp server, this is hosted on an ec2 instance and domain is maintained in Route 53\cloudfare. The domain is working when i checked it using mxtoolbox. The site was working and live till the time i changed my host file in the server. I removed the host file entries accidentally thinking it is a dev site, however i restored it but still the site is not working and i am getting only the "TOO MANY REDIRECTS" error.  The following is the current windows host file details
#
127.0.0.1 localhost
::1 localhost

127.0.0.1 mydomain.com
::1 mydomain.com

I restarted the server and WAMP multiple times but it is not working.
The following is my virtualhost configuration
# Virtual Hosts
#

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride all
    Require all granted
  </Directory>
</VirtualHost>

#
<VirtualHost *:80>
    ServerName mydomain.com
    DocumentRoot "c:/wamp/www/sitefolder"
    <Directory  "c:/wamp/www/sitefolder/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride all
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName www.mydomain.com
    DocumentRoot "c:/wamp/www/sitefolder"
    <Directory  "c:/wamp/www/sitefolder/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride all
        Require all granted
    </Directory>
</VirtualHost>`

A: Clean your cache and browser history first, then try doing it below:
Open your wordpress admin panel --> Settings--> General --> Make sure it points to the correct domain. --> Save

Or go to the wp-config.php file (Try this if the first method fails / can't be accessed)
add:
define('WP_HOME','http://YourDomain.com');
define('WP_SITEURL','http://YourDomain.com');
or
Try to remove or rename default .htaccess

or
Try to disable the plugin (renaming the plugin folder in the "wp-content/plugin/plugin-folder-name"  will non-active that plugin. This might solve the problem if the constraints are due to the plugin)
That's a number of ways when I resolve the ERR_TOO_MANY_REDIRECTS problem. Goodluck


text:
Q: Simple websocket tutorial app not recieving 'chat' events despite being connected I am following along with a tutorial which demonstrates how to set up a very simple chat app with nodejs (express) and WebSockets. I can confirm that the connection between client and server is established but cannot figure out why the 'chat' event does not get processed by the server on the other side. I am using Socket.io 2.04 and my server is running out of Cloud9.  I am just trying to get a working example set up so I have the CSS, HTML, and script in the same file for the webpage. Any idea what I am doing wrong? I've spent enough hours fiddling with this that I could really use some expert advice...
    // server side code

        var express =require("express");
        var app = express();

        var socket = require('socket.io');

        var bodyParser = require("body-parser");

        app.use(bodyParser.json());

        app.use(function(req, res, next) {
          res.header("Access-Control-Allow-Origin", "*");
          res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
          next();
        });

        app.use(express.static(__dirname + "/public"));

       app.get("/websockets", function(req, res) {
       res.render("websockets.ejs");
});

var server = app.listen(process.env.PORT, process.env.IP, function(){
    console.log("SERVER IS RUNNING!");
});

// Socket setup
var io = socket(server);

io.on('connection', function(socket){

    console.log('made socket connection', socket.id);

    // Handle chat event
    socket.on('chat', function(data){
        console.log(data);
        io.sockets.emit('chat', data);
    });

});

and below is the page sent to the client

        <meta charset="utf-8">
        <title>WebSockets 101</title>

           <input id="handle" type="text" placeholder="Handle"/>
           <input id="message" type="text" placeholder="Message"/>
           <button id="send">Send</button>


text:
Q: Applying query filter like the one in codelab (Cloud Firestore) is not working I'm using firestore for my project to store data , my issue is that i can not
filter data just the way codelab filter does .The result of that query gives me the whole collections docs which means the filter is not working.
I've tried many workarounds and find out that only when I cascade whereEqualto()
methods in one line I get what I want of specific docs , but this approach (cascading whereEqualTo inline) is not flexible when giving the user a way to filter searches.I just want to know why that code is not working for me.
// Does not work
Query query = mFirestore.collection("restaurants");

    // Category (equality filter)
    if (filters.hasCategory()) {
        query = query.whereEqualTo("category", filters.getCategory());
    }

    // City (equality filter)
    if (filters.hasCity()) {
        query = query.whereEqualTo("city", filters.getCity());
    }

This works:
   query.whereEqualTo("realEstateType", realEstateType).whereEqualTo("propertyStatus", propertyStatus).whereEqualTo("propertyPhysicalStatus", propertyPhysicalConditionS).addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            }
        }
    });

A: I figured it out ,It seems that I was not assigning to query object the filter as follows:
query = query.whereEqualTo("fieldPath" , ...);


text:
Q: Why is elasticsearch python parallel_bulk using so much memory? I have a pretty simple indexing task that reads line-delimited json from a file, does simple manipulation of incoming data, and then indexes using elasticsearch parallel_bulk. I am using python3, ES 6.7 on the server (2 nodes, 16G each).
When I run the code below, I see pretty steadily-increasing memory usage until the machine starts swapping. The data are not huge (<500 characters per line), so I am surprised by the memory usage.
I have done a little tuning of queue size, thread count, and chunk size and there is quite a bit of sensitivity. I'd like to optimize indexing speed on the client (I have done the work on the server side to speed things up) while keeping memory to a reasonable amount.
Code:
def yield_records(idx='sra_bulk_test_biosample'):
    for fname in list(filter(lambda f: f.endswith('.json.gz'),os.listdir())):
        print(fname)
        with gzip.open(fname, 'r') as f:
            n = 0
            for line in f:
                n+=1
                if(n % 10000 == 0):
                    print(n)
                res = json.loads(line)
                yield {
                    "_op_type": "index",                   # this is the default
                    "_index": idx,
                    "_type": 'doc',                        # no more doc types after es_6
                    "_id": res['accession'], # extract _id from record
                    "_source": res                         # use entire record as "source"
                }

def main():
    for success, info in parallel_bulk(es, actions = yield_records(), chunk_size=1000, queue_size=4, thread_count=4, yield_ok = False):
        if(not success):
            print(info)

if __name__ == '__main__':
    main()


text: Q: Building a classifier using Parzen window Considering the application of the Parzen window method to model a probability density function in a binary classification problem, and assume a training set where the 4 points {−5, −1, 1, 5} belong to C1 and the 2 points {1, 2} belong to C2, a Gaussian kernel with a bandwidth equal to 1, what is the impact of having an occurrence (in this case, x=1) belonging to both classes?


text:
Q: ffmpeg - Get max Y value of video stream is it possible to get the max Y value (of a pixel) of a video stream assuming the video is in YCbCr or YUV ?
if so, what would be the process ?
Thanks.

A: Use
ffmpeg -i video -vf "signalstats,metadata=print:key=lavfi.signalstats.YMAX:file=logfile:direct=1" -an -f null -
This will print the maximum luma value seen in each frame to logfile.


text:
Q: Alexa Voice Serice SSL Handshake when packaged as a jar I am running into a SSL handshake issue when I package up the sample-java-client(from alexa-avs-sample-app https://github.com/alexa/alexa-avs-sample-app ) into a fat jar and run it as part of a new "test java" project which contains only a main function that invokes AVSApp(DeviceConfig config) when starting up.
I am using the nodejs Companion Service and NONE of the paths in config.json are relative.
Wireshark logs show an Encrypted Alert as below:

When running my "test java", I also tried to force it to use the SSL trust-store used by the by alexa-avs-sample-app using -Djavax.net.ssl.trustStore and pointed it to the absolute path of the certs folder in the sample-java-client but still no luck.
Hope someone can help!!!

A: I was able to fix this issue by specifying the appropriate ALPN version and bootclasspath arguments in the startup script.


text:
Q: Generating data from a hypothetical model Let say I have below model
$y_{i,t} = 1 + X_1 + X_2 + {\gamma}_i + \epsilon_{i,t}, \epsilon_{i,t} \sim N \left(0, 1 \right), {\gamma}_i \sim N \left(0, \gamma \right)$
Here, the panel it is represented by suffix $i$ and there is time dependent measures for each $i$ which is represented by $t$
Another constraint is that, within each panel all observations have correlation coefficient as 0.65.
Based on this model, I need to generate 100 datapoints for further analysis.
Can you please help on pointer how I can I generate data based on above data generation process using R?

A: This answer assumes the standard deviation of the Normal distribution you're generating $\gamma_i$ from is NOT $\gamma$.
You could generate data by defining a few function in R similar to this:
epsilonGenerator <- function() {
    eps_i = rnorm(1, mean=0, sd=1)
    return eps_i
}

gammaGenerator <- function(stdev) {
    gamma_i = rnorm(1, mean=0, sd=stdev)
    return gamma_i
}

dataGenerator <- function(X1,X2) {
    y_i = 1 + X1 + X2 + gammaGenerator(stdev) + epsilonGenerator()
    return y_i
}

Then simply call dataGenerator for each each pair of X1 and X2


text:
Q: How to create moment 1 map (also known as velocity filed or velocity map) using python? I need to create a moment 1 map using Python and I cannot use SpectralCube package to produce it (.moment(order=1) method). The problem is I've stucked and basically everything I write is just a garbage. Does anyone have an experience with moment maps and can help with that?
I'm working with cubes and I handle fits using astropy.
Just to make you sure what I mean I'll put an explanation from CASA documentation:
Moments explained

A: Stackoverflow isn't the best place to ask this question; you'd likely benefit from asking on an astronomy-specific forum.
That said, the most likely reason your moment-1 map would look like garbage is if you include a lot of noise.  Since the first moment is the intensity-weighted coordinate, if you have a large cube with a lot of noisy pixels, you may get only noise out.  A good approach is to mask the data before computing the moments.  If you use only pixels with significant detections above the noise, the moment maps will generally come out clean.


text:
Q: OOP - Non-standard syntax, use & to create a pointer to member (Visual Studio C++) I have had problems with my program, for some reason Visual Studio shows the following message when I compile:
'opuntia::menu': non-standard syntax; use '&' to create a pointer to the member

I've seen that this error is related to omitting some (), but I think this is not the case. Any ideas to fix this problem?
opuntia.h
#pragma once

class opuntia{
public:
    int op;
    void menu();

};

opuntia.cpp
#include "opuntia.h"
#include <iostream>
using namespace std;

void opuntia::menu() {
    do {
        cout << "\n \t OPUNTIA: CUIDADO DE AGAVÁCEAS, CACTÁCEAS Y CRASULÁCEAS" << endl;
        cout << "\t Registra tu planta y planea sus cuidados \n" << endl;
        cout << "\t 1. Registro" << endl;
        cout << "\t 2. Registro manual" << endl;
        cout << "\t 3. Miscelánea" << endl;
        cout << "\t 0. Salir \n" << endl;
        cin >> op;
        cin.ignore();

        switch (op) {
        case 1:
            cout << "Registro" << endl;
            break;
        case 2:
            cout << "Registro manual" << endl;
            break;
        case 3:
            cout << "Miscelánea" << endl;
            break;
        case 0:
            cout << "Goodbye" << endl;
            break;
        default:
            cout << "Elige una opción válida" << endl;
            break;
        }
    } while (menu != 0);
}

main.cpp
#include <iostream>
#include <locale.h>
#include "opuntia.h"
using namespace std;

int main() {
    setlocale(LC_CTYPE, "Spanish");

    opuntia ejecutar;
    ejecutar.menu();

    return 0;
}

A: Within the member function menu in the condition of the do-while statement
 do {
     //...
 } while (menu != 0);

you are using the name of the member function menu. It seems you mean
 do {
     //...
 } while (op != 0);


text:
Q: Div not being centered when using margin: auto; (Bootstrap) I have a working example website from the bootstrap template website and was analysing the code to understand how they created it.  Namely how they centered the text on the first page located here. The code for that snipplet is,

                   ...

                   ...

So then I noticed that the m-auto was doing the centering. However, when I attempt to create it from scratch for myself and create this basic code,

 YOU CAN DO IT

 I should be centered

It doesn't center at all.
What am I forgetting here?
I would suspect that the container gets centered inside it's parent, which takes up the page.

A: you have copied the code but styles not included for them if guess correctly. anyway, I have corrected please try this one.

 YOU CAN DO IT

 I should be centered

A: Is this what you're after?
Version 1
https://codepen.io/panchroma/pen/YdEWZJ
HTML

 YOU CAN DO IT

 I should be centered

CSS
#frontpage{
  background-color:pink;
  height: 100vh;
  width: 100vw;
}
.col-8{
  border:1px solid grey;
  margin-left:auto !important;
  margin-right:auto !important;
  text-align:center;
}

Version 2
This also centers the text vertically
https://codepen.io/panchroma/pen/KbygzX
HTML

YOU CAN DO IT

 I should be centered

CSS
#frontpage{
  background-color:pink;
  height: 100vh;
  width: 100vw;
}
.col-8{
  margin-left:auto !important;
  margin-right:auto !important;
  text-align:center;
}

.row.vert-align{
  position: absolute;
  top: 50%;
  left:50%;
  -ms-transform: translateY(-50%);
  transform: translate(-50%, -50%);
}


text:
Q: Laravel - Checking passwords before manually logging in I'm getting problem with manually logging in users using Auth::loginUsingId
. Before I do that I need to check if password matches and there is my problem. Password comparision is always returning false;
That's how I save password to DB:
    $user = User::create([
        'password' => Hash::make(Input::get('password')),
    ]);

And that's how I try to compare these two passwords
$u = User::where('username', $username)->first();
$password = Hash::make(Input::get('password'));
var_dump($u->password == $password);

And this is returning false, and I don't know where the problem is.
EDIT:
In DB field varchar is 70 char long, hash is 60 characters long
Ok I've noticed: that every time Hash::make gives another string from my password. How it's even possible? I mean how then Auth::attempt works?

A: Try the following:
$user = User::where('username', $username)->first();

if (Hash::check(Input::get('password'), $user->password))
{
    // The passwords match...
}

A: Please Try of following
use Illuminate\Support\Facades\Hash;
``
$user = User::where('username', $username)->first();
$password = Input::get('password');
if (!Hash::check($password, $user->password)) {
  // correct
}
// wrong


text:
Q: Requested registry access is not allowed. even with signed exe and admin Privileged in manifest I am trying to access HKEY_LOCAL_MACHINE registry,
This is the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    </requestedPrivileges>
    </security>
</trustInfo>

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
    <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
    <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
    <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
    <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    </application>
</compatibility>

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
</application>
<dependency>
    <dependentAssembly>
    <assemblyIdentity
        type="win32"
        name="Microsoft.Windows.Common-Controls"
        version="6.0.0.0"
        processorArchitecture="*"
        publicKeyToken="6595b64144ccf1df"
        language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>

I also sign the executable with Test Certificate
this is the function:
static string GetDeviceGuid()
{
    const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
    RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey, RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey);
    string[] keyNames = regAdapters.GetSubKeyNames();
    string devGuid = "";
    foreach (string x in keyNames)
    {
        RegistryKey regAdapter = regAdapters.OpenSubKey(x);
        object id = regAdapter.GetValue("ComponentId");
        if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
    }
    return devGuid;
}

this is the result:
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name)
at TestTun.TunTap.GetDeviceGuid()

what should I do to read the registry without Security Exception

A: I found the problem but I don't know why access to this address is impossible
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\Properties

Registry Error on Regedit
Visual Studio Debug
I fixed my code with regex
static string GetDeviceGuid()
    {
        const string AdapterKey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
        RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey(AdapterKey);
        string[] keyNames = regAdapters.GetSubKeyNames();
        foreach (string x in keyNames) {
            Console.WriteLine(x);
        }
        string devGuid = "";
        Regex rx = new Regex(@"\d{4}",
      RegexOptions.Compiled | RegexOptions.IgnoreCase);
        foreach (string x in keyNames)
        {
            if (!rx.IsMatch(x)) {
                continue;
            }
            RegistryKey regAdapter = regAdapters.OpenSubKey(x);
            object id = regAdapter.GetValue("ComponentId");
            if (id != null && id.ToString() == "tap0901") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
        }
        return devGuid;
    }


text:
Q: QUERY function with OR condition > Query Table, Select E where C contains Cell1 *OR* Cell2 limit 1 I am attempting to use OR operator in the following Query.
The idea is that the cell will display mileage from a branch. The user can select a branch at either C12  or E12, and the cell will display the mileage from the table. My next move would be to make an if statement but I'm wondering if its possible to make it work like this
=iferror(query(BranchesHrsKms, "Select E where C matches'"&C12&"' or C matches'"&E12&"'limit 1",0),"")`

What the current code does: Basically just runs this part
C matches'"&E12&"'limit 1",0),"")

But only when there is something in C12.
Any guidance appreciated
Update:
It can work with If and ISBLANK
=IF(ISBLANK(C16)=FALSE, iferror(query(BranchesHrsKms,
"Select E where C matches'"&C16&"' limit 1",0),""),
iferror(query(BranchesHrsKms, "Select E where C matches'"&E16&"' limit 1",0),""))

Copy of sheet to play with: https://docs.google.com/spreadsheets/d/1fn5xzWi47xcgnQiDk5v_t1UDtIF6gHKGB4WoblbT3-Y/edit#gid=686684908

A: try:
=IFERROR(QUERY(BranchesHrsKms,
 "select E
  where C matches '.*"&TEXTJOIN(".*|.*", 1, C12, E12)&".*'
  limit 1", ))

update:
=INDEX(IFERROR(1/(1/(
 IFNA(VLOOKUP(C10:C23, BranchCodes!C:E, 3, ))+
 IFNA(VLOOKUP(E10:E23, BranchCodes!C:E, 3, ))))))

A: There is a lack of space before limit
=iferror(query(BranchesHrsKms, "Select E where C contains '"&C12&"' or C contains '"&E12&"' limit 1",0),"")


text:
Q: PlayFramework ScalaTest Testing webpages with selenium I'm trying to make some test with selenium in my app but I get this error

[error] - com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector: ':checked' error: Invalid selector: *:checked).] sourceName=[http://localhost:9001/assets/javascripts/../lib/jquery/jquery.js] line=[1206] lineSource=[null] lineOffset=[0]

This is my code
class CheckPage extends PlaySpec with OneServerPerSuite with OneBrowserPerSuite with HtmlUnitFactory {

  implicit override lazy val app: FakeApplication =
    FakeApplication(
      additionalConfiguration = Map("ehcacheplugin" -> "disabled")
    )

  implicit override lazy val port = 9001

  "The OneBrowserPerTest trait" must {
    "provide a web driver" in {
      go to (s"http://localhost:$port/login")
      pageTitle mustBe "Archacrom"
      eventually { pageTitle mustBe "scalatest" }
    }
  }

}

A: There is a problem when running HtmlUnit tests with Play 2.4.x and jQuery 2.1.4. More specifically, there is a problem with HtmlUnit 2.18 and jQuery 2.1.4 or bigger. This was reported here:
https://github.com/playframework/playframework/issues/5050
And later, fixed for Play 2.5.0 here:
https://github.com/playframework/playframework/pull/5786
And here:
https://github.com/playframework/scalatestplus-play/pull/40
The later is available at scalatestplus-play 1.5.0. The easiest fix is to manually upgrade HtmlUnit version to 2.20:
libraryDependencies += "net.sourceforge.htmlunit" % "htmlunit" % "2.20"

Or, of course, you can migrate your application to Play 2.5.0 which already uses the updated version of HtmlUnit.


text:
Q: Custom Build Activity to Label Branches after a successful build on TFS I am new to Custombuild activities and I was looking for a way to change the label on a branch after a build is successful, I was reading up on System.Activities namespace. Can anybody guide me in the right direction. I just want to add a label according to the version of the build to my branch.
Thanks.

A: TFS Build by default automatically creates labels for you with the build number.


text:
Q: How to show buttons with user authentication in AngularJS? Currently I am working on my master project. My application is online portfolio management. User can register on app and create profiles. Now i want to give Edit and Delete buttons on the profile view. But just the users who have created the profile are able to see this buttons. For example, if i am a user of app then only i can see the edit and delete buttons on my profile and i can only see the other user's profile.
I am new in AngularJS. It looks easy but still did not work for me. I have a different views of view profile and edit profile. But i have just one controller for both of it.
This is how my view profile code looks like,
HTML

{{profile.firstname}} {{profile.lastname}}

            <button class="btn-success btn-lg" type="button" data-ng-click="profilesCtrl.modalUpdate('lg', profile)">Edit</button>
            <button class="btn-danger btn-lg" type="button" data-ng-click="profilesCtrl.remove(profile)">

            </button>

Controller
profilesApp.controller('ProfilesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Profiles', '$modal', '$log',
    function($scope, $stateParams, $location, Authentication, Profiles, $modal, $log) {

        this.authentication = Authentication;

        // Find a list of Profiles
        this.profiles = Profiles.query();

        // open a modal window to view single profile
        this.modalview = function(size, selectedProfile) {

            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/view-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;

                    console.log(profile);

                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };
                },
                size: size,
                resolve: {
                    profile: function() {
                        return selectedProfile;
                    }
                }
            });

            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        // open a modal window to update single profile
        this.modalUpdate = function(size, selectedProfile) {

            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/edit-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;

                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };

                    $scope.cancel = function() {
                        $modalInstance.dismiss('cancel');
                    };
                },
                size: size
            });

            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        // Remove existing Profile
        this.remove = function(profile) {
            if (profile) {
                profile.$remove();

                for (var i in this.profiles) {
                    if (this.profiles[i] === profile) {
                        this.profiles.splice(i, 1);
                    }
                }
            } else {
                this.profile.$remove(function() {
                    $location.path('modules/profiles/views/list-profiles.client.view.html');
                });
            }
        };

        // Update existing Profile
        this.update = function(updatedProfile) {
            var profile = updatedProfile;

            profile.$update(function() {}, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

    }
]);

Please suggest me some way, how can i fix this issue? Any help would appreciated.

A: you can use a directive like this:
<button access-level="canEdit">Edit</button>

and your directive is bound to accessLevel:
angular.module("app")
    .directive('accessLevel', ['AuthService', 'AUTH_EVENTS', function (authService, authEvents) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var accessLevel;

                attrs.$observe('accessLevel', function (acl) {
                    if (acl) {
                        accessLevel = acl;
                        updateCss();
                    }
                });

                $scope.$on("auth-change", function (event, data) {
                    switch (data) {
                        case authEvents.logoutSuccess:
                        case authEvents.loginSuccess:
                            updateCss();
                            break;
                        case authEvents.notAuthorized:
                        default:

                    }

                });

                function updateCss() {
                    if (accessLevel) {
                        if (!authService.isAuthorized(accessLevel)) {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.hide();
                                    break;
                                default:
                                    element.attr("disabled", "disabled");
                                    break;
                            }
                        } else {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.show();
                                    break;
                                default:
                                    element.removeAttr("disabled");
                                    break;
                            }
                        }
                    }
                }
            }
        }

    }]);

this is a little bit more than what you need, but gives you an idea what you can achieve. (and you have to write your auth service etc.)
as example here is a part of my auth service:
angular.module('app')
    .factory("AuthService", ["$rootScope", "$http", "AuthSession", "AUTH_EVENTS", function ($rootScope, $http, AuthSession, AUTH_EVENTS) {

       AuthSession.load();

       $rootScope.$on('$stateChangeStart', function (event, nextState) {
            if (nextState.data && nextState.data.accessLevel && !service.isAuthorized(nextState.data.accessLevel)) {
                event.preventDefault();
                $rootScope.$broadcast('auth-change', AUTH_EVENTS.loginRequired, nextState.name);
            }
        });

        var service = {
            login: function (credentials) {
                return $http
                            .post('/api/account/login', credentials)
                            .success(function (data, status) {
                                if ((status < 200 || status >= 300) && data.length >= 1) {
                                    $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                                    return;
                                }

                                AuthSession.create(data.AccessToken, data.User);
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginSuccess);
                            }).error(function (data, status) {
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                            });
            },
            logout: function () {
                AuthSession.destroy();
                $rootScope.$broadcast("auth-change", AUTH_EVENTS.logoutSuccess);
            },
            isAuthenticated: function () {
                return (AuthSession.token !== null);
            },
            isAuthorized: function (accessLevel) {
                if (!accessLevel) return true;

                return (this.isAuthenticated() && AuthSession.user.UserRoles.indexOf(accessLevel) !== -1);
            }

        }
        return service;
    }]);

this service retrieves a bearer token from the server and stores it in the authsession service. the user roles are also stored beside of other user information. since the backend is also secured, one who changes the user roles on the client, can't write to the backend. (everything on client side is just for the look and feel of the user)

A: Two ways :

*

*Once the profile is created, let the isProfileCreated (you need to make one) column in user details table be updated. On angular load, call and check whether is profile created. use ng-show to show (edit and delete button)if it is true.

*Or else, if you are going to edit, anyways you need to get the profile details from the table. in that case, let your server send a false if no profile is created or an json object if created.
In your controller use
if(angular.isObject(profile)){
        $scope.showeditbutton = true;

        $scope.showdeletebutton = true;

}


text:
Q: How to program conditional Values across two dataframes in R? I have a couple of data frames that I am attempting to use the values from one data frame to populate the cells of a column in a separate data frame.
They are as follows:
df1 <- data.frame(A = c("Doug", "Michele", "Steve", "John", "Pete", "David"))
df1$B <- 0
df2 <- data.frame(A = c("Doug", "Steve", "John"), B = c(1,1,0))

And the result that I am looking for is:
df1 <- data.frame(A = c("Doug", "Michele", "Steve", "John", "Pete", "David"), B = c(1,0,1,0,0,0))

I tried the following approach, but only Doug has a 1 value while the others are 0.
df1$B[(df1$A == df2$A & df2$B == 1)] <- 1

When attempting an approach with %in%, Doug has a 1 value but John does as well when Steve should be the one to receive the 1.
 df1$B[(df1$A %in% df2$A & df2$B == 1)] <- 1

Am I missing something here that would resolve this issue?
Thanks in advance

A: An option with data.table would be to join on the 'A' column and assign the 'B' from the second dataset (i.B) to 'B' in first data
library(data.table)
setDT(df1)[df2, B := i.B, on = .(A)]

-output
df1
#          A B
#1:    Doug 1
#2: Michele 0
#3:   Steve 1
#4:    John 0
#5:    Pete 0
#6:   David 0


text:
Q: Qt platform plugin Error in runnig container. how to show open cv output image with docker container on linux? I wanna create a docker image on windows and image base [in docker file] for docker image would be linux os. My program uses the open-cv program which its output image has to be shown with CV2.imshow(). but after running container, I get this error.
please help to fix it.
qt.qpa.xcb: could not connect to display
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/usr/local/lib/python3.9/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb.

A: I had this same issue and none of the solutions I looked up solved the issue for me. I even used xhost + and imshow still did not work.
I was using the image tensorflow/tensorflow:2.7.0-gpu as my base image for my project. Seems like the package libsm6 is missing for some reason, and doing apt install libsm6 made it work.
Hope this helped!

A: I also had this issue. The one solution that finally worked was to install an earlier version of opencv-python. The version I had originally installed was 4.6.0.66. I uninstalled opencv pip uninstall opencv-python in docker and reinstalled RUN pip install opencv-python==4.1.2.30 in the dockerfile.


text:
Q: Javascript quiz control flow Can someone tell me what is wrong with the following 5 exercises? I got the other 95 Exercises right but these keep coming up as wrong on repl.
Can you tell me why these Exercises are wrong?
What is the error in the 5 exercises?
I was told an error in 1 exercise can throw error in the rest.

// Exercise One: In this exercise you will create a variable called 'aboutMe'
// This variable should be assigned a new object
// In this object create three key:value pairs
// The keys should be: 'name', 'city', 'favoriteAnimal'
// The values should be strings associated with the keys.
// return the variable 'aboutMe'

var aboutMe = {
  name: 'Brian',
  city: 'Columbus',
  favoriteAnimal: 'Dog'
};

return (aboutMe);
}

function exerciseTwo(animal) {
  // Exercise Two: In this exercise you will be given an object called 'animal'
  // Create a new variable called 'animalName'
  // Accessing the animal object, assign the 'animalName' variable to the 'latinName' key on the object.
  // return the animalName variable.
}

let animalName = {
  animalName: latinName
}
return (animalName)

function exerciseThree(userObject) {
  // Exercise Three: In this exercise you will be given an object called 'userObject'
  // The phonne number for this user is incorrect!
  // reassign the 'phoneNumber' key to the value: '(951)867-5309'
  // return the userObject

  userObject: phoneNumber.(951) 867 - 5309;
}

function exerciseFour(value) {
  let greaterThanFive = true;
  // In this exercise, you will be given a variable, it will be called: value
  // You will also be given a variable named: greaterThanFive
  // Using an 'if' statement check to see if the value is greater than 5. If it is, re-assign greaterThanFive the boolean true.
  if (value > 5) {
    value = greaterThanFive
  }

  // Please write your answer in the line above.
  return greaterThanFive;
}

function exerciseFive(name) {
  let isSondra = false;
  // In this exercise, you will be given a variable, it will be called: name
  // You will also be given a variable named: isSondra
  // Using an 'if' statement check to see if the name is equal to the string 'Sondra'. If it is, re-assign isSondra the boolean true.
  if (name = isSondra) {
    return true
  } else {
    false
  }
  // Please write your answer in the line above.
  return isSondra;
}

A: To get you started....
In the first exercise, you have an extra closing curly brace after the return. Additionally, you can only use return within a function, which your code is not inside of. Instead, you'd have to have the variable logged to the console or shown as an alert or displayed in some other way.

var aboutMe = {
  name:'Brian',
  city:'Columbus',
  favoriteAnimal:'Dog'
};

console.log(aboutMe);


text:
Q: C generate 100 random numbers In C I need to generate 100 random numbers and then sort them in descending order. As of now, I have this, and it is an absolute mess. I can tell I am going about it all wrong but am not experienced enough to actually be able to write this in a sane manner. Can anyone help?
/*100 random numbers in range 1-10*/
/*sorted in descending order*/
#include <stdio.h>
void random(char *nums, int count);

int main(void) {
    int random_num, count;
    char nums[100];
    for(count = 0; count < 100; count++) {
        random(&nums, count);
    }

    for(count = 0; count < 100; count++) {
        printf("%d\t", nums[count]);
    }

    return 0;
}

void random(char *nums, int count) {
    int random_data = fopen("/dev/random", "r");
    nums[count] = fread[random_data];
}

A: please, call rand() on stdlib.h:
#include <stdlib.h>

int main(void) {
    int random_num, count;

    srand(time(NULL));
    char nums[100];
    for(count = 0; count < 100; count++) {
        nums[count] = rand();
    }

    for(count = 0; count < 100; count++) {
        printf("%d\t", nums[count]);
    }

    return 0;
}

A: 1 random number: first srand(time(0)), then using rand() to generate the number you want
2 sort: using qsort(array, n, sizeof(int), comp);
 //here comp let the number in desc order
int  comp(const void*a,const void*b)
{
    return *(int*)b-*(int*)a;
}

both of  them need < stdlib.h>

A: Try this code, I have also included code for sorting the values in descending order.
/*100 random numbers in range 1-10*/
/*Sorted in descending order*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

void sorting(char *numbers) /* Sorting in descending order */
{
    int i,j,temp;
    for(i=1;i<100;i++)
    {
        for(j=0;j<100-i;j++)
        {
            if(numbers[j] < numbers[j+1])
            {
                temp = numbers[j+1];
                numbers[j+1] = numbers[j];
                numbers[j] = temp;
            }
        }
    }
}

int main(void) {
    int random_num, count;

    srand(time(NULL));
    char nums[100];
    for(count = 0; count < 100; count++) {
        /* Mod by 11 as we need range 1-10 */
        nums[count] = rand() % 11;
    }
    /* Sorting in descending order */
    sorting(nums);

    printf("Printing values after sorting.\n");
    for(count = 0; count < 100; count++) {
        printf("%d\n", nums[count]);
    }
    return 0;
}


text:
Q: How can I use AppleScript to find disabled menu items? I have an AppleScript script that will find all of the menu items from all of the menu bar menus. I've filtered out each separator, so I have just the commands, and now I'd like to find out how to find out which menu items are disabled. Does anybody know how I could do that?
Update:
Here's the code I have to get the names of each menu command. It's working fine, and I tried to get the menu items that were enabled in the getAppMenuItems, but it just returned all the menu items, missing values too.
set appName to "Script Editor"
set allMenus to {}
set everything to {}
set onlyEnabled to {}

tell application "System Events" to tell process appName
    set allMenus to name of every menu of menu bar 1
end tell

repeat with menuName in allMenus
    set the end of everything to strings of getAppMenuItems(appName, menuName, onlyEnabled)
end repeat

on getAppMenuItems(appProcess, appMenus, enabledItems)
    tell application "System Events" to tell process appProcess

        (*
        # Get all menu items
        set theItems to every menu item of menu appMenus of menu bar 1

        repeat with i from 1 to number of items in theItems
            set thisItem to item i of theItems

            if thisItem is not enabled then
                log ("Item:          " & name of thisItem & " is enabled")
                set the end of enabledItems to the name of thisItem
            end if
        end repeat
    *)

        return name of every menu item of menu appMenus of menu bar 1
    end tell
end getAppMenuItems

# From the commented part of the 'getAppMenuItems' function above.
# When that part of the function is uncommented, I just get everything,
#   missing values and all
onlyEnabled

# Edit Menu
item 4 of everything

(* Outputs: Half of these items are not enabled

    {"Undo", "Redo", "Cut", "Copy", "Paste", "Paste and Match Style", "Paste Reference", "Delete", "Select All", "Complete", "Find", "Spelling and Grammar", "Substitutions", "Transformations", "Speech", "Start Dictation…", "Emoji & Symbols"} *)

A: In order to get the properties of a menu item, you first need to get a reference to that menu item.  You would then need to go through the various menu items and build lists or records of those that meet your criteria, so that the references can be used as needed.
From the comments, general-purpose handlers to click at or get menu references by using a list of the menu hierarchy would serve your purpose, so those would be something like:
on run -- examples
   #clickMenu at {"Finder", "View", 10, "Name"} -- note that there are 2 "Clean Up" items
   set menuRef to getMenuReference for {"Script Editor", "File", "New"}
   log result
   clickMenu at menuRef -- clickMenu at {"Script Editor", "File", "New"} can also be used
end run

to getMenuReference for menuList -- Get a reference to a menu item in an application's main menu.
   (*
      The menu hierarchy is described in the menuList parameter.
      The last menu item doesn't need to be exact, just close enough for a match.
      Menu items can also be integer indexes (separators are counted).
      When using an index, note that menus can contain dynamic or hidden items.
         parameters: menuList [list] -
                        item 1 [text]: the application name
                        item 2 [text]: the menu bar item name
                        item(s) 3+ [text or integer]: the (sub)menu item(s)
         returns the reference or missing value
      *)
   try
      set itemCount to (count menuList) -- needs to be at least {application, menu, item}
      if itemCount < 3 then error "menuReference handler:  the menu item list contains too few items"
      set {appName, menuName} to items 1 thru 2 of menuList
      set {menuItem, found} to {last item of menuList, false}
      tell application appName to activate
      tell application "System Events" -- set up the menu path
         set appName to (name of application processes whose frontmost is true) as text -- handle different process names
         set menuPath to menu menuName of menu bar item menuName of menu bar 1 of application process appName
         if itemCount > 3 then repeat with i from 3 to (itemCount - 1) -- add sub menu items
            set menuName to item i of menuList
            if class of menuName is integer then set menuName to item menuName of (get name of menu items of menuPath)
            set menuPath to menu (menuName as text) of menu item (menuName as text) of menuPath
         end repeat
         if class of menuItem is not integer then -- the target menu item
            repeat with anItem in (get name of menu items of menuPath)
               if anItem begins with (menuItem as text) then -- match a partial string (also 'contains', etc)
                  set {menuItem, found} to {anItem, true}
                  exit repeat
               end if
            end repeat
            if not found then error "menuReference handler:  menu item " & quoted form of menuItem & " not found"
         end if
         return menu item menuItem of menuPath
      end tell
   on error errorMessage number errorNumber
      log errorMessage
      # error errorMessage number errorNumber -- uncomment to pass error up the chain
   end try
   return missing value
end getMenuReference

to clickMenu at menuItem -- Click a menu item in an application's main menu.
   (*
      The menuItem can be a reference to the menu item or a list of the menu hierarchy.
         parameters: menuItem [reference or list] - see the getMenuReference handler
         returns true if successful, false otherwise
   *)
   try
      if class of menuItem is list then -- get a reference
         set menuItem to getMenuReference for menuItem
         if menuItem is missing value then error "clickMenu handler:  the menu item was not found"
      end if
      tell application "System Events"
         # log (get properties of menuItem)
         if (enabled of menuItem) then -- filter for desired property
            click menuItem
            delay 0.25
            return true -- success
         end if
      end tell
   on error errorMessage number errorNumber
      log errorMessage
      # error errorMessage number errorNumber -- uncomment to pass error up the chain
   end try
   return false -- failure
end clickMenu


text:
Q: Ошибка Android Studio - Connection to the Internet denied как исправить Установил Android Studio создал проект и попробовал его собрать, но ничего не получилось, вывело ошибку:
Connection to the Internet denied.

дальше там есть ссылка на сайт Android Developers попробовал сделать так как там написано, но тоже не получилось. Насколько я понял Брэндмауер виндовс блокирует это подключение. Как можно исправить эту ошибку чтобы подключиться для синхронизации?

A: Решил проблему таким способом:

*

*Закрыл Android Studio.

*Перешел в папку пользователя в проводнике Windows (может у кого-то будет другая папка)

*Удалил папку .gradle

*Запустил Android Studio и дал ей возможность загрузить все зависимости снова.

Все работает теперь нормально.


text:
Q: Xcode malloc error - stack looks weird I'm using cocos2d and I load all my sprites and scenes before my game. However, once loaded, it seems if I click to start the game too quickly I get this crash:
malloc: *** error for object 0x65cdbb4: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

So I did what it suggested, recreated the crash and the stack shows this:
#0 0x9033df7e in malloc_error_break ()
#1 0x9033f128 in szone_error ()
#2 0x9033f29b in free_list_checksum_botch ()
#3 0x9024c186 in tiny_malloc_from_free_list ()
#4 0x9024b2a1 in szone_malloc_should_clear ()
#5 0x9024b148 in malloc_zone_malloc ()
#6 0x90249218 in malloc ()
#7 0x97145617 in operator new ()
#8 0x03adc43f in llvm::User::operator new ()
#9 0x03aab18f in llvm::CastInst::Create ()
#10 0x0341394c in llvm::BitcodeReader::ParseFunctionBody ()
#11 0x034164fe in llvm::BitcodeReader::materializeFunction ()
#12 0x0cd72472 in glvmAddOperation ()
#13 0x0cd4c752 in gleBuildVertexSubmitFunc ()
#14 0x0cd74e0c in cvmsModularBuilder ()
#15 0x03392a67 in cvmsCompBuildModularFunction ()
#16 0x033970a8 in cvmsServerBuildModularFunction ()
#17 0x03394e26 in CVMSBuildModularFunction ()
#18 0x032b0c26 in glvm_deferred_build_modular ()
#19 0x03310404 in glvmDoWork ()
#20 0x902747fd in _pthread_start ()
#21 0x90274682 in thread_start ()

None of these functions listed are mine, any ideas? Thanks.


text:
Q: How to put Powershell code into c# code using pipeline Here is what I use in Powershell:
get-vm -computername CN | select -ExpandProperty networkadapters | select macaddress, ipaddresses | Select-string -pattern "some mac"

Here is what i have in C# so far:
public static string GetIPFromMac(string mac, string Server)
{
    Command command1 = new Command("get-vm");
    command1.Parameters.Add("ComputerName", Server);
    Command command = new Command("select");
    command.Parameters.Add("ExpandProperty", "networkadapter");
    Command command3 = new Command("select");
    command3.Parameters.Add("macaddress");
    command3.Parameters.Add("ipaddresses");
    Command command4 = new Command("select-string");
    command4.Parameters.Add("pattern", mac.Replace("-", ""));

    string ip = string.Empty;
    using(Pipeline hostPipeline = GetRunspace().CreatePipeline())
    {

        hostPipeline.Commands.Add(command1);
        hostPipeline.Commands.Add(command);
        hostPipeline.Commands.Add(command3);
        hostPipeline.Commands.Add(command4);
        ip = hostPipeline.Invoke()[0].ToString().Trim().Split(new []{' '})[1];
        hostPipeline.Stop();
    }
    return ip;
}

On this line I get the next error:
ip = hostPipeline.Invoke()[0].ToString().Trim().Split(new char[] { ' ' })[1];

Error:

An unhandled exception of type
  'System.Management.Automation.ParameterBindingException' occurred in
  System.Management.Automation.dll

I think the problem is with the way I read the two "Select" Commands in, so my question is how would I fix that?

A: Change the following lines:
Command command3 = new Command("select");
command3.Parameters.Add("macaddress");
command3.Parameters.Add("ipaddresses");

to
Command command3 = new Command("select");
command3.Parameters.Add("Property", new string[] { "macaddress", "ipaddresses" });


text:
Q: Display total number of rows in footer of devexpress grid I need to display total number of rows in a grid, in footer.
I have made the footer enable by setting : "this.gridViewTradePoster.OptionsView.ShowFooter = true;", but don't know how to set the text on the footer so that it displays total number of records/row displayed.
i am using Devexpress grid. And it is using C# (.net).
If anyone can help.
Thank you

A: Please take a look at this page on the DevExpress Support Center for information on how to do this.


text:
Q: How to get certain keys from the array of objects and put them in state? I am training to do requests to server with json.placeholder. The result of request is the array of objects with many keys.
For example the array of objects
[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
and so on ...

But I don't need all these keys. Only to take some of them, for example name, username and id and put it in my State.
How to do that properly?

A: TL;DR
response = [ { "id": 1, "name": "Leanne Graham", ...}, {...}, ...]
cleanResponse = response.map(user => return {name: user.name, contact: user.email})

Here, with .map we return an object that has two property : name and contact.
We set name to user.name and contact to user.email
Anwser
I don't know much about ReactJS, but your anwser only require basic javascript :
Array.Map
You can use .map on an array to convert its elements :
nameArray= [ "George", "Alice", "Portevent" ]

presentationArray = nameArray.map(name => "My name is " + name)
// presentationArray  = [ "My name is George", "My name is Alice", "My name is Portevent" ]

nameArray.map will iterate on each element. name will be equal to "George", then "Alice" etc...
Foreach element, it will be replaced with "My name is " + name (remember, name will have each different value).
Note : .map doesn't change the initial array, it just create another array (so we save it inside presentationArray
A more advanced use of map :
numbers = [1, 2, 3]

function tenToPower(n) {
    return 10 ** n
}

numbers.map(number => tenToPower) // [10, 100, 1000]

numbers.map(number => {
   if (number < 3) return "Failed"
   else return "Valid"
}) // ["Failed", "Failed", "Valid"]

A:          const item = data.map((user) => {
             if(user.username === 'Bret'){
                  setName(user.name);
                  setUserName(user.username);
                  setId(user.id)
             }
         })


text:
Q: Blackberry - HttpConnection using EDGE net I want to do an httpconnection for a blackberry application. Im using url like
http://ip:port/prueba.php;deviceside=true
If i want to use it into the device by wifi, i add interface=wifi.
But i dont know why it doesn't connect via EDGE. is there anything else i can do? I hear about something that you have sign your application but i dont understand that.

A: Use : ";deviceside=true;ConnectionUID="+ srTCP.getUid()
 private ServiceRecord srTCP;
 private void init()
    {

        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.getRecords();

        for (int i = 0; i < records.length; i++)
        {
            ServiceRecord myRecord = records[i];
            String cid, uid;

            if (myRecord.isValid() && !myRecord.isDisabled())
            {
                cid = myRecord.getCid().toLowerCase();
                uid = myRecord.getUid().toLowerCase();
                if (cid.indexOf(WPTCP_STR) != -1 && uid.indexOf(WIFI_STR) == -1 && uid.indexOf(MMS_STR) == -1)
                {
                    String httpProxyAddress = getDataString(myRecord, BYTE_PROXY_ADDRESS);
                    if ((httpProxyAddress == null) || StringUtils.isBlank(httpProxyAddress.trim()))
                    {
                        srTCP = myRecord;
                    }
                }
            }
      }
  }


text:
Q: Problem with Select a valid choice. That choice is not one of the available choices in my form.py I have a class StudentsForm:
class StudentsForm(ModelForm):

    def __init__(self, *args, **kwargs):
        students  = kwargs.pop('students')
        course    = kwargs.pop('course')
        super().__init__(*args, **kwargs)

        CHOICE_LIST = [('', '----')]
        i = 1
        for itm in students:
            CHOICE_LIST.append((i, itm))
            i += 1

        self.fields['students'].choices = CHOICE_LIST
        self.fields['students'].initial = ['']
        self.fields['course'].choices = [(1, course), (2, '----'
                )]
        self.fields['course'].initial = [1]

    class Meta:

        model = StudCourse
        fields = (
            'course',
            'students',
            )

        widgets = {
            'course': forms.Select(attrs={'class': 'form-control',
                    'placeholder': 'Select course',
                    'style': 'color: crimson; background-color:ivory;'
                    }),
            'students': forms.SelectMultiple(attrs={'class': 'form-control'
                    , 'placeholder': 'Select students',
                    'style': 'color: crimson; background-color:ivory;'
                    }),
            }

my view.py
def test(request):
    #team = get_team(request)

    # here the second students is a query set of model Student, 2nd course is an object of model      #Course
    form = StudentsForm(students=students, course=course)

    if request.method == 'POST':
        form = StudentsForm(request.POST, students=students, course=course)
        if form.is_valid():
            form.save()
            return redirect('home')

    if team.exists():
        return render(request, 'app/students_goal_form.html', {'form':form})

my students_goal_form.html
{% block content %}

&nbsp

                <form action="" method="post">
                    {% csrf_token %}
                    {{ form.as_p }}
                    <button type="submit" class="btn btn-success">
                     Save
                    </button>
                </form>

&nbsp

&nbsp

&nbsp

{% endblock %}

It works correctly without adding students=students, course=course to form (without modifying __init__ ) , but I need to filter query set in case of students and also need a specific (only one) course. I have also modified __init__ in form to add possibility to choose nothing.
my model StudCourse:
class StudCourse(models.Model):
    course    = models.ForeignKey(Course, verbose_name='Course', on_delete = models.CASCADE, related_name='+', blank=True, null=True, help_text=u'You can choose specific course or group of students')
    students = models.ManyToManyField(Student, null=True,  blank=True, symmetrical=False, related_name='student_name')

    def get_students(self):
        return "\n ".join([p.end_user_id for p in self.students.all()])

    def __str__(self):
        return 'Title: : ' + self.course

Why I have an Error when in view the form is validating: Select a valid choice. That choice is not one of the available choices.
How to modify my form which accept to choose nothing?
[UPDATE] my Student model:
class Student(models.Model):
    name                = models.CharField(max_length=30, verbose_name='Name')
    lastname            = models.CharField(max_length=30, verbose_name='Lastname')
    status              = models.BooleanField(default=False, verbose_name='Is Active?')

    def __str__(self):
        return self.name + ' ' + self.lastname

in view I set to the form next:
students = Student.objects.filter(status=true)

A: The code above doesn't explain in detail how do you generate content for the students variable that you pass to the form, but I guess the issue could be there.
The list of choices for the student's field is generated in a way that in each pair (id, object) the id is a number in a sequence but not the real id of an object.
        CHOICE_LIST = [('', '----')]
        i = 1
        for itm in students:
            CHOICE_LIST.append((i, itm))
            i += 1

        self.fields['students'].choices = CHOICE_LIST

instead, you should use the primary key as an id to reflect the structure of your database
CHOICE_LIST.append((itm.pk, itm))


text:
Q: Loop through a struct containing enum entries in C I am attempting to write a method that loops through a struct and returns an enum variable. The said method is lookup_transitions() and this is my code: (I used enum as a pointer to my functions because I was not sure how to effectively use int pointers in this case).
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

enum ret_codes { ok, fail};
//forward declaration of functions
enum ret_codes s0_state(int);
enum ret_codes s1_state(int);
enum ret_codes s2_state(int);

/* pointer to the functions*/
enum ret_codes (* state[])(int) =
{
  s0_state,
  s1_state,
  s2_state
};

enum state_codes { s0, s1, s2 };

struct transition {
  enum state_codes src_state;
  enum ret_codes   ret_code;
  enum state_codes dst_state;
};

struct transition state_transitions[] = {
  {s0, ok,     s1},
  {s0, fail,   s0},
  {s1, ok,     s2},
  {s1, fail,   s0}};

//function definitions
//these were previously returning int, changed to enum ret_codes
      enum ret_codes s0_state(int digit){
      puts ("\nState s0 (RESET):");
      puts ("(alarm inactive)");
      puts ("Enter password to arm alarm, or 'e' to cancel: ");
      if (digit != 5){
        return fail;
      }
      return ok;
    }
    enum ret_codes s1_state(int digit){
      puts ("\nState s1:\n");
      if (digit != 6)
        return fail;
      return ok;
    }
    enum ret_codes s2_state(int digit){
      puts ("\nState s2, (alarm inactive): \n");
      if (digit != 3)
        return fail;
      return ok;
    }

    enum state_codes lookup_transitions(enum state_codes sc, enum ret_codes myRC){
        //should return s0,s1 or s2
        enum state_codes result = sc;
        for (int i = 0; i < sizeof(state_transitions)/sizeof(state_transitions[0]); ++i)
        {
            if (state_transitions[i].src_state == sc && state_transitions[i].ret_code == myRC)
            {
                result =  state_transitions[i].dst_state;
            }
        }
        return result;
    }

    #define S0_STATE s0

    int main(int argc, char *argv[] ){
        int input;

          enum state_codes curr_state = S0_STATE;

          enum ret_codes (* state_fun)(int);
          state_fun = state[curr_state]; //start at s0
          enum ret_codes rc;

          while (true){
            input = getchar();
            if( input != 'e') {
                rc = state_fun(input);
                curr_state = lookup_transitions(curr_state, rc);//should return s0,s1 or s2
            }
            input = getchar();
          }
      puts ("\nProgram completed successfully");
      return 0;
    }

My lookup_transitions() method does not seem to be correctly iterating the array. can you help me figure this out?