text:
Q: Dynamic class type from file data I have some JSON files in which I define objects of various types.  The types are given as a field within the objects.  I want to load the file and for each JSON object, create a new class of that type and pass the rest of the JSON data to its constructor.
The issue is that I'd rather not have a huge case statement matching the type and creating an object of that type.  Here are some of the possibilities I've considered:

*

*Reflection.  I don't know too much about it, but my understanding is that it might allow me to create a class in this manner.  While I'm aware C++ doesn't provide this capability natively, I've seen a few libraries such as this one that might provide such functionality.

*Create an enum of class types.  Create a template function that takes a type parameter from this enum and creates an object of that type.  Use something like smart_enum to convert the string field.
Option 2 seems like a good one but I haven't been able to get this working.  I've done extensive googling, but no luck.  Does anyone know how I might go about doing this, or if there is a better option which I have not considered?  Apologies if this has been answered elsewhere, perhaps under a term which I do not know; I have spent quite a lot of time trying to solve this problem and had no luck.
Please let me know if I can provide any additional information, and thank you.
Edit: here's an example of what I've tried to get option 2 working.
#include <iostream>
#include <string>

enum class Animals {
    Dog,
    Cat
};

class Dog {
public:
    std::string sound{"woof"};
};

class Cat {
public:
    std::string sound{"meow"};
};

template<Animals animal> void make_sound() {
    new animal();
    cout << animal.sound << endl;
}

int main() {
    make_sound<Animals::Dog>();
    make_sound<Animals::Cat>();

    std::exit(1);
}

A: There are a number of C++ JSON libraries that support mapping polymorphic or std::variant types based on some type selection strategy, which could rely on a type marker (e.g. "cat", "dog"), or alternatively the presence or absence of members. Lacking reflection, such libraries rely on traits. Typically the library provides built-in traits specializations for standard library types such as std::chrono::duration and std::vector, and supports custom specializations for user types. Some libraries offer convenience macros that can be used to generate the code for custom specializations.
The library ThorsSerializer has an example of encoding/decoding JSON for polymorphic types.
The library jsoncons has examples of encoding/decoding JSON for polymorphic types and the std::variant type

A: As noted in the comments, #1 is out, C++ lacks reflection (until P0194 gets adopted).
#2 still requires a big ol' switch block because you're still have to switch on a run-time type ID.
So, I'll propose #3: use a template to generate all those case statements you don't want to have to write (well, a map anyway).
This is the final code, which uses JSON for Modern C++ library for JSON parsing since that's the one that's available from godbolt :).
template <typename T, typename... Args>
struct option {
    using type = T;
    static_assert(std::is_constructible_v<T, Args...>, "constructor doesn't exist");

    static T create(const nlohmann::json& json) {
        return create_impl(json, std::index_sequence_for<Args...>{});
    }

    template <size_t... Is>
    static T create_impl(const nlohmann::json& json, std::index_sequence<Is...>) {
        return { json[Is].get<Args>()... };
    }
};

template <typename...>
struct to_string {
    using type = std::string_view;
};

template <typename... Options>
struct factory_builder {
    using variant = std::variant<typename Options::type...>;

    factory_builder(typename to_string<Options>::type... names)
        : map { std::pair<std::string, std::function<variant(const nlohmann::json&)>> { names, [](const nlohmann::json& json) -> variant { return Options::create(json); } }... }
    { }

    variant operator ()(const nlohmann::json& json) {
        return map[json["type"].get<std::string>()](json["args"]);
    }

    std::map<std::string, std::function<variant(const nlohmann::json&)>> map;
};

Usage:
using factory_t = factory_builder<
    option<Dog, double, std::string>, // Dog & its constructor argument types
    option<Cat, int>                  // Cat & its constructor argument types
>;
factory_t factory("Dog", "Cat");      // String type identifiers for each option
auto my_object = factory( /* ... your JSON */ );

It assumes the JSON takes this form, where "type" is one of the string identifiers passed to the factory_builder constructor, and "args" is a list of arguments:
{
    "type": "TheTypeIdentifier",
    "args": [42, "whatever", false]
}

Demo: https://godbolt.org/z/3qfP9G

That's a lot of code, so let's break it down. First problem you need to solve is how to actually have a variable that can be more than one type, since C++ is strongly typed. C++17 provides std::variant for this, so we'll use that.
using result = std::variant<Dog, Cat>;
result example_result = Dog {};
example_result = Cat {};

Next, you need a way to generically describe, at compile time, how to construct an object: I used a simple struct with a template argument for the type, and a variable number of template arguments for the types going into that constructor:
template <typename T, typename... Args>
struct options;

Given a option<T, Args...>, how do you take a JSON array and pass those items to the constructor? With the nlohmann library, if you have a parsed JSON array called my_array and want to get index n and store it in an object of type T:
my_array[n].get<T>(); // accesses the array, converts, and returns a T&

To do that generically, I took the parameter pack of arguments and converted it into a parameter pack of increasing integers (0, 1, 2...) using std::index_sequence. Then I expanded the two parameter packs into T and n in the example above. It was convenient to put all this inside a static method of option<T, Args...>:
template <typename T, typename... Args>
struct option {
    /* ... */

    static T create(const nlohmann::json& json) {
        return create_impl(json, std::index_sequence_for<Args...>{});
    }

    template <size_t... Is>
    static T create_impl(const nlohmann::json& json, std::index_sequence<Is...>) {
        return { json[Is].get<Args>()... };
    }
};

That solves extracting arguments and calling a constructor for one type generically. Next problem is, how do you generate a function that switches on the type name and calls one of those Option<T, ...>::create functions?
For this solution, I used a map from strings to an std::function that takes JSON in and outputs our variant type:
template <typename... Options>
struct factory_builder {
    // note: using a typedef "type" in options<T, Args...> that just points to T
    using variant = std::variant<typename Options::type...>;

    factory_builder(/* one string for each type */)
    {
        // TODO: populate map
    }

    variant operator ()(const nlohmann::json& json) {
        return map[json["type"].get<std::string>()](json["args"]);
    }

    std::map<std::string, std::function<variant(const nlohmann::json&)>> map;
};

Now we just need to build that map. First, a detour: how do you ask for one string per type in a parameter pack? I used a helper type that takes a template argument and has a typedef that is always a string. Expand into that, and you get a parameter pack of string types:
template <typename...>
struct to_string {
    using type = std::string_view;
};

Then, to populate the map, you can do that right from the initializer list:
using map_t = std::map<std::string, std::function<variant(const nlohmann::json&)>>;
factory_builder(...) : map {
    typename map_t::value_type {
        names,
        [](const nlohmann::json& json) -> variant {
            return Options::create(json);
        }
    }...
}

This is a little confusing, but it's expanding into something like this:
factory_builder(std::string dogName, std::string catName) : map {
    std::pair<...> { dogName, [](auto& j) { return Dog(...); } },
    std::pair<...> { catName, [](auto& j) { return Cat(...); } }
}

And that's it! Hope it helps.


text:
Q: Angular JS, Jquery, dropdown not populating the complex json data Please have a look at the plunker http://plnkr.co/edit/y9hvyxOkdq1jPDKjHgYM?p=preview

*

*Can any one help me to fix the code so that I can populate the customer dropdown with the options as per the data?

*Right now I am trying to assign option value property of the dropdown to json "value"
( "value": "CU18257"). This "CU18257" will be given to dropdown option value.
For example (*)
Is there any possibility for me to assign this json "value" to  some custom property like customerlable for the dropdown options, so that Angular js would generate the dropdown option values. and with that I can access simply customers[2], etc in my controller.
For example I want the dropdown to be poplated as follows:
<option value="0" customerlable= "CU18257"> </option>
<option value="1" customerlable= "----CU18257"> </option>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print from remote server using CUPS and Lpr lets start step by step.
Devices:
REMOTESERVER = ubuntu server 12.04 (ip 95.211.132.49);
LOCALSERVER = ubuntu server 12.04 (public ip 195.91.166.141);
PRINTER_1 = TSC TTP-343C;
PRINTER_2 = HP LaserJet Pro M201dw;
Description:
LOCALSERVER (private ip 192.168.0.1) work as gateway. Both PRINTERS connected to the network by ethernet cable, so the have private ips (192.168.10.38 and 192.168.10.39). REMOTESERVER - apache + php server.
Objective: I want/need print two files from REMOTESERVER by click one button. First file should print on PRINTER_1, second file on PRINTER_2.
What Im doing: Im install CUPS (https://www.cups.org/) and LPR (http://www.wikiwand.com/en/Line_Printer_Daemon_protocol). After that Im add printers to CUPS. lpstat -p -d show both printers. Next I print two files: 1.png by command:
lpr -P ttp 1.png

and 2.png by command:
lpr -P hp 2.png

so its work.
Problem: I cant print files by lpr command from REMOTEHOST. On REMOTESERVER I cant add printers because they have only a private ip. I have no idea how add printers on REMOTESERVER. I also tried add ip of LOCALSERVER and forwards port to one of printers, but it isn't help. I tried use http\ipp\socket and another protocol when I add printers in CUPS. So question is How I can add printer on REMOTESERVER.
Thx very much and sorry for my english.


text:
Q: error with hyperref and the krantz class I'm using the krantz.cls to write a book, and I ran into an error with the hyperref package. Here is a minimal example (test.tex):
\documentclass{krantz}
\usepackage{hyperref}
\begin{document}
\chapter{Introduction}
\end{document}

When I compile it with pdflatex test.tex, I get this error:
Runaway argument?
{Introduction}]{[}{Introduction}]{Introduction} \end {document}
! File ended while scanning use of \Hy@org@chapter.
<inserted text>
                \par
<*> test.tex

Without hyperref, it compiles fine. I appreciate if anyone can tell me why this happens and how to fix it.
$ pdflatex --version
pdfTeX 3.1415926-2.4-1.40.13 (TeX Live 2012/Debian)
kpathsea version 6.1.0
Copyright 2012 Peter Breitenlohner (eTeX)/Han The Thanh (pdfTeX).
There is NO warranty.  Redistribution of this software is
covered by the terms of both the pdfTeX copyright and
the Lesser GNU General Public License.
For more information about these matters, see the file
named COPYING and the pdfTeX source.
Primary author of pdfTeX: Peter Breitenlohner (eTeX)/Han The Thanh (pdfTeX).
Compiled with libpng 1.2.49; using libpng 1.2.49
Compiled with zlib 1.2.7; using zlib 1.2.7
Compiled with poppler version 0.20.4

