text:
Q: kendo chart datasource transport url not working I'm new to kendo UI, my problem is: I'm working on Asp.net MVC, and I'm trying to bind a keno chart using transport Url, but it's not working, I've passed the whole day looking for a solution but couldn't find one, thanks for your help: this is my code:

Controller:
public ActionResult Showchart()
    {
        List<RootObject> Mylist = new List<RootObject>();

        RootObject object1 = new RootObject();
        object1.sales = 200;
        object1.year ="1990";
        Mylist.Add(object1);

        RootObject object2 = new RootObject();
        object2.sales = 230;
        object2.year = "2008";
        Mylist.Add(object2);

        RootObject object3 = new RootObject();
        object3.sales = 260;
        object3.year = "2007";
        Mylist.Add(object3);

        RootObject object4 = new RootObject();
        object4.sales = 659;
        object4.year = "2006";
        Mylist.Add(object4);

        RootObject object5 = new RootObject();
        object5.sales = 400;
        object5.year = "2000";
        Mylist.Add(object5);
        return Json(Mylist);
    }
}

public class RootObject
{
    public int sales;
    public string year;
}

A: Please try with the below code snippet.
VIEW

CONTROLLER
public ActionResult Showchart()
{
    List<RootObject> Mylist = new List<RootObject>();

    RootObject object1 = new RootObject();
    object1.sales = 200;
    object1.year = "1990";
    Mylist.Add(object1);

    RootObject object2 = new RootObject();
    object2.sales = 230;
    object2.year = "2008";
    Mylist.Add(object2);

    RootObject object3 = new RootObject();
    object3.sales = 260;
    object3.year = "2007";
    Mylist.Add(object3);

    RootObject object4 = new RootObject();
    object4.sales = 659;
    object4.year = "2006";
    Mylist.Add(object4);

    RootObject object5 = new RootObject();
    object5.sales = 400;
    object5.year = "2000";
    Mylist.Add(object5);
    return Json(Mylist, JsonRequestBehavior.AllowGet);
}

Note: 1) To run the above code you have to added required kendo javascript library in view code. 2) Replace 'YourControllerName' text with your controller name inside view.
Let me know if any concern.


text:
Q: align label and input (float vs display inline block) I have two examples of a label and a text field that I'm trying to align (You can see it in this fiddle). In the first example I have a label and a text field like this:
Firstname:
<input type="text" style="margin:0;padding:0;" id="firstname" name="firstname" value="" />

In the second example, I have a label and a three floated text fields in a div like this:

Date:

            <input type="text" style="margin:0;padding:0;" id="day" name="day" maxlength="2" size="2" value="" /> /

            Day

            <input type="text" style="margin:0;padding:0;" id="month" name="month" maxlength="2" size="2" value="" /> /

            Month

            <input type="text" style="margin:0;padding:0;" id="year" name="year" maxlength="4" size="4" value="" />

            Year

As you can see above, I give each label a width of 100px, but for some reason, in the second example, there is no space between my label and the first text field. Does anybody know why this is happening and why my width of 100px does not seem to have any effect in my second example (view fiddle link above).
Thank you

A: You can use inline-block instead of float to make it appear as of the previous section to get the margin effect else you need to add a margin with floated element.

Date:

                <input type="text" style="margin:0;padding:0;" id="day" name="day" maxlength="2" size="2" value="" /> /

                Day

                <input type="text" style="margin:0;padding:0;" id="month" name="month" maxlength="2" size="2" value="" /> /

                Month

                <input type="text" style="margin:0;padding:0;" id="year" name="year" maxlength="4" size="4" value="" />

                Year

Demo
or add a margin.

Date:

Demo
On a side note, consider using css rules instead of inline styles

A: The space is because the first element is a replaced inline element, which kinda has the same behaviour as inline-block and adds margin.
And for the width,  remove size="2" and maxlength="2" to make it the same with as the upper input fields

A: Well first of all your first example with the "Firstname" label is using a "label" tag which is treated differently then a "div". That brings me to the second example of "Date" which is surrounded by "div" tags. Because of this, the default way for the browser to handle them is different.
You could easily compensate for this difference by adding a right margin to the label using the "div" to surround it.

Date:

Although it is ok to use inline styles, I would suggest if you are going to be using this in a larger document to put this inside a external CSS file and use a class (or ID) for the div instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to consistently ignore one byte from a string I am dealing with a program that consistently returns many byte objects.
Frequently it returns the null b'00' in the middle of strings.  I want to  completely ignore that, (say if I were to make an array of these bytes). Is the only way to include a:
if bytes != b'\x00':
# Do something

in every single loop / part of my code or is there a better way for me to skip those bytes?
Bonus Question: When referring to situations such as this in Python 3, is a long "string" of bytes a "byte object", "string of bytes" or "byte array"?
What is the proper terminology?

A: Usually you'd use a filtered version of the object, for example:
In [63]: test
Out[63]: 'hello\x00world'
In [68]: for my_bytes in filter(lambda x: x != b'\x00', test):
   ....:     print(my_bytes)
   ....:
h
e
l
l
o
w
o
r
l
d

Note I used my_bytes instead of bytes, which is a built-in name you'd rather not overwrite.
Similar you can also simply construct a filtered bytes object for further processing:
In [62]: test = b'hello\x00world'
In [63]: test
Out[63]: 'hello\x00world'
In [64]: test_without_nulls = bytes(filter(lambda x: x != b'\x00', test))
In [65]: test_without_nulls
Out[65]: 'helloworld'

I usually use bytes objects as it does not share the interface with strings in python 3. Certainly not byte arrays.

A: You can use a membership test using in:
>>> b'\x00' in bytes([1, 2, 3])
False
>>> b'\x00' in bytes([0, 1, 2, 3])
True

Here b'\x00' produces a bytes object with a single NULL byte (as opposed to b'00' which produces an object of length 2 with two bytes with integer values 48).
I call these things bytes objects, sometimes byte strings, but the latter usually in context of Python 2 only. A bytearray is a separate, distinct type (a mutable version of the bytes type).

A: If you have a list in python, you can do
list = [x for x in originallist if x is not None]


text:
Q: Canvas.drawText leading to overlapping of text I am trying draw different text at the same position .I am creating the typeface and paint object in the following code and drawing the text.It works fine till here.It draws the text with the typeface which i have specified.But when i drawtext another time at the same position it overlaps the earlier text .
    mFace = Typeface.createFromAsset(getContext().getAssets(),"digital.ttf");
    text_paint= new Paint();
    text_paint.setColor(Color.BLUE);
    text_paint.setStyle(Paint.Style.FILL);
    text_paint.setTypeface(mFace);
    text_paint.setTextSize((float) (height*0.05076));
    text_paint.setAntiAlias(true);

    canvas.drawText("ABC",(float)(width*0.5) ,(float)(height*0.55), text_paint);
    canvas.drawText("PQRSTUV",(float)(width*0.5) ,(float)(height*0.55), text_paint);

Any idea how to remove the earlier text and add the new text at the same position.

A: Check the below link for the detailed explanations for your problem :
Canvas Text Drawing Issues


text:
Q: how to select row using mysql, php and json I have a problem getting a format that I need in JSON.
This is the code I am using:
<?php

$con = mysqli_connect("localhost", "******", "******");
if (!$con) {
    die('Could not connect: '.mysqli_error());
}
mysqli_select_db("highchart", $con);
$query = mysqli_query("SELECT * FROM trafico");
$category = array();
$category['name'] = 'Time';
$series1 = array();
$series1['name'] = 'Tx';
$series2 = array();
$series2['name'] = 'Rx';

while ($r = mysqli_fetch_array($query)) {
    $category['data'][] = $r['time_1m'];
    $series1['data'][] = $r['Tx'];
    $series2['data'][] = $r['Rx'];
}
$result = array();
array_push($result, $category);
array_push($result, $series1);
array_push($result, $series2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);

?>

This is what I am expecting to get as a result:
[{
"name": "Time",
"data": ["2018-03-28 17:57:01", "2018-03-28 17:58:01", "2018-03-28 17:59:01", "and so on...."]
}, {
"name": "Tx",
"data": [1025.14, 1056.14, 1035.14, 1042.14, 1038.14, and so on...]
}, {
"name": "Rx",
"data": [52, 54, 51, 49, 46, 48, 53, 56, , and so on...]
}]

but the result I am getting at the moment is:
[{"name":"Time"},{"name":"Tx"},{"name":"Rx"}]

I can't figure out why I'm not getting the result I'm looking for.
Any help is greatly appreciated.


text:
Q: can't convert pytorch tensor dtype from float64 to double I need to convert an int to a double tensor, and I've already tried several ways including torch.tensor([x], dtype=torch.double), first defining the tensor and then converting the dtype to double with x_tensor.double(), and also defining the tensor with torch.DoubleTensor([x]) but none actually change the dtype from torch.float64. Here's the code snippet
>>> x = 6
>>> x = torch.tensor([x], dtype=torch.double)
>>> x
tensor([6.], dtype=torch.float64)

>>> x = 6
>>> x_tensor = torch.Tensor([x])
>>> x_double = x_tensor.double()
>>> x_double
tensor([6.], dtype=torch.float64)

>>> x_tensor = torch.DoubleTensor([x])
>>> x_tensor
tensor([6.], dtype=torch.float64)

Any ideas as to why it's not converting?

A: It is converting; torch.float64 and torch.double are the same thing


text:
Q: Spring Security Java Config So recently I migrated the Spring configuration from XML to Java config.
It's a Spring OAuth 2 Server, and some endpoints are secured with clients authentication, and some endpoints (confirm_access) are secured with user authentication, which is delegated to login application with a redirect made from a filter ("authenticationFilter").
But I'm not able to do the same with Spring Security Java config :
Here my working security XML configuration :
<sec:http pattern="/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager"
        entry-point-ref="oauthAuthenticationEntryPoint">
        <sec:intercept-url pattern="/token" access="IS_AUTHENTICATED_FULLY" />
        <sec:anonymous enabled="false" />
        <sec:http-basic entry-point-ref="oauthAuthenticationEntryPoint" />
        <!-- include this only if you need to authenticate clients via request parameters -->
        <sec:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
        <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
    </sec:http>

    <sec:http pattern="/css/**" security="none" />
    <sec:http pattern="/js/**" security="none" />

