Q:

C# - MVC - JSON - Return List From Server Side to Client Side Using ViewBag

Hello everyone,
i'm need to return list to client side using viewbag and return view
let's see code :

Server Side :

var model = _iSiteService.FindProduct(id);
    var UnitsData = _iSiteService.GetAllProductsUnits(id).Where(x => x.Product.IsActive).Select(i => new
                        {
                            i.Id,
                            i.UnitId,
                            i.ConversionFactor,
                            i.ProductId
                        }).ToArray();

                        ViewBag.dataUnitsXX = Json(new
                        {
                            Data = UnitsData.ToArray()
                        }, JsonRequestBehavior.AllowGet);

    return View(model);

Client Side :

var json = @Html.Raw(ViewBag.dataUnitsXX);

Message Error :

var json = System.Collections.Generic.List`1[<>f__AnonymousType2`4[System.Int32,System.Int32,System.Decimal,System.Int32]];

How i can solved it.
please help me to return data in variable in javascript
Thanks You.

A:

You can achieve this by adding the UnitsData list into the ViewBag:
 ViewBag.dataUnitsXX = UnitsData;

and then client side using:
var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.dataUnitsXX));

Please note that the way you try to serialize data is a mix of concepts. The Json you are using there is meant to return an action result of type json. Instead you are returning the model but adding the action result to the ViewBag. You may read more about action result types here.


Q:

IBM Worklight 6.2. Analytics installation on Linux 64 bits. Issue with lib libsigar-amd64-linux.so

I' trying to install analytics in a WAS 8.5 standalone server in a Linux redhat 6 64 bits.
uname -a
Linux localhost.localdomain 2.6.32-71.el6.x86_64 #1 SMP Wed Sep 1 01:33:01 EDT 2010 x86_64 x86_64 x86_64 GNU/Linux

After installing the .war in the server and configuring the classloader with parent last, when I try to access to the console I get this exception in the log although the console is displayed.
[8/6/14 12:31:16:501 EDT] 00000051 SystemOut     O 0 [WebContainer : 1] DEBUG Sigar  - libsigar-amd64-linux.so (Not found in java.library.path)
org.hyperic.sigar.SigarException: libsigar-amd64-linux.so (Not found in java.library.path)
    at org.hyperic.sigar.Sigar.loadLibrary(Sigar.java:172)
    at org.hyperic.sigar.Sigar.<clinit>(Sigar.java:100)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:236)
    at org.elasticsearch.monitor.sigar.SigarService.<init>(SigarService.java:40)
    at org.elasticsearch.monitor.MonitorModule.configure(MonitorModule.java:81)
    at org.elasticsearch.common.inject.AbstractModule.configure(AbstractModule.java:60)
    at org.elasticsearch.common.inject.spi.Elements$RecordingBinder.install(Elements.java:204)

I have not found any documentation about this in the Knowledge center or even in google.
We have tried with yum but we haven't found the lib.
Any hint?

A:

This is a defect. The workaround is to open the analytics WAR file and delete the following directory:
WEB-INF/lib/sigar
The analytics console isn't using sigar, so there shouldn't be any issues when deleting this folder.


Q:

Why is it necessary to add the "of" in "approved of "?

They surely wouldn't have approved my decision.

This sounds like perfect English to me.
But after searching on Google, I realized I was wrong, that I had to write instead:

They surely wouldn't have approved of my decision.

Why?

A:

Both sentences exist but with different meanings. "They surely wouldn't have approved my decision" means "they would not have agreed to accept it" so they had the authority to reject it.
"They surely wouldn't have approved of my decision" means "They would not have considered it to have been a good decision". So they didn't like it but couldn't necessarily have it changed.

A:

Approved implies actual control or supervision: the manager approved my expenses.
Approved of does not; rather, it implies merely an opinion: I approve of his choice of tie.


Q:

Implementation of an Interface with an "anonymous" method

Given the following interface Fn,
interface Fn<A> {
    (): A
}

it is possible to instantiate an object implementing the interface using the builder
function buildFn<A>( val: A ): Fn<A> {
    return () => { return val }
}

Now, using the following interface which is valid in Typescript
interface FnString extends Fn<string> {
    (): string
    toLowerCase(): string
}

how do I write a builder function to instantiate an object implementing FnString ?
edit: solution thanks to @basarat
note:refactored String -> string according to comment
function builderFn(str: string): FnString {
    var fn = <FnString>(() => str)
    fn.toLowerCase = str.toLowerCase
    return fn
}

A:

If you want to create an object that is callable and has other functionality, the best way to do it is by starting with a function object. However since the native inferred type of the function does not match the actual type you are building to, you need a type assertion:
interface Fn<A> {
    (): A
}

function buildFn<A>( val: A ): Fn<A> {
    return () => { return val }
}

export interface FnString extends Fn<string> {
    (): string
    toLowerCase(): string
}

interface Awesome extends FnString { }
export function builderFn(): Awesome {
    var str = ('asdf');
    var fn = <Awesome>(() => str);
    fn.toLowerCase = str.toLowerCase;
    return fn;
}

Also note that string is not the same as String and String is an antipattern (hence I refactored to string).


Q:

How can i extract metdata from django models

Suppose i have this model in django
class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

Now i want to create a serializer in REST to get all the metadata from the models.
Like the resulting JSON should contain
 //rough example
    {
    first_name: {max_length: 30},
    last_name: {max_length:30}
    }

My Aim is to get the meta data on the fly and then create forms dynamically using angularJS schema forms
Any idea on how can i read that meta data for models

A:

You can get a Model's fields and their metadata like this:
def get_model_metadata(model_class, meta_whitelist=[]):
  field_list = model_class._meta.fields
  return_data = {}
  for field in field_list:
    field_name = field.name
    field_meta = field.__dict__
    return_meta = {}
    for meta_name in field_meta:
      if meta_name in meta_whitelist:
        return_meta[meta_name] = field_meta[meta_name]
    if len(return_meta) > 0:
      return_data[field_name] = return_meta
  return return_data

Usage:
from django.contrib.auth.models import User
get_model_metadata(User, meta_whitelist=['max_length'])

Returns:
{
  'username': {'max_length': 30},
  'first_name': {'max_length': 30},
  'last_name': {'max_length': 30},
  'is_active': {'max_length': None},
  'email': {'max_length': 75},
  'is_superuser': {'max_length': None},
  'is_staff': {'max_length': None},
  'last_login': {'max_length': None},
  'password': {'max_length': 128},
  u'id': {'max_length': None},
  'date_joined': {'max_length': None}
}

Improvements to this method would include blacklist of field metadata, whitelist/blacklist for fields, and maybe a boolean for not showing metadata that has None value.


Q:

"Relationship to" vs. "Relationship with"

I found two different terms regarding relationship:
 "Relationship with the applicant" while filling the invitation form
 "Relationship to the applicant" while filling the application form

Whether both are same? I was writing for my wife. Should I write husband in both the case? I am really confused what to write?

A:

A relationship between two people A and B is the set of connections -- familial, social, commercial, etc. -- between them.  The relationship of person A to person B means those connections from the one-way point of view of person A.  In filling out a form, this is almost always a question about familial connection:

Q: What is (person B's) relationship to the applicant (person A)?
  A: Person B is person A's father.

In other words person B's relationship to person A is that of male parent.  Usually, this may be turned around from the point of view of person A:

Person A is person B's son.

That is person A's relationship to person B is that of male offspring.
Relationship with usually asks for the broader mutual connections between the two parties:

Q: What is (person B's) relationship with the applicant (person A)?
  A: Person B and person A have been business partners for three years. They jointly own three commercial buildings, and Person A has sponsored person B for club membership.

Whether this distinction obtains for this particular application cannot be discerned without having the application posted.


Q:

How to enable VS Code HTML error checking / validation?

I have just switched to Visual Studio Code for web development from Netbeans and am finding my way around. In Netbeans, if I forget the closing bracket on a tagname it will indicate my error with a red squiggly underline, and the alert in the left margin.
I would have thought error checking to be a fundamental function in a web dev editor like vs code. Maybe I am just not finding the right option or extension.
How can I achieve this same html, css error checking behaviour in VS Code?

A:

VSCode doesn't have HTML validation by default. But it allows you to add extensions and enable these features.
To add HTML validation (linting), Open VSCode, then press Ctrl + P and then paste ext install HTMLHint in it, and press enter. It will install a HTML validator. You may need to reload VSCode to load the extension.
Now if you open the same html document you had the syntax error, you should see there's an issue shown at the status bar at the bottom :) and it will also show you the errors in those lines.

A:

VS Code default support code formatting and it track the syntactical error. If you create a new file and directly try to write the code than VS Code could not able to understand which language or type of syntax user want to format/correcting.
So, first need to save the new file with the proper extension than visual studio properly identify the syntax.
The code formatting is available in VS Code through the following shortcuts:

On Windows Shift + Alt + F
On Mac Shift + Option + F
On Ubuntu Ctrl + Shift + I

You can add Auto Close Tag from VS Code marketplace.
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.

Automatically add HTML/XML close tag, same as Visual Studio IDE or Sublime Text
ext install auto-close-tag

VS Code integration for HTMLHint - A Static Code Analysis Tool for HTML
ext install HTMLHint

Provides CSS class name completion for the HTML class attribute based on the CSS files in your workspace. Also supports React's className attribute.
ext install html-css-class-completion


Q:

How to check OTG support in Windows 10 Mobile?

When I was on Android I was able to check whether my device supports USB OTG or not using this procedure. I have heard that Windows 10 Mobile supports OTG but neither there is any official content about that nor I could find the list of Handsets that support OTG. So is there any way to check whether my phone is OTG compatible or not? My phone is 535 DS running W10M (14393.693).

A:

No. Lumia 535 dual Sim phone does not support OTG functionality. Me too have that phone. And can confirm that it can't support.
And to check the OTG support there isn't any app available in store which checks for OTG support in phone. Only via official documention of phone you check does a phone support OTG or not.


Q:

When to start with year 0 and when with year 1 when calculating NPV?

I am calculating NPV for one investment plan.
When should I start the calculation of NPV with year 0 and when with year 1?
I know that the year 0 is like the year when the company is just starting up so there are no revenues yet etc... In the first year they will be just doing everything so that in the next year they can start selling their products or services...
However, I have seen some examples of calculating NPV on the internet when there was just years 1,2,3,4 and not starting with year 0.... Is it a case of companies that do not need that first year for starting up but are able to sell their products or services from the first month after they started their business?

A:

The income and recurring costs will be shown at the end of each year, however the initial cost is recorded at the time they are incurred meaning at t=0 (Jan 2014)
The first net profits/loss of 658500 is recorded at the end of Dec 2014 (t=1)
And the remaining four ones at the end of 2015 (t=2) 2016 (t=3) 2017 (t=4) 2018 (t=5)
-8000000 658500  658500 658500 658500 6658500
t=0) -8000000
t=1) 658500
t=2) 658500
t=3) 658500
t=4) 658500
t=5) 6658500