$ head `kpsewhich hyperref.sty` -n 34 | tail -n 4
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\ProvidesPackage{hyperref}
  [2012/05/13 v6.82q %
  Hypertext links for LaTeX]

Update
I contacted the author of this LaTeX class and the problem was solved. See the corrected krantz.cls.


text:
Q: MariaDb / Mysql Rank function- One partition ranked before the other I have two rank functions and one works as expected. However, the other one ranks one partition before the other partitions. Here's the code:
 if(count1>=3 and count2>=2 and count3>=2,
rank() over (partition by examdateID, sClass Order By orderColumn desc), count(StudentID) over (partition by examdateID, sClass)) as ClassRank ,

if(count1>=3 and count2>=2 and count3>=2,
 rank() over (partition by examDateID, sClass, stream Order By orderColumn desc), count(StudentID) over (partition by examdateID, sClass, stream )) as StreamRank from...

I have two streams and I expect the classRank will give a rank of all students across the streams. However all in stream 1 are ranked before stream 2 ...3.. etc
if the condition (count1,2,3) is not met, I just expect the total number of students
could you point me in the right direction?
I'm using MariaDb 10.4.10
Edit::
I've realized that the problem is the if... when I remove it, ranking is ok
Maybe rank() can't be put inside if... still need suggestions


text:
Q: Allow late (past a lock period) downvote reversals without reputation credit The topic itself has been widely discussed and it seems that a solution I like has been broached more than once.  I'm not sure what is the current prevailing opinion, though.
Let's rehash a possible scenario.  I downvoted an answer that seems to be wrong and posted my own one.  Later, after my downvote was already locked, I realized that I read that question wrong and it didn't deserve a downvote.  At such time I can either leave unjust downvote there or do an unneeded edit just to allow myself to undo my downvote.
My initial actions could be construed as tactical downvoting and, from what I understand, the lock is specifically preventing such behavior by not allowing downvoters to reclaim their lost reputation points.
The bottom line here is that a person (for whatever reason) regrets his/her downvote and wants to do something about it.
So, what about a suggestion to allow late downvote removals without crediting back the rep.  This logic is similar to bounty handling.
Is it worth a consideration or are we better off with a trivial edit just to circumvent the lock?


text:
Q: 17.10 personal folder location I have Ubuntu installed and running fine on my 500gb SSD and I want to set up my second hard drive. But I don't just want a new location in my file manager (nemo) I want to set the hard drive location to /home/$USER/Videos
that way when I go to that location and open it the hard drive with all my media on it opens. the second hard drive is NTFS for the moment but that can change if necessary, it doesn't have to be visible to windows but I would prefer it if possible.
I've looked into several things including Ubuntu tweak but it inst around for 17.10 and also this Change default user folders path?

A: I mount a 2nd disk with the following line in /etc/fstab: (Note: Your UUID= value Will Be Different - use lsblk --output="NAME,FSTYPE,MOUNTPOINT,LABEL,UUID")
UUID=362254e8-2b99-442d-8ad9-4a348bc08032 /home/w3/mnt/SP ext4 nodev,nosuid,noexec,noauto,user,rw 0 0

I have to use the noauto, and issue mount ~/mnt/SP after login, because I have an encrypted $HOME, and /home/w3/mnt/SP does not exist earlier.
I also don't want the disk mounted at all times. Since you do, you could put this in your ~/.bashrc:
if [[ $(mountpoint -q $HOME/Videos; echo $?) != 0 ]] ;
then
    mount $HOME/Videos
fi

A: OK guys and gals hear goes. I'm not good at these so bear with.

*

*open terminal and enter (thank to waltinator for the command)
lsblk --output="NAME,FSTYPE,MOUNTPOINT,LABEL,UUID"

*this gave my harddrive id 9A14124414122433

*run command (just in case)
sudo cp /etc/fstab /etc/fstab.backup

*edit fstab and add
UUID=9A14124414122433 /media/Videos ntfs defaults 0 0

*deleted my /home/user/Videos folder and rebooted

*run command
rm -rf ~/Videos && ln -s /media/Videos ~/Videos


text:
Q: Why sDNA error is out of memory? Can it run in 64-bit?
I use sDNA to prepare road network, but as in the pic, the error is out of memory, what can I do with it? And I notice that sDNA is running in 32-bit mode, can it run in 64-bit?

A: A 32 bit application is inherently limited to using about 3.5GB of memory - with a network of half a million links it is possible you have run out.
If you enable 64 bit ArcGIS background processing (geoprocessing -> options -> enable background processing, I think) then sDNA will run in 64 bit mode instead, enabling you to use all the memory available on your machine. Check the output, as you already have, to check this works. In some versions of ArcGIS it will still run in 32 bit mode in the background - if this is the case you will need to install ArcGIS 64 bit background processing first - this is usually on your install disk but needs installing separately to ArcGIS.
(Unfortunately as you take this route you will find there is a bug in ArcGIS whereby although 64 bit background processes will run fine, you can't monitor progress! For this reason, with large networks you may prefer to use the QGIS interface - for which you would need to convert your data to shapefiles first - or the command line interface. See the sDNA manual for more details on either of these.)


text:
Q: Is it possible to retrieve data from users via Withings API? I want to automatize the monitoring of some users of Withings products, like gathering informations (weight, heartbeats etc.) every x time.
For that purpose I tried to interact with the Withing API, using java (OAuth with a scribe class).
I tried the WithingsExample class and tried on my account. Everything goes well, I can access my data, but the problem is that I have to re-authenticate every time, which has no sense in my project since I try to automatize the data collect, my users wouldn't even access their account (I would manage it for them).
Is that possible to authenticate just one time, and then be able to retrieve data from my users several times ?

A: you can make use of the subscibe function, documented here:
http://oauth.withings.com/api/doc#api-Notification-notify_subscribe

A: Yes this is possible.  You simply need to store the access token (http://oauth.withings.com/api received from completing step 3).  This token is your key to the user's data.  If you persist it somewhere, in your program before authenticating again you can check if you already have an access token for the user.  If you do, just pull that token and use it instead of authenticating.


text:
Q: saving selected data in cookie failed I have some dropdowns to choose between a few dates. The issue is that after choosing the date, the user needs to log in. After that, all the session of member date refreshing the choosing date lost (is not only the js, a lot of date coming because of the relevant choosing.
I tried to save the selected item in a cookie, but it didn't work.
I have the session of the index
private int getIndexFromSession()
{
    int index = 0;
    if (Session["DTF_selectedIndex"] != null)
    {
        index = (int)Session["DTF_selectedIndex"];
        // Session.Remove("DTF_selectedIndex");
        if (index > dateTimeFilter.Items.Count)
            index = 0;
    }
    return index;
}

the drop down in .aspx:
<asp:DropDownList ID="dateTimeFilter" runat="server"  OnSelectedIndexChanged="dateTimeFilter_SelectedIndexChanged"

and .cs
protected void dateTimeFilter_SelectedIndexChanged(object sender, EventArgs e)
{
    //   showsDatalistPanel.Visible = true;
    DropDownList ddl = (DropDownList)sender;

    if (ddl.SelectedValue != "0")
    {
        Session["DTF_selectedIndex"] = ddl.SelectedValue;
        HttpCookie cookie = new HttpCookie("DTF_selectedIndex", ddl.SelectedValue);
        DateTime now = DateTime.Now;

        cookie.Expires = now.AddMinutes(10);

        Response.Cookies.Add(cookie);
    }
}

and the request
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["DTF_selectedIndex"] != null)
    {
        Session["DTF_selectedIndex"] = Request.Cookies["DTF_selectedIndex"];
    }
}


text:
Q: UILabel int array concatenation Ok I want to read an array of int's concatenated into a UILabel Here's the code I have. I cannot figure out how to concat them as I am building a number filter system and want to display remaining numbers in a UILabel.
-(IBAction)print {
    for (int i = 0; i <= 100; i++){
        if(myArray[i] != 0){
          printScreen.text = [NSString stringWithFormat:@"%i,",myArray[i]];
        }
    }
}

A: Try this code:
-(IBAction)print {
    NSMutableString *text = [[NSMutableString alloc] init];
    for (int i = 0; i <= 100; i++) {
        if(myArray[i] != 0) {
            [text appendFormat:@"%d,", myArray[i]];
        }
    }
    printScreen.text = text;
}


text:
Q: JS (или jQuery) как добавить функцию в div? Написала такую функцию
var arr = [[1,2],[3,4]]
function tableEditor(someId, arr){
var string = "
";
for (var i = 0; i < arr.length; i++) {
    string += "
";
        for (var j = 0; j < arr.length; j++) {
            string += ""  + arr[i][j] + " 	" ;
        }
    string += "
";
    }
    string  +="
";
    document.write(string);
   }
tableEditor('someId', arr);

Как теперь мне ее добавить в div? div создан в HTML. Думала что то типа $("div").append($(tableEditor)), но это не работает.

A: В вашем коде document.write(string); заменяет все содержимое страницы на html из string. Замените эту строчку на return string; и тогда можно будет вставлять сгенерированный html в любой элемент, например, так $("#block").append(tableEditor(arr)).
Кстати, непонятно, для чего нужен аргумент someId, если в функции он не используется, поэтому я его убрал.

var arr = [
  [1, 2],
  [3, 4]
]

function tableEditor(arr) {
  var string = "
";
  for (var i = 0; i < arr.length; i++) {
    string += "
";
    for (var j = 0; j < arr.length; j++) {
      string += "" + arr[i][j] + " 	";
    }
    string += "
";
  }
  string += "
";
  return string;
}
$("#block").append(tableEditor(arr));

A: Попробуйте вот так, вместо document.write(string);:
   var div = document.getElementById(someId);
       div.innerHTML += string;

string - Ваша строка.
someId - ID div-a, который Вы передаете tableEditor('someId', arr);

A: Еще предлагаю переделать функцию.
При конкатенации строки можно на ошибки наткнуться, так как нет проверки на значение вставляемое, например там может быть символ открывающаяся скобка "<" и тогда вся верстка поплывет.

var arr = [
  [1, 2],
  [3, 4]
]

function tableEditor(arr) {
  var table = $("
");
  arr.forEach(function(row){
    var tr = $("
");
    row.forEach(function(column){
      tr.append( $("").html(column) );
    })
    table.append(tr);
  })

  return table;
}
$("#block").append(tableEditor(arr));


text:
Q: Where can one disable the start menu items for clients of an AD using GPMC? I have a windows AD server setup with a few user groups, however I need to add a policy so that any user that log into the domain items or the entire start menu should be disabled.
I can use Group Policy editor to do it locally (gpedit.msc) however It would be ideal if the policy could be set to a group using the Group Policy Management Console,
Has anyone managed to implement specific polices to a object in GPMC?

A: yes, to edit these settings create a GPO and navigate to user configuration, Administrative Templates, Start Menu and Taskbar. You'll find the settings you are looking for there. Using GPMC, you link the GPO to the OU where your users are. Make sure you test the settings first using a test OU.

A: Another question is how restricted are you looking to make the user experience?
Some other Group Policy Areas you might wish to look at:
User Configuration | Administrative Templates | Desktop (to control how they can access and manipulate their desktop)
User Configuration | Administrative Templates | Control Panel (to lock down what kind of system settings they can look at and change)
User Configuration | Administrative Templates | System (to do things like turn off command line and other methods of bypassing your restrictions)


text:
Q: How to specify default media type for endpoints in a Spring Boot service I am building a Spring Boot service with several endpoints. My service needs to support both json and xml output. Most endpoints will be json only and some will be xml only. I can specify the content type a specific endpoint accepts or returns with annotation @RequestMapping. For example:
@RequestMapping(method = RequestMethod.POST,
                consumes = {MediaType.APPLICATION_XML_VALUE},
                produces = {MediaType.APPLICATION_XML_VALUE})

However, since most my application's endpoints will be json only, I wanted to avoid having to write
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE}

in all of them. Is there a way to make a method annotated with @RequestMapping have a default consumes and produces media type? Whenever I need something different from the default I can specify it.
I have tried setting up content negotiation but it doesn't apply to this. I think that I might be able to do it via content negotiation with a custom ContentNegotiationStrategy but I would need that code to be able to read the annotations of the handler for that request (the specific method annotated with @RequestMapping) and the code only gets a NativeWebRequest.
Is there a global Spring configuration for achieving this?
EDIT:
Setting content negotiation with
@Configuration
@EnableWebMvc
class ContentNegotiationConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorParameter(false)
                  .favorPathExtension(true)
                  .ignoreAcceptHeader(true)
                  .ignoreUnknownPathExtensions(false)
                  .useJaf(false)
                  .defaultContentType(MediaType.APPLICATION_JSON);
    }
}