<sec:http access-denied-page="/errors/access-denied.html" disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint">
        <sec:intercept-url pattern="/authorize" access="ROLE_USER" />
        <sec:intercept-url pattern="confirm_access" access="ROLE_USER" />
        <sec:intercept-url pattern="/device/authorize" access="ROLE_USER" />

        <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <sec:custom-filter ref="authenticationFilter" before="ANONYMOUS_FILTER" />
        <sec:anonymous />
    </sec:http>

<sec:authentication-manager id="clientAuthenticationManager">
        <sec:authentication-provider user-service-ref="clientDetailsUserService" />
    </sec:authentication-manager>

    <sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider ref="authenticationProvider" />
    </sec:authentication-manager>

<sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
        <sec:expression-handler ref="oauthExpressionHandler" />
    </sec:global-method-security>

    <oauth:expression-handler id="oauthExpressionHandler" />

    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

Here is my Java config attempt :
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Order(1)
@Import({WebSecurityConfig.TokenEndpointSecurityConfigurationAdapter.class,
        WebSecurityConfig.ResourceSecurityConfigurationAdapter.class,
        WebSecurityConfig.AnonymousSecurityConfigurationAdapter.class})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ClientDetailsUserDetailsService clientDetailsUserService;

    @Bean(name = "clientAuthenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(clientDetailsUserService);
    }

    @Configuration
    @Order(2)
    public static class TokenEndpointSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        ClientDetailsUserDetailsService clientDetailsUserService;

        @Autowired
        OAuth2AuthenticationEntryPoint oauthAuthenticationEntryPoint;

        @Autowired
        ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter;

        @Autowired
        OAuth2AccessDeniedHandler oauthAccessDeniedHandler;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .userDetailsService(clientDetailsUserService)
                .anonymous().disable()
                .authorizeUrls()
                .antMatchers("/token")
                .fullyAuthenticated()
            .and()
                .httpBasic()
                .authenticationEntryPoint(oauthAuthenticationEntryPoint)
            .and()
                .addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.stateless)
            .and()
                .exceptionHandling().accessDeniedHandler(oauthAccessDeniedHandler);
        }

    }

    @Configuration
    @Order(3)
    public static class ResourceSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter{

        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                .ignoring()
                    .antMatchers("/css/**","/js/**");
        }
    }

    @Configuration
    @Order(4)
    public static class AnonymousSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter{

        @Autowired
        OAuth2AuthenticationEntryPoint oauthAuthenticationEntryPoint;

        @Autowired
        AuthenticationFilter authenticationFilter;

        @Autowired
        PreAuthenticatedAuthenticationProvider authenticationProvider;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(authenticationFilter, AnonymousAuthenticationFilter.class)
                .authorizeUrls().anyRequest().anonymous()
            .and()
                .authorizeUrls()
                .antMatchers("/authorize","confirm_access","/custom/authorize")
                .hasRole("USER")
            .and()
                .exceptionHandling().accessDeniedPage("/errors/access-denied.html");
        }
    }
}

With this config Spring Security tries to authenticate user for all endpoints, and displays generate login form, so custom filter is not added.
Where is my mistake ?

A: Since your original configuration only contains two http elements your new configuration should only contain two WebSecurityConfigurerAdapter instances. Each WebSecurityConfigurerAdapter instance is mapped using the http.antMatchers. Currently WebSecurityConfigurerAdapter is mapped to every URL.
You can refer to the reference for an example of how to use multiple WebSecurityConfigurerAdapter instances (which is the equivalent of )


text:
Q: Disabling warnings about Boost headers in XCode 4.1 I am writing a C++ program that uses Boost, using XCode 4.1 as IDE and compiler front-end. I get quite a lot of warnings in various Boost headers, and I would like to disable all warnings for those headers (but still enable them for my own project). Is there an easy way to do so?

A: I have found a decent workaround, based on what @Georg Fritzsche suggested:
I have added the various incriminated boost headers to the .pch file (the pre-compiled header), and wrapped them around a #pragma push - #pragma pop block, like this:
// We do not want to have warnings about Boost headers!
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wshadow"

#include <boost/date_time/posix_time/posix_time_types.hpp>
...
#pragma GCC diagnostic pop

This works perfectly, and it's not as annoying as having to surround the boost headers with #pragma in each .cpp file, as I feared.

A: Another solution, that I found to work in Xcode 5.x (yet it is expected to work with Xcode 4).
In the Build Settings of the Boost depending target, instead of setting the headers' path under Header Search Paths, I write it under Other C++ Flags, prefixed by -isystem


text:
Q: How to get value from a parent class and a nested array child using linq? I have the following model to get data from database:
    public class CultureResource
    {
        public string KeyName { get; set; }
        public List<Resource> Resources { get; set; }
    }

    public class Resource
    {
        public string Value { get; set; }
        public string Culture { get; set; }
    }

Now my goal is to get data for a list of keys & culture where keys matches with CultureResource.KeyName & culture matches with Resource.Culture. How can I write a linq query on a IQueryable<CultureResource> to get a result of IList<Result> where Result may look like the following:
public class Result
{
    public string KeyName {get; set;}
    public string Value {get; set;}
}

I have tried the following Linq, but it throws $project or $group does not support {document}. error:
public IDictionary<string, string> GetLocalizedValueList(string[] keys, string culture)
{
    // returns IQueryable<CultureResource>
    var cultureResources = _repository.GetItems<CultureResource>();

    /***** This is the query *********/
    var query = from cr in cultureResources
              from r in cr.Resources
              where keys.Contains(cr.KeyName) && r.Culture == culture
              select new { cr.KeyName, r.Value };

    var result = query.ToList()

    //return some data
}

FYI: my underlying database is mongo

A: How about this
        var query = cultureResources.SelectMany(cultureResource => cultureResource.Resources.Select(resource => new { cultureResource.KeyName, resource.Value })).ToList();


text:
Q: Cannot read property Score I am trying to iterate through JSON data

var Source = [{
    "Name": "Man U",
    "Games": 34,
    "Score": 12
  },
  {
    "Name": "Man U",
    "Games": 4,
    "Score": 132
  },
  {
    "Name": "Man U",
    "Games": 3,
    "Score": 5
  },
  {
    "Name": "Man U",
    "Games": 24,
    "Score": 120
  },
  {
    "Name": "Man U",
    "Games": 1,
    "Score": 56
  },
  {
    "Name": "Man U",
    "Games": 7,
    "Score": 7
  },
  {
    "Name": "Man U",
    "Games": 14,
    "Score": 5
  }
];

var newData = [];
var i;
for (i = 0; i < Source.length; i++) {
  if (Source[i].Score === 5) {
    var nexIndx = i + 1;
    if (Source[nexIndx].Score == 120) {
      newData.push(Source[i], Source[nexIndx]);
    }
  }
}
console.log(newData);

I want the users to be able to search vertically
Example
Manchester United Scored 12 goals in League1
The following Season They scored 132.
In the third season, they scored 5 goals,
Then 120 goals in the fourth season

<input type="number" placeholder="Any season">

Next Season

<input type="number" placeholder="The Next season">

<button (click)="FindVertical"> Search
</button>

I want the user to be able to filter a season and the next season

A: This is a classic array overflow issue. You loop over an array, getting the value after the current value to compare it to. Only when you get to the last value, there is no entry after that, so Source[nexIndx] is undefined.
The solution is either to stop one earlier by not executing this code for the last element, or to start one later (i = 0 becomes i = 1) and look backwards instead of forwards. I show the latter below:

var Source = [{
    "Name": "Man U",
    "Games": 34,
    "Score": 12
  },
  {
    "Name": "Man U",
    "Games": 4,
    "Score": 132
  },
  {
    "Name": "Man U",
    "Games": 3,
    "Score": 5
  },
  {
    "Name": "Man U",
    "Games": 24,
    "Score": 120
  },
  {
    "Name": "Man U",
    "Games": 1,
    "Score": 56
  },
  {
    "Name": "Man U",
    "Games": 7,
    "Score": 7
  },
  {
    "Name": "Man U",
    "Games": 14,
    "Score": 5
  }
];

var newData = [];
var i;
for (i = 1; i < Source.length; i++) {
  if (Source[i - 1].Score === 5) {
    if (Source[i].Score == 120) {
      newData.push(Source[i - 1], Source[i]);
    }
  }
}
console.log(newData);

A: first your code is not getting user input on the html page. So you need to define your input variables:
<form id="myForm">
    <input name="season1" type="number" placeholder="Any season">
    <input name="season2" type="number" placeholder="The Next season">
    <button type="submit">Submit</button>
</form>

Season1: {{score1}}

Season2: {{score2}}

then, in order to read vertically the scores, all you need is this:
const form: HTMLFormElement = document.querySelector('#myform');
var score1 = 0;
var score2 = 0;

form.onsubmit = () => {
  const formData = new FormData(form);

  let s1= formData.get('season1') as int;
  let s2= formData.get('season2') as int;

  score1 = Source[s1]["Score"]
  score2 = Source[s2]["Score"]

  return false;
};

A: Here You got that error due to newIndx value.
In your array the last element is {"Name": "Man U", "Games": 14, "Score": 5} means your 6th element, After that your are increase your index position means 6+1 is 7 is your new position. You're trying here like source[7].source === 120 so that it returns Cannot read property Score.
And one more thing is you're push your value in array whenever match your score is 120. You can replace your loop with below one.
for (i = 0; i < Source.length; i++) {
  if (Source[i].Score == 120) {
    newData.push(Source[i], Source[i]);
  }
}


text:
Q: LINQ-To-Sharepoint Multiple content types for a single list I'm using SPMetal in order to generate entity classes for my sharepoint site and I'm not exactly sure what the best practice is to use when there are multiple content types for a single list. For instance I have a task list that contains 2 content types and I'm defining them via the config file for SPMetal. Here is my definition...
<List Member="Tasks" Name="Tasks">
    <ContentType Class="LegalReview" Name="LegalReviewContent"/>
    <ContentType Class="Approval" Name="ApprovalContent"/>
</List>

This seems to work pretty well in that the generated objects do inherit from WorkflowTask but the generated type for the data context is a List of WorkflowTask. So when I do a query I get back a WorkflowTask object instead of a LegalReview or Approval object. How do I make it return an object of the correct type?
[Microsoft.SharePoint.Linq.ListAttribute(Name="Tasks")]
public Microsoft.SharePoint.Linq.EntityList<WorkflowTask> Tasks {
    get {
        return this.GetList<WorkflowTask>("Tasks");
    }
}

