text:
Q: Want to make Func where UnknownType is only known at runtime So, I'm experimenting with expressions atm. Got code below:
Code works fine except for 1 thing: I need to replace ViewModel type with ForeignKeyProperty.PropertyType, which is only known at runtime, at the line of var condition = Expression.Lambda < Func < ViewModel, bool> >
Expected end result:
ForeignKeyProperty.SetValue(model, repository.GetList  <ForeignKeyProperty.PropertyType >().Single(x => x.Id == model.Id));

protected List < Action < IVenturaRepository, ViewModel>> SetForeignKeyProperties<ViewModel>() where ViewModel : BaseViewModel
        {
            var viewModelType = typeof(ViewModel);
            var foreignKeyProperties = viewModelType.GetProperties().Where(x => x.PropertyType.IsSubclassOf(typeof(BaseViewModel)));
            var actions = new List < Action < IVenturaRepository, ViewModel>>();
            var repositoryType = typeof(IVenturaRepository);
            foreach(var ForeignKeyProperty in foreignKeyProperties)
            {
                var foreignKeyIdProperty = viewModelType.GetProperties().SingleOrDefault(x => x.Name == ForeignKeyProperty.Name + "Id");
                //ForeignKeyProperty.SetValue(model, repository.GetList<ViewModel>().Single(x => x.Id == model.Id));
                var listMethod = repositoryType.GetMethods().SingleOrDefault(x => x.Name == "GetList").MakeGenericMethod(ForeignKeyProperty.PropertyType);
                //Expression.Call(singleMethod,);
                var repositoryVariable = Expression.Parameter(repositoryType, "repository");
                var paramViewModelType = Expression.Parameter(viewModelType, "model");
                var paramForeignEntityId = Expression.Property(paramViewModelType, "Id");
                var listMethodCall = Expression.Call(repositoryVariable, listMethod);
                var modelParameter = Expression.Parameter(ForeignKeyProperty.PropertyType, "x");
                var foreignKeyTypeConstant = Expression.Constant(ForeignKeyProperty.PropertyType);
                var condition =
                    Expression.Lambda < Func < ViewModel, bool>>(
                        Expression.Equal(
                            Expression.Property(paramViewModelType, foreignKeyIdProperty.Name),
                            Expression.Convert(Expression.Property(modelParameter, "Id"),foreignKeyIdProperty.PropertyType)
                        ),
                        modelParameter
                    );
                //var singleMethod = typeof(Enumerable).GetMethods().SingleOrDefault(x => x.Name.Equals("SingleOrDefault") && x.GetParameters().Count() ==2).MakeGenericMethod(viewModelType);
                //var singleMethod = typeof(IEnumerable<ViewModel>).GetMethods().SingleOrDefault(x => x.GetParameters().Count() > 0).MakeGenericMethod(viewModelType);
                //var singleLambda = Expression.Lambda(Expression.Property(modelParameter, "Id"), modelParameter);
                var singleMethodCall = Expression.Call(typeof(Enumerable), "SingleOrDefault", new[] { ForeignKeyProperty.PropertyType },listMethodCall, condition);
                //var singleMethodCall = Expression.Call(listMethodCall, singleMethod, condition);
                var setMethod = ForeignKeyProperty.GetSetMethod();
                var oParameter = Expression.Parameter(viewModelType, "obj");
                var vParameter = Expression.Parameter(typeof(ViewModel),"value");
                var method = Expression.Call(oParameter,setMethod, singleMethodCall);
                var expression = Expression.Lambda<Action<IVenturaRepository, ViewModel>>(method);
                actions.Add(expression.Compile());
            }
            return actions;
        }

Could someone point me in the right direction please?

A: use Object as type. then you can check type by getType() at runtime and after check cast to correct type. or use dynamic to avoid casting.

A: So, I did as you suggested and used object instead. It works now.
Code below works in a specific controller that inherits from BaseController.

public override ActionResult Edit(long id, DeliveryEditViewModel model)
        {
            model.SourceModel.DeliveryRound = Repository.DeliveryRounds.Single(x => x.Id == model.DeliveryRoundId);
            model.SourceModel.Sale = Repository.Sales.Single(x => x.Id == model.SaleId);
            return base.Edit(id, model);
        }

Idea is that code below works in BaseController:

        public virtual ActionResult Edit(long id, EditModel model)
        {
            try
            {
                if (setForeignKeyActionList == null)
                    setForeignKeyActionList = SetForeignKeyProperties();
                setForeignKeyActionList.ForEach(action => action(Repository, model.SourceModel));
                Repository.SaveItem(model);
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("Error", ex);
                return View(Repository.GetEditableItem(id));
            }
        }

This is the revised code based on your suggestion to use object type

protected List< Action< IVenturaRepository, ViewModel>> SetForeignKeyProperties()
        {
            var viewModelType = typeof(ViewModel);
            var foreignKeyProperties = viewModelType.GetProperties().Where(x => x.PropertyType.IsSubclassOf(typeof(BaseViewModel)));
            var actions = new List< Action< IVenturaRepository, ViewModel>>();
            var repositoryType = typeof(IVenturaRepository);
            foreach (var ForeignKeyProperty in foreignKeyProperties)
            {
                var foreignKeyIdProperty = viewModelType.GetProperties().SingleOrDefault(x => x.Name == ForeignKeyProperty.Name + "Id");
                //ForeignKeyProperty.SetValue(model, repository.GetList< OtherViewModel>().Single(x => x.Id == model.Id));
                var listMethod = repositoryType.GetMethods().SingleOrDefault(x => x.Name == "GetList").MakeGenericMethod(ForeignKeyProperty.PropertyType);
                var repositoryVariable = Expression.Parameter(repositoryType, "repository");
                var paramViewModelType = Expression.Parameter(viewModelType, "model");
                var paramForeignEntityId = Expression.Property(paramViewModelType, "Id");
                var listMethodCall = Expression.Call(repositoryVariable, listMethod);
            var foreignKeyTypeConstant = Expression.Constant(ForeignKeyProperty.PropertyType);
            var objectType = Expression.Parameter(typeof(object), "model");
            var modelParameter = Expression.Parameter(typeof(object), "x");
            var expressionForeignKeyId = Expression.Property(paramViewModelType, foreignKeyIdProperty.Name);
            var expressionForeignEntityId = Expression.Convert(Expression.Property(Expression.Convert(modelParameter, ForeignKeyProperty.PropertyType), "Id"), foreignKeyIdProperty.PropertyType);
            var condition =
                Expression.Lambda<Func<object, bool>>(
                    Expression.Equal(
                        expressionForeignKeyId,
                        expressionForeignEntityId
                    ),
                    modelParameter
                );
            var singleMethodCall = Expression.Call(typeof(Enumerable), "SingleOrDefault", new[] { ForeignKeyProperty.PropertyType }, listMethodCall, condition);
            //var singleMethodCall = Expression.Call(listMethodCall, singleMethod, condition);
            var setMethod = ForeignKeyProperty.GetSetMethod();
            //var oParameter = Expression.Parameter(viewModelType, "obj");
            var vParameter = Expression.Parameter(typeof(ViewModel), "value");
            var method = Expression.Call(paramViewModelType, setMethod, singleMethodCall);
            var lamdaParameterExpressions = new[]
            {
                repositoryVariable,
                paramViewModelType
            };
            var expression = Expression.Lambda<Action<IVenturaRepository, ViewModel>>(method, lamdaParameterExpressions);
            actions.Add(expression.Compile());
        }
        return actions;
    }


text:
Q: Provision an Office365 Group and disable shared email address I'm wondering about a couple things with Office365 Groups:

*

*Is it possible to provision a group and to disable certain services, e.g. the shared inbox and calendar? (the reason being is to not conflict with existing distribution lists)

Thanks

A: No, it isn't possible. Office 365 Groups are a take it or leave it object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where do I place a WHERE clause in a PIVOT with date transaction amount_usd  paytype SendItemDateTime1
5.00    google  2015-04-01
2.00    google  2015-04-01
5.00    transfer    2015-04-01
15.00   google  2015-04-01
5.00    google  2015-04-01
2.00    google  2015-04-02
60.00   google  2015-04-02
60.00   google  2015-04-02
5.00    google  2015-04-03

Above is my demo database which have amount_usd, paytype, and SendItemDateTime1 column. when i using pivok with query below, it come out result below, which the SendItemDateTime1 is not group by... what is the problem?
 select amount_usd, paytype, SendItemDateTime1 from tblMobile_RequestOrderLog
  where status = 1 and sendstatus = 1 and enable = 1
  and SendItemDateTime1  between '4/1/2015' and '4/30/2015'
  order by SendItemDateTime1

Below is the result from query above.
SenditemDateTime1   google  mol molpay  molstore    paypal  transfer
2015-04-01  15.00   NULL    NULL    NULL    NULL    NULL
2015-04-01  5.00    NULL    NULL    NULL    NULL    NULL
2015-04-01  15.00   NULL    NULL    NULL    NULL    NULL
2015-04-01  5.00    NULL    NULL    NULL    NULL    NULL
2015-04-01  60.00   NULL    NULL    NULL    NULL    NULL
2015-04-01  10.00   NULL    NULL    NULL    NULL    NULL

And below is what i want...
SendItemDate    google  mol molpay  molstore    paypal  transfer
2015-04-01      32      0   0       0          0    5
2015-04-02      122     0   0       0          0    0
2015-04-03      5       0   0       0          0    0

sorry, first time post question here...
Edit
This work for me with "Where" clause:
SELECT SendItemDateTime1, COALESCE([google], 0), COALESCE([transfer], 0),
       COALESCE([paypal], 0),COALESCE([molpay], 0)