and endpoint with
@RequestMapping(method = RequestMethod.GET)

then calling the endpoint
GET https://localhost:8080/endpoint.xml

returns xml output and HTTP 200 instead of HTTP 406.

A: Take a look at ContentNegotiationConfigurer it lets you specify the content type for the whole application. See this question: Spring boot controller content negotiation

A: Add this bean to your configuration:
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void configureContentNegotiation (ContentNegotiationConfigurer configurer) {
      configurer.defaultContentType(MediaType.APPLICATION_JSON);
  }
}

A: Please use this Java Configuration
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(true).
    favorParameter(false).
    parameterName("mediaType").
    ignoreAcceptHeader(false).
    useJaf(false).
    defaultContentType(MediaType.APPLICATION_JSON).
    mediaType("xml", MediaType.APPLICATION_XML).
    mediaType("json", MediaType.APPLICATION_JSON);
}

A: It's all about what content type you return. If you define content negotiation like this:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .favorPathExtension(false)
            .favorParameter(true)
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML);
}

Then you can have a single method which processes different content types, for e.g.:
@RequestMapping(value = "/process/{json}", method = RequestMethod.GET)
public ResponseEntity<?> process(@PathVariable("json") boolean processJson) {
    if (processJson) {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>("someJSONObject", headers, HttpStatus.OK);
    } else {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        return new ResponseEntity<>("someXMLObject", headers, HttpStatus.OK);
    }
}

If you need to pass the objects directly to the response so that they would be serialized correctly you'll need to use message converters as well. For e.g.:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
    converters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper));
}


text:
Q: How to remove  tags from post contents I have migrated my contents from a Yii site to Wordpress and I have all my posts filled with div tags with all kind of styles and ids and class and I want to use a pattern to remove them all. I searched the internet and came with this function, yet it does remove the closing tag, but not the opening tags which contains other attributes like style id or class:
  function remove_divs($data) {
    $filteredContent = preg_replace(array('/<\s*div.*?>/', '
'), '', $data['post_content']);
    $data['post_content'] = $filteredContent;

    return $data;
}
add_filter('wp_insert_post_data', 'remove_divs', 99);

Can you help me figure what isn't working?

A: Being inspired by the previous answer, I edited my function and it worked just fine. Here is the code:
function remove_divs($data) {
    $filteredContent = preg_replace(array('/<\s*div[^>]*>/', '
'), '', $data['post_content']);
    $data['post_content'] = $filteredContent;

    return $data;
}
add_filter('wp_insert_post_data', 'remove_divs', 99);

Thank you for your answer!

A: You can try this pattern
$pattern = "/
]*>(.*?)<\/div>/";
$content = '
Alpha Beta Gamma
Test
Delta Gamma Eta
';
preg_match_all($pattern, $content, $match);
var_dump($match);


text:
Q: Why is Flow Type not inferring the correct Generic Type We have been trying to annotate our Higher Order Components in React in our codebase with Flow, without much success.
We have

*

*adapt Higher order component which accepts an adapter as an argument.

*adaptDataProp which accepts a dataAdapter which will only be invoked on the props.data object

Here is the implementation without Flow implemented
function adapt(adapter) {
    return (Component) {
        return (props) => <Component {...adapter(props)} />;
    };
}

function adaptDataProp(dataAdapter) {
    function adapter(inputProps) {
        const { data, ...rest } = inputProps;
        return ({ ...dataAdapter(data), ...rest });
    }

    return adapt(adapter);
}

 const TestFunction = ({ moo, className }) =>
{ moo }

const dataAdapter = ({ a }) => ({ moo: a });
const AdaptedTestFunction = adaptDataProp(dataAdapter)(TestFunction);

// rendering
<AdaptedTestFunction data={{ a: 'a' }} className='b' />

Below are the test cases we have:
// Test example 1: Should fail as data prop passed in is wrong
<AdaptedTestFunction data={{ b: 'b' }} className='b' />

// Test example 2: Should fail as missing className prop
<AdaptedTestFunction data={{ a: 'a' }} />

// Test example 3: Should pass
<AdaptedTestFunction data={{ a: 'a' }} className='b' />

Our flow annotation for the above uses Generic Types.
We have adapt, adaptDataProp in separate files.
// Functional Component for React
type FunctionalComponent<Props> = (props: Props) => ?React$Element<any>;
// Union of Functional Component or a Class React Component
type ComponentDefinition<DefaultProps, Props, State> = FunctionalComponent<Props> | Class<React$Component<DefaultProps, Props, State>>;

type AdaptReturnType<AdaptedProps, Props> = ComponentDefinition<void, AdaptedProps, *> => FunctionalComponent<Props>;

function adapt<
  Props: Object,
  AdaptedProps: Object
>(adapter: Props => AdaptedProps): AdaptReturnType<AdaptedProps, Props> {
    return (Component: ComponentDefinition<void, AdaptedProps, *>): FunctionalComponent<Props> => {
        return (props: Props) => <Component {...adapter(props)} />;
    };
}

function adaptDataProp<
    Data: Object,
    AdaptedData: ?Object,
    Rest: Object
>(dataAdapter: Data => AdaptedData):
    AdaptReturnType<
        Rest & AdaptedData,
        Rest & { data: Data }
    > {
    function adapter(inputProps: Rest & { data: Data }): Rest & AdaptedData {
        const { data, ...rest } = inputProps;
        return ({ ...dataAdapter(data), ...rest });
    }

    return adapt(adapter);
}

type Props = {
    moo: string,
    className: string
};

type AdaptedProps = {
   moo: string
};

type Data = {
    a: string
};

const TestFunction = ({ moo, className }: Props) =>
{ moo }

const dataAdapter = ({ a }: Data): AdaptedProps => ({ moo: a });
const AdaptedTestFunction = adaptDataProp(dataAdapter)(TestFunction);

However, for test example 3, I get the following error:
 const TestFunction = ({ moo, className }: Props) =>
{ moo }

                                            ^ property `moo`. Property not found in
 <AdaptedTestFunction data={{ a: 'a' }} className='b' />
  ^ props of React element `AdaptedTestFunction`

We expect the above to pass because AdaptedTest should only fail if it does not conform to Rest & { data: Data }.
Is this an issue with Flow itself or am I doing something wrong?

A:
Warning: Flow does not infer generic types.
If you want something to have a generic type, annotate it. Otherwise, Flow may infer a type that is less polymorphic than you expect.

via: https://flow.org/en/docs/types/generics/


text:
Q: How can I create c# .net generic list like in Ruby? I'm trying to map features that I used from .net with Ruby
How can I create c# .net generic list like in Ruby?
public class ClientList : List<Client> { }

A: Ruby is a very dynamic language. It does not have strong types like in C#, and therefore, it does not have (or need generics).
You can create a List in Ruby like this:
list = []

http://langref.org/ruby/lists

A: class A
end

list = [] # create
list << A.new # add

Something like this? Here list is dynamic you can add any object to it.


text:
Q: Only display some html if a row is selected I'm using DataTables and have this code to highlight the rows selected:
    /* Click event handler */
    $('#items-table tbody tr').live('click', function () {
        var id = this.id;
        var index = jQuery.inArray(id, aSelected);

        if ( index === -1 ) {
            aSelected.push( id );
        } else {
            aSelected.splice( index, 1 );
        }

        $(this).toggleClass('row_selected');
    } );

What I would like to do is only display the following html if one or more rows are selected:

Delete selected rows

How can I achieve this?

A: you can do that by doing this after the toggleClass
if($('#items-table tbody tr.row_selected').length > 0) {
    $("p").show();
else
    $("p").hide();

A: if ($('#items-table tbody tr.row_selected').length > 0){
    $('#delete').show();
}
else {
    $('#delete').hide();
}

A: You could create a function that checks on every click how many rows are selected.
For example:
function checkRows(){
    if( $('.row_selected').length > 0 ){
       $('#delete').show();
    }else{
       $('#delete').hide();
    }
}

Then have this on the delete button:
$('#delete').click(function(){
    $('.row_selected').slideUp(200,function(){
        $(this).remove();
    });
    $(this).hide(); // Hide delete button again
});

Hope that helps :)


text:
Q: POST JSON array with indices using retrofit I'm using retrofit to POST a json array to server. Data is something like this:
{something:
    {somethings:
        [
            {"param1":"value", "param2":value},
            {"param1":"value", "param2":value}
        ]
    }
}

however, my server forces me to MUST include the indices in the array like:
{something:
    {somethings:
        {
         "0":{"param1":"value", "param2":value},
         "1":{"param1":"value", "param2":value}
        }
    }
}

In other words  cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]

I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]

How to do this using retrofit?
My interface looks like this:
interface ApiService {
    @POST("endpoint")
    public Callback<Something> postSomething (@Body Something something);
}

My classes look like following:
public class PostSomething {
    private MapOfSomething something = new MapOfSomething();

    public MapOfSomething getSomething() {
        return portfolio;
    }

    public void setSomething(MapOfSomething something) {
        this.something = something;
    }
}

public class MapOfSomething {
    private JSONObject somethings = new JSONObject();

    public JSONObject getPortfolios() {
        return somethings;
    }

    public void setSomethings(List<Something> somethingList) {

        for (int i = 0; i<somethingList.size(); i++) {

            try {
                somethings.put(String.valueOf(i).toString(), somethingList.get(i));
            } catch (JSONException e) {
            e.printStackTrace();
            }
        }
    }

}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);