UPDATE
Thanks for getting back to me. I'm not sure how I recreate the type based on the SPListItem and would appreciate any feedback.
ContractManagementDataContext context = new ContractManagementDataContext(_url);
WorkflowTask task = context.Tasks.FirstOrDefault(t => t.Id ==5);
Approval a = new Approval(task.item);

public partial class Approval{
     public Approval(SPListItem item){
         //Set all properties here for workflowtask and approval type?
         //Wouldn't there be issues since it isn't attached to the datacontext?
    }

    public String SomeProperty{
        get{ //get from list item};
        set{ //set to list item};
}

A: Linq2SharePoint will always return an object of the first common base ContentType for all the ContentTypes in the list. This is not only because a base type of some description must be used to combine the different ContentTypes in code but also it will then only map the fields that should definitely exist on all ContentTypes in the list. It is however possible to get access to the underlying SPListItem returned by L2SP and thus from that determine the ContentType and down cast the item.
As part of a custom repository layer that is generated from T4 templates we have a partial addition to the Item class generated by SPMetal which implements ICustomMapping to get the data not usually available on the L2SP entities. A simplified version is below which just gets the ContentType and ModifiedDate to show the methodology; though the full class we use also maps Modified By, Created Date/By, Attachments, Version, Path etc, the principle is the same for all.
public partial class Item : ICustomMapping
{
private SPListItem _SPListItem;
public SPListItem SPListItem
{
    get { return _SPListItem; }
    set { _SPListItem = value; }
}
public string ContentTypeId { get; internal set; }
public DateTime Modified { get; internal set; }

public virtual void MapFrom(object listItem)
{
    SPListItem item = (SPListItem)listItem;
    this.SPListItem = item;
    this.ContentTypeId = item.ContentTypeId.ToString();
        this.Modified = (DateTime)item["Modified"];
}

public virtual void MapTo(object listItem)
{
    SPListItem item = (SPListItem)listItem;
        item["Modified"] = this.Modified == DateTime.MinValue ? this.Modified = DateTime.Now : this.Modified;
}

public virtual void Resolve(RefreshMode mode, object originalListItem, object databaseObject)
{
    SPListItem originalItem = (SPListItem)originalListItem;
    SPListItem databaseItem = (SPListItem)databaseObject;

        DateTime originalModifiedValue = (DateTime)originalItem["Modified"];
        DateTime dbModifiedValue = (DateTime)databaseItem["Modified"];

    string originalContentTypeIdValue = originalItem.ContentTypeId.ToString();
    string dbContentTypeIdValue = databaseItem.ContentTypeId.ToString();

    switch(mode)
    {
        case RefreshMode.OverwriteCurrentValues:
                this.Modified = dbModifiedValue;
            this.ContentTypeId = dbContentTypeIdValue;
            break;

        case RefreshMode.KeepCurrentValues:
                databaseItem["Modified"] = this.Modified;
            break;

        case RefreshMode.KeepChanges:
                if (this.Modified != originalModifiedValue)
                {
                    databaseItem["Modified"] = this.Modified;
                }
                else if (this.Modified == originalModifiedValue && this.Modified != dbModifiedValue)
                {
                    this.Modified = dbModifiedValue;
                }
            if (this.ContentTypeId != originalContentTypeIdValue)
            {
                throw new InvalidOperationException("You cannot change the ContentTypeId directly");
            }
            else if (this.ContentTypeId == originalContentTypeIdValue && this.ContentTypeId != dbContentTypeIdValue)
            {
                this.ContentTypeId = dbContentTypeIdValue;
            }
            break;
    }
}
}

Once you have the ContentType and the underlying SPListItem available on your L2SP entity it is simply a matter of writing a method which returns an instance of the derived ContentType entity from a combination of the values of the base type and the extra data for the missing fields from the SPListItem.
UPDATE: I don't actually have an example converter class as we don't use the above mapping extension to Item in this way. However I could imagine something like this would work:
public static class EntityConverter
{
    public static Approval ToApproval(WorkflowTask wft)
    {
        Approval a = new Approval();
        a.SomePropertyOnWorkflowTask = wft.SomePropertyOnWorkflowTask;
        a.SomePropertyOnApproval = wft.SPListItem["field-name"];
        return a;
    }
}

Or you could put a method on a partial instance of WorkflowTask to return an Approval object.
    public partial class WorkflowTask
    {
        public Approval ToApproval()
        {
            Approval a = new Approval();
            a.SomePropertyOnWorkflowTask = this.SomePropertyOnWorkflowTask;
            a.SomePropertyOnApproval = this.SPListItem["field-name"];
return a;
        }

        public LegalReview ToLegalReview()
        {
            // Create and return LegalReview as for Approval
        }
    }

In either situation you would need to determine the method to call to get the derived type from the ContentTypeId property of the WorkflowTask. This is the sort of code I would normally want to generate in one form or another as it will be pretty repetitive but that is a bit off-topic.


text:
Q: Using Tomcat 7 and SuperCSV - in generated and downloaded files non-English characters are all replaced with "?" What could be causing this, and how can I correct it? The pom.xml includes the line "<uriEncoding>utf-8</uriEncoding>".

A: I fixed the problem by adding charset="UTF-8" to the response's content type.


text:
Q: Separating Twitter's Streaming Response for Track/Follows I created a streaming query with 400 track keywords and 5,000 follows.
When I get a response from Twitter , how do I associate which follow/keyword triggered the response?

A: One of the Twitter developers replied :
Twitter dev froum link
For matching follows:
In nutshell Twitter documentation says:
1.Tweets created by the user.
2.Tweets which are retweeted by the user.
3.Replies to any Tweet created by the user.
4.Retweets of any Tweet created by the user.
5.Manual replies, created without pressing a reply button (e.g. "@twitterapi I agree").

to match posting user Id :
1 and 2 are in the user object of the top-level tweet, like tweet['user']['id']

4 is the inner-level tweet, retweeted_status - so tweet['retweeted_status']['user']['id'] should be one of your follow ids.

3 can be checked in in_reply_to_user_id field, or mentions.

5 and 3 can be checked together from the mentions: tweet['entities']['user_mentions']

Additionally, if "truncated": true you might have to dig into extended_tweet

To match tracks I just build a regex and attempt to match against my keywords. I 've also toyed with in-memory Lucene parser.


text:
Q: nvm vs nave vs n | packages processing comparsion Node.js is sometimes confusing when it comes to version management...
I am trying to arrange various projects as i am doing with ruby projects. For example:
With ruby i can create file such as .rvmrc and fill with something like rvm --create use 1.9.3@my-app
This thing creates and uses all gems specifically to configured gemset. Which allows to have various options for any kind of project, and switch easily among them. So ruby does this in one place.
I want to achieve this for node.js projects.
Node works differently. I want to know the details about that, and especially of each node version management tool.
The point is to know which version management tool for which goal...
And why there are so many.
More accurately: i want npm install <package-name> to chosen node version. And after switching to other versions, this installed package to be missing, or have different version installed before (or certain one). Just like gemset is working.

A: I've been looking for clarification too:

*

*Both allow switching & installing between node versions.

*nvm will symlink the different versions to /usr/local/bin/node, and n will move your node installs to the path (/usr/local/bin/node).

*n downloads and installs binary files, and nvm downloads, compiles, installs from the source.

I don't fully understand the latter part of your question, but in regards having control with node projects/apps, you can use npm install [package_name] --save-dev to save your npms within your 'project'.
These npm module versions (^semver) get detailed in your package.json file, for example "gulp": "^3.8.5" is different from "gulp": "3.8.5" (the later being specific to v3.8.5, and the ^3.8.5 means allowing any future version of 3, but not 4.0.0)
The differences between npm and gem is that npm installs the specified packages in the local node_modules folder (the current working directory using the --save-dev), so you have less worries with cross project module versions.
Important note: Running --save (instead of --save-dev) installs any missing dependencies.
I hope that helps a little :o)

A: Just tried to install nvm and it works for switching from one version to another. In header of nave.sh it says "# This program contains parts of narwhal's "sea" program, as well as bits borrowed from Tim Caswell's "nvm"", so you might try both and see the tiniest difference. Also check the "popularity" of each and contributors to get some insight). There is also a nodeenv which uses python, but I don't any reason why use python here. So, my answer would be no big difference.


text:
Q: Showing button below a fragment in an activity I'm quite new to Android. I have a very simple layout that doesn't work yet:
<LinearLayout android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/relativeLayout">
    <fragment android:layout_width="fill_parent"
          android:layout_height="match_parent"
          android:name="pl.nscr.playwatch.MainActivity$WatchListFragment"
          android:id="@+id/watchlist"/>
    <Button android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Start service"/>
</LinearLayout>

Now my problem is that the fragment spans the whole available height in an activity. I'd like to be able to see that button below it, but I don't actually know how to layout this thing.
I tried using RelativeLayout, but I ended up with the button showing above the fragment which looks ugly. What am I doing wrong?
Update
Apparently it was a silly mistake. I changed back again to RelativeLayout but the layout now has width and height set to 'fill_parent' and everything works as expected.
<RelativeLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/relativeLayout">
    <fragment android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:name="pl.nscr.playwatch.MainActivity$WatchListFragment"
            android:id="@+id/watchlist"
            android:layout_above="@+id/btnStartService"/>
    <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:id="@id/btnStartService"
            android:text="Start service"/>
</RelativeLayout>

A: do the following

*

*add android:orientation="vertical" attribute to <LinearLayout>

*add layout_weight="1" attribute to <fragment />

A: Add android:orientation="vertical" to the LinearLayout..


text:
Q: How hide and show admob banner adview runtime Hello guys I am using admob banner to show ads.
So I left some space at bottom so admob mob banner load.
So if user turn off internet then I want to use that banner space to show content of my activity. while if user turn on his internet again then I shrink my activity content and show admob banner again, So in short I want to grow or shrink layout space.
This is code I try. This code removes banner space if internet is off. but I dont know how to add banner again if user turn on internet.

    public class MainActivity extends AppCompatActivity {

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

            MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");

            final AdView mAdView = (AdView) findViewById(R.id.adView);
            final AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);

            mAdView.setAdListener(new AdListener() {
                @Override
                public void onAdFailedToLoad(int i) {
                    //super.onAdFailedToLoad(i);
                    mAdView.setVisibility(View.GONE);
                }

            });
        }

    }