Q:

Retrieve media Entry comments kaltura

Basically what the title says.
I can't find a relative service to their api. I have tried many ways but nothing worked so far. I'd really appreciate any help.
Thank you

A:

You should use CuePoint service with List action and filter with KalturaCuePointFilter property EntryIdEqual - put entry's ID, which comments you want to recieve, and you will get list of all comments belonging to that entry.


Q:

Can proc argument be variable

I just tried the following in tclsh:
proc pp {$ag} { puts hi}
pp  whatever

To my surprise, this works fine! I had expected a syntax error because the proc argument is a variable. But it seems tcl takes it fine.
Then I experimented:
proc pp {$ag} { puts "hi $ag"}
pp  whatever

and
proc pp {$ag} { puts "hi ${$ag}"}
pp  whatever

I got error, can't read "ag": no such variable.
This makes me wondering, can proc argument be variable? If not, why not error out in the first script?

A:

The first case works because you never use the parameter to pp.
When you invoke the proc command, the text of the invocation is evaluated just like in any other command invocation. In all the above cases, the third argument (which will become the argument list of the pp command) is is wrapped in braces, which means it won't be evaluated as a variable but as a string of three characters: "$ag" (i.e. the dollar sign is just a regular character here). This is not an error, and does work, just not the way you seem to expect it to.
It's a bit tricky to get the value of the parameter $ag, though. This works:
proc pp {$ag} {puts "hi [set {$ag}]"}

The dollar notation is actually just syntactic sugar for the unary set command. Sometimes the dollar notation won't work, and you need to fall back to an explicit set.
This does work too, though:
proc pp {$ag} {puts "hi ${$ag}"}

So, in your invocations, the third argument to proc isn't really a variable evaluation, it just looks like one. You can of course use an actual variable evaluation in the invocation of proc:
set foo {bar baz}
proc qux $foo {puts $bar ; puts $baz}
qux abc def
# => abc
# => def

What the Tcl interpreter really sees here is:
proc qux {bar baz} {puts $bar ; puts $baz}

Or you can go really crazy:
set foa {proc qux}
set fob {bar}
lappend fob baz
set foc {puts $bar}
set fod "puts \$baz"
{*}$foa $fob [join [list $foc $fod] { ; }]

Which amounts to the same thing as the previous invocation of proc. (If you don't believe me, try list {*}$foa $fob [join [list $foc $fod] { ; }])
This example just looks (and is) weird, but many times it's actually useful to construct new commands within your program, and in those cases it's really nice that the text used in the invocation of proc, like with any other command, is simply text that the evaluation rules of Tcl can be applied to. You can use any kinds of string or list operations on it and join up pieces of text from various sources, even user input (if you can trust it).
Documentation: Tcl evaluation rules including $ and {*}, join, lappend, list, proc, puts, set


Q:

BLToolkit: Trying to update an entity and getting "can't convert to SQL error"

I have an update method:
protected int ProcessUpdate(TUpdateDto updateDto, Func<IQueryable<TEntity>, IUpdateable<TEntity>> firstSetter, params Func<IUpdateable<TEntity>, IUpdateable<TEntity>>[] setters)
    {
        Checker.AssertNull(updateDto);
        int id = updateDto.Id.FailIfNull();

        IQueryable<TEntity> query = from item in new Table<TEntity>()
                                    where item.Id == id
                                    select item;

        IUpdateable<TEntity> updateable = firstSetter(query);

        foreach (var setter in setters)
        {
            setter(updateable);
        }

        Checker.AssertNull(updateable);
        updateable.Update();

        return id;
    }

And entity:
[TableName("Test")]
public class Test
{
    [PrimaryKey, Identity]
    public int Id { get; set; }

    public string Field1 { get; set; }
}

And here is the update code:
 ProcessUpdate(updateDto, x => x.Set(e => e.Id, updateDto.Id),
                          x => x.Set(e => e.Field1, updateDto.Field1));

When I try to update an entry in a table I get "'Convert(item).Id' cannot be converted to SQL." error. I have tried not to update id and results were the same. I wish I could find the solution, but I can not. Thanks for your answers.

A:

The solution was about modifying BLToolkit sources.


Q:

How the following SQL query is working?

How is the given query correct as it is using T1 inside the with clause and T1 is declared after the clause within WITH is completed.
WITH T1(Emp,Manager,Salary) AS
(
SELECT tt2.[Emp],tt2.[Manager],tt2.[Salary]
FROM [YourTable] AS tt1
RIGHT OUTER JOIN [YourTable] AS tt2 ON tt1.[Emp]=tt2.[Manager]
WHERE tt1.[Emp] is NULL
UNION ALL
SELECT r.[Emp],T1.[Manager],r.[Salary]
FROM [YourTable] AS r
INNER JOIN T1 ON r.[Manager]=T1.[Emp]
)
SELECT [Manager],SUM([Salary]) AS Salary
FROM T1
GROUP BY [Manager]
ORDER BY SUM([Salary]) DESC

Above query is answer to following question -
I have table with columns (Employee, Manager, Salary). Need to calculate aggregate salary for all employees corresponding to top-level managers in one SQL. For example
Input table is :
Emp Manager Salary
A   T   10
B   A   11
C   F   13
D   B   5

Result should be :
Top-Lvl Manager Salary(agg)
T   26
F   13

Manager-Employee layering can go multiple levels.

A:

This is a recursive query. The part before UNION ALL gets the base records. The part after it recursively gets more rows attatched to the former.
The first part is confusingly written. It is an anti-join pattern inplemented even with a right outer join which many consider hard to read. It merely means this:
select emp, manager, salary
from yourtable
where manager not in (select emp from yourtable);

So you get all employees that have no manager (i.e. the super managers).
With the part after UNION ALL you get their subordinates and the subordinates of these etc. A hierarchical query.
At last in
SELECT [Manager],SUM([Salary]) AS Salary
FROM T1
GROUP BY [Manager]
ORDER BY SUM([Salary]) DESC

you use those rows to get a cumulated salary per manager.
You can read up on recursive queries in SQL Server here: https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx.


Q:

How can I get all users an object has specific permissions to in django guardian?

There is
from guardian.shortcuts import get_objects_for_user

But what about
from guardian.shortcuts import get_users_for_object

Thanks.

A:

Actually there is a shortcut for that
http://django-guardian.readthedocs.io/en/stable/api/guardian.shortcuts.html#get-users-with-perms
>>> from django.contrib.flatpages.models import FlatPage
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import assign_perm, get_users_with_perms
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
>>> assign_perm('change_flatpage', joe, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage']}

A:

This is my workaround. This is Model method. You can encapsulate it in mixin.
def get_users_with_perm(self, permission):
    '''
    Returns list of users(worn:not QuerySet) with specific permission for this object
    :param permission: permission string
    '''

    anyperm = get_users_with_perms(self, attach_perms=True)
    result = []
    for user, perms in anyperm.iteritems():
        if permission in perms: result.append(user)
    return result


Q:

AWS CLI - No JSON object could be decoded

Im using the CLI for AWS to create a cluster and use the parameters from a json file. Here is the CLI command string Im using:
aws emr create-cluster --name "Big Matrix Re Run 1" --ami-version 3.1.0 --steps file://Segmentgroup1.json --release-label --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m3.xlarge InstanceGroupType=CORE,InstanceCount=2,InstanceType=m3.xlarge --auto-terminate

My json file (Segmentgroup1.json) is in the same folder in which Im running the AWS command string from, but I keep getting the following error:
No JSON object could be decoded

Based on what Ive found its not finding the json file. Any ideas?

A:

I ran into the same problem under my Mac, and I found the cause is the path for the json file instead of the content of the json file. To make it right:

You need to append file:// protocol as the prefix for your path
and use absolute path to your JSON file as parameter

Try something like this:
aws ecs register-task-definition --cli-input-json file://<absolute_path_to_json>/your_json.json

If you don't want to hard code the file path, you may use command like pwd to do this:
aws ecs register-task-definition --cli-input-json file://`pwd`/your_json.json


Q:

What is the code " length === +length" mean in JavaScript?

I just read the underscope source code, and cannot get the point from this code:
_.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    iterator = createCallback(iterator, context);
    var i, length = obj.length;
    if (length === +length) {   // why +length?
        for (i = 0; i < length; i++) {
            iterator(obj[i], i, obj);
        }
    } else {
        var keys = _.keys(obj);
        for (i = 0, length = keys.length; i < length; i++) {
            iterator(obj[keys[i]], keys[i], obj);
        }
    }
    return obj;
};

why length===+length ? I guess this used for force to convert if length is not a number?
Could somebody give me a hand?

A:

+length is a method to convert anything to a number.
If it's a number, the value doesn't change, and the comparison returns true.
If it's not a number, the assertion is false.
What is unary + used for in Javascript?


Q:

I never get RESULT_OK while taking a picture in my android app but the picture is there

i have a android application which uses a intent. here is the code:
private static final int CAPTURE_IMAGE= 1;
[...]
Uri imageUri = helper.createImageDestinationUri(null, filename);
[...]
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE);

and then i get the result here:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE) {
        if (requestCode == Activity.RESULT_OK) {

            Toast.makeText(this, "Image saved to:\n" +
                    data.getData(), Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
        }
    }
}

i have all the permissions wich are needed.
the strange thing:
at the end the picture is always on my SD card but i never get the RESULT_OK result.
what is wrong there?

A:

You're checking requestCode for RESULT_OK
if (requestCode == Activity.RESULT_OK)

when you should be checking resultCode
if (resultCode == Activity.RESULT_OK)


Q:

Staying in Germany more than 3 months

I'm from Iran but I live in Hungary now, I have resident permit for students for 1 year. I want to go to Germany and stay there more than 3 months, but I'm not sure about regulations. Is it possible? Will I get in trouble for rent a house or other things?

A:

Your Hungarian residence permit allows you to visit other Schengen states as if you had a C visa, i.e. 90 days out of every 180 days. To stay any longer, you would need a German D visa.
Renting a flat or house should be possible, but doing so will draw attention to the fact that you're living at least part of the time in Germany and not in Hungary. (As a resident in Germany, you have to register all your residences with the municipal offices and you have to designate one of them as your primary residence for tax purposes, etc.) This could bring extra scrutiny to the question if you're following the 90/180 rule.


Q:

Tracing disk and memory usage on startup