A: One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
    @POST("endpoint")
    public Callback<Something> postSomething (@Body JSONObject jsonObject);
}

Now you need to create the JSONObject , here is how I have created your desired JSONObject
    JSONObject mainJson = new JSONObject();

    JSONArray list = new JSONArray();

    JSONObject singleElement1 = new JSONObject();

    try {
        singleElement1.put("param1","value1");
        singleElement1.put("param2","value2");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject singleElementSet1 = new JSONObject();

    try {
        singleElementSet1.put("1",singleElement1);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject singleElement2 = new JSONObject();

    try {
        singleElement2.put("param1","value1");
        singleElement2.put("param2","value2");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject singleElementSet2 = new JSONObject();

    try {
        singleElementSet2.put("2",singleElement2);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    list.put(singleElementSet1);
    list.put(singleElementSet2);

    JSONObject subJson = new JSONObject();

    try {
        subJson.put("something",list);
        mainJson.put("something",subJson);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.d("json",""+mainJson.toString());

I am assuming right now you are calling your service like this way
  Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);

But now you have to replace this with the following
  Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier

Hope it helps
EDIT
        JSONObject mainJson = new JSONObject();

        JSONObject singleElement1 = new JSONObject();

        try {
            singleElement1.put("param1","value1");
            singleElement1.put("param2","value2");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject singleElement2 = new JSONObject();

        try {
            singleElement2.put("param1","value1");
            singleElement2.put("param2","value2");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();

        //hope you can add item to this arraylist via some loop
        jsonObjectArrayList.add(singleElement1);
        jsonObjectArrayList.add(singleElement2);

        JSONArray list = new JSONArray();

        for(int i = 0;i<jsonObjectArrayList.size();i++){

            JSONObject elementSet = new JSONObject();
            try {
                elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            list.put(elementSet);
        }

        JSONObject subJson = new JSONObject();

        try {
            subJson.put("something",list);
            mainJson.put("something",subJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }


text:
Q: jasmine sinon synchronous ajax call causes infinite loop I'm using jasmine to do unit testing and sinon to mock an ajax call. However, this causes an infinite loop where my test case is called repeatedly. The ajax call is made synchronously. If I change the ajax call to be asynchronous, the infinite loop does not occur. Any help or pointers will be greatly appreciated!
Here is the function with the ajax call:
define([
    // Utils
    'util/logging',
    // Project Dependencies
    'views/core/baseView',
    'i18n!i18n_DNA/nls/basePage',
    'i18n!i18n_DNA/nls/consentSettingsView',
    'duster!templates/widgets/testSettings/consentSettings.dust.html'
], function (Log, BaseView, i18n_basePage, i18n_consentSettingsView, template) {
    'use strict';

    // ConsentSettingsView
    // -----------------------------------------------------------------------------------------
    return BaseView.extend({

        events: {
            'click #deleteTestButton': 'deleteTestModal'
        },

        className: 'connectDelete',

        // initialize()
        // ---------------------------------------------------------------------------------------
        initialize: function () {

            this.hasConsented = this.options.hasConsented;
            this.testId = this.options.testId;
            this.appRouter = this.options.appRouter;

            // Call `super()`.
            BaseView.prototype.initialize.call(this);
        },

        // render()
        // ---------------------------------------------------------------------------------------
        render: function () {

            var self = this;

            var context = {
                i18n_basePage: i18n_basePage,
                i18n_consentSettingsView: i18n_consentSettingsView,
                hasConsented: this.hasConsented,
                testId: this.testId
            };

            dust.render('templates/widgets/testSettings/consentSettings.dust.html', context, function (err, out) {
                if (err) {
                    console.error(err);
                } else {
                    self.$el.html(out);
                }
            });

            return self;
        },

        // deleteTestModal()
        // ---------------------------------------------------------------------------------------
        deleteTestModal: function () {
            AcomModal.open('deleteTestModal');
            $('#pDelId').click($.proxy( this.deleteTest, this));
        },

        // deleteTest()
        // ---------------------------------------------------------------------------------------
        deleteTest: function () {

            var self = this;

            $.ajax({
                url: 'testSettings/' + encodeURIComponent(this.testId),
                dataType: 'json',
                data: {
                    password: $('#pUserPwd').val(),
                    testId: self.testId
                },
                async: false,
                type: 'DELETE',
                success: function (data, textStatus, jqXHR) {
                    Log.info("Successfully deleted test #", self.testId, data, textStatus, jqXHR);
                },
                error: function (jqXHR, textStatus, errorThrow) {
                    Log.error(jqXHR, textStatus, errorThrow);

                    switch (jqXHR.status) {
                        case 401:
                            self.appRouter.navigate("#login", {trigger: true});
                            break;
                        case 404:
                            self.appRouter.navigate("#404", {trigger: true});
                            break;
                        default:
                            self.appRouter.navigate("#serviceUnavailable", {trigger: true});
                    }
                },
                complete: function (jqXHR, textStatus) {
                    $('#pDelId').unbind('click');
                    window.location = window.location.origin + window.location.pathname + window.location.search;
                }
            });
        }
    });
});

Here is my test case:
define([
    'backbone',
    'views/widgets/testSettings/consentSettingsView'
], function (Backbone, ConsentSettingsView) {

    // deleteTestModal()
    // ---------------------------------------------------------------------------------------
    describe('ConsentSettingsView.deleteTest()', function () {

        var server;
        var appRouter;
        var consentSettingsView;

        // Setup
        // -----------------------------------------------------------------------------------------
        beforeEach(function(){

            appRouter = {
                navigate: function () {
                    console.log('navigate called', arguments);
                }
            };

            consentSettingsView = new ConsentSettingsView({
                hasConsented: false,
                testId: 1,
                appRouter: appRouter
            });

            server = sinon.fakeServer.create();

            server.respondWith(/testSettings\/(\d+)/, function(xhr, id) {
                switch (id) {
                    case '1':
                        xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify({id: id, success: true}));
                        break;
                    case '2':
                        xhr.respond(401, {'Content-Type': 'application/json'}, JSON.stringify({id: id, success: false}));
                        break;
                    case '3':
                        xhr.respond(404, {'Content-Type': 'application/json'}, JSON.stringify({id: id, success: false}));
                        break;
                    default:
                        xhr.respond(500, {'Content-Type': 'application/json'}, JSON.stringify({id: id, success: false}));
                        break;
                }
            });
        });

        afterEach(function(){

            server.restore();
        });

        it('makes a successful ajax call', function () {

            consentSettingsView.testId = 1;
            consentSettingsView.deleteTest();
        });
    });
});

A: if you want a Async test, you need to use the Jasmine right way for async tests, they are different from sync, if you change your code now to async, it will return nothing, then you will expect strange behavior.
Take a look in: http://pivotal.github.com/jasmine/#section-Asynchronous_Support
Now your test should be something like this:
    it('makes a successful ajax call', function () {
        runs(function() {
            consentSettingsView.testId = 1;
            consentSettingsView.deleteTest();
        });

        var timeoutIn = 1000; // A second
        waitFor(function() {
            // Return something that flags your test is ok or not after the timeout time
        }, 'No server response', timeoutIn);

        runs(function() {
            // Expected result to check from your test
        });
    });

Personal I think the better way to do this async test is change your method deleteTest to be able to pass a callback as argument like in promisses pattern:
deleteTest: function (success, fail) ....

Then you can type check and run in the desired context like this:
if (typeof success === 'function') { success.call(this); }

Same for fail, but inside the ajax failure callback function from jQuery options.
Now you can add to your test something like this:
    it('makes a successful ajax call', function () {
        var result = false;
        runs(function() {
            consentSettingsView.testId = 1;
            consentSettingsView.deleteTest(function () {
                result = true;
            }, function () {
                result = false;
            });
        });

        var timeoutIn = 1000; // A second
        waitFor(function() {
            return result;
        }, 'No server response', timeoutIn);

        runs(function() {
            // Expected result to check from your test
            expect(result).toBe(true);
        });
    });

Posting looking in the google, I found this article.
He explains very like I've done to you, hope that can help you.


text:
Q: Do I need to delete arangodb cursor after query? I want to know whether a cursor can be auto deleted or should I delete it manually. If I don't delete it, does it cause memory leaks?

A: It will be automatically deleted when you retrieve all requested documents. From docs:

The cursor will automatically be destroyed on the server when the
  client has retrieved all documents from it. The client can also
  explicitly destroy the cursor at any earlier time using an HTTP DELETE
  request. The cursor id must be included as part of the URL.
Note: the server will also destroy abandoned cursors automatically
  after a certain server-controlled timeout to avoid resource leakage.


text:
Q: Javascript return occurence of highest score in array I have this array
array = [{name:name,score:2},{name:name2,score:2},{name:name3,score:3},{name:name4,score:4},{name:name5,score:4}]

Please help me to get any highest and lowest occurence(score) of this array.
Highest
highestoccurence = [{name:name4,score:4},{name:name5,score:4}]

lowestoccurence = [{name:name,score:2},{name:name2,score:2}]

Thanks

A: you can do it in the following way

let array = [{name:'name',score:2},{name:'name2',score:2},{name:'name3',score:3},{name:'name4',score:4},{name:'name5',score:4}];

let max = array.reduce(function(a, b){
    if(a.score > b.score)
        return a;
    return b;
})

max_array = array.filter(function(element){
    return element.score == max.score;
});

console.log(max_array);

let array = [{name:'name',score:2},{name:'name2',score:2},{name:'name3',score:3},{name:'name4',score:4},{name:'name5',score:4}];

let min = array.reduce(function(a, b){
    if(a.score < b.score)
        return a;
    return b;
})

min_array = array.filter(function(element){
    return element.score == min.score;
});

console.log(min_array);

A: First find min and max values:
var array = [{name:'abc',score:2},{name:'gdf',score:2},{name:'ghd',score:3},{name:'asdf',score:4},{name:'qwer',score:4}];

var max = -Infinity;
var min = +Infinity;

array.forEach(function(obj) {
    if(obj.score > max) {
        max = obj.score;
    }
    if(obj.score < min) {
        min = obj.score;
    }
});

And then filter your array using that information:
var highestoccurence = array.filter(function(el) {
    return el.score == max;
});

var lowestoccurence = array.filter(function(el) {
    return el.score == min;
});

A: Take a look at Lodash.
const maxItems = _.filter(array, { score: _.maxBy(array, 'score').score });
const minItems = _.filter(array, { score: _.minBy(array, 'score').score });

_.maxBy(array, 'score') returns the first max score item.
_.filter(array, { score: maxItem.score }) will return items that have same score as the max one.

A: Check separately for higher and lower and make array

array = [{name:"name",score:2},{name:"name2",score:2},{name:"name3",score:3},{name:"name4",score:4},{name:"name5",score:4}];
highest = [];
highestScore = 0;
lowest = [];
lowestScore = 0;
for(i in array){
  if(i == 0){
    lowestScore = array[i].score;
    highestScore = array[i].score;
    lowest.push(array[i]);
    highest.push(array[i]);
  }else{
    if(array[i].score <= lowestScore){
      if(array[i].score != lowestScore){
        lowest = [];
        lowestScore = array[i].score;
      }
      lowest.push(array[i]);
    }
    if(array[i].score >= highestScore){
      if(array[i].score != highestScore){
        highest = [];
        highestScore = array[i].score;
      }
      highest.push(array[i]);
    }
  }
}

console.log("lowest",lowest);
console.log("highest",highest);


text:
Q: exchangelib Library failure in Python with PyInstaller I am writing an application that will connect to the Exchange Server and send an email to a recipient on a scheduled basis.  This application depends upon a successful import exchanglib.
I'm able to import exchangelib and get all the components I need, when I execute the program as a .py file.  I can run it successfully from the command line, as well as from Jupyter Notebook, but it fails when I transform it into an executable, using PyInstaller.
Here are the relevant lines of code:
print("Attempting: import exchangelib")
try:
    import exchangelib
    print("SUCCESS: import exchangelib")
except Exception as expOutput:
    print("FAILED: import exchangelib")
    print(expOutput)

print("Attempting: from exchangelib import DELEGATE, Account, Credentials, Configuration, Message, Mailbox, FileAttachment, HTMLBody")
try:
    from exchangelib import DELEGATE, Account, Credentials, Configuration, Message, Mailbox, FileAttachment, HTMLBody
    print("SUCCESS: import DELEGATE, Account, Credentials, Configuration, Message, Mailbox, FileAttachment, HTMLBody")
except Exception as expNewOutput:
    print(expNewOutput)

When I run this from the .py file (Test_exchangelib.py) I get what I expect:
"SUCCESS: import exchangelib"
"SUCCESS: import DELEGATE, Account, Credentials, Configuration, Message, Mailbox, FileAttachment, HTMLBody"

When I run it as an exe, I get the following output:
    Attempting: import exchangelib
    FAILED: import exchangelib
    module 'zoneinfo' has no attribute 'ZoneInfoNotFoundError'
    Attempting: from exchangelib import DELEGATE, Account, Credentials, Configuration, Message, Mailbox, FileAttachment, HTMLBody
    module 'zoneinfo' has no attribute 'ZoneInfoNotFoundError'

Here are my PyInstaller commands that I use to transform Test_exchangelib.py into an executable:
C:\>cd C:\Users\aguler\AppData\Roaming\Python\Python37

C:\Users\aguler\AppData\Roaming\Python\Python37>ProjectEnvironment\Scripts\activate.bat

(ProjectEnvironment) C:\Users\aguler\AppData\Roaming\Python\Python37>Scripts\pyinstaller --onefile C:\PyFiles\Email_Troubleshoot\Test_exchangelib.py --paths=C:\Users\aguler\AppData\Roaming\Python\Python37\site-packages\tzdata --paths=C:\Users\aguler\AppData\Roaming\Python\Python37\site-packages\tzdata\zoneinfo --paths=C:\users\aguler\appdata\roaming\python\python37\projectenvironment\lib\site-packages\exchangelib --paths=C:\Users\aguler\AppData\Roaming\Python\Python37\ProjectEnvironment\Lib\site-packages\backports

The zoneinfo class is called from backports, in the account.py file which is implemented by calling exchangelib.  This means that the executable is not bringing in backports correctly, because it is leaving out zoneInfo.
What am I missing? How can I get the whole backports library into the executable?

A: The error message means that Python can find a zoneinfo module, but zoneinfo.ZoneInfoNotFoundError does not exist. So, you either have a really old version of backports.zoneinfo installed (the class was introduced in v0.1.0) or the zoneinfo module is picked up from something that is not the backports.zoneinfo package - for example if you have a zoneinfo.py file in your path somewhere.


text:
Q: TreeView double click event I want to define a double click even on a TreeView so that I will be able to know which item in the TreeView was selected and to get his title.
The way I try to get it's title gets me "MyProject.MenuItem".
How can I refer to the selected item on the tree, make sure it's not the root, and get it's title?
What I did:
<TreeView Name="trvMenu" HorizontalAlignment="Left" Height="312" VerticalAlignment="Top" Width="200" MouseDoubleClick="TreeView_MouseDoubleClick" >
        <TreeView.ItemTemplate>
               <HierarchicalDataTemplate DataType="{x:Type local:MenuItem}" ItemsSource="{Binding Items}">
                     <TextBlock Text="{Binding Title}" />
               </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
</TreeView>

The MessageBox shows "MyProject.MenuItem", what I want to do is not show a messagebox, but to get the title of the selected treeview item, after checking it is not the root
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
    {
        if (sender is TreeViewItem)
            if (!((TreeViewItem)sender).IsSelected)
                return;
        TreeViewItem tviSender = sender as TreeViewItem;
        MessageBox.Show(trvMenu.SelectedItem.ToString());
    }

A: Change your double click handler like shown below. Instead of calling ToString it accesses the Title property of your MenuItem item class.
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
    var menuItem = trvMenu.SelectedItem as MyProject.MenuItem;

    if (menuItem != null)
    {
        MessageBox.Show(menuItem.Title);
    }
}


text:
Q: aws_s3 module version id error with Ansible 2.4 I have simple task to download file from s3 bucket which works fine with Ansible 2.3, when I have upgraded the ansible from 2.3 to 2.4, it complain that I need to use the aws_s3 module instead of s3 which I did and getting the following error:
─➤ansible-playbook -i localhost, playbook.yml                                                                    4 ↵

PLAY [all] *******************************************************************************************************************

TASK [Download the latest version of from S3 bucket] *************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "Key /node/qa/1.0.483/node.tar.gz with version id None does not exist."}

PLAY RECAP *******************************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1

Here is my task:
- name: Download the latest version of from S3 bucket
  aws_s3:
    aws_access_key: "xxxxxxxxxxx"
    aws_secret_key: "yyyyyyyyyyyyyyyyyyyyyyy"
    bucket: "artifacts-bucket"
    object: "/node/qa/1.0.483/node.tar.gz"
    mode: get
    dest: "node.tar.gz"

Few notes:
- versioning is not enabled on my s3 bucket
- installed the boto3 that is the requirement for aws_s3 module
- the exact same tasks work fine with ansible 2.3 and did give this error
"Key /node/qa/1.0.483/node.tar.gz with version id None does not exist."

A: There is a bug due to boto3. Prior to porting this module to boto3 object: /path/to/object refered to bucketname/path/to/object. In 2.4 this became bucketname//path/to/object.
Omitting the leading / in object is a workaround. This code work for me:
- name: Download the latest version of from S3 bucket
  aws_s3:
    aws_access_key: "xxxxxxxxxxx"
    aws_secret_key: "yyyyyyyyyyyyyyyyyyyyyyy"
    bucket: "artifacts-bucket"
    object: "node/qa/1.0.483/node.tar.gz"
    mode: get
    dest: "node.tar.gz"

Hope it will help other. Open a bug over ansible github repo, hopefully it will fix in Ansible 2.4.1


text:
Q: UPlay Plus free month: What happens if I cancel now? I activated my free trial of UPlay+ yesterday, and successfully downloaded some games. If not cancelled at the latest at the end of the month (September 30th), I will be charged 14,99€ / month from there on by Ubisoft, according to them.
If I cancel right now, how will it affect the running free trial? Will there be any penalties / limitations to what I can do with UPlay+ or the games I downloaded?

A: If you cancel the trial now, the trial will continue until the end date and then terminate. Upon the terminations, games downloaded via UPlay+ will cease working and do nothing but take space in your hard drive.
It basically functions the same as any other subscription based system. However, if you do buy a game, that game will remain with you even after the subscription ends. This means you actually bought the game via store, rather than gained access through subscription.
Source:

*

*https://support.ubi.com/en-GB/faqs/000045736

*https://support.ubi.com/en-GB/faqs/45739/Information-about-the-Uplay-free-trial/


text:
Q: How can i correctly use boolean to use different parts of a method I have a MP3Player class which has a method pressStop. I want to check if the method was used before reset the playlist and if not just pause the song. I've tried with booleans using them in different parts but to no avail. I will appreciate an explanation
Code:
public void pressStop() {
        boolean isStopped = false;
        if(isStopped) {
            currentSong = 0;
            System.out.println("Songs are stopped");

        }
        if(!isStopped){
            System.out.println("Song " + currentSong + " is stopped");
            isStopped = true;
        }
    }

A: This code just won't work.
isStopped will always be false, so the first conditional will never be entered

One way you could handle these actions is to use callback listeners, like any popular GUI framework will provide on button clicks.
The idea here - you have one class that maintains the "state" of the player, and any events acting on that state are injected from outside the class.
public class MP3Player {

    private boolean playing; // defaults to false
    private MP3Player.StopButtonListener stopListener;

    public MP3Listener(StopButtonListener stopListener) {
        this.stopListener = stopListener;
        // TODO: Add listeners for other buttons, like start/next/prev
    }

    public interface StopButtonListener {
        public void onStopClicked();
    }

    public void stop() {
        System.out.println("stopping player!");
        this.playing = false;
        if (this.stopListener != null) {
            this.stopListener.onStopClicked();
        }
    }

    // TODO: add start

}

With this, you can add actions to whenever the mp3 player is stopped.
public class MP3Demo {

    public static void main(String[] args) {

        MP3Player.StopButtonListener l = new MP3Player.StopButtonListener() {
            @Override
            public void onStopClicked() {
                System.out.println("got stop event for player!");
                // TODO: Reset the player, update some other information in your app, etc.
            }
        };
        final MP3Player p = new MP3Player(l);
        p.stop();
    }

}

A: You're setting the isStoppedvariable at the start of the method. It is always false.
You can try :
public void pressStop() {
    // boolean isStopped = false;
    if (isStopped) {
        currentSong = 0;
        System.out.println("Songs are stopped");
    } else {
        System.out.println("Song " + currentSong + " is stopped");
    }
    isStopped = true;
}

public void pressPlay() {
    // set the currentSong and do whatever
    isStopped = false;
}


text:
Q: How to install django spirit ? I am getting the error command not found: spirit I tried install django spirit using
mkvirtualenv env -p /usr/bin/python3
pip install django-spirit
spirit startproject mysite

but get the error:

spirit command not found

Any solutions ?

A: by default from pip you installed the spirit==0.4.8 version, but command spirit is added in new 0.5 version, so you should install from git repo:
pip install git+https://github.com/nitely/Spirit.git

A: @Vardha Try the following steps:

*

*git clone https://github.com/nitely/Spirit.git

*python3 -m venv spirit-env  ## Create the Virtual Environment

*source spirit-env/bin/activate ## Activate the Virtual

*pip install <path_to_cloned_spirit>/Spirit

*cd <path_to_cloned_spirit>/Spirit

*spirit startproject forum

*cd forum

*python manage.py migrate

*python manage.py runserver


text:
Q: Using Tibco EMS with node.js I am working on an app which has recently converted to a node.js back end.
My original plan is to use Tibco EMS to publish messages through a queue, and use websockets to fire these to the front end, however I wanted to know if this is feasible for a relative beginner using node.js? And if so what is the best way to go about this?

A: TIBCO EMS supports the JMS standard but has client libs for various platforms, e.g. C Lib could be used in a custom node module to access EMS. Someone asked the question a while before (see here: Tibco EMS protocol).
There's an experimental EMS node plugin on github, but not sure if in usable status so far: https://github.com/JensWalter/node-ems
Another option if your company has TIBCO's Web messaging addon for EMS is to use websockets like described here Tibco EMS connectivity using nodejs /Javascript
Hope that helps


text:
Q: Finding words in a file, checking if they are palindrome I've tried to write a program which finds a word(s) from reading file and checks if it is palindrome (same word from both sides) and if they are, they are saved into another file separated by return. Words in a reading file can be written in any way: separated by space, in a sentence or by return.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX 255

int palindrome(char *x, int y, int i)
{
    while(i<=y){
        if(x[i]!=x[y])
            return 0;
        i++;y--;
    }
    return 1;
}

int main()
{
    char *reading;
    int length;
    int x=0;
    int y=0;
    char read[MAX];
    char write[MAX];
    FILE *r;
    FILE *w;
    puts("Enter read file name");
    scanf("%s", read);
    puts("Enter write file name");
    scanf("%s", write);
    r=fopen(read, "r");
    if(r==NULL)
        perror("File does not exist");
    w=fopen(write, "w");
    reading=malloc(MAX*sizeof(char));
    while(fgets(reading, MAX, r)!=NULL)
    {
        length=strlen(reading);
        while(x<=length){
            for(x=y; ;x++){
                printf("%c\n", reading[x]);
                if((reading[x]>='a'&& reading[x]<='z') || (reading[x]>='A' && reading[x]<='Z'))
                    break;
            }
            for(y=x; ;y++){
                printf("%c\n",reading[y]);
                if((reading[y]>='a'&& reading[y]<='z') || (reading[y]>='A' && reading[y]<='Z'));
                else
                    break;
            }
            if(palindrome(reading, y, x)==1)
                for( ;x<=y;x++)
                fputc(reading[x], w);
            x=y;
        }
    }
    fclose(r);
    fclose(w);
    return 0;
}

The problem is that code doesnt work, how to fix it?

A: I spotted an error in your code here with the wrong limit for x
length=strlen(reading);
while(x<=length){

so I made quite a few changes to the way the probem is tackled rather than figuring out what other limits you might be breaking. I have written output to stdout rather than to a file. Note that I also added "t" to the file opening mode.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 255

int palindrome(char *string, int x, int y)
{
    if (x >= y)
        return 0;
    while (y > x)
        if (tolower(string[x++]) != tolower(string[--y]))
            return 0;
    return 1;
}

int main()
{
    char reading[MAX+1];
    char readfile[MAX+1];
    int x, y, i;
    FILE *r;
    puts("Enter read file name");
    scanf("%s", readfile);
    r=fopen(readfile, "rt");
    if(r==NULL)
        perror("File does not exist");
    else {
        while (fgets (reading, MAX, r) != NULL) {
            x = 0;
            do {
                while (reading[x] && !isalpha (reading[x]))
                    x++;
                y = x;
                while (isalpha (reading[y]))
                    y++;
                if (palindrome (reading, x, y)) {
                    printf ("Palindrome: ");
                    for (i=x; i<y; i++)
                        printf ("%c", reading[i]);
                    printf ("\n");
                }
                x = y;
            }
            while (reading[x]);
        }
        fclose(r);
    }
    return 0;
}


text:
Q: Getting "TypeError: something.map is not a function" in React in production mode, try to parse it in json object but return a html file First I get "TypeError: book.map is not a function" in production mode after I ran "npm run build" which I did not get this error in localhost.
render() {
        const books = this.state.books;

        return (

                    {books.map(book =>

                        <img src={`/${book.bookImage}`} className="card-img-top" alt="comic book coverpage" />

Then I tried to parse the setting book state into JSON object but getting another error.
componentDidMount() {
        try {
            axios.get("/app/books")
            .then(response => {
                console.log(response.data);
                // this.setState({books: [JSON.parse(response.data), true]});
                this.setState({books: JSON.parse(response.data)})

            })
        }
        catch (err) {
            console.log(err);
        }
    }

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
In the network tab, I am getting status code 304, the response is a html file. I am testing the above on Heroku local and getting these error, I tested everything on local machine it works perfectly so I thought I am ready to deploy. If I open the deployed app in Heroku, the app is just blank, it said I have server 503 service unavailable error, I don't know what to do now.....
About the Heroku deployment, I have an env file to store stuff, I know I have to copy these to Heroku dashboard config var, and I had done that, just not sure whether I had set the port number right.
DATABASE_ACCESS = mongodb+srv://Victoria:Victoria@comic-bookstore.4zots.mongodb.net/Member?retryWrites=true&w=majority
PORT = 797459
JWT_SECRET = HJ2H2WUHJ2CHghwhh3hjndsndhje3ujjwquyhnshwy22
NODE_ENV = production

This is my server.js
const PORT = process.env.PORT || 3001;


text:
Q: Can I transform those seperate forcecasts into one for loop? The data is in quarters and starts from 1955 till 2019, what I'm trying to do is obtaining the fixed horizon forecasts by increasing the sample period by one point incrementally, and repeating the estimation and forecasting process for this new sample period, and extract the year ahead (h=4) forecast. I want to forecast from the second quarter of 2017.
however I've tried using for loop but it just dosen't work, is it possible to condense this code into a for loop function
a <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2016,4), frequency = 4)
aa <- auto.arima(a)
aa
forecast(aa,h = 4)

b <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,1), frequency = 4)
bb <- auto.arima(a)
bb
forecast(bb,h = 4)

c <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,2), frequency = 4)
cc <- auto.arima(a)
cc
forecast(cc,h = 4)

d<- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,3), frequency = 4)
dd <- auto.arima(d)
dd
forecast(dd,h = 4)

e <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2017,4), frequency = 4)
ee <- auto.arima(e)
ee
forecast(ee,h = 4)