A: First you need to decide when your application will check connection again.
Check the lifecycle at https://developer.android.com/reference/android/app/Activity.html
After, lets suppose you want to check everytime the application back to the acitivty that you want to show your adview.
 @Override
    protected void onRestart() {
        if(checkAppConnectionStatus(MainActivity.this)){mAdView.setVisibility(View.VISIBLE);}
        else{ mAdView.setVisibility(View.GONE);}
        super.onRestart();
    }

public static boolean checkAppConnectionStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }else{
        return false;
    }
}

Check my other answer to know more about how to use like in an utils class appConnectionStatus:
Internet Connection


text:
Q: Angular 5: Hiding elements (if user isn't authenticated) not working this is app.component.html

  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

  </button>

Posts

Profile

Settings

Register

Login

Administration

<router-outlet></router-outlet>

authentication.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {User} from "../../interfaces/user.interface";

@Injectable()
export class AuthenticationService {
logging: boolean = false;

constructor(private http: HttpClient) { }

isloggedin() {
this.http.get('/loggedin')
  .toPromise()
  .then((data: any) => {
    console.log('data', data);
    if (data) {
      return true;
    } else {
      return false;
    }

  });
 }

}

app.component.ts
import {Component, OnInit} from '@angular/core';
import {AuthenticationService} from
"../../services/authentication/authentication.service";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
 })
export class AppComponent implements OnInit{
title = 'twittscheR';
loggedin: any;

constructor(private http: HttpClient) {
 this.loggedin = AuthenticationService.isloggedin();
}
ngOnInit(){
 this.loggedin = this.isloggedin();
}
isloggedin() {
 return this.http.get('/loggedin');
}
}

I'm really new to Angular 5. How can I implement, that some elements in the navbar are only visible, if loggedin is true? Even the page is reloaded. Login functionality is working, but ngIf does not update the variable in navbar
Thanks

A: Create an varibale loggedin of type BehaviorSubject<boolean> in your authentication.service.ts:
loggedin: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

Now modife your isLoggedIn()-function so, that if you get data then set loggedin to true, if no data then set it to false;
isloggedin() {
this.http.get('/loggedin')
  .toPromise()
  .then((data: any) => {
    console.log('data', data);
    if (data) {
      // login success
      this.loggedid.next(true);
    } else {
      // login fails
      this.loggedid.next(false);
    }

  });
 }

Now you can subscribe to loggedin varibale in your component. For that you should inject your authentication.service in app.component.ts.
loggedin: boolean;

constructor(private http: HttpClient, private authService: AuthenticationService) {
 this.authService.loggedin.subscribe(v => this.loggedin = v);
}

Now you can use loggedin variable from app.component.ts in your app.component.html.
Beware: For bring this solution to work, you should run your isLoggedIn() function e.g. by clicking on login button.
If you need more explanation, then let me know and I write larger tutorial.


text:
Q: Does number of programs installed on my pc affect its speed? I have windows xp and it has started responding very slowly, so was thinking if the various software I've installed might be affecting its speed.
PS: Even if I run one program/software at a time the same thing happens

A: Yes, the more number of programs, the slower is the windows by nature. You may not be running all the programs, but programs by themselves can run some services or processes to have them updated and can consume memory, which can result in slow down of system.

A: No, the speed of your PC is the same no matter what is installed, but the number of programs installed does affect the performance of your PC.  Malfunctioning hardware can also cause performance issues.  I would start by reviewing your installed programs (Control Panel) and removing what you don't really need.
Also, Windows XP is no longer supported by the vendor (Microsoft).  You may want to consider upgrading to a more current OS (i.e., Windows 7).

A: Yes, Every program increase the fragmentation of your files and also the size and fragmentation of your registry files. To reduce the slow up, defragment your drives and use tools like CCleaner to clean your disk and registry and Free Registry Defrag to defrag your registry.

A: There can be many reasons for this:

*

*Many programs you install start some kind of background process when the computer is started. These all take a tiny toll on the performance of the computer, both CPU and working memory; when it sums up, it could be significant enough to feel it as a performance degradation. And you cannot see that these background processes are running. They often, though, but not always, add a tiny icon in the System Tray in the lower right of the screen. Each of those icons are connected to at least one background process running all the time. But there are many more background processes that you cannot see. Press Ctrl+Shift+Esc to get the Task Manager. Switch to the Processes view. Click the CPU column header twice so it sorts by CPU usage, highest first. Then you can see the processes that use most CPU. Sometimes a process can even be a runaway process that uses lots of CPU. Try ending that process if it keeps using lots of CPU and see if it helps; that can help diagnose the problem.

*When you install programs and in general use the computer, the disk becomes more fragmented. This slows down the performance. Defragmenting the hard disk can help with that.

*When you install programs, you get less free disk space. The less free disk space, the slower Windows gets; it gets harder for Windows to find the empty space it needs for temporary files etc. So be sure to keep a lot of free space on your disk. Remove anything that you do not need. Move that data to external disks, for instance. And uninstall programs you really don't need.

*Programs tend to get larger and larger for each new version. Mostly because functionality is added. Also, they tend to get functionality that requires more and more ressources (CPU and memory) from the computer. So just keeping your programs up to date slows down the performance of your computer over time. There is no real remedy for this, as programs get unsafe if you use old versions. For some programs, though, there are old versions that are still being updated with security patches. For instance, there is still the old and fast Opera 12 browser (I believe it is still being maintained with security patches, although I am not sure).

*Programs also tend to get larger and larger in working memory (RAM) footprint for each new version; they require more RAM when running. This includes the background processes that you cannot see. And your computer has limited RAM. When your computer is out of RAM, it uses the harddisk instead. This slows down the computer extremely much. Press Ctrl+Shift+Esc to get Task manager. Switch to the Performance tab. There you can see the memory usage as a graph. Compare that to the total memory (RAM) your computer has. When it is getting close to the maximum, performance will fall considerably.

*Programs such as Google Chrome use a lot of memory, and more and more for each tab that is open. Keep the number of open tabs in web browsers, especially Google Chrome, down to a minimum.

*In general, my experience is that working memory running low is the most important reason for a computer system to be slow.
a. Adding more memory is of course the best solution to that. But sometimes this is not possible; there are upper limits to how much RAM a computer supports.
b. Removing memory hogs such as reducing the number of programs that start when you start the computer is another solution.
c. Upgrading to Windows 7 will give you the option of using ReadyBoost which can significantly improve the speed of a system with limited memory; also, you would get a more secure system that is still being maintained with security patches.
d. Swapping your hard disk with a new and fast SSD could also make a significant improvement to the speed of your computer. Remember that there are fast and slow SSDs – find a fast one if you choose this path. But it does require copying (cloning) all the data from the old hard disk to the new SSD. Some SSDs come with a kit, software and instructions on how to do that. Remember to turn off any defragmentation programs after deploying the SSD; defragmentation is meaningless on an SSD and even shortens its life.
There can be many other reasons, but these are the ones that come to my mind, having had several slow computers over the years due to lack of funds – or, in case I had the funds, my lack of willingness to use them on buying a faster computer. :-)


text:
Q: Should I host the static content of my webapp on AWS S3 For a web app with a moderate amount of static media content which will be deployed on an Amazon EC2 instance, does it make sense to include the static content inside the war file or to host it on a separate S3 instance.
What will be the differences in terms of performance?
What will be the differences in terms of service costs?
What will be the differences in terms of complexity?

A: Absolutely. For 4+ reasons:

*

*Amazon S3 is almost management-free, so no hassles on provisioning, scaling, etc.

*You will reduce EC2 server load

*The storage is cheaper in S3 than in EC2 EBS volumes, as in S3 you only pay for what you consume, in EC2 you pay for the whole EBS provisioned storage (so there is some free space which you are paying for)