FROM (Select SendItemDateTime1, paytype, amount_usd
      from tblMobile_RequestOrderLog
      where gameidn = 248 and status = 1 and sendstatus = 1 and enable = 1
            and SendItemDateTime1 between '4/1/2015 12:00:00 AM'
                                      and '4/30/2015 11:59:59'
) X
PIVOT
(
  SUM(amount_usd)
  for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv;

A: You can pivot the data in your first table with the below query - you'll just need to list all the payment type columns explicitly. I've assumed SUM() as the aggregation to be applied:
SELECT SendItemDateTime1, [google],[transfer],[paypal],[molpay]
FROM MyTable
PIVOT
(
 SUM(amount_usd)
 for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv;

SqlFiddle here
Edit, Re where do I filter
If the filter predicate can be applied to the final columns, then WHERE can be applied after the PIVOT. Otherwise, if the filtering needs to be done in unpivoted columns, then you can use a CTE, or derived table as you have done. Here's an example of prefilter in CTE and postfilter WHERE:
-- Prefilter of non-pivot columns done in CTE or Derived table
WITH cte AS
(
  SELECT [amount_usd], [paytype], [SendItemDateTime1]
  FROM MyTable
  WHERE [amount_usd] > 2
)
SELECT SendItemDateTime1, COALESCE([google], 0), COALESCE([transfer], 0),
       COALESCE([paypal], 0),COALESCE([molpay], 0)
FROM cte
PIVOT
(
 SUM(amount_usd)
 for [paytype] IN ([google],[transfer],[paypal],[molpay])
) piv
-- Post filter of pivot columns done on the final projection
WHERE SendItemDateTime1 > '2015-01-01';

Updated Fiddle


text:
Q: Ocultar DIV o variable en una condicional sólo si el resultado del loop no existe. Wordpress <?php

$title = '
' . 'Víveres' . '
'; ?>

<?php
        if (is_tax($WCMp->taxonomy->taxonomy_name)){
            $vendor_id = get_queried_object()->term_id;
            if ($vendor_id){
                $vendor = get_wcmp_vendor_by_term($vendor_id);
               echo $title;
            echo '
 $vendor->id,
            'post_type' => 'product',
            'post_status' => 'publish',
            'ignore_sticky_posts' => 1,
            'orderby' => 'title',
            'order' => 'desc',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'terms' => 'proteinas',// categories
                    'field' => 'slug',
                    'operator' => 'IN'
                )
            )
        );
        echo '
';
    // End query
      }
}
        $products = new WP_Query( $args, 'wcmp_product_category'); ?>

<?php   if (have_posts()):
            while ($products->have_posts()):
                $products->the_post();

                /**
                 * Hook: woocommerce_shop_loop.
                 */
                do_action( 'woocommerce_shop_loop' );
                wc_get_template_part( 'content', 'product' );
            endwhile;
    endif;
    ?>

En el código anterior estoy haciendo un loop personalizado para llamar y obtener resultados de una categoría de productos específica de un usuario, el código funciona "bien" pero estoy tratando de hacer que, si la categoría de productos no existe o no hay disponibilidad de stock no muestre el h4 ($title).
Alguna sugerencia? Gracias.

A: Lo mas simple es agregar css a la etiquete H4
<h4 style="display:<?php echo $muestraonomuestra;?>;"

if($hayproductos==true){
$muestraonomuestra="block";
} else{
$muestraonomuestra="none";
}


text:
Q: Facebook.Client WP8 uses which Facebook API version? I've been using the NuGets from Outercurve Foundation (Facebook and Facebook.Client) and I've just updated to the latest stable version for both of them since Facebook API 2.0 and 2.1 will be depricated on the 7th August 2016 and they are forcing us to use the later verstions of their API.
Here is the thing... the website facebooksdk.net which had documentation and such was down for some time and now it redirects to hackerapp.com which has no documentation whatsoever...
Does any one know the version of Facebook API that the NuGet Facebook 7.0.6 and Facebook.Client 1.0.4 are using?
I think that the facebook button (from Facebook.client) is using the 2.1 version of the API. because I saw it in the query when it opens the browser just before the login prompt.
Does any one know which version is used? and if there is another way to login using the 2.5 or 2.6 API version?

A: I believe the client does not enforce any API version, so it will make unversioned calls. And in this case, it will use the default API version that is set on your Facebook App...
You can check the default API version for your app in your app's dashboard in https://developers.facebook.com
Mine is currently v2.0 (I don't know yet how to change manually that version. Facebook will certainly upgrade it when v2.0 expires)

I am using an even older version of the nuget package (6.4.2) and was able to override the version simply setting it in the endpoint being called:
Exmaple:
var client = new FacebookClient(accessToken);

dynamic facebookUser = client.Get("me"); //this will use v2.0 currently (default API version)
dynamic facebookUser = client.Get("v2.6/me"); //this will use v2.6

PS: version 2.0 will expire 7th August 2016... version 2.1 will expire only in 30 October 2016 (2 years after 2.2 was launched)

A: For those wanting to use Facebook.Client with Facebook API v2.5 you can use this one https://github.com/rickrvo/facebook-winclient-sdk
it's just the same as the version 1.0.4 but changed all hardcoded calls using v2.1 to use v2.5


text:
Q: How to plot multiple variables of a data.table in R? I have a time series that has a DateTime variable and 4 more variables, which are measured over time.
I'm trying to create a function in R which gets the data set (as a data.table) and creates 4 plots, each plot showing one of the four variables (y axis) against time (x axis).
I already found out that I can create multiple plots by using
par(mfrow=c(4,1))

But the problem is that I don't know how to reference each of the 4 columns in the "plot" function.
If I do a single plot without a function, it looks like this:
plot(DT[,DateTime],DT[,VAR1],type="l",ylab="VAR1")

This is exactly the line which I want for VAR1...VAR4 using a function. Note that I do not want a plot which depicts all 4 variables in a single plot, but rather 4 plots, one for each variable.
Thanks!

A: lapply(c("VAR1", "VAR2", "VAR3", "VAR4"), function(x){
    plot(DT[,DateTime], DT[, ..x], type="l", ylab=x)
})


text:
Q: Why does socket connection not work inside onsubmit-event? Spent a good while wondering why the connection to websocket ("var..." and  "socket.on..." statements) do not work when placed inside the function that follows onsubmit:
document.addEventListener('DOMContentLoaded', () => {

        document.querySelector('#display_name').innerHTML = localStorage.getItem('display_name');

        document.querySelector('#new_channel').onsubmit = () => {

          const new_channel_name = document.querySelector('#new_channel_name').value;
          console.log(`New channel name: ${new_channel_name}`);

          var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
          socket.on('connect', () => {
            console.log("THIS NEVER GETS EXECUTED");
          });

       };
   });

When moving the connection statements out, the connection seems to work:
document.addEventListener('DOMContentLoaded', () => {

        document.querySelector('#display_name').innerHTML = localStorage.getItem('display_name');

        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
        socket.on('connect', () => {
          console.log(`Connected to SOCKET ID: ${socket.id}`);
            });

        document.querySelector('#new_channel').onsubmit = () => {

          const new_channel_name = document.querySelector('#new_channel_name').value;
          console.log(`New channel name: ${new_channel_name}`);

          };
      });

Looks like a fundamental lack of understanding something here on my side, but no luck finding explanations as to why... Anyone can help me understand why?
Ultimately my goal is to make a chat app using multiple channels or namespaces (with a Flask server using SocketIO), hence my desire to only create the connection once a user submits the new channel form, and not before when the client does not know what path/channel to connect to. And I know that I will have to change the socket-initialization to include some path to the non-default channel (so far I am simply trying to get it to connect). Anyone know how to get around this? Thank you!

A: As the other answer noted, you need to call event.preventDefault() in order to prevent the page from reloading.
Another issue is you're trying to connect each time the submit button is clicked, but you don't send any parameter to the server that indicates the channel, so it's best to send the correct channel name to the server.
So, the best solution is:

*

*add e.preventDefault()

*store sockets in a sockets global variable, and push to it whenever there is a new connection along with the channel name

*send channel name to the server

*if there is a connection request, first check if that channel name exists in sockets

A: If you are referring to the submit event fired by a form, you may need to prevent default to keep the page from reloading? A page reload would end your socket connection.
https://www.codexpedia.com/javascript/submitting-html-form-without-reload-the-page/
x.onsubmit = (e) => { e.preventDefault(); more code}


text:
Q: Parsing through CSV using DictReader in Python I have a large CSV file with many columns, something like this:
id, col1, col2, col3, col4, col5
1, a, b, 2, d, e
2, b, c, 4, e, f
3, c, d, 6, f, g

I want to be able to create a dictionary in which only certain columns are used. For example, the dictionary would have the id number, col2, and col3. Additionally, it should only store the rows that have the highest 10 numbers in col2. This is the code I have:
import csv
reader = csv.DictReader(open('SNPs.csv', newline=''), delimiter=',', quotechar='"')

But I do not know how to tell it to ignore certain columns, and I don't think that I can use max() to return multiple values.
max(2, 4) returns 4.

EDIT
I tried using Daniel's Code, but for some reason the sort function isn't working correctly. (I also need to use reverse sort instead of sort). It only outputs four different keys, and additionally, they aren't actually sorted in descending numerical order. It also returns the headers as one of the values.
import csv
f = open('SNPs.csv', "rU")
reader = csv.reader(f)
output = [row for row in reader]
output.sort(key=lambda x: x[32], reverse=True)
print dict((row[10], (row[11], row[8], row[32])) for row in output[:10])

A: col2 doesn't have any numbers. I'll assume you meant col3.
You can't tell which are the ten highest numbers in col3 until you've read them all. So since you're going to be doing that anyway, you might as well read everything, then extract the top ten afterwards. So you can do something like this:
output = []
for row in reader:
    output.append(dict(k, v) for k, v in row if k in ('id', 'col2', 'col3'))
output.sort(key=lambda x: x['col3'])
return output[:10]

Edit Now I see your desired output, you want something completely different to what I imagined. In fact DictReader is completely pointless here, so I'll rewrite with the normal Reader.
f = open('SNPs.csv')
reader = csv.Reader(f, delimiter=',', quotechar='"')
output = [row for row in reader]
output.sort(key=lambda x: x[3])
return dict((row[0], (row[3], row[4])) for row in output[:10])

A: Maybe this works:
f = open("SNPs.csv", "rU")
reader = csv.reader(f)
data = [row for row in reader] #This only works if you have enough memory to do so
set_highest_ten = set(row[32] for row in sorted(
                                      data, key = lambda x: x[32], reverse = True)[0:10])
d = dict((row[10], (row[11], row[8], row[32])) for row in data
                                                       if row[32] in set_highest_ten)

I've tested with a small amount of data and it seems fine, but I'm not sure if this is exactly what you are looking for.


text:
Q: Get the response of a HTTP GET request I'd like to use http://www.imdbapi.com/ in Java, but I don't know I can access the http response. I tried the following:
public Map<String, String> get(String title)
{
    URL url = new URL("http://www.imdbapi.com/?t=" + title);
    URLConnection conn = url.openConnection();

    conn.getContent();

}

A: You can use URLConnection#getInputStream():
InputStream input = conn.getInputStream();
// ...

Or just the shorthand URL#openStream() directly:
InputStream input = url.openStream();
// ...

Once having it, just send it to a JSON parser of your choice, such as for example Gson:
InputStream input = new URL("http://www.imdbapi.com/?t=" + URLEncoder.encode(title, "UTF-8")).openStream();
Map<String, String> map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), new TypeToken<Map<String, String>>(){}.getType());
// ...

(note that I fixed your query string to be properly URL encoded)
See also:

*

*Using java.net.URLConnection to fire and handle HTTP requests

*Converting JSON to Java

A: When you go the website and type in the sample movie (i did True Grit ) you are actually able to see the response you would be getting. It looks something like this:
{"Title":"True Grit","Year":"2010","Rated":"PG-13","Released":"22 Dec 2010","Genre":"Adventure, Drama, Western","Director":"Ethan Coen, Joel Coen","Writer":"Joel Coen, Ethan Coen","Actors":"Jeff Bridges, Matt Damon, Hailee Steinfeld, Josh Brolin","Plot":"A tough U.S. Marshal helps a stubborn young woman track down her father's murderer.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjIxNjAzODQ0N15BMl5BanBnXkFtZTcwODY2MjMyNA@@._V1._SX320.jpg","Runtime":"1 hr 50 mins","Rating":"8.0","Votes":"51631","ID":"tt1403865","Response":"True"}

After knowing this info, you can easily parse your InputStream, which you obtain from your connection.
Good luck!

A: The below code should get you started. You need to add URL encoding if you are going to send special characters. In-order to parse JSON response you could probably use parser available in java at [link] http://www.JSON.org/
package problem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class Test {

public static void main(String args[])
{
 BufferedReader rd;
 OutputStreamWriter wr;

try
{
    URL url = new URL("http://www.imdbapi.com/?i=&t=dexter");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    wr = new OutputStreamWriter(conn.getOutputStream());
    wr.flush();

    // Get the response
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
       System.out.println(line);
    }
}
catch (Exception e) {
        System.out.println(e.toString());
    }

  }
 }

A: I recomend use http-request built on apache http api.
private static final HttpRequest<Map<String, String>> HTTP_REQUEST =
        HttpRequestBuilder.createGet("http://www.imdbapi.com/",
             new TypeReference<Map<String, String>>{}
        ).build();

public Map<String, String> get(String title) {
   ResponseHandler<Map<String, String>> responseHandler = HTTP_REQUEST.execute("t", title);
   return responseHandler.orElse(Collections.emptyMap()); //returns response parsed as map or empty map when response body is empty
}


text:
Q: kendo grid add non displayed field to store original value from valid field in datasource I have a datasource that has a column value i want to store in another "new" field that the datasource doesn't know about or care about.
I tried using the "from:" notation when adding the field, but i get error indicating my "legal" datasource field is undefined. Code snippet is below. I am adding this line to my model in the schema section of the KendoGrid definiton.
The column that has its value supplied by datasource directly is "remQty".
Can anyone spot why I get the "remQty" is undefined error?
schema: {
    model: {
            id: "myid",
            fields: {
                remQty: {type: "number",editable : true},
                originalRemQty: {type: "number", from: "remQty", editable : false}
        }
}

A: I think you can't use from to copy another field.

The option is supposed to get the value from the specified field in the raw JavaScript object and store it in a field of the model with a different name.

Source: http://www.telerik.com/forums/model---options-fields-fieldname-from-description-not-clear#3Nrb09uB5kmXOI2F3Xsbrw


text:
Q: Unable to load Ubuntu after installing Windows I had Ubuntu 11.10 installed, I installed Windows 7 on another partition but now on booting I cant see dual boot options and Windows 7 is loaded.
How can I run Ubuntu now?

A: Your grub2 installation was removed from the MBR by the Windows installation.
Please follow the instructions in the Recovering Ubuntu After Installing Windows wiki page, the graphical method should restore your grub2 install that was over written by the Windows installation.

*

*Insert your Ubuntu CD, reboot your computer and set it to boot from CD in the BIOS and boot into a live session. You can also use a LiveUSB if you have created one in the past.

*Install and run Boot-Repair

*After this, click "Recommended repair" and apply. If you are willing to use the advanced options, make sure you leave the "Reinstall GRUB" checkbox ticked.
  Now reboot your system. The usual GRUB boot menu should appear. If it does not, hold Left Shift while booting. You will be able to choose between Ubuntu and Windows.

The recovery method should detect both your new Windows and the Ubuntu install.

A: Is seems you have to reinstall grub as it was wiped after installing Windows 7. If I'm correct you will be looking for reinstalling grub 2. There seems to be some options for restoring grub 2 given on the ubuntu community help site: https://help.ubuntu.com/community/Grub2#Reinstalling_GRUB2

A: Re install GRUB. If you have a Ubuntu Live CD and you know the partition where Ubuntu is installed, then this blog post will help you for sure :-)
Restore Ubuntu after installing Windows

A: Windows 7 has its own boot manager which boots Windows, so when you install Windows 7 grub isn't avaible to load both operative systems, to solve this i'd use http://www.supergrubdisk.org/ , then you'll be able to get in ubuntu, upgrade your grub: sudo update-grub and this should fix your problem-


text:
Q: how do i set a condition on an onSubmit im working with a form and i want every first onSubmit to pop up an error message, and then work normally the second time around and so forth. heres what i have
const [submitting, setSubmitting] = useState(false);

const handleSubmit = event => {
    event.preventDefault();
    setSubmitting(true);

    setTimeout(() => {
      setSubmitting(false);
    }, 1000);
  }

and heres the error message i wanna inject for every first onSubmit
    setSubmitting(false);
  }, 2000);

  alert("An error has occured");

i want to be able to define whether or not my error message has already been shown, but after the first submit, my form forgets that the error message has already been shown. How should i go about solving  this?

A: Just track it in your state:
const [errorHasShown, setErrorHasShown] = useState(false);

if (!errorHasShown) {
    setErrorHasShown(true);
    alert("An error has occured");
}


text:
Q: How to build twitter's elephant-bird for thrift 0.9.1? The README file for elephant-bird mentions:

Thrift 0.5.0, 0.6.0, 0.7.0, greater versions than 0.9 are provided via thrift9 maven profile

I am using mvn package -e -Dprotobuf.version=2.6.1 -Dthrift.version=0.9.1 but it gives me the error:
.
.
.
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/user/Downloads/elephant-bird-elephant-bird-4.13/core/thrift7/src/test/java/com/twitter/elephantbird/thrift/TestThrift7BinaryProtocol.java:[24,12] error: cannot find symbol
.
.
.

Have I must install thrift 0.7.0 to get it working or is there some way that I am unaware of?

A: protobuf version : 2.5.0 and thrift version : 0.9.0 worked for me
mvn package -Dprotobuf.version=2.5.0 -Dthrift.version=0.9.0