f <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,1), frequency = 4)
ff <- auto.arima(f)
ff
forecast(ff,h = 4)

g <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,2), frequency = 4)
gg <- auto.arima(g)
gg
forecast(gg,h = 4)

h <- ts(data$UK.GDP.UA.MP, start = c(1955,1), end = c(2018,3), frequency = 4)
hh <- auto.arima(h)
hh
forecast(hh,h = 4)

A: library(forecast)
ukgdp <- ts(data$UK.GDP.UA.MP, start=1955, frequency=4)

fc <- matrix(NA, ncol=4, nrow=8) %>% ts(start=c(2016,4), frequency=4)
colnames(fc) <- paste("h =",1:4)

for(i in seq(8)) {
  ukgdp_train <- window(ukgdp, end = c(2016, 3+i))
  fit <- auto.arima(ukgdp_train)
  fc[i,] <- forecast(fit, h=4)$mean
}

Created on 2019-12-06 by the reprex package (v0.3.0)


text:
Q: How do I programmatically load animations in Godot, separating animation from armature/skeleton? I'm trying to load 3D animations separately from the 3D armature that will be using the animation.
I can import animations from 3d formats (.gltf, .escn) and generate Godot animation files by setting the Animation->Storage option to either ".anim" or ".tres".
How do I load one of those files (.anim, .tres) into an AnimationPlayer (or equivalent) from a GD script at runtime?
My ultimate goal is character customization.  Different parts are assembled to compose a standard armature/skeleton, and the animation is loaded on top at runtime. However, I would like different animations under standard names. Like different "walk" cycles for different styles of character (the cloaked mage walks differently than the armored knight), but the code should just read something like:
$AnimationPlayer.play("walk")
I shy away from procedural animation because of the performance hit. There may be hundreds of characters on-scene at one time.