*You could eventually add a CloudFront distribution to approach the static content to your users wherever they are (http://aws.amazon.com/cloudfront)

*probably more ...

In terms of costs:

*

*the data transfer from S3 to internet would be the same as you would pay on EC2

*you will probably reduce the cost of the storage

*you will have an additional cost for the number of requests made to your S3 files (http://aws.amazon.com/s3/#pricing)

*on high traffic loads, you will also probably need less EC2 instances / resources (this is obviously not a fact, as it depends 100% on your app)

You will also have an overhead of complexity when releasing a new version of the app, because besides deploying it into the EC2 instances, you will also have to upload the new static file versions to S3. But you could automate this with a pretty simple script.


text:
Q: Not distinguishable testing of pointers and pointer refs in C I'm not distinguishable pointers and pointer references in 'if' statement of C. I'm reading the book, Object-Oriented Programming in C (ooc).
Here is the code I can't understand that why use 'element' instead of '*element' in 'if' statement.
It has already the value of address to 'element' (not ref) even 'find' function returns NULL?.
void * drop (void * _set, const void * _element)
{
    int * element = find (_set, _element);

    if (element)
        * element = MANY;

    return element;
}

A: In C the value 0 is equivalent to false and everything nonzero is true.
Null is predefined to be 0.
So if (element) is checking to see if element is Null or not. If element is Null the statement will be false and it will jump straight to the return, otherwise it will be true and run *element = MANY; before returning.
The other way of thinking of this is mentioned in the comments. if (element) == if (element != NULL).


text:
Q: print the last line of a loop What I'm trying to do is print the results in increments of 5 - DONE. Then, print only the last line of the loop. For ex: if z=26, print results of z @ 5, 10, 15, 20, 25. Then println with z @ 26. I'm stuck and can't figure it out.
for (int i = 1; i <= z; i++) {
    b = b + (b * y) + x + w;

    if (i % 5 == 0)
        //input 1
        System.out.println("In " + i + " years, IRA value: " + b);

    //input 2 - value of IRA when retirement is reached
    System.out.println();

A: I don't know what initial values b, x, w and y got so I just initialized them somehow ..
But I think you want something like this:
public class HelloWorld{

     public static void main(String []args){

        int z = 26;
        int b = 0;
        int x = 1;
        int w = 2;
        int y = 1;

        for (int i = 1;i<=z;i++) {
            b = b+(b*y)+x+w;
            if (i % 5 == 0)
                System.out.println("In " + i + " years, IRA value: " + b);
        }

        System.out.print(z);
     }
}

Output:
In 5 years, IRA value: 93
In 10 years, IRA value: 3069
In 15 years, IRA value: 98301
In 20 years, IRA value: 3145725
In 25 years, IRA value: 100663293
26

A: Change your condition to
if(i%5==0 || i==z)

A: Adding an or (|| i==z) in the if will do the work
for (int i = 1;i<=z;i++) {
    b = b+(b*y)+x+w;
    if (i%5==0 || i==z)

    //input 1
    System.out.println("In " + i + " years, IRA value: " + b);

    //input 2 - value of IRA when retirement is reached
    System.out.println();

    //end
}


text:
Q: How can I keep deleted files from showing up in TextMate 2 file-browser sidebar? In Textmate 2, when you rename a file, the new filename shows up in the file-browser sidebar, but the old filename does, too, with a red X. The old filename won't go away until you commit your name change. This has been infuriating me for years. I refactor & rename a lot, and I constantly click on the wrong/deleted filenames during the refactor.
Is there a way to disable this behavior?
I have tried disabling all SCM-related bundles, but that doesn't do the trick.

A: This is new last week:

It is possible to set excludeSCMDeleted = true in a .tm_properties file to hide the "ghost" items that appear after deleting a file on disk which is still tracked by your version control system.


text:
Q: empirical quantiles in matlab does anyone know how to calculate the empirical quantiles of a distribution in matlab? specifically I have issues working w the empiricalQuantiles() function and need to calculate empirical quantiles of a rolling population (a matrix that is say 49x1025 for every 100 points).
if you can also give information on how to calculate the inverse of the empirical distribution (which should give approximately the same answer) that would be great

A: % Simulating empirical data
empiricalData=randn(50000,1);
% Quantile evaluation
% For instance: Median
y = quantile(empiricalData,[.50]);


text:
Q: How to interpret quantum fields? As an analogy of what I am looking for, suppose $f(x,t)$ represents a classical field. Then we may interpret this as saying at position $x$ and time $t$ the field takes on a value $f(x,t)$.
In quantum field theory the fields are now operator valued distributions. Suppose $\varphi$ is a quantum field, thus it must be of the form $\varphi(f)$ where $f$ is some suitably nice test function. What is the physical interpretation here analogous to the classical field case? Is the test function $f$ supposed to represent the state of the system (as it would in quantum mechanics, i.e. $f \in \mathcal{H}$ where $\mathcal{H}$ is some Hilbert space)?
To word things different, what exactly does it mean to apply the resulting operator valued distribution $\varphi$, for example, $\varphi | 0 \rangle$? Physically what does this tell us?

A: There is one usual confusion about quantum fields which is, at least in my perspective, perhaps caused by one very familiar example which we all have met before studying QFT. This example is that of the electromagnetic field. We are all used from electrodynamics to talk about electric and magnetic fields $\mathbf{E}$ and $\mathbf{B}$ as measurable quantities. As such, we often think that in QFT, the quantum fields should represent observables.
While this is true in some particular cases (the electromagnetic field one for example), it is not true in general. For example, a spinor field, like the electron field $\Psi(x)$, is not even Hermitian, so it does not qualify as an observable as per the postulates of QM.
All that said, in my opinion the best way to interpret quantum fields is that quantum fields are building blocks for observables, introduced as mathematical constructs which facilitate us to build relativistic interactions obeying cluster decomposition. That is quite a bit, so I'll elaborate.
Please, bear in mind that what follows is a very rough summary of a logic that Weinberg constructs through four long chapters in his book. I encourage you to study Chapters 2 - 5 of Weinberg's "The Quantum Theory of Fields" to get the full picture.
Now, the argument is roughly this. We start with relativistic particles. We want to build interactions for these particles which satisfy two properties: (1) they are compatible with the relativistic symmetry encoded in the Poincaré group and (2) they satisfy cluster decomposition, which means that experiments conducted far away should have nothing to do with each other.
The most simple way to satisfy cluster decomposition is to build our interaction potential $V$ as a kind of polynomial in the creation and annihilation operator where the coefficients obey one kind of regularity condition. Likewise, the most simple way to satisfy relativistic invariance is to build $V$ as
$$V(t)=\int d^3 \mathbf{x} {\cal H}(t,\mathbf{x})$$
where ${\cal H}(t,\mathbf{x})$ is a scalar which commutes with itself at spacelike separations.
Now, one must be able to combine the two things. But it is a bit hard because while the creation and annihilation operators $a(p,\sigma)$ and $a^\dagger(p,\sigma)$ transform very simply under translations, they have a complicated transformation law under Lorentz transformation. So the most simple way around this is to repackage these operators into quantum fields, which are demanded to have simple transformation laws under Lorentz transformations. Once that is done, constructing such ${\cal H}(t,\mathbf{x})$ becomes extremely simple.
Weinberg then introduces the formalism of canonical quantization in which you start from a classical Lagrangian density ${\cal L}$ and derive from it the interaction Hamiltonian. I do believe this is the best moment to introduce it, since now we know what is a quantum field and why it is reasonable to use them. Canonical quantization bypasses the need to construct such interaction Hamiltonians by hand, and so what one gets is a framework for constructing relativistic theories. The advantage of Weinberg's point of view is that at this point we already know the correct relation between fields and particles and know which particles can be described by each field. In particular I find it very beautiful that as Weinberg shows, if you try to encode spin one massless particles into a vector field $A_\mu(x)$ you can't really get an object transforming as a vector field. Rather, $A_\mu(x)$ transforms as a vector field up to a gauge transformation, and then the requirement of gauge invariance appears naturally.
So in the end, I would say that today I view this point of view exposed in Weinberg's textbook as the most natural way to interpret a quantum field. They are objects introduced for convenience in order to construct relativistic theories obeying cluster decomposition. It does happen that some of them are observables (like the electromagnetic field $F_{\mu\nu}$), but it is not a general rule (as we see in the electron field $\Psi(x)$), and with this point of view this is not an issue at all.

A: Perhaps the most direct (but not only) interpretation is to say that $\phi(x)$ represents a local observable.$^\star$ In other words, $\phi(x)$ represents the value of the field at $x$. You can (in principle) perform a measurement to learn the value of the field at $x$.
Just like in normal quantum mechanics, in a general state $|\Psi\rangle$, you cannot predict precisely what the outcome will be of measuring $\phi(x)$. You can only make such predictions in special states, field eigenbasis states. For example, there is an eigenstate $|\varphi(x)\rangle$ where the field will take on the value $\varphi(x)$:
\begin{equation}
\phi(x)|\varphi(x)\rangle = \varphi(x) |\varphi(x)\rangle
\end{equation}
However, in other states, like the ground state (also called the vacuum state) $|0\rangle$, the field does not take on a definite value. There is a superposition of field values, represented by the Schrodinger wavefunctional (which is the generalization of the Schrodinger wavefunction of quantum mechanics, to quantum field theory).
Frequently we are interested in the correlation functions of the field, in some state (usually the vacuum). This is a way to capture the probability distribution over different field configurations. From these correlation functions, we can extract other observables we care about (such as scattering amplitudes in particle physics). Some examples of correlation functions are
\begin{equation}
\langle 0 | \phi(x) \phi(y) | 0 \rangle, \langle 0 | \phi(x) \phi(y) \phi(z) |0 \rangle, \cdots
\end{equation}
Note that because of operator ordering ambiguities, in practical applications it is important to specify how the operators are ordered when defining and computing correlation fucntions.
The reason that the field is an operator valued distribution, and not simply an operator valued function, is because it is quite a singular object. For example, the two point function is divergent in the limit $x\rightarrow y$
\begin{equation}
\lim_{x\rightarrow y} \langle 0 | \phi(x) \phi(y) | 0 \rangle = \infty
\end{equation}
Therefore, one typically "smooths out" the correlation function by integrating the field against a test function.

$^\star$ As Gold mentioned in their answer, this is a simplification. Because of the freedom to do field redefinitions, and in gauge theories the ability to do gauge transformations, the value of the field itself is not a physically invariant quantity. For the field value itself to be meaningful, you have to couple the field to a probe that will measure the field's value.


text:
Q: Flutter java.lang.IllegalArgumentException: Service not registered: com.google.android.gms.measurement.internal Every time I build and run my Flutter app, I get this error message:
Exception thrown while unbinding
java.lang.IllegalArgumentException: Service not registered: com.google.android.gms.measurement.internal.zzjp@9f10cc9
    at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1044)
    at android.app.ContextImpl.unbindService(ContextImpl.java:1337)
    at android.content.ContextWrapper.unbindService(ContextWrapper.java:616)
    at com.google.android.gms.common.stats.ConnectionTracker.zza(com.google.android.gms:play-services-basement@@17.3.0:55)
    at com.google.android.gms.common.stats.ConnectionTracker.unbindService(com.google.android.gms:play-services-basement@@17.3.0:50)
    at com.google.android.gms.measurement.internal.zziv.zzag(com.google.android.gms:play-services-measurement-impl@@17.5.0:245)
    at com.google.android.gms.measurement.internal.zziv.zzal(com.google.android.gms:play-services-measurement-impl@@17.5.0:262)
    at com.google.android.gms.measurement.internal.zziv.zzc(com.google.android.gms:play-services-measurement-impl@@17.5.0:336)
    at com.google.android.gms.measurement.internal.zziu.zza(com.google.android.gms:play-services-measurement-impl@@17.5.0:2)
    at com.google.android.gms.measurement.internal.zzai.run(com.google.android.gms:play-services-measurement-impl@@17.5.0:7)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at com.google.android.gms.measurement.internal.zzfy.run(com.google.android.gms:play-services-measurement-impl@@17.5.0:21)

App doesn't crash, but I'd like to understand what's going on.I'm using firebase_core, firebase_auth and cloud_firestore. I spent some time researching, but didn't succeed to find an explanation.


text:
Q: OP-AMP Positive/Negative Feedback together I've read several articles about the application of OP-AMP negative feedback. As far as an application for positive feedback, I came across hysteresis and it makes sense.
Are other uses for positive feedback other than hysteresis?
I am also not sure why in some applications they use both the positive and negative feedback path?
I've leanred that if the net gain on the negative feedback path is more than the net gain on the positive feedback path, then it acts as an OP-AMP with negative feedback, and vice versa.
If we tend to get an overall negative feedback or an overall positive feedback, then what is the point of using both paths at the same time, at the first place?
Why do we even bother ourselves to use both paths, if at the end all we care about is to have either a net positive or negative feedback?

A: See my answer here for an example of why you might want to use negative and positive feedback at the same time. The 598.3K resistor in the positive feedback path maintains a constant current through the variable resistor and the negative feedback path determines the gain (output volts per ohm of resistance of the variable resistor).

To see how this yields a constant current, consider Scott's generalized NIC answer. This is also a NIC- creating a negative resistance to cancel out the incremental effect of the 100K resistor R2, so the current remains constant.

Looking into the non-inverting input of the op-amp (without R2 and the variable resistor connected, but with R4 in place), the resistance looks like:

Referring to the NIC schematic, we have:-
R1 = 100K || 25.68K = 20.43K
R2 = 122.2K
R3 = 598.3K
\$ R_{IN} = \$ - 598.3K \$ \cdot \$ \$ 20.43K \over 122.2K\$
= -100K, which exactly cancels out the effect of the 100K resistor R2 (R2 on the original schematic).

A: @Rudy01, you have asked an excellent question that deserves an exact answer...
The positive feedback can be used for amplifying purposes as well... and it was used in the past to increase the gain of the then amplifiers having fixed, stable but low gain. Nowadays the situation is just the opposite - we have (op)amps with enormous but not exactly specified gain. For this reason, we use a negative feedback to reduce their excessive gain... and make it stable and exactly specified. So, the negative feedback is used, as a rule, in any amplifier.
Now let's see when we add an additional positive feedback... or, as you asked, "why in some applications they use both the positive and negative feedback path?" Of course, the current inversion NIC - INIC (in the Wikipedia picture above) is the most typical example of using this mixing technique. As the best way to understand circuits is to build them, I suggest to do it with this odd circuit.
The idea of creating this kind of negative resistance (we can name it voltage controlled) is extremely simple - we connect an opposing voltage source (in the simplest case, 2V) via a positive resistor (R) to the input voltage source (V). As a result, the current through the positive resistor is reversed (thus the name INIC)... and the resistor as though produces instead to consume a current V/R. To implement this opposing voltage source, we need a fixed-gain non-inverting amplifier... and we make it by applying a negative feedback to an op-amp that reduces its excessive gain to the finite value 1 + R2/R1.
Then, to obtain the negative resistance, we should apply this opposing voltage back to the input voltage source. So, we connect the op-amp output via a resistor (R3 in the picture) with its input. Now, if the input voltage source is perfect (Rin = 0), nothing new (regarding the feedback) will happen - a negative resistor -R will be connected to the perfect input voltage source... and it will pass back current V/R through it... but there will be no positive feedback. Usually, voltage sources are not perfect (they have some internal resistance), or we intentionally connect a positive resistance in series to the input source... so, in this cases, a positive feedback appears... and we have the both kinds of feedback... We have only to make the negative feedback dominate over the positive one to keep the circuit stable (to avoid the "hysteresis" as you said in your question)...
Now about the most interesting part of this discussion where you asked, "How does the positive path maintain a constant current?"... and commented, "but it is only changing the direction in the positive feeback path, correct? The current througth the source is always the same direction, correct?"... and simply you wanted to know the meaning of all this...
First at all, Spehro Pefhany should note that this circuit is known as Howland current source (pump). It was invented in the early 60's simultaneously by Howland and Deboo. Simply speaking, it is a mixture of two opposite but equivalent resistors - positive (R2 = 100 kom) and negative (RN = -100 kom, the whole INIC). They completely neutralize each other and the result is an infinite (differential!) resistance connected in series with the input voltage source (+5 V). So, the whole combination (excluding only the rheostat) acts as a perfect current source suplying the rheostat...
Like negative feedback, in most cases, the negative resistance is something "positive" (useful, "helping"). Think of the combination Vin + R2 as an imperfect current source that is affected (disturbed) by the rheostat (this current source "wants" to pass a current Vin/R2 = 5/100 = 50 mA through the rheostat but the current is less - Vin/(R2 + Rrh)):
I = (Vin - Vrh)/R2 = Vin/R2 - Vrh/R2 = Idesired - Ierror
As you can see, the part (a kind of current) Vrh/R2 is the error, and the negative resistor adds exactly this current. Thus the negative resistor "helps" the input source in its "striving" to pass the "desired" current through the rheostat by adding an additional current to it. So, in this circuit, both the input source and INIC (the op-amp output through R4) pass currents in the same direction through a common load - the rheostat.
Now about the discrepancy with the Wikipedia article. There the simplest case is shown - a voltage source (with positive voltage) "loaded" by an INIC. In this simple case, really the INIC "pushes" back (sources) the current into the input source since there is no load to divert the current. I have illustrated this situation in the picture below by means of voltage bars and current loops; so you can see where currents flow:

If the input source had a negative voltage, the INIC would sink the current from the source:

I have explained in detail this topic in my stories below; maybe they would be useful for you:
Revealing the Mystery of Negative Impedance
How to Compensate Resistive Losses by Parallel Connected Negative Resistor
Linear Mode of Current Inversion NIC
What Is the Basic Idea behind a Negative Impedance Converter (NIC)?  (WP talk)

A: Yes.  You can use positive feedback techniques to make a negative impedance converter. http://en.m.wikipedia.org/wiki/Negative_impedance_converter
Such techniques can be used to do things like null out the large capacitance of a microelectrode so you can recover the high frequency response.


text:
Q: angular 4 persistance storage usage in promise then function Trying to use angular-persistance in promise then function but always says undefined
import { Component, OnInit, Injectable } from '@angular/core';

import {Router} from "@angular/router";
import {PersistenceService, StorageType} from "angular-persistence";

export class ProcessingComponent implements OnInit {

  myfunc: any;

  constructor(private PersistenceService: PersistenceService ){
  }

  ngOnInit() {

    this.myfunc = new myfunction();

    this.shaObj.generateIdentity().then(function (result, PersistenceService) {
      console.log(PersistenceService.set('identityKey')); // getting undefined
    }.bind(this.PersistenceService));

  }

So the bind service does not seem to be working, how to get the outer scope 'this' to be passed into the '.then' function.

A: You should be using this.injectableName instead of directly using ClassName
console.log(PersistenceService.set('identityKey'));

should be
console.log(this.PersistenceService.set('identityKey'));

Note: As per guideline and to avoid confusion use cammelCase for injected dependency

constructor(private persistenceService: PersistenceService ){}

Also you could use Arrow function's ES6 beauty instead of using .bind(this)
this.shaObj.generateIdentity().then((result, PersistenceService) => {
  //Assuming you changed dependency name to `persistenceService`
  console.log(this.persistenceService.set('identityKey'));
});


text: Q: Do I need a Microsoft Developer Edition Tools license to code in VBA in Office 2000 thru Office 2007? I have a job involving old versions of VBA/Access code I'm tasked with fixing. To my utter dismay, the only version of Microsoft Office Developer Edition Tools I can find to fix this company's problems with their pre Office 2010 Access VBA coded screens is an Office 97 version, which is a vald license of the Microsoft Office 97 Developer Edition Tools.  My question is this: supposing I get there and the guy has it coded in Office 2003.  Am I going to have to go out on the web and try to find an old Developer Tools for 2003 just to do the work?  Same thing if its 2007 I find in use.  Basically, I need to know whether I can even do dev work on Office 2003 or 2007 or even 2010 without a developers licence, like we had to in the old days, or whether I will be able to edit & fix code issues in the older versions if the company I go to does not have the developers licence versions appropriate for the work in these older versions of Office.  I know for a fact that, until the versions like Office 2013, 2016, and 365, you needed a dev licence that cost extra money but you can develop right out of the box on the newer ones.  But that begs the question of what I will need to do the work in on of the version from the wayback machine, such as 2000, 2003, or 2007.  Thats what I need an answer to.


text: Q: Change color of particular date in CalendarView I am creating android app with CalendarView in which user can add events. I want to highlight dates on which user already added events like dates with events will be shown in red color or text of date will appear in red color. I tried searching for it on google but found nothing. I don't know if any method to this thing exist for CalendarView. Sorry for my bad English..


text:
Q: How to get the taggable_friends user profile id's using Cordova-plugin-facebook4? PICTURE! Id's are like these. and they got changed everytime i hit SubmitI am using Facebook Graph API to login with facebook in my ionic App project.
I successfully login in using their javascript sdk and sample code.
The problem occurs at the point when i try to fetch my taggable friends. All friends are coming back as response but the id's of friends are a long string and gets change on every request. What is that id? Because the facebook profile id for each user is short and sweet which only contains numbers. But this id is type of encrypted key. Can anybody help me solving this mystery? How can i get the correctly formatted user profile id from facebook javscript sdk.
PS i am using Cordova-plugin-facebook4 plugin for this. Because i am working in ionic.

A: It is a tagging token, and you can only use it for tagging. There is no way to get IDs of users who did not authorize your app.


text:
Q: IIS url rewrite ignores .chtml ( Razor ) files I have a rewrite rule that says.
site.one/content/templates/whatever.cshtml -> site.two/content/templates/whatever.cshtml
The problem occurs when site.one trying to fetch .cshtml files. It returns a 404.
However if i change the extension to .js or .html then the rule works.
If i use the site.two link the request handles it just fine, this is without any rewriterules ofcourse.
site.one can also handle .cshtml files from within its own directory.
Iam using IIS 10, Urlrewrite module 2, and Application Request Routing 3.
UPDATE
So the .cshtml in this case are template files that is fetched with async text.js, and then gets compiled with handlebars as the last step before rendered, but some of them need to get processed by razor engine because of the translations. This works if not rewriting.

A: Razor files are never served by the MVC framework or IIS. Razor files are processed by MVC and the result of the processing is sent to the output through a controller action method. The server is correctly responding with a 404 response in this case, because these files are blocked by default (you would never want to serve an unprocessed .cshtml file with source code to the user).
Since these files are blocked by IIS, there is no way to redirect them using the URL Rewrite Module (nor should there be).
I am guessing that you probably want to redirect your MVC URLs, which don't have an extension by default. The default way they are accessed (which can be customized) is /{controller}/{action}/. For example, the in the MVC template the default way to get to the about page is through the URL /Home/About/.


text:
Q: Video in JavaFX8 doesn't replay after building a jar with Zenjava plugin I'm trying to make video play indefinite number of times and use this code:
Media media = new Media(getClass().getResource("/media/video.mp4").toExternalForm());
MediaPlayer video = new MediaPlayer(media);
video.setCycleCount(MediaPlayer.INDEFINITE);
root.getChildren().add(video);
...
video.play();

Everything works fine while I'm running it inside Intellij, however, when I build it to executable jar with Zenjava JavaFX Maven plugin and run it, video plays only ones and then stops forever.
Edit:
Found out that after building MediaPlayer doesn't detect endOfMedia. By this line (prints nothing to the console, while working before building):
video.setOnEndOfMedia(() -> System.out.println("Ended"));

Any suggestions why is it happening and how to avoid it?
Update: I built executable jar with another library (Maven Assemble PLugin) and problem is still there. So problem is not with the builder.
Also found out that in some cases (didn't find out precisely in which) video stops forever after pause. However, if I call
video.stop();
video.play();

it plays fine from start till the end where it again stops forever.


text:
Q: Android SQLite Beginner Error Just a real quick question, probably something really simple but I've never done ANYTHING with databases before, can someone tell me why the second line is giving me an error?
Thank you! :)
        SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS index (ChalNum INT(3));");

ERROR:
ERROR: 02-12 05:21:47.573: E/AndroidRuntime(1199): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.example/com.example.Home}:
android.database.sqlite.SQLiteException: near "Index": syntax error (code 1): ,
 while compiling: CREATE TABLE IF NOT EXISTS Index (ChalNum INT(3));

A: INDEX is a SQLite keyword. Choose a different name for your table.

A: You can not use the Index name for the Table. Its a keyword for SQLite.
Try out with Index1 or some other name.
Besides using exact word Index use Index1 as below:
    db.execSQL("CREATE TABLE IF NOT EXISTS Index1 (ChalNum INT(3));");

A: You will like to use:
db.execSQL("CREATE TABLE IF NOT EXISTS index1 (ChalNum INTEGER);");

Emil


text:
Q: Swagger with ServiceStack does not send elements to server on POST I have a simple session object which looks like this
[Route("/Session", Summary = "Creates a security session", Notes = "Some session related notes here")]
public class Session : IReturn<SessionResponse>
{
    [ApiMember(Name = "DomainName", Description = "The Security Domain", ParameterType = "path", DataType = "string", IsRequired = true)]
    public string DomainName { get; set; }

    [ApiMember(Name = "UserName", Description = "The User Name", ParameterType = "path", DataType = "string", IsRequired = true)]
    public string UserName { get; set; }

    [ApiMember(Name = "Password", Description = "The password", ParameterType = "path", DataType = "string", IsRequired = true)]
    public string Password { get; set; }
}

When I go to swagger UI I can see the elements
However when I enter the element and press Try it now, I see that the request contents are not sent to the server.
Have I configured my poco correctly with parameterType="path" or should I be doing something else here? Please advise.

A: Has there been any update on getting this to work without seeing your path parameters in the body parameter definition?
[Route("/users/{UserId}/races", "POST", Summary = "Associates a race with a user")]
public class AddUserRace : IReturnVoid
{
    [ApiMember(Description = "User Id to associate a race with to", ParameterType = "path", Verb="POST", DataType = "int", IsRequired = true)]
    public int UserId { get; set; }
    [Description("Race Id of race to associate with user")]
    public int RaceId { get; set; }
}

Ideally, since UserId is a path param, I'd want it hidden from the DTO body.

A: Have I configured my poco correctly with parameterType="path" or should I be doing something else here?
I don't think so. Configuring each of your Session properties to ParameterType='path' suggests that you want each property to be a variable/field with the path/url (documentation here). So you would want your ServiceStack route to look something like this if you want to use 'path'.
[Route("/Session/{DomainName}/{UserName}/{Password}"]

To me, 'query' or 'body' would be a better choice. Also, This might contain useful information as well.

A: I got this to work , here is what I had to do
[Route("/Session", "POST", Summary = "Creates a security session", Notes = "Some session related notes here")]
public class Session : IReturn<SessionResponse>
{
    [ApiMember(Name = "SessionData", Description = "The Session Data", ParameterType = "body", DataType = "SessionData", IsRequired = true)]
    public string DomainName { get; set; }

    //[ApiMember(Name = "UserName", Description = "The User Name", ParameterType = "path", DataType = "string", IsRequired = true)]
    public string UserName { get; set; }

    //[ApiMember(Name = "Password", Description = "The password", ParameterType = "path", DataType = "string", IsRequired = true)]
    public string Password { get; set; }
}

So now I get a text area box and I need to enter the JSON for the entire session object so that the DomainName, UserName and Password get transferred, but somehow this does not seem right.

A: To support sending data in the request body with the current implementation of Swagger in ServiceStack, you should have exactly one ApiMember with ParameterType = "body" (you can still have other ApiMember attributes with other other ParameterType values, if you have variables in your URL for example).
The ApiMember with ParameterType = "body" will represent the entire content of your request body. It doesn't really matter which property of your request DTO you decorate with this attribute. We do something like this to make it clear in the Swagger UI that the textarea generated for this ApiMember should be used to populate the entire request body:
[ApiMember(Name = "RequestBody", ParameterType = "body", IsRequired = true,
    Description = SomeLongStringConstantThatDescribesTheEntireDTO]

In the Swagger UI, this will display a textarea, you will need to enter the entire DTO as JSON in this text area. In your case, it would be something like:
{"DomainName": "...", "UserName": "...", "Password": "..."}


text:
Q: Operadores lógicos javascript Tenho uma dúvida
Porque essa operação não funciona?
if ($(v).attr('jgForm-required') || $(v).attr('jgForm-email') && $(v).is(":visible")) {
......................
}

E essa funciona ? Qual a diferença?
if ($(v).attr('jgForm-required') || $(v).attr('jgForm-email')) {
    if($(v).is(":visible")){
    ...............................
    }
}

EXEMPLO

A: O operador and (&&) tem maior precedência do que o or (||). Isso quer dizer que, numa sequência de ands e ors, os ands são resolvidos antes. Portanto a primeira versão é interpretada como:
X || (Y && Z)

Você pode forçar a interpretação que quer usando parênteses:
(X || Y) && Z

Ou seja:
if ( ($(v).attr('jgForm-required') || $(v).attr('jgForm-email')) && $(v).is(":visible")) {
    // ...
}


text:
Q: Prove $\frac{x}{y+z}+\frac{y}{z+x}+\frac{z}{x+y} \geqslant \frac32+ \frac{27}{16}\frac{(y-z)^2}{(x+y+z)^2}$
$x,y,z >0$, prove
  $$\frac{x}{y+z}+\frac{y}{z+x}+\frac{z}{x+y} \geqslant \frac32+ \frac{27}{16}\frac{(y-z)^2}{(x+y+z)^2}$$

This inequality is easier than the other one. Previously, I learned from Jack D'Aurizio at this post, so my first step is to use the Lagrange's identity. I get
$$\sum_{cyc}\frac{x}{y+z}=\frac32+\frac12\sum_{cyc}\frac{(x-y)^2}{(x+z)(y+z)}$$
Thus it remains to prove
$$\tag{1}\sum_{cyc}\frac{(x-y)^2}{(x+z)(y+z)} \geqslant \frac{27}{8} \frac{(y-z)^2}{(x+y+z)^2}$$
I spent several hours to prove (1) but not success. Please help.

A: Here's a proof.
Following the task description, we want to establish
$$
\sum_{cyc}\frac{(x-y)^2}{(x+z)(y+z)} \geqslant \frac{27}{8} \frac{(y-z)^2}{(x+y+z)^2}
$$
We will follow two paths for separate cases.
Path 1:
Clearing denominators, we obtain
$$
(x-y)^2 (x+y) + (y-z)^2 (y+z)+  (z-x)^2 (z+x) \geq  \frac{27}{8} \frac{(y-z)^2}{(x+y+z)^2} (x+y) (y+z) (z+x)
$$
Now we use the general formula (by AM-GM):
$$
 (a+b+c)^3 \geq 27  a b c
$$
Applying this to $a =  (x+y); b =  (y+z); c =  (z+x)$ gives
$$
(x+y+z)^3 \geq \frac{27}{8} (x+y) (y+z) (z+x)
$$
It then suffices to show
$$
(x-y)^2 (x+y) + (y-z)^2 (y+z) + (z-x)^2 (z+x) \geq  \frac{(y-z)^2}{(x+y+z)^2} (x+y+z)^3
$$
which is
$$
(x-y)^2 (x+y) +  (z-x)^2 (z+x)  \geq (y-z)^2 x
$$
Since
$$
 (y-z)^2 = (y-x + x- z)^2 = (y-x)^2  + (x- z)^2 + 2 (y-x)(x-z)
$$
this translates into
$$
(y-x)^2 y +  (x-z)^2 z \geq  2 x(y-x)(x-z)
$$
For the two cases $y\geq x ; z\geq x $ and $y\leq x  ; z\leq x $ the RHS $\leq 0$ so we are done. For the other two cases, by symmetry, it remains to show the case  $y>  x  ; z <  x $.
Rearranging terms, we can also write
$$
(y-x)^3 - (x-z)^3 +x ((y -  x) + (z-x))^2 \geq 0
$$
This holds true at least for $(y-x)^3 \geq  (x-z)^3$ or $y+z\geq 2 x$.
So the proof is complete other than for the case $y+z < 2x$ and [ $y>  x  ; z <  x $ or  $z>  x  ; y <  x $ ].
Path 2.
For the remaining case  $y+z < 2 x $ and  [$y>  x ; z <  x$ or  $z>  x  ; y <  x $]  we will follow a different path. Again, by symmetry, we must inspect only  $y+z < 2x$ and  $y>  x > z$.
Clearing all denominators gives
$$
8 (x+y+z)^2 \sum_{cyc} {(x-y)^2}{(x+y)} - 27 (y-z)^2 (x+y)(y+z) (z+x) \geqslant 0
$$
By homogeneity, we set  $y=1+z$.
The condition $y+z < 2x$ then translates into $1+2z < 2x$, hence we further set $x = z + (1 +q)/2$ where $0\leq q \leq 1$ since also $x = z + (1 +q)/2 < y = 1 +z$.
This gives a lengthy expression
$$
8 (3 z + 3/2 + q/2)^2 \left\{ ((q-1)/2)^2 (2z + (3 +q)/2) + ((1 +q)/2 )^2(2z +(1 +q)/2 ) + (1 + 2z) \right\} - 27  (2z + (3 +q)/2) (2z +(1 +q)/2 )(1 + 2z)\geqslant 0
$$
The LHS  is a third order expression in $z$ with leading (in $z^3$ ) term $72 q^2 z^3$, hence for large enough $z$ it is rising with $z$. A remarkable   feature of this expression is that for the considered range $0\leq q \leq 1$ it is actually monotonously rising for all $z$. To see this, consider whether there are points with zero slope. The first derivative of the expression with respect to $z$ is
$$
216 q^2 z^2 + (84 q^3 + 216 q^2 - 108 q) z + (81 q^2)/2 + 42 q^3 + 8 q^4 - 54 q + 27/2
$$
Equating this to zero gives
$$
z_{1,2} = -(18 q \pm q \sqrt{q^2 - 45} + 7 q^2 - 9)/(36 q)
$$
however there are no real roots in the considered range $0\leq q \leq 1$, so monotonicity (rising with $z$) is established.
Hence, to show the inequality it suffices to inspect the LHS at the smallest $z=0$. This gives
$$
q^5/2 + 4 q^4 + 10 q^3 + (9 q^2)/4 - (27 q)/2 + 27/4 \geq 0
$$
An even stronger requirement is
$$
f(q) =
10 q^3 + (9 q^2)/4 - (27 q)/2 + 27/4 \geq 0
$$
In the considered range $0\leq q \leq 1$, $f(q)$ has a minimum which is obtained by taking the first derivative,
$$
30 q^2 + (9 q)/2 - 27/2
$$
and equating to zero, which gives $q = 3/5$, and the above $f(q)$ then gives
$$
f(q = 3/5) = 81/50
$$
This establishes the inequality. $ \qquad \Box$


text:
Q: Passing path parameter into power shell script using batch file I would like to pass in a path variable --> param ([string]$w) into another parameter that store the path in power shell script. Then this power shell script is called using another batch file. I failed to pass in the $ which is the folder name that completes the full path . Please suggest me solution on this
$FilePath = "C:\Root\Main\Subfolder\param ([string]$w)\Table\"
$FileExists = Test-Path $FilePath

  If ($FileExists -eq $True)
     { Get-ChildItem -path C:\Root\Main\Subfolder\param ([string]$w)\Table\ -Recurse -Filter *.sql |
      ` Sort-Object -Property DirectoryName -Desc | `
      Foreach-Object -Process {$_.FullName } |ForEach-Object {sqlcmd -i $_}
     }

  Else {Write-Host "No file at this location"}

This is my batch file command line
 PowerShell.Exe -File C:\Users\AZ\Desktop\PowerShell\untitled7.ps1 "Payment"

A: Try putting this at the top of your script:
param(
        [Parameter(
                    Mandatory=$true,
                    Position=0,
                    HelpMessage='Set path variable')]
        [string] $w
)

Replace:
param ([string]$w)

with:
$w

where it appears in your script.


text:
Q: Sublime Text 3 error in C++, how to fix it? I'm getting a variable array problem in Sublime Text 3 even after building the system with MinGW64.
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a,b;
    cin>>a>>b;
    cout<<(a+b)<<endl;
    int n;
    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin >> arr[i];
    }
    for(int i=0;i<n;i++)
    {

        cout<<arr[i]<<endl;
    }
    cout<<"hello";
    return(0);
}

A: You have not provided the value of 'n', it is some garbage value, may be you want to
define a macro using
#define N 10 //say

then you can use this to make a array of size N
int arr[N];

A: ISO C++ forbids variable length array 'arr' tells the whole story. In C++, the size of arrays need to be known at compile time since they're statically allocated, whereas right now you're trying to set the size of the array at run time since you're obtaining the size of the array from n, which is a variable. There's the other issue that Mahendra suthar points out that n is uninitialized, but I'm assuming that you want the size of the array to be changeable at run time based on a and b, so you'll either need to use dynamic memory allocation or use std::vector:
#include <bits/stdc++.h>
#include <vector>
using namespace std;

int main()
{
    int a,b;
    cin>>a>>b;
    cout<<(a+b)<<endl;
    int n;
    std::vector<int> arr;
    for(int i=0;i<n;i++)
    {
        int temp;

        cin >> temp;
        arr.push_back(temp);
    }
    for(int i=0;i<n;i++)
    {

        cout<<arr[i]<<endl;
    }
    cout<<"hello";
    return(0);
}


text:
Q: An $N$-qubit system keeps $2^N$ pieces of information or should we say $2^{N+1}$? Say my quantum register is of size $3$ qubits. This means I'll need $2^3$ complex
numbers to describe all of its possible arrangements.  But each complex number requires $2$ real numbers, so maybe I could say I'll need $2^{3}\times2 = 2^4$ real numbers.  Is this correct?
Granted, a complex number is a number.  But when we implement a complex number on any classical computer, we always reserve two numbers for it.  A complex number is a number, but down to computer technology it really is a pair of numbers.  When it comes to storing information, the matter is more about technology than abstract science.
I know in complexity theory it doesn't matter if $2^{N}$ or $2^{N+1}$, but I haven't seen any mention of this little detail anywhere and I've been reading every introduction on quantum computing I can find.  Please do mention any source that you might know that has touched on this little technicality.  Thank you!

A: You are right to say that every complex number (that represents an quantum amplitude) is represented by a pair of real number on a classical computer.
But, in my opinion, you are confusing a simulation of a real life quantum system
with a classical simulation.

*

*In a classical simulation of a real life quantum system (say a quantum circuit that has not been built) we would associate a pair of real number-for representing a complex number that is a quantum amplitude of that quantum circuit -as you pointed out.

*But if we actually build the quantum circuit in real life (rather than simulating it on a classical computer) then those complex amplitudes are actually an intrinsic part of the qubit (which may be implemented by ions, or photons)-because quantum states occur naturally-this is just basic physics.
Another thing to know is that the "amplitude model" of reality is based on the postulates of quantum mechanics.


text:
Q: How check a users name when accessing a route Hi guys ive spent the last 3 hours trying to get this work so any help would be greatly appreciated. So i made an express webapp that has an admin page. I have the register and login done using passport and i can check if the user is logged in with the function
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
    return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');}

I when i click on the link for my admin route i want to check to see if the users username is equal to example and if it is allow it into the page. My code so far is
  var isAdmin = function (req, res, next) {

    if (req.session.username === 'example') {

    return next();
  }else{
  // if the user is not authenticated then redirect him to the login page
  res.redirect('/');
}

and my route is
router.get('/admin', isAdmin, function(req, res){
    res.render('admin', { title : 'admin' });
});

I have both of these code snipets in my index route file. The problem that i am getting is that when i try to log in with the user called example it returns me to the login page. Any ideas how to fix?

A: You could do this as long as you have the session package installed. You will also need the body parser package installed.
router.get('/admin', function(req, res){
    if (req.session.passport.user === undefined || req.session.passport.user !== 'example') {
        res.redirect('/login');
    } else{
        res.render('admin', {title: 'admin'});
    }
});

A: I got it working :)
app.get('/admin', function(req, res){
if (req.user.username === undefined || req.user.username !== 'example') {
    res.redirect('/');
} else{
    res.render('admin', {title: 'admin'});
}
 });


text:
Q: Redirect a raw C array data into a data file in embedded system industries I have seen some codes that have no function. They just have data and the file is supposed to be converted to a data file not an executable.
For example, it is something like
config.c
const unsigned char configData[] = \
"Cnf"
"\0x01\0x01\0x00\0x00\0x00\0x00\0x00\0x00"
"LOCAL/ITEM.MSG\0x00"
"\x7E\xD1\xF5\x3A\0x00\0x00\0x00";

The file is supposed to turn into config.dat as binary starting with Cnf\0x01\0x01... and ending with \xF5\x3A\0x00\0x00\0x00 with no header or footer.
What is the name of such an action? I have problem for google keywords.
And, how can such an action be done using a gcc compiler?

Update: I am not after using fwrite or a library. I do not want to add anything to the above code or remove any line from it. Lets keep this file intact. My problem is not to create a binary file. My problem is mostly understanding how these particular files are handled by the compiler. I have seen such files in the embedded system industries. But not yet found how they work.

A: Interpreting as: "How can I embed a binary file into my C program at build time?"
This is how I do it. I use a custom build step to convert the binary file to a .c file.
In Makefile:
program: main.c configData.c resource.h # and more
    $(CC) -o program main.c configData.c # and more

configData.c: configData.dat bin2c
    ./bin2c configData.dat configData.c

bin2c: bin2c.c
    $(HOSTCC) -o bin2c bin2c.c

In resource.h:
extern char configData[];
extern size_t configDataLen;

In bin2c.c:
#include <stdio.h>
int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "Usage: bin2c binary.dat binary.c symbol\n");
        return 1;
    }
    FILE *in = fopen(argv[1], "rb");
    if (!in) { perror(argv[1]); return 1; }
    FILE *out = fopen(argv[2], "w");
    if (!out) { perror(argv[2]); return 1; }
    int c;
    long len = 0;
    fprintf(out, "#include <stddef.h>\n");
    fprintf(out, "char %s[] = {"
    while ((c = getc(in)) > EOF) {
        if (len > 0) puts(',', out);
        fprintf("%d", c);
        ++len;
        if (ferror(out)) { perror(argv[2]); return 1; }
    }
    fprintf(out, "};\n");
    fprintf(out, "size_t %sLen = %ld;", len);
    if (ferror(out)) { perror(argv[2]); return 1; }
    if (fclose(out)) { perror(argv[2]); return 1; } /* Yup check fclose for errors */
    if (ferror(in)) { perror(argv[1]); return 1; }
    return 0;
}