I'm running on Vista Home Premium and running into some startup performance issue recently. It takes around 4 - 6 minutes from the moment I turn on the laptop Power to the Desktop ready to be used. I only have 4 startup programs running (ATKMedia, ATKHotkey, Symantec and Synaptic Driver). For services, I've already turned off Super Prefetch and Indexing.
After booting, I can use the laptop no problem (i.e. it's fast), but this slow bootup is bothering me.
Is there any tools out there that can help me tell where the bottleneck is on startup?
Thank's in advance for your responses (if any).
NB : I remember that there's a parameter in the registry if turned on, will verbosely output what file is being processed when the Windows is booting up, but I forgot what :(.
My Spec:
P8600 dual core @2.4MHz,
4GB of RAM,
5400 RPM HDD

A:

Try this tool:
http://soluto.com/


Q:

ListPicker Data Showing in Windows Phone

I am writing Windows Phone 8.1 app, I have binded listpicker with data, those data come from web service result, now, my problem is that, there are plenty and too much records, and therefore my app gets crash. How do I show just " 1 to 50" records?
See my code below:
XDocumnet doc = XDocument.Parse(e.Result);

List<string> list = new List<string>();

list = (from query in doc.Descendants("row")
       select new string
       {
           Id = query.Element("Id").Value,
           Name = query.Element("Name").Value
        }).ToList();

listPicker1.ItemsSource = list;

A:

Use Take
listPicker1.ItemsSource = list.Take(50);


Q:

Is there a way to skip the header when using CsvBeanReader?

I have a project in which I am supposed to write the object into a CSV file. I am currently using ICsvBeanWriter for it but each time a new record is passed it writes the header as well. It creates issues when reading from the file.
Below are methods for reading and writing respectively:
    public static ArrayList<communication> readCSV() throws IOException {
    ArrayList<communication> fileText = new ArrayList<>();
    ICsvBeanReader beanReader = new CsvBeanReader(new FileReader("products.csv"), CsvPreference.STANDARD_PREFERENCE);
    String[] header = beanReader.getHeader(true);
    CellProcessor[] processors = new CellProcessor[]{
            new ParseDouble(), // Distance
            new ParseDouble(), // Efficiency
            new ParseDouble(),// fuel
            new ParseDouble(),// total
    };
    communication com;
        while ((com = beanReader.read(communication.class, header, processors)) != null) {
                fileText.addAll(Collections.singletonList(com));
        }
    return fileText;
}

public static void writeCSV(double tripDistance, double fuelEfficiency, double costOfFuel, double totalCost) throws Exception {

    // create a list of employee
    List<communication> EmployeeList = new ArrayList<>();
    EmployeeList.add(new communication(tripDistance, fuelEfficiency, costOfFuel, (Math.round(totalCost * 100.0) / 100.0)));

    ICsvBeanWriter beanWriter = new CsvBeanWriter(new FileWriter("products.csv",true),
            CsvPreference.STANDARD_PREFERENCE);

    String[] header = new String[]{"TripDistance", "FuelEfficiency", "FuelCost", "Total"};

    beanWriter.writeHeader(header);
    CellProcessor[] processors = new CellProcessor[]{
            new ParseDouble(), // Distance
            new ParseDouble(), // Efficiency
            new ParseDouble(),// fuel
            new ParseDouble(),// total

    };

    for (communication com : EmployeeList) {
        beanWriter.write(com, header, processors);
    }
    beanWriter.close();
}

I would like a way in which it either skips writing or reading the header or create method that deletes all the header rows(skipping the 1st row).
This is the error that appears:
org.supercsv.exception.SuperCsvCellProcessorException: 'TripDistance' could not be parsed as a Double
processor=org.supercsv.cellprocessor.ParseDouble

A:

These lines of code create a header:
String[] header = new String[]{"TripDistance", "FuelEfficiency", "FuelCost", "Total"};
beanWriter.writeHeader(header);

I guess you can just remove them from you code.


Q:

using the outlook object model, can i get the fields that i see in the outlook contact

i am able to look through the global address book using the outlook object model but is there anyway using the outlook object model from csharp i can get the following properties of a person:
City, State, Country/Region
Alias
Title
Phone
i can't seem to find these properties on the AddressEntry object.

EDIT: I started a bounty here.  I got this working using LDAP queries but they are such a pain.  I am shocked that outlook doesn't support this in its simple api.  i wanted to see if anyone else got it working or can explain / justify why outlook would not have support for this

A:

Using Microsoft.Office.Interop.Outlook
You need to use the ExchangeUser object and the GetExchangeUser method on the AddressEntry Object.
using System;
using Microsoft.Office.Interop.Outlook;
static class Program
{
    static void Main(string[] args)
    {
        ExchangeUser oExUser;
        Application app = new Microsoft.Office.Interop.Outlook.Application();
        foreach (AddressList addressList in app.Session.AddressLists)
        {
            if (addressList.Name == "Global Address List")
            {
                foreach (AddressEntry item in addressList.AddressEntries)
                {
                    Console.WriteLine(item.Address);
                    oExUser = item.GetExchangeUser();
                    if (oExUser != null)
                    {
                        Console.WriteLine(oExUser.FirstName);
                        Console.WriteLine(oExUser.LastName);
                        Console.WriteLine(oExUser.StreetAddress);
                        Console.WriteLine(oExUser.CompanyName);
                        Console.WriteLine(oExUser.Department);
                        Console.WriteLine(oExUser.OfficeLocation);
                        Console.WriteLine(oExUser.JobTitle);
                    }
                    Console.WriteLine();
                }
            }
        }
        Console.Read();
    }
}


Q:

Finding the sums of all the solution for values of $z$ where $f(3z)=7$ in $f(\frac{x}{3})=x^2+x+1$

Problem
The problem asks us to find the values of all solution of $z$ in which it satisfies $f(3z)=7$ in the equation $f(3z)=7$ in $f(\frac{x}{3})=x^2+x+1$
My steps
step 1
I substituted $\frac{3}{x}$ into the equation to get $f(\frac{1}{x})=\frac{3}{x}^2+\frac{3}{x}+1$
but i am sure that this step wasn't correct so i went onto step 1.1:
So then i substituted 0 into the equation to get f(0)=1
then that is where i had gotten stuck
then because i could not go anywhere i went on to substituting x as 3 as shown in step 1.2
through that i had gotten by substituting x as 3:
$f(1)=13$
And this is where i really got stuck

A:

Notice that,$$f(3z) = (9z)^2+9z+1.$$
Since $f(3z) = 7$,$$f(3z) = (9z)^2+9z+1 = 7 $$$$\Rightarrow z = -\frac{1}{3} \text{ or } \frac{2}{9}$$


Q:

replace all  tag to some character in php

I want to replace  to [] in php,
as example if I have :
This is sample test to say you   help and  you can redirect me to answer
I want it replaced to
This is sample test to say you  [help] and  you can redirect me to [answer],
How can I achieve this job in php with regex?

A:

Use a Document Object Model and avoid regular expressions to parse HTML at all costs.
echo "[".$dom->getElementsByTagName('a')->item(0)->nodeValue."]";

Demo
The code.. (for the edited question)
<?php
$html='This is sample test to say you   help and  you can redirect me to answer';
$dom = new DOMDocument;
$dom->loadHTML($html);
$srch=array();$rep=array();
foreach($dom->getElementsByTagName('a') as $atag)
{
   $srch[]=trim($atag->nodeValue);
   $rep[]="[".trim($atag->nodeValue)."]";
}

echo str_replace($srch,$rep,strip_tags($html));

OUTPUT :
This is sample test to say you   [help] and  you can redirect me to [answer]


Q:

Sum of geometric points on large interval

I have a large interval [0 ... 2^32 - 1]. There are approximately 2^20 points with some coordinate and value, for example:
1; 435
5; 5454
345345; 5485;
9999999; 43435
4294967294; 35353

Also I have set of intervals. Number of intervals is less than 2^22. For example,
1 3; // sum is 435
1 3535; // sum is 435 + 5454
99994 4294967294; // sum is 5485 + 43435 + 35353

For each interval I have to calculate sum modulo 2^32.
There is naive algorithm. I can iterate over all points for each interval. It is require O(number of queries * number of points). It is too slow.
Is there more quicker algorithm?

A:

Sort the points. Iterate over the points and compute the running sum of the values up to each point. Store the sums in an array. When you want to compute the sum for an interval, find the lower and upper limit by binary search, then look up the lower sum and upper sum. The difference of these sums is the sum for the interval.
For the example you gave, the points are indexed as follows:
{0: 1, 1: 5, 2: 345345, 3: 9999999, 4: 4294967294}

The sums are the following:
{0: 0, 1: 435, 2: 5889, 3: 11374, 4: 54809, 5: 90162}

To calculate the sum in the interval [a..b], find the indices p(a) and p(b) of the smallest points that are no bigger than a and b, and return sums[p(b)+1] - sums[p(a)].
For 1 and 3, we find the indices 0 and 0. The result is sums[1] - sums[0].
For 1 and 3535, we find the indices 0 and 1. The result is sums[2] - sums[0].
For 99994 and 4294967294, we find the indices 2 and 4. The result is sums[5] - sums[2].
It takes O(number of points) to prepare the array of sums. Each query takes O(log(number of points)).


Q:

How to update record after some time based on certain criteria?

Suppose I have a record that is created with status X, and I need to check it 60 days later if it still has the same status. If it is X, then change it to Y.
I think this is doable with time-based workflow rules, but I don't know whether the workflow will be fired if the status is changed before the 60 days or not. If the status is changed to Y before the 60 days, the workflow can not fire.
I've been searching for a while now, and I couldn't find anything that clears this doubt. I would like not to use Apex for this, if possible, but I know that I can create a class that runs everyday and checks this.

A:

See the Time-Based Workflow FAQ:

Will the pending actions in the queue ALWAYS trigger?
No. Time-dependent actions remain in the Workflow Queue until processed or the rule criteria for the Workflow Rule are evaluated as "false." If a record no longer matches the rule criteria when the rule is evaluated, Salesforce removes the time-dependent actions queued for that record.

Example: An Opportunity Workflow Rule may specify:

A criteria set to "Opportunity: Status not equals to Closed Won, Closed Lost."
An associated time-dependent action with a time trigger set to 7 days before the Opportunity close date. If a record matching the criteria is created on July 1st and the Close Date is set to July 30th, the time-dependent action is scheduled for July 23rd. However, if the Opportunity is set to "Closed Won" or "Closed Lost" before July 23rd, the time-dependent action is automatically removed from the queue.


Q:

Why was Vader surprised that Obi-Wan's body disappeared?

OK, I understand that Obi-Wan turned into a force ghost when Vader struck him down, but why was Vader surprised by the lack of a body? It's not the transition into a force ghost but Vader's reaction that bugs me.

A:

At the end of Revenge of the Sith (2005), Yoda talks to Obi-Wan Kenobi about meeting an old friend, his old master, Qui-Gon Jinn, who we know became a force ghost.

02:04:50 - Yoda: One who has returned from the netherworld of the Force.
02:04:53 - Yoda: Your old master.
02:04:56 - Obi-Wan: Qui-Gon?
02:05:00 - Yoda: How to commune with him I will teach you.

This is the first time, chronologically in the films, that the audience and any of the relevant main characters are introduced to the concept of force ghosts. Indeed Obi-Wan is surprised to hear about Qui-Gon in this scene.
Presumably, Anakin had also never heard of this concept of force ghosts before, or even if he did, at the very least could not fathom that Obi Wan could achieve such a feat. We can see from his reaction that he is unable to comprehend what just happened, he probably assumes that he defeated him, confused about the phenomena of the body disappearing, and later concludes that he died.
The following dialogue is from their lightsaber duel scene in Star Wars (1977).

01:27:08 - Ben: You can't win, Darth. If you strike me down...
01:27:12 - Ben: I shall become more powerful than you can possibly imagine.
01:27:22 - Vader: You should not have come back.

From Anakin's line (and his physical reaction, poking around the robes with his feet) there is evidence to suggest that he was, at least at the time, oblivious to the possibility of Obi-Wan becoming one with the force (turning into a force ghost).

A:

He didn’t understand what had happened
The knowledge of how to become a Force ghost was known to very few. Anakin certainly did not know it back during the Clone Wars era:

ANAKIN: Everything that we know about the Force tells us that an individual
  retaining their identity after death is impossible.
YODA: Everything that we know, yes.
  But what about what we know not? Hmm?
The Clone Wars: “Voices”

Qui-Gon learned it from the Force Priestesses, who had preserved this ancient art. Yoda learned it from Qui-Gon, with some help from the priestesses.

YODA: Now does my training begin?
PRIESTESS: The one you know as Qui-Gon Jinn will commune with you and
  guide your training. Like us, you shall learn to maintain your
  consciousness after death.
The Clone Wars : “Sacrifice”

If  even Yoda, Grand Master of the Jedi Order, was unaware of the possibility of becoming a Force ghost, surely Anakin, later Vader, also was. One might imagine that Palpatine might have told him, but Palpatine almost certainly was also unaware. Palpatine sought to cheat death, in the tradition of Darth Plagueis, but not by becoming a Force ghost: he wanted to make himself physically immortal and rule the temporal world. He wanted to control the midi-chlorians of life, not survive as a disembodied spirit and ultimately merge with the Cosmic Force. As Yoda says, after acquiring the knowledge of the Force Priestesses:

YODA: Yet, open to us, a path remains that unknown to the Sith is.
  Through this path, victory we may yet find. Not victory in the Clone
  Wars but victory for all time.
The Clone Wars: “Sacrifice”

Vader’s behavior and words bear this out. He appears to be entirely unaware that Obi-Wan exists as a Force ghost, even as of The Empire Strikes Back. He believes that Obi-Wan can no longer help Luke, for example:

“He could destroy us,” the Emperor croaks.
For a moment, Vader does not speak. When he does, his rich voice is
  slow and deliberate. “He is just a boy. Obi-Wan can no longer help
  him.”
The Empire Strikes Back: So You Want to Be a Jedi?

He also claims that Obi-Wan was "destroyed" and that there is no life after death:

“Don’t let yourself be destroyed, as Obi-Wan did.”
Vader’s black helm shimmers in the dim light of the reactor core. His
  cape sways softly, like silk, with each step he takes. “Do not believe
  the Jedi lies. There is no life after death. There is only death.”
  Behind his mask, he is smiling. He must be.
The Empire Strikes Back: So You Want to Be a Jedi?

In particular, as Sith, both Vader and Palpatine believed that the Jedi belief in life after death (even as part of the Force) was mistaken. They didn’t even believe that one could become one with the Force, let alone retain one’s identity.

SITH: We are the Sith.
YODA: Afraid of you I am not.
SITH: We shall
  see. There is no life after death. Only nothingness awaits you, Jedi.
  Your fear feeds
  our hunger for power.
  They will know you are here.
  We will tell them.
  You will die
  and be nothing.
The Clone Wars: “Sacrifice”

Now, what did he think had happened? It’s not clear. Probably he could sense through the Force that Obi-Wan was no longer there, so he did not believe that he had, for example, turned invisible. He was surely too arrogant to believe that Obi-Wan had, as he suggested, become “more powerful than [he] could possibly imagine” (nor would he have understood what that meant, even if he credited it). Perhaps he believed that Obi-Wan had used some trick to destroy himself, committing suicide rather than let Darth Vader kill him.

One might recall that Qui-Gon Jinn appeared to Anakin in the Mortis arc of The Clone Wars, and wonder why this hadn’t convinced him of the possibility of survival as a Force spirit. In that same arc, though, the Son, a powerful entity of the Dark Side, had appeared to him in the form of his deceased mother, Shmi Skywalker! He (and even Ahsoka and Obi-Wan) would have had ample reason to suspect that the vision of Qui-Gon was simply the Son, Daughter, or Father appearing in a different form for their own goals. Even without this sort of thing going on, many Jedi suspected that Qui-Gon was a trick of the Sith when Yoda heard him.


Q:

LinkedList (2.0): removing items iteratively

I need to iterate through a LinkedList<T> (in .NET 2.0) and remove all the items according to a given criteria.
It was easy way under Java, since I could do the following:
Iterator<E> i = list.iterator();
while (i.hasNext()) {
    E e = i.next();
    if (e == x) {
        // Found, so move it to the front,
        i.remove();
        list.addFirst(x);
        // Return it
        return x;
    }
}

Unfortunately, in the .NET behavior of IEnumerator<T> (the equivalent of Iterator<E>) there's no remove method to remove the current element from the collection.
Also, in the LinkedList<T> there's no way to access an element at a given index, to accomplish the task by iterating back from the last to the first.
Have you got any idea on how to do it? Thank you very much!

A:

This will remove all nodes that match a criteria, in one loop through the linked list.
LinkedListNode<E> node = list.First;

while (node != null)
{
    var next = node.Next;
    if (node.Value == x) {
        list.Remove(e);
    }
    node = next;
}

I believe that's what you're attempting... You also added back in the node at the beginning of the list (so your java code didn't remove all of the nodes, but rather moved the first matching to the beginning of the list).  That would be easy to do with this approach, as well.


Q:

Grouping lists into groups of X items per group

I'm having a problem knowing the best way to make a method to group a list of items into groups of (for example) no more than 3 items. I've created the method below, but without doing a ToList on the group before I return it, I have a problem with it if the list is enumerated multiple times.
The first time it's enumerated is correct, but any additional enumeration is thrown off because the two variables (i and groupKey) appear to be remembered between the iterations.
So the questions are:

Is there a better way to do what I'm trying to achieve?
Is simply ToListing the resulting group before it leaves this method
really such a bad idea?
public static IEnumerable<IGrouping<int, TSource>> GroupBy<TSource>
              (this IEnumerable<TSource> source, int itemsPerGroup)
{
    const int initial = 1;
    int i = initial;
    int groupKey = 0;

    var groups = source.GroupBy(x =>
    {
        if (i == initial)
        {
            groupKey = 0;
        }

        if (i > initial)
        {
            //Increase the group key if we've counted past the items per group
            if (itemsPerGroup == initial || i % itemsPerGroup == 1)
            {
                groupKey++;
            }
        }

        i++;

        return groupKey;
    });

    return groups;
}

A:

Here's one way to do this using LINQ...
public static IEnumerable<IGrouping<int, TSource>> GroupBy<TSource>
    (this IEnumerable<TSource> source, int itemsPerGroup)
{
    return source.Zip(Enumerable.Range(0, source.Count()),
                      (s, r) => new { Group = r / itemsPerGroup, Item = s })
                 .GroupBy(i => i.Group, g => g.Item)
                 .ToList();
}

Live Demo

A:

I think you are looking for something like this:
return source.Select((x, idx) => new { x, idx })
      .GroupBy(x => x.idx / itemsPerGroup)
      .Select(g => g.Select(a => a.x));

You need to change your return type as IEnumerable<IEnumerable<TSource>>

A:

.net Fiddle
Essentially you have an IEnumerable, and you want to group it into an IEnumerable of IGroupables which each contain the key as an index and the group as the values. Your version does seem to accomplish on the first pass, but I think that you can definitely stream line a little bit.
Using skip and take is the most desirable way to accomplish in my opinion, but the custom key for grouping is where there is an issue. There is a way around this which is to create your own class as a grouping template (seen in this answer: https://stackoverflow.com/a/5073144/1026459).
The end result is this:
public static class GroupExtension
{
    public static IEnumerable<IGrouping<int, T>> GroupAt<T>(this IEnumerable<T> source, int itemsPerGroup)
    {
        for(int i = 0; i < (int)Math.Ceiling( (double)source.Count() / itemsPerGroup ); i++)
        {
            var currentGroup = new Grouping<int,T>{ Key = i };
            currentGroup.AddRange(source.Skip(itemsPerGroup*i).Take(itemsPerGroup));
            yield return currentGroup;
        }
    }
    private class Grouping<TKey, TElement> : List<TElement>, IGrouping<TKey, TElement>
    {
        public TKey Key { get; set; }
    }
}

And here is the demo in the fiddle which consumes it on a simple string
public class Program
{
    public void Main(){
        foreach(var p in getLine().Select(s => s).GroupAt(3))
            Console.WriteLine(p.Aggregate("",(s,val) => s += val));
    }
    public string getLine(){ return "Hello World, how are you doing, this just some text to show how the grouping works"; }
}

edit
Alternatively as just an IEnumerable of IEnumerable
public static IEnumerable<IEnumerable<T>> GroupAt<T>(this IEnumerable<T> source, int itemsPerGroup)
{
    for(int i = 0; i < (int)Math.Ceiling( (double)source.Count() / itemsPerGroup ); i++)
        yield return source.Skip(itemsPerGroup*i).Take(itemsPerGroup);
}


Q:

Erro ao gerar um APK assinado

É assim, estou desenvolvendo um app onde quero usar o Google Maps, mas quando tento gerar o APK assinado recebo 2 (dois) erros:

Error:The number of method references in a .dex file cannot exceed 64K.
  Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

e

Error:Execution failed for task ':app:transformClassesWithDexForRelease'. > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_101\bin\java.exe'' finished with non-zero exit value 2
  :app:transformClassesWithDexForRelease FAILED

O que pode ser? E qual é a possível solução?

A:

Vai no seu arquivo build.gradle (dentro da pasta /app)
e no seu defaultConfig, adicione essa linha:
multiDexEnabled true

Vai ficar assim:
defaultConfig {
        applicationId "br.com.package.example"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true
    }


Q:

What is meant by “they silence him” when the prayer leader says “We give thanks, we give thanks”

The Mishna in Brochos 5 (3) says

האומר על קן צפור יגיעו רחמיך, ועל טוב יזכר שמך, מודים מודים, משתקין
  אותו.
The one who says, “On a bird’s nest may Your mercy be extended,” [or]
  “For good may Your name be blessed” or “We give thanks, we give
  thanks,” they silence him.

What exactly is meant by “they silence him”?
I could imagine the following possibilities:
They shout out “Shh Shh” meaning - stop saying that and continue properly or
They tell him to stop and put another person in his place.
Related Rashi on Berachos 33b "al kan tzipor yagiu rachamecha"

A:

Two incidents described in the Talmud there might give us a clue:

ההוא דנחית קמיה דרבה ואמר אתה חסת על קן צפור אתה חוס ורחם עלינו אמר רבה כמה ידע האי צורבא מרבנן לרצויי למריה א"ל אביי והא משתקין אותו תנן ורבה נמי לחדודי לאביי הוא דבעי ההוא דנחית קמיה דר' חנינא אמר האל הגדול הגבור והנורא והאדיר והעזוז והיראוי החזק והאמיץ והודאי והנכבד המתין לו עד דסיים כי סיים א"ל סיימתינהו לכולהו שבחי דמרך למה לי כולי האי אנן הני תלת דאמרינן אי לאו דאמרינהו משה רבינו באורייתא ואתו אנשי כנסת הגדולה ותקנינהו בתפלה לא הוינן יכולין למימר להו ואת אמרת כולי האי ואזלת משל למלך בשר ודם שהיו לו אלף אלפים דינרי זהב והיו מקלסין אותו בשל כסף והלא גנאי הוא לו
A certain [reader] went down [before the Ark] in the presence of Rabbah and said, 'Thou hast shown mercy to the bird's nest, show Thou pity and mercy to us'. Said Rabbah: How well this student knows how to placate his Master! Said Abaye to him: But we have learnt, HE IS SILENCED? — Rabbah too acted thus only to test  Abaye.
A certain [reader] went down in the presence of R. Hanina and said, O God, the great, mighty, terrible, majestic, powerful, awful, strong, fearless, sure and honoured. He waited till he had finished, and when he had finished he said to him, Have you concluded all the praise of your Master? Why do we want all this? Even with these three that we do say,  had not Moses our Master mentioned them in the Law  and had not the Men of the Great Synagogue come and inserted them in the Tefillah, we should not have been able to mention them, and you say all these and still go on! It is as if an earthly king had a million denarii of gold, and someone praised him as possessing silver ones. Would it not be an insult to him?
(Soncino translation)

In the first incident someone violated one of the rules mentioned in the Mishnah for which we silence people. Yet it does not say that Rabbah, or Abbaye, interrupted the person or threw him down. It appear that they merely raised the issue afterwards.
In the second incident we are introduced to another problematic form of prayer – using too many adjectives to describe God's greatness. In this case, too, we do not find that R. Chanina interrupted the person. In fact the Talmud explicitly states He waited till he had finished.
In his commentary there, R. Samuel Eidels point this out and suggests that that is in fact what the Mishnah meant by "we silence him":

הא דלא היו משתקין אותו בתפלתו לא רבה ולא אביי י"ל דלאחר תפלתו קאמר דמשתקין אותו שלא יעשה כן פעם אחרת וכן לקמן גבי המרבה בשבחות קאמר המתין לו עד דסיים כו
As for this that neither Rabbah nor Abbaye silenced him during his prayer, one could say that [the Mishnah] meant that after his prayer we silence him so that he won't do it again. And similarly, later on by the one who was excessive with praises it says that he waited for him until he finished, etc.

On the other hand, R. Ezekiel Landau in his commentary there interprets "silence him" literally:

לשון הרמב"ם בפירוש המשנה ענין מה שאמרו על קן צפור וכו' שיאמר כמו שחמלת על קן צפור וכו' כן רחם עלינו וכן פירש הברטנורא וכבר ראיתי מי שתמה הלא סיום דבר זה לא נזכר במשנה אבל טעות הוא בידם שהתנא קמ"ל שאין מניחין אותו לסיים דבריו ומשתקין אותו תיכף בתחלת דבריו
The wording of the Rambam in the Commentary to the Mishnah is the matter of that which they said "on the bird's nest etc." that someone says "just like you had mercy on the bird's nest etc. so too have mercy on us. And the Bartenura explains likewise. And I have already seen people who wondered "this ending is not mentioned in the Mishnah!" But it is a mistake in their hands, because the tanna is teaching us that we don't leave him to finish his words; we silence him immediately at the beginning of his words.

A Gaonic interpretation (Otzar Hagaonim, Berachot, HaPeirushim p. 46) refers to it as removing the person with scolding:

עד דאמ' כזה מסלקין אותו בנזיפה

R. Moses Shick in a responsum (O.C. 31) cites the questioner as saying:

וגם מה שאמרו בברכות [ל"ג ע"ב] דשמע שמע כגון דאמר מילתא מילתא ותני לה מגונה הוי ואף דאין משתקין אותו בשעת מעשה מכל מקום צריך למחות בו שלא יעשה כן בפעם אחרת כיון דהוי מגונה
And also that which they said in Berachot (33b) that "shema shema" in the form of saying it word by word, they taught about it that it is deplorable, and even though we don't silence him at the moment we nevertheless must protest it so that he doesn't do it again, since it is deplorable.

And then acknowledges that the questioner is correct:

ונכונים כל דבריו
And all his words are correct.

If for things which the Talmud does not rule to "silence him" we don't silence him in the moment but instead rebuke him later, the implication is that when the Talmud does rule to "silence him" we silence him on the spot.


Q:

jQuery Watermark and using .Val()

I have a problem in that I am using a simple watermark plugin such that it works
jQuery('#selector').Watermark('Watermark text here ...');

The problem is - when I try and use something like
if (jQuery('#selector').val() != "") { //do stuff }

The statement is True because of the watermark. Is there anyway I can somehow "ignore" this watermark value for my If statement ?
Thanks

A:

if (jQuery('#selector').val() != "" && jQuery('#selector').val() != "'Watermark text here ...'") { //do stuff }

This only assumes that the watermark text is static across examples. If not then you may need a collection of watermark texts?


Q:

Meaning of a passage in "Night on Highway 128" by Cary Mullis

From Night on Highway 128 by Cary Mullis:

I was driving up a long and winding road between Cloverdale and Booneville in Mendocino County, heading for my weekend cabin. My girlfriend was asleep and I was functionally sober (or the road would have proven my undoing) but it was late at night and I was feeling weird. Strange things had happened to me on 128 before. Furtive old men in… what was that? A grey robe. In that field. I didn’t see anything. Or lost time: the distinct feeling, shared by my former wife, pulling into Booneville and recalling that we had just left Cloverdale, now thirty five miles to the southeast.

I struggle to understand the meaning of this passage. Does it mean the author had prevously seen "a furtive old man (or men)" wearing grey robe/robes when riding along this road, but on this account he didn't see anything of such sort?

A:

This seems like a writing style question. The entire piece is a description of the author's thought process regarding a scientific problem. The paragraph you cite begins a narrative in which he ascribes a mystic quality to Highway 128. My interpretation is that, as the author begins slipping into deep thought late at night during his drive, he has a minor hallucination in that specific moment, while he is driving, that snaps him out of his thought for a moment.
I'm not sure what the context of your question is, but-- in terms of style-- the car ride adds an element of narrative interest to the story, but provides no significant meaning to the actual article itself. In that sense, if there are other interpretations, that wouldn't change the article's meaning in any way.


Q:

WebStorm lags when I type

I am running the 64 bit version of WebStorm 2016.1.1, and it lags every few characters that I type. I've tried disabling plugins and increasing the max allocated memory to 8GB, but the performance hasn't improved.
It doesn't lag for a fresh new project so it must be my project size.  However, I have not typed up that much code (< 5k lines), so I've concluded it must be all my node_modules.
I've marked my build directory and node_modules directory as excluded, but for some reason only the build directory appears in red (which is the color of an excluded directory). The node_modules appears in my list of excluded directories when I check my settings, but it still appears yellow in the project list:

The only other thing I can think of that seems suspicious is that it says "library root" next to node_modules, but I haven't been able to find much info on that.
I am completely out of ideas.  What on earth could the problem be that's causing the editor to lag so bad?

A:

node_modules directory is set up as a JavaScript Library. Libraries can't be excluded from indexing, thus excluding node_modules does nothing.
Please remove it from libraries (Preferences (Settings)/Languages & Frameworks/JavaScript/Libraries, select '<project name> node_modules' there, press Remove, OK). Then make sure that node_modules is shown as excluded.
Further investigations revealed problems updating VCS checklists. It is fixed in WebStorm 2016.2 EAP


Q:

deleteCell doesn't work with directly selected trs

I'm trying to access a tr directly and dynamically.
the tr is selected or so I think , but when I'm applying the deleteCell method it saysthat the object doesn't have such method!
a portion of the code :
set: function(f, res){
        var row = $('tr#moRow'+f), arr = res.split('|'), cell,
        links = new Array(
            'forums.php?f='+f+'&option=mo',
            'forums.php?f='+f+'&option=ho',
            'forums.php?f='+f+'&option=rmo',
            'forums.php?f='+f+'&option=rho',
            'pm.php?mail=new&f=-'+f
        );
        if(row){
        alert(row);// gives [object object]
            row.deleteCell(1);
            for(var x = 0; x < arr.length; x++){
                cell = row.insertCell(x + 1);
                cell.className = (arr[x] > 0 ? 'asFirstB' : 'asNormalB')+' asCenter';
                cell.innerHTML = (arr[x] > 0) ? ""+arr[x]+"" : "0";

any ideas ?

A:

If you want to use native JS functions on an element, you need to address the DOM element instead of the jQuery one.
row[0].deleteCell(1);


Q:

Suggestion about Real time update word cloud that read from MYSQL database

I'm hoping to make a dynamic word cloud that updates in (as close to) real time as possible, pulling the words and sentences from the MYSQL database. The MYSQL is then queried every few seconds to update the word cloud.
I found this library from google and this is working good for a static word cloud. But not in dynamic word cloud https://github.com/timdream/wordcloud2.js
When I update the words list array, say, I add one word in into the list array, whole word cloud will refresh, but not just add the newly added word to the word cloud. So, is there a way to implement a dynamic word cloud?
Thanks for the great help.

A:

There's always a way, but you're missing a few building blocks.
You've got two places where your cloud exists:
1) Server side (database + php)
2) Client side (the browser)
The PHP (presumably) creates a flat page containing information the JS at the client side uses to render the cloud. Your browser (the JS) does the real work.
To retrieve updates, the JS needs to pull fresh information from the server every certain amount of time. The easiest way to do that is reload the page. Another way to do that is to retrieve a fresh array using AJAX and re-rendering the cloud. You'll need to dive deeper into the JS for that.
What you're probably looking for is to periodically retrieve a fresh array using AJAX and not re-render the cloud from scratch, but to loop through every word in the array and every word in previous array and remove any words that disappeared, add any new words, and update the HTML (size) of any words if their value has changed.
Looking at the JS you're using it doesn't seem to include that functionality. Which requires you to investigate and comprehend the workings of the JS script.
So your options are:
a) Find a different word cloud script that already has this functionality
b) Write your own JS script that updates the cloud. (And maybe push the changes to the original github repo if they'll have it?)


Q:

Would an expression tree work here?

I have the below method that I currently use to get the DB length of certain string fields (each property has an attribute called MetaDataFieldAttribute). It seems to work nicely however it's very 'stringly' typed with the property name.
     public static void Main(string[] args)
        {
            ...
            obj.PropertyName = str.TrimIfRequired(obj, "PropertyName");
        }

        public static string TrimIfRequired(this string str, object obj, string property)
        {
            var pi = obj.GetType().GetProperty(property);
            var attribute = pi.GetCustomAttributes<MetaDataFieldAttribute>().FirstOrDefault();
            if (attribute == null) return str;

            int length = attribute.Precision;
            return str.Length > length ? str.Substring(0, length) : str;
        }

I have a fairly basic understanding of expression trees, and my initial thought is that I could make the object/parameter of the method strongly typed rather than just passing through the string. Is this possible?

A:

Yeah, you can use Expressions here just to get strong typing for property names, so instead of writing property name as string, you can use expression with property access, and then code will get MemberInfo item for specific property from expression and will get attribute from here. So if you change propertyName in the future, this part won't compile as it will be strong typed.
here is working sample on .NetFiddle - https://dotnetfiddle.net/qYOfhE
And here is the code itself:
using System;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
    public static void Main(string[] args)
    {
        var str = "TestTestTest";

        var propertyName = str.TrimIfRequired<Customer>((c) => c.FirstName);
        var propertyNameValue = str.TrimIfRequired<Customer>((c) => c.Age);
        Console.WriteLine(propertyName);
        Console.WriteLine(propertyNameValue);
    }
}

public static class Extensions
{
    public static string TrimIfRequired<T>(this string str, Expression<Func<T, object>> expr)
    {
        var me = expr.Body as MemberExpression;
        if (me == null && expr.Body is UnaryExpression)
        {
            me = ((UnaryExpression) expr.Body).Operand as MemberExpression;
        }

        if (me == null)
        {
            throw new ArgumentException("Invalid expression. It should be MemberExpression");
        }

        var pi = me.Member;
        var attribute = pi.GetCustomAttributes(typeof(MetaDataFieldAttribute), false).FirstOrDefault() as MetaDataFieldAttribute;
        if (attribute == null) return str;

        int length = attribute.Precision;
        return str.Length > length ? str.Substring(0, length) : str;
    }
}

public class Customer
{
    [MetaDataField(Precision = 6)]
    public string FirstName { get; set; }

    [MetaDataField(Precision = 2)]
    public int Age { get; set; }
}

public class MetaDataFieldAttribute : Attribute
{
    public int Precision { get; set; }
}


Q:

Maybe a typo mistake

I was reading news and found a mistake. I have just wanted to confirm that, as it does not sound natural to my ears. I feel that the article(a) or maybe this word(many) are not sounding naturally here. The writer should have used one of them instead of both, please check and let me know your feedback.
I read this in a newspaper:

At a time when she is expected to win many a trophy for her
  performance in queen (a Bollywood movie).

As per my opinion, these both options could be possible:

At a time when she is expected to win many trophies for her
  performance in queen(a Bollywood movie).
At a time when she is expected to win a trophy for her performance in
  queen(a Bollywood movie).

Both below sentences are sounding fine to me, but first one does not sound natural to me.

A:

Nice question +1.
The word many here is used for the large indefinite number. And at times, this sort of phrase is used to describe that something which is after many is expected in large quantity. I'm familiar with this structure.

...expected to win many a trophy for her performance...

Simply means she's expected to win many trophies. It's the other way to tell that.
I found a reference here...

many a (adj) - each of a large indefinite number; "many a man"; "many another day will come"

Another interesting thing is on Cambridge. It defines many a time is equal to many times. Compare many a trophy = many trophies this way.


Q:

How to remotely deploy actor with dynamic name in Akka.NET

When I look at the samples of the Akka.NET actor remote deployment, it is done via actor system configuration like this:
actor {
    provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
    deployment {
        /MyActor {
            remote = ""akka.tcp://MyActors@127.0.0.1:8091""
        }
    }
}

The string "MyActor" above is the actual actor name. It is not clear to me how would I deploy an actor that would have dynamic name (e.g. "MyActor:{UID}") or deploy unknown number of actors remotely? Is there a way to dynamically configure deployment options via code? It seems a bit tedious and very limited to specify all the remotely deployable actor names in the configuration.

A:

You can set deployment options using actor's Props like: Props.Create(() => new MyActor).WithDeploy(new Deploy(new RemoteScope("akka.tcp://remote-system-name@ip:port/"))).


Q:

git push -f 以外で git のリモートリポジトリのコミットログを編集する方法

例えばリモートリポジトリにpushした後にうっかり git commit --amend や rebase してcommitのhashが変えてしまった場合は仕方がなくpullするか、git push -f するなどあまりgitの使い方的に良くない状態にしてしまう事をする羽目になってしまうと思います。
このようなケースの時の対処法で例えばgit commit --amendやrebaseを取り消すなどリポジトリを上記のような状態にせずに解決する方法はありますか？

A:

git commit --amend や rebase を取り消してしまって良いのであれば、例えば git reset --hard origin/master のように resetコマンド を使って現在のブランチをリモートレポジトリのmasterに戻してしまえば commit --amend, rebase はなかったことになります。
もし手元で行っているまだコミットしていない変更を失いたくないということであれば、--soft あるいは --mixed でワーキングツリーを維持しつつ HEAD を origin/master に戻してからコミットすればよいかと思います。もし、push の後に行った rebase (commit --amend) よりも前のコミットを失いたくないということであれば、 git reset --hard ORIG_HEAD で rebase の直前のコミットの状態に戻ることもできます。


Q:

Is WAP still a relevant protocol stack?

Please overlook any oversight. I couldn't find much recent material on the internet, and just had a networks course this semester.
The wiki page mentions that as of 2013, it's usage has largely been absent.
But I found a stack exchange thread dated 2011 that the WAP 2.0 is still in use.
As of 2015, with the current crop of smartphones and high-speed 3g/4g services provided by the operators, is WAP still supported or used? And what version(s) exactly?

A:

WAP is still used. I don't know which version it is. It's usage is really small. In our network it generates 200-300 times smaller traffic compared to the other mobile Internet traffic (http, ftp and other).
I don't know why it is still used. Maybe some companies have old devices which are using this protocol - like taxi, tracking, cash terminals, or other similar devices (this is just an example - I'm not sure if these devices actually use WAP).


Q:

Login App with IdentityServer4

I have to develop a SSO system and I have to do it using IdentityServer4. I have gone through the documentation and examples but I have some doubts. To be honest I don't quite get it, but I am really new in Oauth2 and OpenId Connect.
We will have a bunch of clients (web apps), each of one of those will have their own Web  APi. And we have to have a centraliced Login App for all of those.  I think the example with the javascript client is the closes to the thing we want to achieve. Also, a user might have permission to access one client (app), but not another, so the IdentityServer must provide information about wich clients (apps), that particularly user can access.
So, These are the things I don Understand:
1.- In the documentation I can read there are two tokens, an Identity Token and Access token. But in the examples all I see are the access tokens. It seems to me that the access token is the one with all de info needed. am I wrong?
2.- Also, I have read about de Grant Types and I'am not quite sure wich one we must use. At first I thought to use the ResourceOwner password, because it requires the client, the secret, a user and a password, wich I assumed it could be the end user. I found this example http://sunilrav.com/post/How-to-Customize-Authentication-in-Identity-Server-4 were one could customise the class that validate the user and password. I thought that this could be the way to go but the documentation statesa about this grant type  "...This is so called “non-interactive” authentication and is generally not recommended.". The javascript client example uses the implicit Grat type, wich the documentation states is for browser-based applications (our client apps will all be browser based using react).
3.- can my Login app be a Javascript (react) app? The example Quickstart is made in MVC.NET. This login app connects directly to de IS4 server without asking for a access token? (In the example the app is embebed in the IS4).
4.- Can I protect with IS4 a WEB API which is developed in .net framework (4.6.2) and not in .Net Core? I havent Found Any examples.
the documentatios I followed is the offcial. The examples (quickstart) are also there. (I can't post more than two links).
thank you very much for reading and for your help.

A:

Identity Token and Access token
Identity token is the one that contains the identity of the user, that will tell the client app that what user it is. After successful login, user will be redirected to the client app with these tokens. Response will also have claims, such as permission scopes, name , email you can add custom claims as well.
Access token is used to access your protected web api resource. You have to send the access token with each request to access the api.
Grant Types
Grant types is basically how you want your client app to interact with the auth server. https://identityserver4.readthedocs.io/en/release/topics/grant_types.html
can my Login app be a Javascript (react) app? Your client app can be a javascript app but your auth server that is the identity server which will have the login/signup pages(and other login jazz) and account controllers should be you MVC app. As, everything is already done using MVC and Entity framework, why you want to re do everything.
Can I protect with IS4 a WEB API I am not sure about this one, but I dont see why you would not be able to do it.
This is a good answer for basic IdSrv flow!
UPDATE In my understanding, the answer to which Grant Type to use it depends on your client application requirement. If you want to use a Javascript client you can use Implicit Flow, but you won't be able to use refresh tokens and your access token is not 100% secured with the browser as client can access it.
If you want to open your web api to public then you can use client credentials flow. If you want to be more secure you should use Hybrid flow or HybridClient credential flow. ( again depends on the requirements ). with this you will be able to use refresh tokens and in this way your access token would be more secure.


Q:

Check id from two tables, if there is no match delete it

i need to check on TimeEntries from two different databases.
one is where we log our hours(LogDB), the other is for managing those hours(ManagerDB).
so if the timeEntry is removed from where we log our hours, it needs to be removed from our manager as well.
but how do i check this ?
here i get my data :
ManagerDB:
    // get TimeEntries from ManagerDB, add timespan of 10 years.
var DBTimeEntries = GetTimeEntriesFromDB(new TimeSpan(3650, 0, 0, 0));

(returns a list of ID's)
LogDB
    // get TimeEntries from LogDB, add timespan of 10 years.
var TickTimeEntries = GetTickTimeEntries<TimeEntry>(new TimeSpan(3650, 0, 0, 0)).Select(x=> x.id);

(returns a list of ID's)
and here im trying to check if there is no match.
foreach (InternExternalId te in DBTimeEntries)
{// Manager Data:
    foreach (int t in TickTimeEntries)
    {// Logger data.

            if (te.TickId != t)
            {
                delete method here...
            }

    }
}

it should only delete the data fra ManagerDB, if there is no match what so ever, meaning it has been deleted from LogDB.

A:

Hope I got your scenario right. You could use linq instead of the nested foreach statments:
var idsToRemove = TickTimerEntries.Except(DBTimeEntries.Select(t => t.TickId));
// Entries that existed in LogDB but not in ManagerDB no populate idsToRemove.
// You should now delete the entries which appear in idsToRemove


Q:

Copy dependency of a maven project to specific folder

I am trying to get all the jar required for a maven project inside a particular folder.
I have used mvn dependency:copy-dependencies command.
It gives me the required jar files inside taget/dependeny folder.
Although I can use move or copy coommand to copy those jars to another directory, is there any way to copy the dependencies in directory of my choice directly?

A:

You need to use the outputDirectory property to define the required location where you would like the jars to be copied to.
Here is an example of the configuration you would add in your POM:
<plugins>
...
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
    ...
</plugins>

Alternatively you can pass this configuration directly via the command line:
mvn -DoutputDirectory=alternativeLocation dependency:copy-dependencies


Q:

Unity3D: How does Spectator View work through user side of Hololens?

I am having a hard time understanding the documentation. So I trying to spectate using a Hololens mounted on a camera. The user Hololens has an application. What do I need to do on the user side Hololens to enable Spectator View? Does it require MRTK? What components do I need to add to make on the Unity3D application (user side) to make it visible by the Spectator Hololens

A:

What do I need to do on the user side Hololens to enable Spectator View? Does it require MRTK?

First, you need to go through the Getting Started to obtain and reference the MixedReality-SpectatorView codebase in your project.
Then, add the MixedReality.SpectatorView/SpectatorView/Prefabs/SpectatorView.prefab to the primary scene and choose a Spatial Alignment Strategy, following Basic Unity Setup for step-by-step tutorial.
For Video camera rig HoloLens, you need to calibrate and test your device according to this document: Spectator View Video Camera Setup.
After that, the PC listens to pose updates from video camera rig hololens and gets scene information from the user HoloLens, then composites this application content into the video camera stream.
Besides, MRTK as an SDK is intended to accelerate the development of MR projects and is not required to enable SpectatorView.


Q:

jquery variable scope problem

I have a chat class with two methods: updateChat and sendChat.
//chat.js
var state;
var room;

function Chat (theRoom) {
    this.update = updateChat;
    this.send = sendChat;
    this.room = theRoom;
}

function updateChat(){
        alert('ROOM: '+this.room);

        $.ajax({
            type: "POST",
            url: "/chat/process.php",
            data: {
                'function': 'update',
                'state': state,
                'room': this.room
            },
            dataType: "json",
            success: function(data){
                if(data.text){
                    for (var i = 0; i < data.text.length; i++) {
                        $('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
                    }
                }
                if(data.state)
                    state = data.state;
            }
        });
    }
}

//send the message
function sendChat(message, nickname)
{

    alert('A'+state); //20

    //XXX
    updateChat();

    alert('B'+state); //20

    $.ajax({
        type: "POST",
        url: "/live-event/chat/process.php",
        data: {
            'function': 'send',
            'message': message,
            'nickname': nickname,
            'room': this.room
        },
        dataType: "json",
        success: function(data){

alert('C'+state); //wrong!: 2 //it should be 20!

                    //XXX
            updateChat();

alert('D'+state); //21

        },
    });
}

The constructor of the chat object:
var chat =  new Chat(4); //4 = the number of the chat room

chat.send('test', 'tester');

My problem are the method calls at the locations marked with XXX.
In the updateChat() method, this.room is undefined if I call the updateChat methods like that.
But I need to pass the room number to get the right state (state is simply the number of lines in the chat room's text file).
I think it's a problem with variable scope or with the methods not being called in the context of the object.

A:

You need to maintain this when calling those methods, so instead of this:
updateChat();

You can use .call() to maintain context (so this doesn't revert to window inside the called function), like this:
updateChat.call(this);

Or call the method on the object as @casablanca points out below:
this.update();

There also one more issue, this won't be what you want in your $.ajax() callbacks, it'll be the ajax settings object by default, so you need to set the context option to maintain it, like this:
$.ajax({
  context: this,
  type: "POST",
  //...rest of your current options/methods


Q:

Parsing JSON with Sencha Touch 2 MVC not working

I am trying to parse a JSON file and display different values using a sliderfield.drag() method, but for some reason it's not working. I am not even getting a value on the console.log. What is missing?
app/model/agenda.json
{
 "agenda":
    [
        {
            "id": 1,
            "name": "Ed Spencer",
            "email": "ed@sencha.com"
        },
        {
            "id": 2,
            "name": "Abe Elias",
            "email": "abe@sencha.com"
        }
    ]
}

app/model/Contact.js
Ext.define('Test.model.Contact', {
    extend: 'Ext.data.Model',
    config: {
        fields: ['id', 'name', 'email'],
        autoLoad: true,
        proxy: {
            type: 'ajax',
            url : 'agenda.json',
            reader: {
                type: 'json',
                rootProperty: 'agenda'
            }
        }
    }
});

app/controller/Settings.js
Ext.define('Test.controller.Settings', {
    extend: 'Ext.app.Controller',
    requires: ['Test.model.Agenda'],
    config: {
        refs: {
        },
        control: {
            'mainview sliderfield[action=updateSurface]': {
                drag: 'updateSurface'
            },
        }
    },
    updateSurface: function(me){
        var value = me.get('value');

        var yields = Ext.create('Test.model.Contact');
        console.log(yields);
        yields.load({
            success: function(){
                console.log(yields.getName());
            }
        });
    }
});

A:

I practically solve this problem using JavaScript instead of SenchaTouch Models.
app/listener/Agenda.js
Ext.define('Test.listener.Agenda', {

    parse: function(){

        var request = new XMLHttpRequest();
        request.open("GET", "resources/json/agenda.json", false);

        request.send(null);
        var data = JSON.parse(request.responseText);

        return data.agenda[0].name;
    },
});

app/controller/Settings.js
Ext.define('Test.controller.Settings', {
    extend: 'Ext.app.Controller',
    requires: ['Test.listener.Agenda'],
    config: {
        refs: {
        },
        control: {
            'mainview sliderfield[action=updateSurface]': {
                drag: 'updateSurface'
            },
        }
    },
    updateSurface: function(me){
        var agenda = new Test.listener.Agenda();
        console.log(agenda);
    }
});


Q:

GO: Why does dialing from the address on which the client is listening not work, but the opposite does?

I wonder why dialing from the address on which the client is also listening does not work (Version A) but listening on the connection address the client is dialing to the server does actually work (Version B)?!
Can someone explain this to me. Go is new to me and I still learning a lot of things.
Here is an example:
Server Programm:
package main

import . "fmt"
import "net"
import "os"

func main() {
    Println("server")

    var listener, listenerError = net.Listen("tcp", "localhost:8080")

    if listenerError != nil {

        Println(listenerError)
        os.Exit(1)
    }

    for {
        con, _ := listener.Accept() // I don't care about the error in this example
        Printf("LocalAddr: %v\n", con.LocalAddr())
        Printf("RemoteAddr: %v\n", con.RemoteAddr())
    }
}

Client version A (not working):
package main

import "net"
import . "fmt"
import "os"

func main() {

    var listener, listenerError = net.Listen("tcp", "localhost:0")

    if listenerError != nil {

        Println(listenerError)
        os.Exit(1)
    }

    var dialer = new(net.Dialer)
    dialer.LocalAddr = listener.Addr()

    con, err := dialer.Dial("tcp", "localhost:8080")
    if err != nil {

        // dial tcp 127.0.0.1:60229->127.0.0.1:8080: bind: address already in use
        Println(err)
        os.Exit(2)
    }

    Printf("LocalAddr: %v\n", con.LocalAddr())
    Printf("RemoteAddr: %v\n", con.RemoteAddr())
}

Client version B (working):
package main

import "net"
import . "fmt"
import "os"

func main() {
    Println("client")

    con, err := net.Dial("tcp", "localhost:8080")
    if err != nil {

        Println(err)
        os.Exit(2)
    }

    // magic happens here
    var listener, listenerError = net.Listen("tcp", con.LocalAddr().String())

    if listenerError != nil {

        Println(listenerError)
        os.Exit(1)
    }

    Println("LISTENING")
    conn, _ := listener.Accept() // will accept on con.LocalAddr()
    Printf("LocalAddr: %v\n", conn.LocalAddr())
    Printf("RemoteAddr: %v\n", conn.RemoteAddr())
}

A:

"Version B" works as a side effect of the Go's POSIX default of setting SO_REUSEADDR, which will allow binding to an addr:port pair even if it's in use by an existing connection. The 2 sockets can be differentiated, because the established connection is identified by the 4-tuple of (LocalAddr, LocalPort, RemoteAddr, RemotePort).
"Version A" doesn't work, because when setting up the connection it needs to call bind to set the requested local address, and there is already a listening socket bound to that port.
There's no need to try and exploit this loophole, and you should use 2 ports for your client and server connections.


Q:

How to properly transform UIView's scale on UIScrollView movement

To have a similar effect to Snapchat's HUD movement, I have created a movement of the HUD elements based on UIScollView's contentOffset. Edit: Link to the Github project.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    self.view.layoutIfNeeded()

    let factor = scrollView.contentOffset.y / self.view.frame.height

    self.transformElements(self.playButton,
                           0.45 + 0.55 * factor, // 0.45 = desired scale + 0.55 = 1.0 == original scale
                           Roots.screenSize.height - 280, // 280 == original Y
                           Roots.screenSize.height - 84, // 84 == minimum desired Y
                           factor)
}

func transformElements(_ element: UIView?,
                       _ scale: CGFloat,
                       _ originY: CGFloat,
                       _ desiredY: CGFloat,
                       _ factor: CGFloat) {
    if let e = element {
        e.transform = CGAffineTransform(scaleX: scale, y: scale) // this line lagging

        let resultY = desiredY + (originY - desiredY) * factor
        var frame = e.frame
        frame.origin.y = resultY
        e.frame = frame
    }
}

With this code implemented the scroll as well as the transition appeared to be "laggy"/not smooth. (Physical iPhone 6S+ and 7+).
Deleting the following line: e.transform = CGAffineTransform(scaleX: scale, y: scale) erased the issue. The scroll as well as the Y-movement of the UIView object is smooth again.
What's the best approach to transform the scale of an object?

There are no Layout Constraints.
func setupPlayButton() {
        let rect = CGRect(x: Roots.screenSize.width / 2 - 60,
                          y: Roots.screenSize.height - 280,
                          width: 120,
                          height: 120)
        self.playButton = UIButton(frame: rect)
        self.playButton.setImage(UIImage(named: "playBtn")?.withRenderingMode(.alwaysTemplate), for: .normal)
        self.playButton.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.view.addSubview(playButton)
}

A:

This is happening because you are applying both: transform and frame. It will be smoother, if you apply only transform. Update your transformElements function as below:
    func transformElements(_ element: UIView?,
                       _ scale: CGFloat,
                       _ originY: CGFloat,
                       _ desiredY: CGFloat,
                       _ factor: CGFloat) {
    if let e = element {
        e.transform = CGAffineTransform(scaleX: scale, y: scale).translatedBy(x: 0, y: desiredY * (1 - factor))

    }
}


Q:

Prove that a continuous real function with finite limits is bounded

$f: \mathbb{R} \rightarrow \mathbb{R}$ is a continuous function. Assume that $\lim_{x \rightarrow \pm \infty} f(x)$ exist and are finite. Prove that $f$ is bounded.
So to show that $f$ is bounded, I must show that $\exists M \in \mathbb{R}$ such that $|f(x)| \leq M$ for all $x \in Dom(f)$. Assuming that $f(x)$'s limit exist, then I know that $\forall \epsilon  > 0$, $\exists N$ such that for $n > N$, $|f(n) - L| < \epsilon$. But I am having trouble with figuring out how to connect the two ideas together.

A:

The answer was essentially given. Here is an explicit way to connect the ideas.
Take $\epsilon=1$ in the definition of limit. So,

due to $\lim_{x\to-\infty}=L_1$, there exists $N_1$ such that $f(x)\in(L_1-1,L_1+1)$ for all $x<N_1$.
due to $\lim_{x\to\infty}=L_2$, there exists $N_2>N_1$ such that $f(x)\in(L_2-1,L_2+1)$ for all $x>N_2$.

Finally, due to continuity, $f$ is bounded on the compact interval $[N_1,N_2]$. Hence, there exists $C$ such that $|f(x)|\leq C$ for all $x\in[N_1,N_2]$.
So, you can take $M=\max\{|L_1-1|,|L_1+1|, |L_2-1|, |L_2+1|,C\}$ to conclude that $|f(x)|<M$ for all $x\in\mathbb{R}={\rm Dom}(f)$.


Q:

Twitter's Bootstrap Popover: Won't work, even when other JS is working ok

I want to set up a popover using Twitter's Bootstrap.
I've successfully used other JavaScript (dropdown, and tooltips), but I can't get this one working.
I've got this html inside my page:
hover for popover

I've set inside the document body this:

I've called the files like this, using hotlinks:

A:

Yes - if you load the CSS from elsewhere, everything works: http://jsfiddle.net/dirkk0/5DGef/


Q:

Implementing per-user storage usage quota in SaaS products

In a SaaS solution, that allows users to maintain their data on the server, if I have to implement various pricing schemes, where each scheme offers different storage quota, say, Basic subscription gets you 2GB storage, whereas Premium gets you 10GB storage - what kind of architecture one has to use?

Do I need to maintain against user profile the quota being used?
Will this work only if data is maintained in file system?  What happens if data is stored in relational or NoSQL database - how one keeps track of user-level usage of storage in such cases?

A:

Add a size field to each thing that is stored.  This field could be approximate, but it should be updated to reflect the new size whenever the item is modified.

Add a space_used field on the User. Whenever something with a size is added or modified, run a query for all the items the user owns, sum the size fields, and update the space_used field on the user.  If you aren't using a relational database, you could try little efficiency tricks like just adding or subtracting the size change of the item they just modified, but this will fail if there is any possible way that a user could modify 2 items at once.

Either on the User, or on the Company (depending on who is paying for the licenses) you need to store the space_quota to compare against.

The result:
You'll have to check User.space_used < space_quota before allowing the user to add any items or increase the size of any items, so space_used needs to be pre-calculated to keep the query fast.  You need Item.size to later answer the question, "How did we calculate User.space_used because it looks wrong?"
Using such a system, it should be easy to give the user warning when they reach 80% or 95% of their quota.


Q:

tr:last-child not working

Probably some stupid reason for it not working, but i tend to mess up the css a bit. So maybe it will apply to others aswell. CSS:
.bet_history table {
    width: 1000px;
    display: block;
    border-collapse: collapse;
}
.bet_history td {
    padding: 0;
    font-size: 13px;
    text-align: center;
    padding-top: 1px;
    padding-bottom: 1px;
    background: #0361ba;
    color: #BDD6CE;
}
.bet_history tr {
    border-bottom: 1px solid black;
}
.bet_history tr:last-child {
    background: red;
}
.bet_history td.bet_history2 {
    color: #F0F0F0;
    width: 650px;
}
.bet_history td.bet_history1 {
    background-color: #0354a1;
    color: white;
    width: 100px;
    cursor: pointer;
    -o-transition:.5s;
    -ms-transition:.5s;
    -moz-transition:.5s;
    -webkit-transition:.5s;
    transition:.5s;
}
.bet_history td.bet_history1:hover {
    color: #3399FF;
}

And here is the HTML: Edited!

admin1

Bet ID: #6. 09-22-2014 16:08	Match ID #6	10000 minerals on Cure(2.00). Your bet returned 0 minerals. Better luck next time!

Bet ID: #5. 09-22-2014 16:06	Match ID #4	2222 minerals on Snute(2.30). Your bet returned 5110.6 minerals. Congratulations!

Bet ID: #4. 09-22-2014 15:58	Match ID #4	2222 minerals on Snute(2.30). Your bet returned 5110.6 minerals. Congratulations!

Bet ID: #3. 09-22-2014 15:25	Match ID #5	600 minerals on Lars(4.00). Your bet returned 2400 minerals. Congratulations!

Bet ID: #2. 09-22-2014 12:03	Match ID #3	64 minerals on naniwa(9.00). Your bet returned 576 minerals. Congratulations!

Bet ID: #1. 09-20-2014 16:00	Match ID #1	20 minerals on Snute(2.20). Your bet returned 44 minerals. Congratulations!

Why is the last-child not applying to the last tr? It will if i set it to td. Im sure its some stupid thing i did in the css.. This is no finished product. Im just wondering why the last-child doesnt work.

A:

As @Vucko mentioned in the comments the tr:last-child style is applied, however the td's in that row override that style.
If you want all the td's in the last row to be red edit your class to:
.bet_history tr:last-child td {
    background: red;
}

FIDDLE


Q:

Standard way of Serializing utf-8 characters in a JSON String

What's the standard way of serializing a utf-8 string in JSON? Should it be with u escaped sequence or should it be the hex code.
I want to serialize some sensor readings with units in a JSON Format.
For example I have temperature readings with units °C. Should it be serialized as
{
 "units": "\u00b0"
}
´´´
or should it be something like
´´´
{
 "units":"c2b0"
}

Or could both of these supported by the standard.

A:

If JSON is used to exchange data, it must use UTF-8 encoding (see RFC8259). UTF-16 and UTF-32 encodings are no longer allowed. So it is not necessary to escape the degree character. And I strongly recommend against escaping unnecessarily.
Correct and recommended
{
  "units": "°C"
}

Of course, you must apply a proper UTF-8 encoding.
If JSON is used in a closed ecosystem, you can use other text encodings (though I would recommend against it unless you have a very good reason). If you need to escape the degree character in your non-UTF-8 encoding, the correct escaping sequence is \u00b0.
Possible but not recommended
{
  "units": "\u00b0C"
}

Your second approach is incorrect under all circumstances.
Incorrect
{
  "units":"c2b0"
}

It is also incorrect to use something like "\xc2\xb0". This is the escaping used in C/C++ source code. It also used by debugger to display strings. In JSON, it always invalid.
Incorrect as well
{
    "units":"\xc2\xb0"
}


Q:

Proving $\frac1{n+1}+\frac1{(n+1)^3} < \frac1n-\frac1{n^3}$

Prove that the sequence of closed intervals
$\left[ \dfrac1n-\dfrac1{n^3}~~,~~ \dfrac1n+\dfrac1{n^3}\right]$ for $n>2$ are disjoint.
For this to be true I guess we could show that the minimum of the interval is larger than the maxixmum of the subsequent interval :
$\dfrac1{n+1}+\dfrac1{(n+1)^3} < \dfrac1n-\dfrac1{n^3}$ for $n\in \mathbb{N}$,
$n>2$.
How could we prove this inequality?

A:

Write the fractions under common denominator and after some calculation you will get:
$$\frac{1}{n+1} + \frac1{(n+1)^3} \le \frac 1n - \frac 1{n^3} \iff 1 + 3n + 2n^2 <n^4$$
Now use induction to prove that this is true for $n\ge 2$
Obviously it's true for $n=2$, as $16>15$. Now assume it holds for $k$ and we have:
$$1 + 3(k+1) + 2(k+1)^2 = (1+3k + 2k^2) + 5 + 4k < k^4 + 4k + 5 < (k+1)^4$$
where we used the hypothesis and the fact that $k\ge2$


Q:

Disabling form action field from external Javascript

I have an html form with action="result.php.
Now the problem is, I want my form to only proceed to result.php only if certain function inside my javascript returns true and i have this to achieve this,
function init() {
    var form1 = document.getElementById("test");
    if (validat() == true){
        form1.onsubmit = validatequiz;
    }
}

window.onload = init;

validat function either return true or false, so in the above function i am checking its return value and executing the onsubmit, but even if the value return by my validate() function is false, I am still redirected to result.php which I do not want to do.
The problem is, the action is set inside the html file and i am checking the form in the external javascript file, I am not allowed to use internal javascript within the html file thats why I am having this issue.

A:

Your Javascript doesnt do anything to stop the submit action from completing. To stop the form from submitting you need to explicitly stop it within the Javascript using
return false;

or
event.preventDefault();

Question: How do I prevent the browser's default action in a
  JavaScript event handler?
Answer: In the early days of JavaScript, to prevent the default
  response to an event, you could simply refurn false from the
  respective event handler. For example, returning false from an
  onsubmit event handler would prevent the browser from submitting the
  form; returning false from the onclick event handler of a link would
  prevent the browser from following the link. In most modern browsers,
  behavior like the above still works; however, now there are many more
  supported event types, and the actual behavior may depend on the
  browser and the event type.

via http://www.javascripter.net/faq/eventpreventdefault.htm


Q:

Click event not working on iPad with touch event

I am using a click event on a page link. It works good on iPad's Safari, but when I use touch events on the same page then the click event stops working; only the touch event works there on the iPad.
Click event:
 link.onclick = onLinkClick;

Touch event:
$('#sdiv').bind({
    'touchstart': function (e) {
        onTouchStart(e, sdiv);
    }
});

$('#sdiv').bind({
    'touchend': function (e) {
        onTouchEnd(e);
    }
});

$('#sdiv').bind({
    'touchmove': function (e) {
        onTouchMove(e);
    }
});

$('#sdiv').bind({
    'touchcancel': function (e) {
        onTouchCancel(e);
    }
});

A:

Finally, I differentiate both platforms, iPad and desktop. Using 'navigator.platform', if it's iPad then the touch event works, else the Click event.
 var platform = navigator.platform;

 if( platform == 'iPad') { _link.ontouchend = onLinkClick;}

  else { _link.onclick = onLinkClick; }

Thanks to all,


Q:

Wordpress youtube plugin - Changing feed from channel to favourites (PHP Guru required)

I am not new to Wordpress, but new to PHP. I have managed to get the plugin working (thumbnails etc) but I cannot seem to change the default feed from the default youtube channel to my favourites. I found a post where the dev says to edit the url feed on line 268 of /core/parse.php
Which looks like this:
    'url' => 'http://gdata.youtube.com/feeds/api/users/'.$v.'/uploads?orderby=published&max-results='.$z.'&start-index='.$i,

I searched google high n low, I found this:
https://gdata.youtube.com/feeds/api/users/default/favorites
And tried different variations of it. 0 videos imported.
http://wordpress.org/extend/plugins/automatic-youtube-video-posts/

A:

According to this URL: https://developers.google.com/youtube/2.0/developers_guide_protocol_favorites
The correct code would be
 'url' => 'http://gdata.youtube.com/feeds/api/users/'.$v.'/favorites?orderby=published&max-results='.$z.'&start-index='.$i,