A: You can load the animations you saved (E.g. from the animation panel, Animation -> Save as) and from GDScript load them with load and then call add_animation on the AnimationPlayer passing the the name and the loaded resource as parameters:
AnimationPlayer.add_animation("Walk", load("res://animations/walk.tres"))


text:
Q: rails unexpected text node at bottom of page I am running this view

Users

    <form>
        <%= form_for :users, method: :get do |f| %>

                <%= label_tag   :keywords, nil, class: "sr-only" %>
                <%= text_field_tag :keywords, nil, placeholder: "Search for first name, last name or email address", class: "form-control input-sm"%>
                <%= submit_tag "Find", class: "btn btn-primary btn-sm" %>

        <% end %>
    </form>

Results

        <%= @users.each do |user| %>

created <%= user.created_at.to_time %>

<%= user.first_name %> <%= user.last_name %> <%= user.username %>

                <%= link_to "Show", users_path(@user), class: "pull-right" %>

<%= user.email %>

        <% end %>

While the search and form function ok for the rest, my page renders with a text node (see screenshot) at the bottom and I have no clue as to why???

A: Change the erb blocks around your loops from <%= to <%.  Otherwise you're going to print the enumerator itself to the screen, like you are now.
From:
<%= @users.each do |user| %>

To:
<% @users.each do |user| %>