In .gitignore:
bin2c
configData.c

People have done better than this. I've seen fancy linker scripts that enable the linker to take dat files. My method has the advantage of being easy to understand and portable.


text:
Q: setting VIew color in Android App I've already spent a couple hours trying to figure it out:
I have colors defined in colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="route_1">#C781D9</color>
    <color name="route_2">#015486</color>
....
</resources>

But when I try to set color of ImageView or Text those colors appear too dark and indistinguishable.
color_box.setColorFilter(my_color, PorterDuff.Mode.MULTIPLY);

However when I set color:
color_box.setColorFilter(Color.BLUE);

It works just fine. I have already tried:
int r = (my_color >> 16) & 0xFF;
int g = (my_color >> 8) & 0xFF;
int b = (my_color >> 0) & 0xFF;

color_box.setColorFilter(Color.rgb(r, g, b));

And it still gives me incorrect color.
Any ideas what is going on?

A: Try the following:
color_box.setColorFilter(getResources().getColor(my_color), PorterDuff.Mode.MULTIPLY);

This assumes that it will be called from inside an Activity. Also, it assumes that my_color is an int that equals R.color.route_1 or R.color.route_2. You can just do the following also:
color_box.setColorFilter(getResources().getColor(R.color.route_1), PorterDuff.Mode.MULTIPLY);