text:
Q: How can I access and use button of one fragment inside another fragment? I've one fragment, HomeFragment(). In this fragment I've TabLayout with ViewPager2. In viewPager2 there is another fragment called ordersFragment(). Is it possible that I can click on any button that is placed in HomeFragment() and display some text in ordersFragment()`?

A: I'd really recommend using the modern approach, which is the ViewModels component. A view model is basically a class that holds your data and state, and the component enables each fragment in your activity to fetch the same view model instance, so they're all looking at the same thing
That way, one fragment can set a value for some data, while another fragment observes it and gets notified whenever there's an update. Neither fragment needs to know about each other, they're just talking to the view model and observing the stuff they need to worry about. There's an example of this kind of thing in the docs
You can coordinate all this stuff yourself (e.g. by going through the parent Activity and making that talk to the other fragment) but you're adding a lot of work and boilerplate which ViewModels take care of for you. And it helps you to separate your UI (displaying stuff, handling user interactions) from the business logic (doing something with that data, updating the app state). It's definitely good to know and makes communication around your app a lot easier

A: The best practice is to use callback implemented in one fragment and call that in another fragment.
if you are using kotlin check this..
link
(i don't want to copy paste same code here)


text:
Q: How to sort rect coordinates stored in a std::vector in vertical and horizontal lines I have a robot that prints lines on the floor and I command it by sending it a set of x,y points.
The points are contained in a file like the one in this figure that reports two rectangles to print.

I'm able to correctly collect all the points and load them into a std::vector in this way:
struct Coordinate
{
    double x0, x1, y0, y1;

    Coordinate(double paramx0, double paramy0, double paramx1, double paramy1) : x0(paramx0), y0(paramy0), x1(paramx1), y1(paramy1) {}
};

std::vector<Coordinate> coords;
...
coords.push_back(Coordinate(global_x0, global_y0, global_x1, global_y1));
...
cout<<coords.size()<<endl;

for (unsigned int i = 0; i < coords.size(); ++i)
{
   cout << i << " X[0]: " << coords[i].x0 << " Y[0]: " << coords[i].y0 << " || X[1]: " << coords[i].x1 << " Y[1]: " << coords[i].y1 << endl;
}

and this is a sample result obtained by the figure below.
0 X[0]: 62.5852 Y[0]: -36.5942 || X[1]: -62.5852 Y[1]: -36.5942
1 X[0]: 62.5852 Y[0]: -36.5942 || X[1]: 62.5852 Y[1]: 36.5942
2 X[0]: 62.5852 Y[0]: 36.5942 || X[1]: -62.5852 Y[1]: 36.5942
3 X[0]: -62.5852 Y[0]: -36.5942 || X[1]: -62.5852 Y[1]: 36.5942
4 X[0]: 62.5852 Y[0]: -76.4212 || X[1]: -62.5852 Y[1]: -76.4212
5 X[0]: 62.5852 Y[0]: -76.4212 || X[1]: 62.5852 Y[1]: -61.4214
6 X[0]: 62.5852 Y[0]: -61.4214 || X[1]: -62.5852 Y[1]: -61.4214
7 X[0]: -62.5852 Y[0]: -76.4212 || X[1]: -62.5852 Y[1]: -61.4214

My problem now is to understand what's the better way to create a list of x,y points related to only the horizontal lines and another list that contains only the vertical lines starting from the lowest coordinate.
The robot will move by firstly print the vertical lines and then all the horizontal lines.
In the figure below, for example, the robot will first print line 1, 2, 3, 4 and it will stop and then it will print lines 5, 6, 7, 8.
So, I need to communicate to the robot all the waypoints in the correct order.
What is the best way to create these two groups and order each lines based on their distance? The robot needs to optimize the path by firstly print all the segments that belong to the same direction.
P.S. I'm using C/C++ and Ubuntu.


text:
Q: How To Set Default Home Page in Node.Js? Here Is My Code I am Able To See this File Content but on refresh, not as soon i type localhost and port.
// Include http module,
var http = require("http"),
// And url module, which is very helpful in parsing request parameters.
    url = require("url");
 var EventEmitter = require('events').EventEmitter;
 var fs = require('fs');
 var emitter = new EventEmitter;
var fdata="";
http.createServer(function (request, response) {

if(request.url=="/")
{
        response.writeHead(200, {'Content-Type': 'text/html'});
      fs.readFile("xhtmlJs.xhtml","UTF-8" ,function (err, data){
           fdata=data;
    });
    response.write(fdata+"<br/>"+request.url);
     response.end();
 }
}).listen(1234);


text:
Q: Set transition to start in motion layout after transitionCompleted I have a motion layout with left drag, When the transition is completed I want it to go back to the start state automatically. I tried the transitionListener, onTransitionCompleted function to set the motion layout to start but it's not working.
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val ml = findViewById<MotionLayout>(R.id.motionLayout)
    val customListener = object : MotionLayout.TransitionListener {
        override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) {
            Toast.makeText(applicationContext, "started", Toast.LENGTH_SHORT).show()
        }

        override fun onTransitionChange(p0: MotionLayout?, p1: Int, p2: Int, p3: Float) {
            if(p0?.progress == 1f){
                p0.transitionToStart()
            }
        }

        override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) {
            Toast.makeText(applicationContext, "Ended", Toast.LENGTH_SHORT).show()

                p0.transitionToStart()

        }

        override fun onTransitionTrigger(p0: MotionLayout?, p1: Int, p2: Boolean, p3: Float) {

        }

    }

    ml.setTransitionListener(customListener)
}

App:

A: In the transition you can set
  <Transition
    motion:constraintSetEnd="@+id/end"
    motion:constraintSetStart="@+id/start"
    motion:autoTransition="animateToStart"
    motion:duration="1000">

This will automatically transition to the start when it reaches the end
If you are using an OnSwipe 2.1
has
<OnSwipe ...
motion:onTouchUp="neverCompleteToEnd" />


text:
Q: SQL Server 2005 View get the calling SQL Statement I have a view, now I need in my view the SQL Statement that is selecting me.
For example:
SELECT col1, col2, col3 FROM myView WHERE col1 LIKE 'test%'

Now in my view I need my calling SQL Statement to send it with an CLR Function to a web service.
Is it possible to get this SQL Statement that SELECTS the view inside the view?
I tried it with
SELECT sqltext.TEXT
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exex_sql_text(sqlhandle) AS sqltext

but it gives me all statements that currently running, so I get when I do 3 SELECTS I get all of them in my result.
Or gives me the statement I tried all statements that are executed in this connection?


text:
Q: Pandas series substring starts and ends with letter I have a large pandas series containing approximately half a million rows of this form:
pd.Series(['Lorem ipsum dolor sit amet',
            'consectetur adipiscing elit',
            'quis euismod mi, id venenatis urna',
            'curabitur vel augue viverra diam imperdiet laoreet'])

and I would like to filter the series by words that start and end with a specific letter. For example, if start letter is 'l' and end letter is 'm', then I want to include rows that have 'lorem' as substrings, or rather '^l.*m$'.
So I need to split my string into substring and do .str.contains('^l.*m$'), however I don't know of an optimised way to do this.

A: You can use word boundaries matching from L to m \bL\w*m\b and in between match 0 or more word characters.
import pandas as pd

s = pd.Series(['Lorem ipsum dolor sit amet',
           'consectetur adipiscing elit',
           'quis euismod mi, id venenatis urna',
           'curabitur vel augue viverra diam imperdiet laoreet'])
s = s.str.contains(pat = r'\bL\w*m\b', regex = True)
print(s)

Output
0     True
1    False
2    False
3    False
dtype: bool


text:
Q: Scanning use error while compiling Devanagari text I tried to run the Latex code posted by Stephen Kottwiz as an answer to this question: How to make Sanskrit Title in Devanagari Package
Here's the same code repeated:
\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{devanagari}
\usepackage{fontspec,bera}
\begin{document}
\title{{\dn vivekachoodama.ni}}
\author{Sri Sankaracharya}
\maketitle
\begin{flushleft}
{\dn sarvavedaantasiddhaantagocara.m tamagocara.m | \\ govinda.m paramaananda.m {sad}guru.m pra.nato.asmyaham ||  1}

\end{flushleft}
\end{document}

I tried using PDFLatex to process the code and am getting the following error.
line 0: File ended while scanning use of \iow_wrap_loop:w
Can anyone shed any light on this matter?

A: Since fontspec is being loaded, you need to process the example with xelatex; however, the original code won't work as expected (using xelatex) and will produce the error message
) Runaway argument? \q_stop \exp_args:NNo \group_end: \iow_term:n \l__iow_wrap_tl \iow_term:n \ETC. ! File ended while scanning use of \__iow_wrap_loop:w. <inserted text>
                \par  l.269 \luatex_if_engine:T
                          { \RequirePackage{fontspec-luatex} \endinput } ?

in order for the example to work (at least in TeX Live2012) it's necessary to load fontspec before devanagari (and the fontenc and inputenc packages should not be loaded):
\documentclass[10pt]{article}
\usepackage{fontspec}
\usepackage{devanagari}
\usepackage{bera}

\title{{\dn vivekachoodama.ni}}
\author{Sri Sankaracharya}

\begin{document}

\maketitle

\begin{flushleft}
{\dn sarvavedaantasiddhaantagocara.m tamagocara.m | \\ govinda.m paramaananda.m {sad}guru.m pra.nato.asmyaham ||  1}
\end{flushleft}

\end{document}

This produces the following output:

and a warning about some fonts not being available:
LaTeX Font Warning: Font shape `EU1/fve/m/n' undefined (Font)
      using `EU1/lmr/m/n' instead on input line 11.

Not loading the bera package suppresses the warning.
If you want to process with pdflatex, remove the fontspec package (and you can again load fontenc and inputenc):
\documentclass[10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{devanagari}
\usepackage{bera}

\title{{\dn vivekachoodama.ni}}
\author{Sri Sankaracharya}

\begin{document}

\maketitle

\begin{flushleft}
{\dn sarvavedaantasiddhaantagocara.m tamagocara.m | \\ govinda.m paramaananda.m {sad}guru.m pra.nato.asmyaham ||  1}
\end{flushleft}

\end{document}

This time no warning is produced.


text:
Q: bash retry function with silencer I found a bash function, that let's me retry commands.
function retry {
  local n=1
  local max=50
  local delay=1
  while true; do
    "$@" && break || {
      if [[ $n -lt $max ]]; then
        ((n++))
        echo "[$n/$max] ($?) $@:" >&2
        sleep $delay;
      else
        fail "The command has failed after $n attempts."
      fi
    }
  done
}

function fail {
  echo $1 >&2
  exit 1
}

I use it like this
$ retry ping -q -c 1 $ip

However, when retrying commands, I never want to see the commands stderr or the stdout output. How can I silence the command when retrying like this?

A: If you want to silence all output of the command executed by the retry function, change
"$@" && break || {

to:
"$@" &>/dev/null && break || {

in the script or simply give it along with the argument, e.g.:
retry "ping -q -c 1 $ip &>/dev/null"

If you however want to silence all output of the whole function, either comment out every echo line in your script and do the change explained above or append &>/dev/null on the command line, e.g.:
retry ping -q -c 1 $ip &>/dev/null

A: I do my testing on bsd/macos, this seems to work. The other answer didn't work. I'm guessing it would also work in my ubuntu production environment.
function retry {
  local n=1
  local max=50
  local delay=1
  echo contained "$@"
  while true; do
    eval "$*" &>/dev/null && break || {
      foo=$?
      if [[ $n -lt $max ]]; then
        ((n++))
        echo "[$n/$max] ($foo) $@" >&2
        sleep $delay;
      else
        fail "The command has failed after $n attempts."
      fi
    }
  done
}

retry "ping -q -c 1 $ip"


text:
Q: How to animate translate between elements of two arrays function Counter() {
  const [list1, setList1] = createSignal([1, 2, 3, 4, 5]);
  const [list2, setList2] = createSignal([6, 7, 8, 9, 10]);

  setTimeout(() => {
      setList1([1, 2, 3, 4, 5, 8, 9, 10])
      setList2([6, 7])
  }, 1000)

  return (<>

    <For each={list1()}>{ (item, i) =>
       <span style={`position: absolute; color: blue; transform: translate(${i()}em, 0)`}>{item}
    }</For>
    <For each={list2()}>{ (item, i) =>
       <span style={`position: absolute; color: red; transform: translate(${i()}em, 2em)`}>{item}
    }</For>

    </>)
}

render(() => <Counter />, document.getElementById("app"));

Bonus would be for animating the color too.

A: We have found two ways of solving that currently:

*

*Combining two For-s to one Index that would render the combined array - preventing existing elements to switch their position in the dom. And calculating their actual value based on the index.

link: https://playground.solidjs.com/?hash=562431964&version=1.3.16

*Utilising the TransitionGroup with For. So that TransitionGroup can take care of elements that switch their position in array.

link: https://playground.solidjs.com/?hash=-283765756&version=1.3.16
Both methods rely on using only one Control Flow component though.


text:
Q: How to add SQL file with PHP to WordPress database I have SQL file with US zip codes (over 41000 lines of code). I want make a plugin that inserts this SQL file into WP database so user can do a search by zip codes. I want to insert SQL with PHP rather than PhpMyAdmin

A: See the WordPress Codex on Creating Tables with Plugins.

A: I have not created a plugin that does what you want, but I have been playing with a plugin that creates its own tables.
The plugin in comes with an SQL.txt file in case your WordPress install does not have permissions to create tables (in which case you would have to manually run the SQL file)
So it seems that a plugin that creates tables could potentially be problematical during install.
Another thing that this same plugin does is use an array from another file to display things. This seems like it would be a better approach because you would not have to mess with people's DB, and you could easily update the file that holds your array of zip codes.
Here is some of the code it uses for doing that:
 //Build new blog_type array item.
    $blog_type_item = array('name' => $name,
                            'nicename' => empty($nice_name) ? strtolower(str_replace(' ', '_', $name)) : $nice_name,
                            'description' => $description,
                            'signup_only' => $signup_only);

    //Append new blog_type array item to global array.
    $blog_types[] = $blog_type_item;

    return $blog_type_item;

<?php
                    foreach ($blog_types as $blog_type) {
                        $selected = '';
                        foreach ($selected_blog_types as $selected_blog_type) {
                            if ($selected_blog_type == $blog_type['nicename']){
                                $selected = ' selected="selected"';
                                $selected_blog_type_store = $blog_type['nicename'];
                            }
                        }
                        echo '<option value="' . $blog_type['nicename'] . '" ' . $selected . '> ' . $blog_type['name'] . '</option>';
                    }
                    ?>


text:
Q: Socks Server Behind HTTP Proxy I have a notebook(let's call it NOTEBOOK A) that is connected to INTERNAL NETWORK A. In order to browse the internet, NOTEBOOK A connects to a HTTP PROXY server which also resides in INTERNAL NETWORK A.
A second notebook (NOTEBOOK B), does not have the wifi password to access INTERNAL NETWORK A. So, NOTEBOOK B wants to access INTERNET and use NOTEBOOK A as tunnel. NOTEBOOK B successfuly established a network connection to NOTEBOOK A thru blueooth's Network Service.
NOTEBOOK A installed FreeProxy Software and hosted as a SOCKS server, which is for NOTEBOOK B to tunnel over. NOTEBOOK B then set its firefox to use SOCKS proxy and point to NOTEBOOK A. NOTEBOOK B managed to browse all the websites resides in INTERNAL NETWORK A, but the problem now is it can't browse the internet.
So, question is, how to configure the HTTP proxy for NOTEBOOK B? or it's suppose to handle by the SOCKS SERVER side?

A: Rather get notebook A to provide access to the proxy server with a DNAT iptables rule, and configure notebook B to use that instead of SOCKS.


text:
Q: Hide a check box conditionally I have a kendo grid containing following columns.
1.Name
2.Age
3.Gender{checkbox(male, female)}
I need to hide a column in specific row. In my problem, want to hide Gender cell which contain checkbox if Age value equal to 18 or 19 or 20.

A: As @Carsten said, you can't hide a cell, but only hide it's content. You can use a template for that:
template: "# if (data.Age < 18 || data.Age > 20) { #<input type='checkbox' name='Gender'># } #"

Dojo
In your case, using Asp.Net MVC you should use ClientTemplate. Something like this(can't test it):
columns.Bound(p => p.Gender).ClientTemplate("# if (data.Age < 18 || data.Age > 20) { #<input type='checkbox' name='Gender'># } #")

Source 1, source 2, source 3

A: You can't hide the cell but you can hide the content depending of the other columns. See https://docs.telerik.com/aspnet-mvc/helpers/grid/faq#how-to-apply-conditional-logic-to-client-column-templates on how to apply conditional logic to columns.


text:
Q: Converting character to numeric and then back to character I would like to know if it is possible in R to convert a vector of characters to numerical values, and then convert those numerical values back to their original characters?
For example, my code is:
data <- c("red","blue","green","red","yellow")
factor_data <- factor(data)
num_data <- as.numeric(factor_data)
print(num_data)

I would get
3 1 2 3 4

where blue = 1, green = 2, red = 3, yellow = 4
is there a way I can use num_data and get the corresponding character of colors to it?
My attempt was the code:
(factor_data)[num_data]

but that just returned me:
green red blue  green red

which is not the same as the original vector of colors.

A: You can use the factor's levels to effectively revert back to the original character vector.
levels(factor_data)[num_data]
# [1] "red"    "blue"   "green"  "red"    "yellow"

Data from the question:
data <- c("red","blue","green","red","yellow")
factor_data <- factor(data)
num_data <- as.numeric(factor_data)


text:
Q: TeXStudio and GSview problem: file .ps does not exist I have updated TeXStudio and now, when I compile, all work without errors. But If I "compile and view" or simple "view" The answer is:

File 'path\paper.ps' does not exist

from GSview.
Till yesterday, I had not any kind of this problem. Today I add the command \hyphenation in the code, but TeXStudio and MiKTeX work fine and I have my PDF output without errors.

A: This topic is quite old, but I just had the same issue and found a solution.
For some reason, an update changed the "Default Viewer" in Options > Configure TeXstudio > Build. I simply copied the line from the PDF Viewer command (for me txs:///view-pdf-internal --embedded). I have not encountered this with build and view, but if you do the script might have changed for ps viewer. For an embedded pdf : txs:///pdf-chain.
Hope it helps someone in the future.

A: I have solve in this way:

TeXStudio -> Menu -> Options -> Restore Default Settings...

Unfortunately, in this way I can not say you where is the problem.
Thanks.

A: I just into the same issue. I realized that for some reason the default viewer has changed to "txs:///view-ps" as soon as switched it back to "txs:///view-pdf" everything just worked fine again.
TexStudio -> Options -> Build -> Default Viewer


text:
Q: Camel Throwing MethodNotFound for method that exists and is public I'm testing a camel round but when I have the route try to access a particular method in a bean it keeps saying that there is no such method found. Source:
public class CommunicatorTest
{
    FakeMessageConverter converter;
    CamelContext context;
    ProducerTemplate template;
    String producerEndpoint = "seda:messagesFound";
    long test = 123456789;

    static final Logger logger = Logger.getLogger(CommunicatorTest.class);

    public CommunicatorTest()
    {

    }

    @Before
    public void setUp() throws Exception
    {
        converter = new FakeMessageConverter();
        SimpleRegistry registry = new SimpleRegistry();
        registry.put("converter", converter);
        context = new DefaultCamelContext(registry);
        template = context.createProducerTemplate();
        context.addRoutes(new CommunicatorRoute());

        logger.info("Done creating context");

        context.start();
    }

    @After
    public void tearDown() throws Exception
    {
        context.stop();
    }

    @Test
    public void testExistanceOfBean()
    {
        Object lookup = context.getRegistry().lookup("converter");
        assertTrue("Object not a MessageConverter", lookup instanceof FakeMessageConverter);
    }

    @Test
    public void testRoute()
    {
        Message msg = new Message();
        msg.setHeader(new MessageHeader());
        msg.getHeader().setSourceId(test);

        logger.info("Sending data");
        template.sendBody(producerEndpoint, msg);

        assertEquals("value not the same", test, converter.getSid());
        logger.info("Done Sending");
    }

    private static class FakeMessageConverter
    {

        private long sid;
        private boolean edited = false;

        public FakeMessageConverter()
        {
        }

        public void processMessage(Message msg)
        {
            sid = msg.getHeader().getSourceId();
            edited = true;
            logger.info("The sid"+sid);
        }

        /**
         * @return the sid
         */
        public long getSid()
        {
            return sid;
        }

        /**
         * @param sid the sid to set
         */
        public void setSid(long sid)
        {
            this.sid = sid;
        }
    }

}

The route is as follows:
public class CommunicatorRoute extends RouteBuilder
{

    @Override
    public void configure() throws Exception
    {
        from("seda:messagesFound").bean("converter", "processMessage");
    }

}

The exception is as follows:
ERROR [org.apache.camel.component.seda.SedaConsumer] - Error processing exchange. Exchange[Message: net.package.Message@f593af]. Caused by: [org.apache.camel.component.bean.MethodNotFoundException - Method with name: processMessage not found on bean: converter. Exchange[Message: net.package.message.Message@f593af]]

org.apache.camel.component.bean.MethodNotFoundException: Method with name: processMessage not found on bean: converter. Exchange[Message: com.saic.jswe.common.cdif.message.Message@f593af]
I'm still fairly new to camel so if I'm making some really simple mistake please let me know.

A: You class is private static. It must be public static so Camel can access it.

A: So I figured this out and it was a simple error. The routebuilder used the line from("seda:messagesFound").bean("converter", "processMessage"); which didn't work. BUT by changing the route to from("seda:messagesFound").beanref("converter", "processMessage"); and (as Claus mentions changing the access to public on the inner class) it worked fine. Just changing the class to public instead of private  only changes the error it would seem.
The crux of the issue is that the .bean() method doesn't look at the registry, so when I passed it converter I thought I was giving it the name of the bean to use, but the only .bean() variation that fits is public Type bean(Object bean, String method). So of course camel couldn't find the method: It was trying to find the method "processMessage" not in my converter but in the very string I passed it.


text:
Q: Como utilizar o maxResults e startAt corretamente em requisição ao jira Tenho a seguinte requisição ao jira:
https://jira.spring.io/rest/api/latest/search?jql=project=SPR+and+issuetype=Bug

Mas ela sempre retorna apenas as 50 mais recentes, como posso mudar para receber mais de 50 e também definir um valor inicial ?
Sei que e utilizado maxResults e startAt mas não consegui colocar eles na requisição sem dar erro.

A: Conseguir resolver o problema da seguinte forma:
https://jira.spring.io/rest/api/2/search?jql=project=SPR+and+issuetype=Bug&maxResults=-1&startAt=0


text:
Q: Finding the set "max_result_window" for Elastic Search index? So when querying ElasticSearch, I know you can constrain the size with the "size" parameter. By default, it's 10,000. I was wondering how to know what's the max (if it has been changed from 10,000)?
I have tried "/index/_settings" in hopes of finding the max_window_size, but couldn't find anything. I'm not necessarily sure if that's because it doesn't have a limit at all, or if I am doing something wrong.
So to rephrase my question: I basically want to know how to find the max size when trying to query "size: xx" to an elastic search server. If the size is 10,000/the default, then I want to know where I can find this number.
Any tips or guidance?

A: If the value isn't specified on the index itself (in _settings where you were looking), then it is 10000. You can change this setting only on the index itself as far as I know. To automatically apply it to new indices you can use an index template.
It appears to be an oversight by the devs to me, if you use rolling indices by date for example then there is no single index for you to query modifications to the value from (sure you could guess one). I think you just have to make sure to match your query code assumptions to your index template. In my opinion there should be a way to just ask for max results possible without needing to know that value beforehand.

A: You are correct in that elastic search default max query size is 10000. The way to get more is to use the "scroll" api:
https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-body.html#request-body-search-scroll
This essentially uses pagination to split your result into user defined segments and allows you to "scroll" to the next one using a "Scroll_id" that's returned from the initial query.


text:
Q: Script to convert filenames to lowercase depending on extension Script to convert filenames to lowercase depending on extension

A: To do it recursively for a number of extensions, you could use zsh's zmv:
zsh -c '
   autoload zmv
   ext=(jpg mp3 ogg)
   zmv -n "(**/)(*.(#i)(${(j:|:)ext}))" "\$1\${(L)2}"'

(remove -n (or replace it with -v) when happy).
Above the (#i) is to turn on case insensitive globbing, and ${(j:|:)ext} is to join the elements of the $ext list with |. You could also directly write it:
zsh -c '
   autoload zmv
   zmv -n "(**/)(*.(#i)(ogg|jpg|mp3))" "\$1\${(L)2}"'

A: I'm not sure how your question links to the code, so I'll focus on the question.
In bash versions 4 and above, you can do this by using something like the following:
for file in ./*.JPG; do     # Iterate over all items in the current directory that match *.JPG
    mv "$file" "${file,,}"  # Move the file found to a lowercase mapping (this is what the ,, parameter expansion method does)
done

Obviously replace *.JPG with the equivalent extension you're wanting.


text:
Q: Draw SVG Bezier curve I have an array of control points that represent a high-order Bezier curve.
How can I draw this curve using a single SVG-path?

UPD:
For example, I have a set of points: (x1, y1) (x2, y2) (x3, y3) (x4, y4) (x5, y5).How SVG-path will look like in the terms of C, S, Q or T?
UPD 2: SOLUTION
I asked this question to depict a object path animated with TweenMax.
Later I received reply on GreenSock forum.
Here's CodePen example.

A: Short answer: you can't.
SVG only has built in Quadratic (2nd order) and Cubic curves (3rd order), whereas the curve you're showing is Quartic (4th order). SVG has no generic "N term Bezier" draw instruction, so you're going to have to compromise here.
Some options:

*

*convert the curve to a (series of) cubic curves and render those instead. This is a pretty hard problem and not really recommended.

*sample your curve at enough points such that the polygon through those points looks like a curve at the resolution and zoom level people will be looking at it. This is easy to do, but of course you no longer have a "curve", you now have a polygon.

*as above, but fewer points, and then compute the Catmull-Rom curve sequence that goes through those points, then convert those CR curves to cubic Bezier (they're the same type of function, and can be 1:1 transformed from one to the other). This is nicer than 2 because you have a curve, but it might not look quite the same as the original. Of course the more points you use, the better the result will be.

*use a canvas to draw your Nth degree Bezier curve, build an image out of the result using the toDataURL function and then load that image as image in your SVG. This will work perfectly fine, but if you use created SVG path styling, making the canvas generate the same style could be a challenge.

*this list can get very long, so let's stop here for now.

Bottom line: if you need to show higher order Bezier curves, SVG is not an appropriate technology to use (I'd recommend just doing your animation using the canvas, or better yet, something like d3.js or paper.js. Probably the latter).
And if you end up rolling your own, the sampling function is ludicrously simple. Curves are parametric, controlled by a value t that runs from 0 to 1 (inclusive), and can be written as a nested linear interpolation:
getCurvePoint(t, points) {
  if (points.length === 1) return points[0];
  var newpoints = [];
  for(var i=0,j=1; j<points.length; i++,j++) {
    newpoints[i] = lerp2d(t, points[i], points[j]);
  }
  return getCurvePoint(t,newpoints);
}

with the lerp function being the standard linear interpolation function:
lerp(ratio, start, end) {
  return ratio*start + (1-ratio)*end;
}

lerp2d(ratio, start, end) {
  return {
    x: lerp(ratio, start.x, end.x),
    y: lerp(ratio, start.y, end.y)
  };
}

And a simple jsbin example: http://jsbin.com/pesutibefu/edit?html,js,output using points
var points = [
  {x:50, y:100},
  {x:50, y:250},
  {x:210, y:250},
  {x:250, y:50},
  {x:380, y:150}
];

gives us:

Although a Paper.js sketch would be easier to work with if you need animated pretty paths, with draggable control points, etc.

A: SVG does not support Bezier curves other than Quadratic and Cubic. So there is no representation in terms of commands(C, S, Q or T).
A Bezier curve can be defined in two ways: With a "C" command for cubic or with a "Q" command for quadratic. Those command have fixed length of parameters which is
4 for quadratic and 6 for cubic so an example SVG string will look like "Q 150,-300 300,0" you can see an SVG string like that "Q 150,-300 300,0 50,150 100,200" but that is just two quad curves one after another and the number of parameters will always be always multiple of 4 for "Q" and multiple of 6 for "C".
Every command in the list:
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
S = smooth curveto
Q = quadratic Bézier curve
T = smooth quadratic Bézier curveto
A = elliptical Arc
Z = closepath
has a representation in JavaScript or in fact in any other standard API (.NET Drawing, Core Graphics, Android Canvas) but in all of them there is no method for anything other than Cubic or Quad. Also in my experience I have never seen a drawing application that has a feature to draw a higher order Bezier curve. So your best option is to simplify the high order curve to a Q or C.


text:
Q: Select cells in a pandas DataFrame by a Series of its column labels Say we have a DataFrame and a Series of its column labels, both (almost) sharing a common index:
df = pd.DataFrame(...)
s = df.idxmax(axis=1).shift(1)

How can I obtain cells given a series of columns, getting value from every row using a corresponding column label from the joined series? I'd imagine it would be:
values = df[s]  # either
values = df.loc[s]  # or

In my example I'd like to have values that are under biggest-in-their-row values (I'm doing a poor man's ML :) )
However I cannot find any interface selecting cells by series of columns. Any ideas folks?
Meanwhile I use this monstrous snippet:
def get_by_idxs(df: pd.DataFrame, idxs: pd.Series) -> pd.Series:
    ts_v_pairs = [
        (ts, row[row['idx']])
        for ts, row in df.join(idxs.rename('idx'), how='inner').iterrows()
        if isinstance(row['idx'], str)
    ]

    return pd.Series([v for ts, v in ts_v_pairs], index=[ts for ts, v in ts_v_pairs])

A: I think you need dataframe lookup
v = s.dropna()
v[:] = df.to_numpy()[range(len(v)), df.columns.get_indexer_for(v)]


text:
Q: Tsrange - Subtracting the differences between two tables based on an id field I have two tables. free_time and appointment. I would like to subtract all of the appointment records from the records of free time. The result would be a set of records in which free time remains. The appointments are guaranteed to exist within the range of free_time. I would like to make this query WHERE doctor_id = 1.
They have the following records:
CREATE TABLE free_time
AS
  SELECT freetime::tsrange, doctor_id
  FROM ( VALUES
    ('[2017-04-19 09:00, 2017-04-19 12:30)', 1),
    ('[2017-04-19 13:30, 2017-04-19 15:30)', 1),
    ('[2017-04-20 08:30, 2017-04-20 16:30)', 1),
    ('[2017-04-19 09:00, 2017-04-19 16:30)', 2)
  ) AS t(freetime, doctor_id);

CREATE TABLE appointment
AS
  SELECT appointment::tsrange, doctor_id
  FROM ( VALUES
    ('[2017-04-19 10:30, 2017-04-19 11:30)', 1),
    ('[2017-04-19 13:30, 2017-04-19 14:30)', 1),
    ('[2017-04-20 10:30, 2017-04-20 13:30)', 1),
    ('[2017-04-20 14:30, 2017-04-20 16:30)', 1),
    ('[2017-04-19 10:30, 2017-04-19 11:30)', 2)
  ) AS t(appointment, doctor_id);

The result set should look something like:
["2017-04-19 09:00:00","2017-04-19 10:30:00"),
["2017-04-19 11:30:00","2017-04-19 12:30:00"),
["2017-04-19 14:30:00","2017-04-19 15:30:00"),
["2017-04-20 08:30:00","2017-04-20 10:30:00"),
["2017-04-20 13:30:00","2017-04-20 14:30:00"),

A: There are two functions (from my older answer with minor fix):
create or replace function range_exclude(anyelement, anyelement) returns anyarray as $$
declare
  r1 text;
  r2 text;
begin
  -- Check input parameters
  if not pg_typeof($1) in ('numrange'::regtype, 'int8range'::regtype, 'daterange'::regtype, 'tsrange'::regtype, 'tstzrange'::regtype) then
    raise exception 'Function accepts only range types but got % type.', pg_typeof($1);
  end if;

  -- If result is single element
  if ($1 &< $2 or $1 &> $2) then
    return array[$1 - $2];
  end if;

  -- Else build array of two intervals
  if lower_inc($1) then r1 := '['; else r1 := '('; end if;
  r1 := r1 || lower($1) || ',' || lower($2);
  if lower_inc($2) then r1 := r1 || ')'; else r1 := r1 || ']'; end if;

  if upper_inc($2) then r2 := '('; else r2 := '['; end if;
  r2 := r2 || upper($2) || ',' || upper($1);
  if upper_inc($1) then r2 := r2 || ']'; else r2 := r2 || ')'; end if;
  return array[r1, r2];
end $$ immutable language plpgsql;

create or replace function range_exclude(anyelement, anyarray) returns anyarray as $$
declare
  i int;
  j int;
begin
  -- Check input parameters
  if not pg_typeof($1) in ('numrange'::regtype, 'int8range'::regtype, 'daterange'::regtype, 'tsrange'::regtype, 'tstzrange'::regtype) then
    raise exception 'Function accepts only range types but got % type.', pg_typeof($1);
  end if;

  if array_length($2,1) is null then
    return array[$1];
  end if;

  $0 := range_exclude($1,$2[array_lower($2,1)]);
  for i in array_lower($2,1) + 1 .. array_upper($2,1) loop
    select array(select x from (select unnest(range_exclude(x,$2[i])) from unnest($0) as t(x)) as t(x) where not isempty(x)) into $0;
  end loop;
  return $0;
end $$ immutable language plpgsql;

After that your query could be:
with t as (
  select ft.doctor_id, freetime, range_exclude(freetime, array_agg(appointment)) as ex
  from free_time ft join appointment ap on (ft.doctor_id = ap.doctor_id)
  group by ft.doctor_id, freetime)
select doctor_id, unnest(ex) from t order by 1,2;

Result:

╔═══════════╤═══════════════════════════════════════════════╗
║ doctor_id │                    unnest                     ║
╠═══════════╪═══════════════════════════════════════════════╣
║         1 │ ["2017-04-19 09:00:00","2017-04-19 10:30:00") ║
║         1 │ ["2017-04-19 11:30:00","2017-04-19 12:30:00") ║
║         1 │ ["2017-04-19 14:30:00","2017-04-19 15:30:00") ║
║         1 │ ["2017-04-20 08:30:00","2017-04-20 10:30:00") ║
║         1 │ ["2017-04-20 13:30:00","2017-04-20 14:30:00") ║
║         2 │ ["2017-04-19 09:00:00","2017-04-19 10:30:00") ║
║         2 │ ["2017-04-19 11:30:00","2017-04-19 16:30:00") ║
╚═══════════╧═══════════════════════════════════════════════╝


text:
Q: why email component dont sent activation code to gmail? i tried to send activation code to user mail (currently gmail) from localhost.. when submit the user information saved in database but the message not sent..so why not sent ?
var $components = array('Email','Auth','Recaptcha');
// Allows a user to sign up for a new account
    function register () {
        if (!empty($this->data)) {
            // See my previous post if this is forgien to you
  if($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])){
                $this->User->data = Sanitize::clean($this->data);
            // Successfully created account - send activation email
        if($this->Recaptcha->valid($this->params['form'])){
            if ($this->User->save()) {
                $this->__sendActivationEmail($this->User->getLastInsertID());
                $this->Session->setFlash('activation code sent check your mail');
                $this->redirect('/users/register');
            }else {
             $this->data['User']['password'] = null;
            }

        }else{
            $this->data['User']['password'] = null;
          $this->Session->setFlash('wrong captcha please try again');
        }
  }else{
      $this->data['User']['password'] = null;
      $this->Session->setFlash('password not match');
  }

    }
   }

this function   Send out an activation email to the user.id specified by $user_id
      @param Int $user_id User to send activation email to
      @return Boolean indicates success
function __sendActivationEmail($user_id) {
        $user = $this->User->find(array('User.id' => $user_id), array('User.id','User.email', 'User.username'), null, false);
        if ($user === false) {
            debug(__METHOD__." failed to retrieve User data for user.id: {$user_id}");
            return false;
        }

        // Set data for the "view" of the Email

        $this->set('activate_url', 'http://' . env('SERVER_NAME') . '/cakenews/users/activate/' . $user['User']['id'] . '/' . $this->User->getActivationHash());
  $this->set('username', $this->data['User']['username']);

        $this->Email->to = $user['User']['email'];
        $this->Email->subject = env('SERVER_NAME') . ' - Please confirm your email address';
        $this->Email->from = 'spcialist@gmail.com';
        $this->Email->template = 'user_confirm';
         $this->Email->delivery = 'smtp';
       $this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'spcialist@gmail.com',
'password'=>1234567,

               );
        $this->Email->sendAs = 'text';   // you probably want to use both :)
        return $this->Email->send();
    }

A: You wrote you are on localhost, you probably can't send emails but will probably work once online.
try debugging
function __sendActivationEmail($user_id) {
    $this->Email->delivery = 'debug';
    ....
}

Then in your layout
<?php echo $this->Session->flash('email'); ?>

And see what comes out.


text:
Q: Puppetter : Get a link in a body I've a link in a body like that :
      "uri": "https://dispatch-nvidia.digitalriver.com/v1/shoppers/me/products/5438795200/inventory-status",
      "availableQuantityIsEstimated": "false",
      "productIsInStock": "true",
      "productIsAllowsBackorders": "false",
      "productIsTracked": "true",
      "requestedQuantityAvailable": "true",
      "status": "PRODUCT_INVENTORY_OUT_OF_STOCK",
      "statusIsEstimated": "false"

I want the url,  how to do that ?
I've try let bodyHTML = await page.evaluate(() => document.body.innerHTML);
But don't work.
Thanks in advance

A: Nobody know ?
I've try with Regex
const regex = /(https?:\/\/)(\s)?(www\.)?(\s?)(\w+\.)*([\w\-\s]+\/)*([\w-]+)\/?/gm;

Without success ...
Edit : Find the solution :
    const bodyHTML = await page.evaluate(() => document.body.innerHTML);
    console.log(bodyHTML)
    const regex = /(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm;

const found2 = String(bodyHTML.match(regex));


text:
Q: How to use System Propery values as a part of logger handler pattern I'm using java.util.logging.logger as the logging engine for my application. I want to set a system property as a part of the value of handler pattern which is mentioned in the logging.properties file like below,
java.util.logging.FileHandler.pattern = path/${custom.home}/logs/server.log

I tried setting the above value, but it doesn't resolve custom.home property instead use that as a string and give below error while initializing the handler
Can't load log handler "java.util.logging.FileHandler"
java.nio.file.NoSuchFileException: path/${custom.home}/logs/server.log.lck
java.nio.file.NoSuchFileException: path/${custom.home}/logs/server.log.lck
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixFileSystemProvider.newFileChannel(UnixFileSystemProvider.java:177)
    at java.nio.channels.FileChannel.open(FileChannel.java:287)
    at java.nio.channels.FileChannel.open(FileChannel.java:335)
    at java.util.logging.FileHandler.openFiles(FileHandler.java:459)
    at java.util.logging.FileHandler.<init>(FileHandler.java:263)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at java.util.logging.LogManager$5.run(LogManager.java:966)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.loadLoggerHandlers(LogManager.java:958)
    at java.util.logging.LogManager.initializeGlobalHandlers(LogManager.java:1578)
    at java.util.logging.LogManager.access$1500(LogManager.java:145)
    at java.util.logging.LogManager$RootLogger.accessCheckedHandlers(LogManager.java:1667)
    at java.util.logging.Logger.getHandlers(Logger.java:1777)
    at java.util.logging.Logger.log(Logger.java:735)
    at java.util.logging.Logger.doLog(Logger.java:765)
    at java.util.logging.Logger.log(Logger.java:788)

Is there any way of achieving this requirement?
Thanks
Danesh

A: The path path/${custom.home}/logs/server.log doesnt exists!
Use:
`java.util.logging.FileHandler.pattern = "path/"+`System.getProperty("user.home")+"/logs/server.log";

instead.
But eclipse says : "FileHander.pattern is not visible!"

A: From your question I'm assuming you have manually set a system property called custom_home as a launch argument.  You can then subclass the java.util.logging.FileHandler to recognize the new pattern syntax:
public class EnvFileHandler extends FileHandler {

    private static String pattern() throws IOException {
        String prefix = EnvFileHandler.class.getName();
        String v = LogManager.getLogManager().getProperty(prefix +".pattern");
        return v.replace("${custom_home}", System.getProperty("custom_home", "%hjava.log"));
    }

    public EnvFileHandler() throws IOException {
        super(pattern());
    }
}

Then instead of installing the FileHandler, you install the FileHandler subclass using your logging.properties.
.handlers=package.of.EnvFileHandler
package.of.EnvFileHandler.pattern=path/${custom_home}/logs/server.log

If you have not set this custom property this code example will default to the home directory.


text:
Q: MVC Repository with Unit Of Work, Automapper and Generic Repository I've been looking at a few blog posts to try and create an appropriate solution for the following requirements but I can't seem to piece them together. Hope fully someone can help.
I've been using Repository pattern with interfaces using Automapper...here's a trimmed down example:
public class BookingRepository : IBookingRepository
{
    Entities context = new Entities();

    public IEnumerable<BookingDto> GetBookings
    {
        get { return Mapper.Map<IQueryable<Booking>, IEnumerable<BookingDto>>(context.Bookings); }
    }

    public BookingDto GetBookingWithProduct(Guid bookingId)
    {
        return Mapper.Map<BookingDto>(context.Bookings.Include(c => c.Products).SingleOrDefault(c => c.BookingId == bookingId));
    }

    public void Update(BookingDto bookingDto)
    {
        var booking = Mapper.Map<Booking>(bookingDto);
        context.Entry(booking).State = EntityState.Modified;
    }

    public void Save()
    {
        context.SaveChanges();
    }

    public void Dispose()
    {
        context.Dispose();
    }
}

public interface IBookingRepository : IDisposable
{
    IEnumerable<BookingDto> GetBookings { get; }
    BookingDto GetBooking(Guid bookingId);
    void Update(BookingDto bookingDto);
    void Save();
}

With a seperate Repository for a different Entity, for example
public class ProductRepository : IProductRepository
{
    Entities context = new Entities();

    public IEnumerable<ProductDto> GetProducts
    {
        get { return Mapper.Map<IQueryable<Product>, IEnumerable<ProductDto>>(context.Products); }
    }

    public ProductDto GetProductWithDesign(int productId)
    {
        return Mapper.Map<ProductDto>(context.Products.Include(c => c.Designs).SingleOrDefault(c => c.ProductId == productId));
    }

    public void Update(ProductDto productDto)
    {
        var product = Mapper.Map<Product>(productDto);
        context.Entry(product).State = EntityState.Modified;
    }

    public void Save()
    {
        context.SaveChanges();
    }

    public void Dispose()
    {
        context.Dispose();
    }
}

public interface IProductRepository : IDisposable
{
    IEnumerable<ProductDto> GetProducts { get; }
    ProductDto GetProduct(int productId);
    void Update(ProductDto productDto);
    void Save();
}

Then in my Controller I'm using the repositories as so:
public class HomeController : Controller
{
    private readonly IBookingRepository bookingRepository;
    private readonly IProductRepository productRepository;

    public HomeController() : this(new BookingRepository(), new ProductRepository()) { }
    public HomeController(IBookingRepository bookingRepository, IProductRepository productRepository)
    {
        this.bookingRepository = bookingRepository;
        this.productRepository = productRepository;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing && this.bookingRepository != null)
            this.bookingRepository.Dispose();

        if (disposing && this.productRepository != null)
            this.productRepository.Dispose();

    }
}

So now I'm hoping to create a Unit Of Work to abstract these repositories and share the context and also create a generic repository for the duplicated actions (Save and Update) bearing in mind I'm passing in Dtos and Mapping to Entity objects. I'm having difficulty understanding how to knit it all together.
Additionally, I've seen this post
Repository pattern with generics and DI
which states "You should not have other repository interfaces besides your generic repository" and that custom queries "deserve their own (generic) abstraction:" which is adding another complication to my overworked brain as my repositories will have custom queries that return complex linked objects using Include Statements as Lazy Loading is disabled.
So I'm prepared to be shot down and told that I'm going about this the wrong way but would be grateful for any direction given.
Thanks in advance.

A: Don't use generic repositories. They are all leaky abstractions. Ask yourself, what benefit to you get by using an abstraction that doesn't really abstract away something? You could use your OR/M directly in those cases.
What I means is that anything that exposes IQueryable<T> forces the user to learn about the weaknesses that the underlying OR/M has. Examples: How do the orm handle lazy loading? How do I eagerly load related entities? How do I create a IN clause?
If you truly want to use the repository pattern either use it together with the specification pattern (you can keep on using a generic repository then) or create repositories that are specific for each root aggregate.
I've blogged about it: http://blog.gauffin.org/2013/01/repository-pattern-done-right/

A: What I usually do in this case is to create a Base abstract Repository class like this:
public abstract class BaseRepository<T> : IRepository<T>
{
    Entities context = new Entities();

    public virtual T GetAll()
    {
        return context.Set<T>();
    }
    // Add base implementation for normal CRUD here
}

If you don't need special queries then you don't need to create special interface and classes (but you can of course, to improve readability). So you will use, for example:
var bookingsRepo = new BaseRepository<BookingsDto>();
var allBookings = bookingsRepo.GetAll();

If you need some special queries, you create an interface that extends the base interface:
public interface IProductRepository : IRepository<Product>
{
    Product GetSpecialOffer();
}

Then create your class:
public class ProductRepository : BaseRepository<Product>, IProductRepository
{
    public Product GetSpecialOffer()
    {
        // your logic here
    }
}

That way you only specify a minimal number of special cases while relying on the Base abstract implementation for all things normal.
I added virtual to the base methods because I always like to give derived class the ability to override stuff...


text:
Q: Unity Android game crash on update - Upgrading PlayerPrefs storage I am developing game with 100 levels in Unity3D (5.3.1f1) for Android & iOS. 45 levels are published  already. Now want to release update with 100 levels. But while testing, when I updated market build  (version 1.4) with test build(version 1.5), I found a **Force close** at the begining of level  16. Upto 16th level I could play without problem. Log says,
2\sdk\platform-tools>adb logcat -s Unity

* daemon not running. starting it now on port 5037 *
* daemon started successfully *

--------- beginning of /dev/log/system

--------- beginning of /dev/log/main

I/Unity   ( 8720): Upgrading PlayerPrefs storage

I/Unity   ( 8720): (Filename:  Line: 133)

Is it something with player preferences? There are almost 100 player preferences used. I am taking  care to save all prefernces when they are set or reset.
Logic for level 16 & above is same as that of levels 1 to 16.
If anybody is having any idea about this crash -Upgrading PlayerPrefs storage, please let me know.  Any help will be appreciated. Thank you in advance.


text:
Q: Sum specific cells if other cells match source cell in Numbers on Mac So, I'm making a personal budget table that is similar to YNAB in functionality. I want to use Numbers but I can easily switch to Excel if this can't be achieved.
I have two sheets; Budget and Transactions.
In Transactions, I have a list of bank transactions with a category (matching a list of categories in the Budget sheet) and their in/out values. I need to sum all in/out values that are in the same row as any matching category on the budget page. For example;
Budget Sheet
    A              B         C        D
1 Categories   Budgeted    Spent    Remaining
2 CategoryA      100        <?>     SUM(Budgeted, Spent)
3 CategoryB      250        <?>     SUM(Budgeted, Spent)

Transactions Sheet
   A            B           C            D      E
1 Date      Category    Description     Out     In
2 1/1/2017  CategoryA   cat-a desc.     57
3 1/2/2017  CategoryB   cat-b desc.             15

A: This SUMIF (two of them in the formula, one for the In column and one for the Out) formula should do the trick:
=(SUMIF(Sheet2!$B$2:$B$1000,"CategoryA",Sheet2!$D$2:$E$1000))+(SUMIF(Sheet2!$B$2:$B$1000,"CategoryA",Sheet2!$E$2:$E$1000))

It'll look in column B (from row 2 to 1000, change to your situation) for CategoryA and if it is CategoryA it will add the number in columns D and E to the total sum.
Just change the two instances of CategoryA to CategoryB for row 3 on the Transection Sheet.


text:
Q: How can I resolve the issue of app crashes On Button click? Whenever I press second button(fireb) my app crashes. However first button(click) is working fine.
public class MainActivity extends AppCompatActivity {

    Button click;

    public  static TextView data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        click = (Button) findViewById(R.id.button);
        data = (TextView) findViewById(R.id.fetcheddata);

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fetchData process = new fetchData();

                process.execute();

            }

        });

        Button fireb =(Button) findViewById(R.id.fire);

        fireb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Member go = new Member();

                go.execute();
                DatabaseReference reff;
                reff= FirebaseDatabase.getInstance().getReference().child("Member");
                reff.push().setValue(go);
                Toast.makeText(MainActivity.this,"Data Inserted Sucessfully",Toast.LENGTH_LONG).show();
            }
        });

Actually I want to execute the class "Member" with object "go" and then want to post that data contained in "go" to firebase database .
Here is the crash log....
--------- beginning of crash
05-11 14:35:51.301 3457-3457/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 3457
    com.google.firebase.database.DatabaseException: Invalid key: . Keys must not contain '/', '.', '#', '$', '[', or ']'
        at com.google.firebase.database.core.utilities.Validation.validateWritableKey(com.google.firebase:firebase-database@@19.3.0:120)
        at com.google.firebase.database.core.utilities.Validation.validateWritableObject(com.google.firebase:firebase-database@@19.3.0:103)
        at com.google.firebase.database.DatabaseReference.setValueInternal(com.google.firebase:firebase-database@@19.3.0:283)
        at com.google.firebase.database.DatabaseReference.setValue(com.google.firebase:firebase-database@@19.3.0:159)
        at com.example.myapplication.MainActivity$2.onClick(MainActivity.java:51)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-11 14:36:01.830 3457-3472/? I/art: Background partial concurrent mark sweep GC freed 17161(834KB) AllocSpace objects, 9(611KB) LOS objects, 39% free, 3MB/5MB, paused 545us total 172.404ms
05-11 14:36:05.223 3457-3457/? I/Process: Sending signal. PID: 3457 SIG: 9

And here is the Member class.
public class Member extends AsyncTask<Void,Void,Void> {
    String mdata = "";
    String ad_id = "";
    String price = "";
    String username = "";

    @Override
    protected Void doInBackground(Void... voids) {

        try {
                   .
                   .
                   .
            JSONObject JO1 = new JSONObject(mdata);
            JSONObject JO2 = JO1.getJSONObject("data");
            JSONArray JA = JO2.getJSONArray("ad_list");
            JSONObject JO3 = JA.getJSONObject(0);
            JSONObject JO4 = JO3.getJSONObject("data");
            JSONObject JO5 = JO4.getJSONObject("profile");

            username = (JO5.getString("username")).trim();
            ad_id = JO4.getString("ad_id").trim();
            price = JO4.getString("temp_price").trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

May be it is easy but I am developing my first app:)

A: This issue is related to firebase as showing in logs.

A: The reason is that you setValue with:

Invalid key: . Keys must not contain '/', '.', '#', '$', '[', or ']

But after looking at your code, there is something that I can't understand.
            go.execute();
            DatabaseReference reff;
            reff= FirebaseDatabase.getInstance().getReference().child("Member");
            reff.push().setValue(go);

You do AsyncTask, and you don't listen to the result.


text:
Q: Convert XML to Dataset or Excel Tables I have the following xml file
    <rootTag Type="TheRootType" CollectionTime="2016-02-06T" secretNumber="12345">
  <Toyota Type="Car">
    <item Name="EToyotaID" Valuetype="System.Int32">1</item>
    <item Name="EIdentifier" Valuetype="System.String">KKPP</item>
    <item Name="THEID" Valuetype="System.Int32">0</item>
    <item Name="TheValue" Valuetype="System.Int32">5040</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Toyota>
  <Toyota Type="Car">
    <item Name="EToyotaID" Valuetype="System.Int32">2</item>
    <item Name="EIdentifier" Valuetype="System.String">PPLL</item>
    <item Name="THEID" Valuetype="System.Int32">0</item>
    <item Name="TheValue" Valuetype="System.Int32">3230</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Toyota>
  <Mazda Type="Car">
    <item Name="EMazdaID" Valuetype="System.Int32">1130</item>
    <item Name="EIdentifier" Valuetype="System.String">RRR</item>
    <item Name="TheValue" Valuetype="System.Int32">10</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Mazda>
  <Mazda Type="Car">
    <item Name="EMazdaID" Valuetype="System.Int32">1131</item>
    <item Name="EIdentifier" Valuetype="System.String">SetTemp</item>
    <item Name="TheValue" Valuetype="System.Int32">7</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Mazda>
  <Honda Type="Car">
    <item Name="EHondaID" Valuetype="System.Int32">1726</item>
    <item Name="EIdentifier" Valuetype="System.String">SetUp</item>
    <item Name="THEID" Valuetype="System.Int32">11</item>
    <item Name="IDNum" Valuetype="System.Int32">13</item>
    <item Name="TheValue" Valuetype="System.Int32">327</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Honda>
  <Honda Type="Car">
    <item Name="EHondaID" Valuetype="System.Int32">1727</item>
    <item Name="EIdentifier" Valuetype="System.String">SetUp</item>
    <item Name="THEID" Valuetype="System.Int32">11</item>
    <item Name="IDNum" Valuetype="System.Int32">14</item>
    <item Name="TheValue" Valuetype="System.Int32">327</item>
    <item Name="Num" Valuetype="System.String">1104</item>
  </Honda>
</rootTag>

I would like to write this to Excel file where I have three tabs at the bottom. each for each car, so one for Toyota, one for Mazda, and one for Honda. In each tab I would like to have a table with the data for each car since all the cars with same name will have the same number of attributes.a
I have tried to get a dataset from the xml but that seems not to work correctly.
in the dataset I got the following 5 tables
1 ) rootTag
2 ) Toyota <= only has 2 columns "car" and "0"
3 ) item  <== it has all the data I need but it is a mess
4 ) Mazda <= only has 2 columns "car" and "0"
5 ) Honda <= only has 2 columns "car" and "0"
here is the code I used

public static DataSet ConvertXMLToDataSet(string xmlData)
    {
        StringReader stream = null;
        XmlTextReader reader = null;
        try
        {
            DataSet xmlDS = new DataSet("rootTag");
            stream = new StringReader(xmlData);
            // Load the XmlTextReader from the stream
            reader = new XmlTextReader(stream);
            xmlDS.ReadXml(reader);
            return xmlDS;
        }
        catch
        {
            return null;
        }
        finally
        {
            if (reader != null) reader.Close();
        }
    }// Use

}

I also have the XML Schema but I am not sure how to make use of that in my case.
thanks

A: I use datasets to export (and load) XML files for such things like config files. The loading code looks OK, except I use StreamReader instead of StringReader. How was your XML created? The XML you posted won't import into a dataset/table. I suggest you loop though the XML nodes and add the values into a pre-built dataset. Then you can use the code below to create the correct schema.
    dsRelease _Data = null; // Dataset.

    private void Load_Data()
    {
        StreamReader sr;
        XmlReader reader;

        _Data = new dsRelease(); //new dataset

        sr = new StreamReader(_SavePath, Encoding.UTF8);
        reader = new XmlTextReader(sr);

        _Data.ReadXml(reader, XmlReadMode.ReadSchema);

        if (reader != null) reader.Close();
        if (sr != null) sr.Close();
    }

    public void Save_Data(string savepath)
    {
        XmlTextWriter writer = null;

        writer = new XmlTextWriter(savepath, Encoding.UTF8);

        //Write Dataset.
        _Data.WriteXml(writer, XmlWriteMode.WriteSchema);
    }

A: Try this code:
var ds = new DataSet();
var xml = XElement.Load("test.xml");

var cars = xml.Elements().GroupBy(elem => elem.Name, elem => elem.Elements());

foreach (var car in cars)
{
    var dt = new DataTable(car.Key.LocalName);

    foreach (var elem in car.First())
    {
        dt.Columns.Add(elem.Attribute("Name").Value,
            Type.GetType(elem.Attribute("Valuetype").Value));
    }

    foreach (var elem in car)
    {
        dt.Rows.Add(elem.Select(x => x.Value).ToArray());
    }

    ds.Tables.Add(dt);
}

It gives you a filled dataset.