text:
Q: How can I find the missing parameters in a C# function call? When a named parameter in a C# function is missing, the compiler only prints the number of arguments that are missing instead of printing the name of each missing parameter in the function:
prog.cs(10,27): error CS1501: No overload for method `createPrism' takes `2' arguments`.

However, for debugging purposes, it is often necessary to obtain the names of the parameters that are missing in a function call, especially for functions that take many parameters. Is it possible to print the missing parameters in a C# function call?
using System;
public class Test{
    public static int createPrism(int width, int height, int length, int red, int green, int blue, int alpha){
        //This function should print the names of the missing parameters
        //to the error console if any of its parameters are missing.

        return length*width*height;
    }
    static void Main(){
        Console.WriteLine(getVolume(length: 3, width: 3));
        //I haven't figured out how to obtain the names of the missing parameters in this function call.
    }
}

A: You can make all parameters nullable and set them a default value. Then, in your method you can check what parameters have null value and do something about it.
   public static int createPrism(int? width=null, int? height=null){
       if(!height.HasValue){
         Console.Write("height parameter not set")
       }
   }

A: The only think I can think of that comes close is using optional parameters:
public static int createPrism(int width = -1, int height = -1, int length = -1, int red = -1, int green = -1, int blue = -1, int alpha = -1){
    if(width == -1)
        Console.WriteLine("Invalid parameter 'width'");
    if(height == -1)
        Console.WriteLine("Invalid parameter 'height'");
    ...

    return length*width*height;
}

This will print out the correct result in the case of:
createPrism(length: 3, width: 3);

However, there's nothing to prevent a user from writing something like this:
createPrism(width: -1, height: -1);

alex's answer is another form of this that works equally well. The trick is to ensure that the default value is one that's not an valid parameter value.

Another technique would be to use a dictionary of parameters
public static int createPrism(Dictionary<string, int> parameters){
    if(!parameters.ContainsKey("width"))
        Console.WriteLine("Missing parameter 'width'");
    if(!parameters.ContainsKey("height"))
        Console.WriteLine("Missing parameter 'height'");
    ...

    return parameters["length"] * parameters["width"] * parameters["height"];
}

But calling this becomes very cumbersome:
createPrism(new Dictionary<string, int>() { { "length", 3 }, { "width", 3 } });

You can overcome this to some degree using a dynamic parameter type:
public static int createPrism(dynamic parameters){
    if(parameters.GetType().GetProperty("width") == null)
        Console.WriteLine("Invalid parameter 'width'");
    if(parameters.GetType().GetProperty("height") == null)
        Console.WriteLine("Invalid parameter 'height'");
    ...

    return parameters.length * parameters.width * parameters.height;
}

Which becomes:
createPrism(new { length: 3, width: 3 });

Though ultimately, the best option is simply to let the compiler do it's job. Your original declaration is sufficient to ensure that the calling code has provided all necessary parameters for your function to return successfully. In general, if the function can execute without a given parameter, it should be made optional (either through a default value or with an overload that omits it), and the compiler will take care of the rest. All you should worry about is whether the value provided by the caller is valid.


text:
Q: How to use ngTable pagination with Firebase Array I am trying to use ngTable to organize my array information into a table. I know that doing the length of $scope.laundryData will return 0 so I made a variable ($scope.arrayLength) that keeps track of the length of the array from Firebase. The problem is that the table displays fine with the pagination buttons, but it doesn't do pagination. If I select the 10 pagination button, it still shows 13 items (all of the items in the list). I got the $scope.tableParams from the ngTable website.
'use strict';

/**
 * @ngdoc function
 * @name laundrytrackerApp.controller:ReportsCtrl
 * @description
 * # ReportsCtrl
 * Controller of the laundrytrackerApp
 */
angular.module('laundrytrackerApp')
  .controller('ReportsCtrl', function ($scope, $firebaseArray, ngTableParams) {
    var ref = new Firebase("firebase url");
    $scope.laundryData= $firebaseArray(ref);
    //console.log($scope.laundryData.length);

    $scope.laundryData.$loaded().then(function(laundryData) {
        console.log(laundryData.length); // data is loaded here
        $scope.arrayLength = laundryData.length;
    });

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10           // count per page
    }, {
        total: $scope.arrayLength, // length of data
        getData: function ($defer, params) {
            $defer.resolve($scope.laundryData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
    })
  });

Here's the view:

Spending Reports

                    {{laundry.date}}
                    {{laundry.user}}
                    {{laundry.loads || '-'}}
                    {{(laundry.refill | currency) || '-'}}
                    {{(laundry.cost | currency) || '-'}}
                    {{(laundry.balance | currency) || '-'}}

A: Try repeating over $data instead of $scope.laundryData:

    {{laundry.date}}
    {{laundry.user}}
    {{laundry.loads || '-'}}
    {{(laundry.refill | currency) || '-'}}
    {{(laundry.cost | currency) || '-'}}
    {{(laundry.balance | currency) || '-'}}

I believe $data is used internally by ngTable to keep track of the paginated array.


text:
Q: Do the aticonfig --set-powerstate and aticonfig --lsp options no longer exist? When I try either of these options I get
 aticonfig: unrecognized option '--lsp'
 aticonfig: parsing the command-line failed.

Does the latest fglrx driver not make use of these power setting options any longer? In which case how is low power setting configured on the card now?
It seems fglrx still installs the script /etc/acpi/fglrx-powermode.sh and in that script there are calls such as
/usr/bin/aticonfig --set-powerstate=$powermode --effective=now"

which one can see are intended to set low power setting whenever the events laptop lid closed, or AC disconnect occur (see /etc/acpi/events/fglrx-ac-aticonfig and /etc/acpi/events/fglrx-lid-aticonfig), but these calls are going to do nothing at all without aticonfig having the --set-powerstate option.
On top of all this I noticed that /etc/init.d/atieventd is not starting the atieventsd on startup, and I traced this to the fact the DAEMONPATH=/usr/sbin/atieventsd was looking for the daemon is sbin when it actually exists in regular old bin.
Is this all intentional, have these methods of controlling power been superseded?


text:
Q: Is QuickTime Player needed to install iOS apps through iTunes? I need to know whether it's possible to install iOS apps through iTunes without installing QuickTime Player.
QuickTime Player is needed by iTunes only when installing media apps, is this true?
Is it needed to install QuickTime Player as well as iTunes on a Windows machine to install an app on an iOS device?

A: Yes, there is no need of quick time player to install iPhone app. You only need is iTunes.

A: If you're asking about installing ad hoc builds, do yourself a favour and get iPhone Configuration Utility from Apple's site.


text:
Q: insert element at the beginning of std::forward_list I want to remove element from std::forward_list and insert it to the beginning of list
But there is no insert method ... It just has insert_after !
How can I  insert element at the beginning of std::forward_list ?

A: Use std::forward_list::push_front.
Example:
// forward_list::push_front
#include <iostream>
#include <forward_list>
using namespace std;

int main ()
{
  forward_list<int> mylist = {77, 2, 16};
  mylist.push_front (19);
  mylist.push_front (34);

  std::cout << "mylist contains:";
  for (int& x: mylist) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

Output: mylist contains: 34 19 77 2 16

A: You can use method
push_front
to insert an element at the beginning of the list
Another approach is to use method insert_after.
Here is an example of using the both methods
std::forward_list<int> l;

l.push_front( 1 );
l.insert_after( l.cbefore_begin(), 0 );

for ( int x : l ) std::cout << x << ' ';
std::cout << std::endl;


text:
Q: How to toggle a class with React inside a map I would like to toggle a class when I click on an element of a list but I only can add a class, not remove it.
Several answers can be selected and therefore have the "active" className.
I try before with toggle() method:
const ChoiceList = (props) => {

  const { choices } = props

  // ----------First method with toggle-----------------

  const answers = document.querySelectorAll(".answer")
  console.log("Answers array :", answers)

  answers.forEach(answer => {

    answer.addEventListener("click", () => {

      answer.classList.toggle("active")

    })

  })

  const choicesItemsJsx = choices.map(({id, value, weight}, index) => {
    return
 {}}
    >{value}

  })

  return
{choicesItemsJsx}

}

ChoiceList.defaultProps = {
  choises: []
}

With this one, I can neither add nor remove my class
And then with add() and remove():
  // ----------Second method with add & remove----------------

  const answers = document.querySelectorAll(".answer")
  console.log("Answers array :", answers)

  answers.forEach(answer => {

    answer.addEventListener("click", () => {

      if (answer.classList.contains("active")) {
        answer.classList.remove("active")
      } else {
        answer.classList.add("active")
      }

    })

  })

It doesn't work too, I can neither add nor remove my class.
Yet in doing this, I can at least add my class for each element of my list, why ?
  const answers = document.querySelectorAll(".answer")
  console.log("Answers array :", answers)

  answers.forEach(answer => {

    answer.addEventListener("click", () => {

      if (answer.classList.contains("active")) {
        return
      } else {
        answer.classList.add("active")
      }

    })

  })

I think, it's better to use a state for my objective, but before, I would like to know why it doesn't work with this code.
Thank you


text:
Q: How do I interpret this partial function syntax in f#? I am reading f# code and I am confused by the syntax. A Parser type is introduced as follows:
type Parser<'r> = Parser of (char list -> ('r*char list) list)

This is evaluated by the interpreter as:
type Parser<'r> = | Parser of (char list -> ('r * char list) list)

which makes sense to me. Then, a new line of code is introduced: 'A parser function also needs to be applied so we define a partial function for that:', and the code that follows:
let parse (Parser p) = p

and the interpreter output is:
Parser<'a> -> (char list -> ('a * char list) list)

I am surprised this is even valid syntax. What is it and why is it needed?
Many thanks

A: In general
let fpattern=body
is equivalent to
let f = function
|pattern ->body
or, even more verbosely,
let f x =
    match x with
    |pattern->body
This allows you to avoid introducing a new identifier which is immediately destructured and then never used again.
In this particular example, that means that parse is equivalent to:
let parse x =
    match x with
    | Parser p -> p

Since there is only a single case in the Parser type, this destructuring will always succeed.

A: You can easily interprete these types if you understand the type of (char list -> ('r*char list) list) as a black box.
Suppose we have a type abbreviation:
type R<'r> = char list -> ('r*char list) list

Then Parser<'r> could be written as:
type Parser<'r> = Parser of R<'r>

When you declare a function:
let parse (Parser p) = p

the type checker infers the parameter of type Parser<'r> (by looking into the structure of Parser p). Therefore, the return value p obviously has type of R<'r>:
val parse : Parser<'a> -> R<'a>

Hypothetically, substituting R<'r> by its real declaration:
val parse : Parser<'r> -> (char list -> ('r*char list) list)

So the types inferred here totally make sense.


text:
Q: PHP POD returns 0 affected rows after update I am working on script which takes file name and update user info, here is the snippet.
$fname =  $_FILES['photo']['name'];
$userId = cleanString($_POST['uid']);
$sql= 'UPDATE `contacts` SET `imgpath` = ? WHERE `contact_id` = ?';
$stmt = $DBH->prepare($sql);
    if($stmt === false) {
        trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $DBH->error, E_USER_ERROR);
    }
$stmt->bind_param('ss',$fname , $userId);

$stmt->execute();
echo $stmt->affected_rows;
$stmt->close();

After running the script it showing 0 affected rows. ( I am not getting any errors while running the script.)


text:
Q: XML Deserialization Coming up NULL My Deserializer executes without exception, but the resulting object is coming up with nulls. The source XML clearly shows values that for some reason are not being set in the target object.  I can't for the life of me figure out why?
Source XML:
<soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>soapenv:Client</faultcode>
<faultstring>Could not insert new row - duplicate value in a UNIQUE INDEX column (Unique Index:).</faultstring>
<detail>
    <axlError>
        <axlcode>-239</axlcode>
        <axlmessage>Could not insert new row - duplicate value in a UNIQUE INDEX column (Unique Index:).</axlmessage>
        <request>addRoutePartition</request>
    </axlError>
</detail>

Class:
using System.Xml.Serialization;

namespace AXLClassLibrary
{
[XmlRoot(ElementName = "Fault", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Fault
{
    [XmlElement(ElementName = "faultcode")]
    public string Faultcode { get; set; }
    [XmlElement(ElementName = "faultstring")]
    public string Faultstring { get; set; }
    [XmlElement(ElementName = "detail")]
    public Detail Detail { get; set; }
    [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string Soapenv { get; set; }
}

[XmlRoot(ElementName = "axlError")]
public class AxlError
{
    [XmlElement(ElementName = "axlcode")]
    public string Axlcode { get; set; }
    [XmlElement(ElementName = "axlmessage")]
    public string Axlmessage { get; set; }
    [XmlElement(ElementName = "request")]
    public string Request { get; set; }
}

[XmlRoot(ElementName = "detail")]
public class Detail
{
    [XmlElement(ElementName = "axlError")]
    public AxlError AxlError { get; set; }
}
}

Deserializer Code:
                var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                XDocument xd = XDocument.Parse(resp);
                XNamespace ns1 = "http://schemas.xmlsoap.org/soap/envelope/";
                XNode faultXML = xd.Descendants(ns1 + "Fault").DescendantNodesAndSelf().First();
                XmlRootAttribute xRoot = new XmlRootAttribute();
                xRoot.ElementName = "Fault";
                xRoot.Namespace = "http://schemas.xmlsoap.org/soap/envelope/";
                xRoot.IsNullable = false;
                resp = faultXML.ToString();

                Fault currentFault;
                XmlSerializer serializer = new XmlSerializer(typeof(Fault), xRoot);
                using (TextReader readFault = new StringReader(resp))
                {
                    currentFault = (Fault)serializer.Deserialize(readFault);
                }


text:
Q: rename a directory or a file I'm using Laravel 5.0 Facades Storage

use Illuminate\Support\Facades\Storage;

and I can use it like
Storage::..

In the Laravel 5.0 Docs,there's nothing like rename a file or folder from the storage.
Any help, ideas, clues, suggestions, recommendations on how to rename a file or folder using the Storage?

A: Laravel Docs
The move method may be used to rename or move an existing file to a new location:
Storage::move('hodor/file1.jpg', 'holdthedoor/file2.jpg');

this way, you can rename without moving
Storage::move('hodor/oldfile-name.jpg', 'hodor/newfile-name.jpg'); // keep the same folder to just rename

Source

A: You can rename directories using
Storage::rename('oldFolder/', 'newFolder/');

A: Well, I had almost the same issue but i solved it like this: rename($path, $newPath) using the built-in php function rename(),and guess what, everything worked like a charm!


text:
Q: Spring Data JPA/Hibernate OneToMany remove ManyToOne Child I am experiencing the following problem:
I have 3 Pojo's

*

*Artist

*Album

*Track

With the Artist having a OneToMany relationship with Album, and Album having a OneToMany relationship with Track.
Artist.class
@Entity
public class Artist {

    @Id
    @GeneratedValue
    @Column(name = "artist_id")
    private long artist_id;

    @Column(name = "artist_name", nullable = false, length = 32)
    private String artist_name;

    @Column(name = "artist_bio", nullable = false, length = 255)
    private String artist_bio;

    @Lob
    @Basic(fetch = FetchType.EAGER)
    @Column(name = "artist_avatar")
    private byte[] artist_avatar;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "artist", orphanRemoval = true)
    private List<Album> albumList;

Album.class
@Entity
public class Album {

    @Id
    @GeneratedValue
    @Column(name = "album_id")
    private long album_id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "artist_id", nullable = false)
    private Artist artist;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "album", orphanRemoval = true)
    private List<Track> trackList;

    @Column(name = "album_name", nullable = false, length = 32)
    private String album_name;

    @Column(name = "album_description", nullable = false, length = 255)
    private String album_description;

    @Lob
    @Basic(fetch = FetchType.EAGER)
    @Column(name = "album_avatar")
    private byte[] album_avatar;

Track.class
@Entity
public class Track {

    @Id
    @GeneratedValue
    @Column(name = "track_id")
    private long track_id;

    @Column(name = "track_no", nullable = false, length = 2)
    private String track_no;

    @Column(name = "track_name", nullable = false, length = 32)
    private String track_name;

    @Column(name = "track_length", nullable = false, length = 32)
    private String track_length;

    @Column(name = "track_file", nullable = false, length = 128)
    private String track_file;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "album_id", nullable = false)
    private Album album;

Track Controller.class
@RequestMapping(value = "/track", params = "delete", method = RequestMethod.POST)
@Transactional
public String postDeleteTrack(@RequestParam Long album_id, Long track_id) {
    trackService.deleteTrack(track_id);
    return "redirect:album/" + album_id;
}

Track Service.class
public void deleteTrack(Long track_id) {
    trackRepository.delete(track_id);
}

TrackRepository.class
@Repository
public interface TrackRepository extends CrudRepository<Track, Long>{
}

When I call the trackService.deleteTrack(track_id); the track in my MySQL database isn't deleted.
Hibernate just gives me a lot of select statements as output.
Any help is appreciated and if you need more information from me feel free to ask.

A: In your repository method, add  this
@Query("delete  from Track t where t.id=:id")
void  delete(@Param("id")String id);

Since you didnt override the cascade policy,default cascade policy is none, i believe this will work.
reference- http://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html_single/


text:
Q: Use order output parameter and specify serialization key with marshmallow-sqlalchemy I'm using marshmallow 3.4.0 and marshmallow-sqlalchemy 0.22.2
I have this SQLAlchemy model and Marshmallow schema
class Zone(Base):
    zone_id = Column(Integer, primary_key=True)
    name = Column(String(65))
    location_id = Column(Integer, ForeignKey('locations.location_id'))
    location = relationship("Location", lazy="joined")

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    zone_id = auto_field(data_key="id")
    location = fields.Nested(LocationSchema)

If I remove
zone_id = auto_field(data_key="id")
the fields are ordered as requested.
If I remove
fields = ("zone_id", "name", "location")
ordered = True

The key is set to id as requested.
If I run the code above, I get this error

  File "[...]/models_schema.py", line 30, in <module>
    class ZoneSchema(SQLAlchemySchema):
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 107, in __new__
    cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in _get_fields
    fields.sort(key=lambda pair: pair[1]._creation_index)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in <lambda>
    fields.sort(key=lambda pair: pair[1]._creation_index)
AttributeError: 'SQLAlchemyAutoField' object has no attribute '_creation_index'

Could someone explain to me how I can set access the zone_id field and add the "data_key" property ?

A: As a last resort, I read the documentation and I managed to find an answer by myself.
class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    location = fields.Nested(LocationSchema)

    @pre_dump
    def set_data_key_for_zone_id(self, data, many, **kwargs):
        self.fields.get("zone_id").data_key = "id"
        return data

As you can see, I kept the ordered = True part and use the pre-dump decorator to access the zone_id field and set the data_key attribute.
If there is a better way to do this, please let me/us know !


text:
Q: Invoke function on an object of unknown type Is it possible in .NET, to invoke a method/function on an object and get back it's return value without knowing the type of the object?
All the examples I could find so far use reflection and need to know the type of the object to get it's method list to invoke them.
In short, I want to invoke a method of a given name and with given parameters on any object, and get back the return value, in case this method really exists.
For example: Let's say I have a library X.dll with a class Y and a function Z inside it. Function Z takes two string parameters and returns a string.
I have another library A.dll, which is NOT referencing X.dll. A.dll has a function B somewhere inside it, which takes an object of type Y as a parameter, but since there's no referencing, this parameter is declared as object. Inside this function B I need to invoke function Z and do something with it's return value.

A: Unfortunately, C# does not support class level generic type inference. There were many occasions which I wished to use reflection with the same purpose you described. It seems the feature's outweghts its costs. There is a throughout discussion about this theme here:
Why can't the C# constructor infer type?