Q: How to work with a Generic List of a Generic Type in a Generic Class In the example console app below, you will notice that the program is attempting to create a basketball team and, then, add a player and a coach to the team.
The design of the application implements generic classes (Team and Person) which concrete classes (Lakers(), Player(), and Coach()) will inherit.
The program throws build exceptions at the point where I attempt to add the Person object to the team.Members list.
The exception reads:

The best overloaded method match for
  'System.Collections.Generic.List>.Add(Person)' has some invalid
  arguments.

I don't understand why the compiler doesn't allow me to add the generic Player (Kobe and Phil) to the Members list when Members is defined as a generic list of a generic Player.
Can you explain the cause of the error and how to work around it?
Also, can you fill me in on whether or not the example program below is not typically how we should be implementing generics? In other words, given the errors in the program below, it makes me wonder why I should implement generics and not stick with a normal abstract class.
By the way, please don't down-vote simply because you don't like the Lakers ;)
class Program
    {
        static void Main(string[] args)
        {
            //Create a team
            Team<Lakers> team = new Lakers();

            //Create a player then add the player to the list of team members
            Person<Player> p = new Player();
            p.Name = "Kobe";
            team.Members.Add(p); //Invalid argument exception here

            //Create a coach then add the coach to the list of team members
            Person<Coach> c = new Coach();
            c.Name = "Phil";
            team.Members.Add(c); //Invalid argument exception here

            //Display the members of the team
            team.Members.ForEach(n => Console.WriteLine(n.Name));
            Console.ReadLine();
        }
    }

    //A generic class containing a generic list of a generic type
    abstract class Team<T>
    {
        public List<Person<T>> Members = new List<Person<T>>();
    }

    //A concrete basketball team
    class Lakers : Team<Lakers>
    {
    }

    //A generic class that represents a person
    abstract class Person<T>
    {
        public string Name { get; set; }
    }

    //A concrete person that represents a basketball player
    class Player : Person<Player>
    {
    }

    //A concrete person that represents a basketball coach
    class Coach : Person<Coach>
    {
    }

A: Why not just:
//An abstract class that represents a person
    abstract class Person
    {
        public string Name { get; set; }
    }

    //A concrete person that represents a basketball player
    class Player : Person
    {
    }

    //A concrete person that represents a basketball coach
    class Coach : Person
    {
    }

The usage of generics seems totally unnecessary. the simple hierarchy should be enough for you.

A: You seem to be mixing up inheritance and generics. While technically different, you can see a generic class as template, and not as an is-a relationship. Normal inheritance is all you want here.

A: Because you declare Team as type Lakers and Person as type Player.  Those are not equal.
Do you need to constrain your List with ?  Can't you just declare it as Person?
abstract class Team<T>
    {
        public List<Person> Members = new List<Person>();
    }


Q: Getting type of not initialized variable There is main a variable which has uninitialized variables. I need to retrieve the Type of uninitialized varible type with reflection. Because I am generating the values dynamically but can't get the types of main variable's type of vars.
In the picture Quick Watch is showing the type name of ameliyatGirisBilgileri variable even it is not initialized.

A: You should be able to get the FieldInfo for the variables within the type using the GetField(...) or GetFields(...) method on the main type. Below is a short program demonstrating how you might go about it:
class Program
{
    public string mStringType = null;

    static void Main(string[] args)
    {
        var program = new Program();

        try
        {
            var field = program.GetType().GetField("mStringType");

            Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program));

            program.mStringType = "Some Value";

            Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program));
        }
        catch (NullReferenceException)
        {
            Console.WriteLine("Error");
        }

        Console.ReadKey();
    }
}

This gives the following output on the Console window:

Field 'mStringType' is of type 'System.String' and has value ''.
Field 'mStringType' is of type 'System.String' and has value 'Some Value'.

Note: If the fields are not public, you will have to pass some BindingFlags into the GetField(...) or GetFields(...) methods.

A: FieldInfo fieldInfo = typeof(MyClass).GetField("ameliyatGirisBilgileri", BindingFlags.Public | BindingFlags.Instance);
Type fieldType = fieldInfo.FieldType;

Sorry but I'm too lazy to type the name of your class completely.


Q: How to call enum with a value from a another method In Interfaces.cs I have:
private enum InstructionType
{
    ADD = 1,
    UPDATE = 2,
    DELETE = 3
}

What I want to do is call each TransactionType individually in IWorks.svc.cs that will handle the logic for adding updating and deleting.
How is this done?

A: If you simply want to enumerate through your enum type you can use this:
   foreach (InstructionType type in Enum.GetValues(typeof(InstructionType)))
   {
        if (type.ToString() == "ADD")
           //do sth here
   }

Problem is your enum is private, so it's not realy a possibility. The only option you have is to write a public method in  IWorks.svc.cs that will do what you need, f.e:
public void foreachType(Action<T> action) {
//action can be invoked so it should be exacly what you want
}


Q: How can extract Custom Property value from lambda expression? I have the following class definition
Person.cs
class Person {

  [Column("first_name")]
  public string FirstName { get; set; }

  [Column("last_name")]
  public string LastName { get; set; }
}

I wrote an HTML Helper extension to extract the ColumnAttribute value from a given instance. However, it does not work as I expect.
Here is what I tried:
Index.cshtml
@model Person

ColumnName is @Html.ColumnNameFor( model => model.FirstName )

HtmlExtensions.cs (public static class)
public static string ColumnNameFor<T, P>(this HtmlHelper<T> helper, Expression<Func<T, P>> expression)
{
    var name = ExpressionHelper.GetExpressionText(expression);
    var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

    // this line causes a runtime error:
    //  Sequence contains no elements
    var attr = (ColumnAttribute)metadata.GetType().GetCustomAttributes(typeof(ColumnAttribute), false).First();

  return attr.Name;    // ColumnAttribute stores the value in .Name
}

For the record, I am able to extract the value using GetCustomAttributes, provided that I pass a reference to the property, which I think will make the code in the View look very different from the built in ASP MVC code for Html.TextBoxFor and Html.DisplayFor, etc.

A: Thanks to @benuto for his answer, I was able to find out how I could extract any required custom attribute or property using MemeberExpress. I wanted the answer to help others, so I made a working example. Bear in mind that you will need to check if the object does have a custom property or not, to avoid crashing when accessing FirstOrDefault().Name.
 public static string ColumnNameFor<T, P>( this HtmlHelper<T> helper,
                                           Expression<Func<T, P>> expression)
 {
      var name = ExpressionHelper.GetExpressionText(expression);

      MemberExpression me = expression.Body as MemberExpression;

      var cp = (ColumnAttribute)me
                  .Member
                  .GetCustomAttributes(typeof(ColumnAttribute), false)
                  .FirstOrDefault();

      return (cp == null) ? null : cp.Name;
 }


Q: Parsing in C# using JSON.Net (very confusing!) I want to parse the following JSON:
{"0":{"igloo_id":"0","name":"Igloo Removal","cost":"0"},"1":{"igloo_id":"1","name":"Basic Igloo","cost":"1500"},"2":{"igloo_id":"2","name":"Candy Igloo","cost":"1500"},"3":{"igloo_id":"3","name":"Deluxe Blue Igloo","cost":"4000"},"4":{"igloo_id":"4","name":"Big Candy Igloo","cost":"4000"},"5":{"igloo_id":"5","name":"Secret Stone Igloo","cost":"2000"},"6":{"igloo_id":"6","name":"Snow Igloo","cost":"1000"},"8":{"igloo_id":"8","name":"Secret Deluxe Stone Igloo","cost":"5000"},"9":{"igloo_id":"9","name":"Deluxe Snow Igloo","cost":"3000"},"10":{"igloo_id":"10","name":"Bamboo Hut","cost":"3200"},"11":{"igloo_id":"11","name":"Log Cabin","cost":"4100"},"12":{"igloo_id":"12","name":"Gym","cost":"4800"},"13":{"igloo_id":"13","name":"Split Level Igloo","cost":"4600"},"14":{"igloo_id":"14","name":"Candy Split Level Igloo","cost":"4600"},"15":{"igloo_id":"15","name":"Snowglobe","cost":"3700"},"16":{"igloo_id":"16","name":"Ice Castle","cost":"2400"},"17":{"igloo_id":"17","name":"Split Level Snow Igl","cost":"4600"},"18":{"igloo_id":"18","name":"Fish Bowl","cost":"2400"},"19":{"igloo_id":"19","name":"Tent","cost":"2700"},"20":{"igloo_id":"20","name":"Jack O' Lantern","cost":"2700"},"21":{"igloo_id":"21","name":"Backyard Igloo","cost":"4200"},"22":{"igloo_id":"22","name":"Pink Ice Palace","cost":"2400"},"23":{"igloo_id":"23","name":"Ship Igloo","cost":"4300"},"24":{"igloo_id":"24","name":"Dojo Igloo","cost":"1300"},"25":{"igloo_id":"25","name":"Gingerbread House","cost":"2100"},"26":{"igloo_id":"26","name":"Restaurant Igloo","cost":"4800"},"27":{"igloo_id":"27","name":"Tree House Igloo","cost":"4500"},"28":{"igloo_id":"28","name":"Theatre Igloo","cost":"4600"},"29":{"igloo_id":"29","name":"Circus Tent","cost":"0"},"30":{"igloo_id":"30","name":"Snowy Backyard Igloo","cost":"3000"},"31":{"igloo_id":"31","name":"Cave Igloo","cost":"1500"},"32":{"igloo_id":"32","name":"Green Clover Igloo","cost":"2050"},"33":{"igloo_id":"33","name":"Grey Ice Castle","cost":"2400"},"35":{"igloo_id":"35","name":"Cozy Cottage Igloo","cost":"2500"},"36":{"igloo_id":"36","name":"Estate Igloo","cost":"2500"},"37":{"igloo_id":"37","name":"In Half Igloo","cost":"2300"},"38":{"igloo_id":"38","name":"Shadowy Keep","cost":"2400"},"39":{"igloo_id":"39","name":"Dragon's Lair","cost":"3000"},"40":{"igloo_id":"40","name":"Mermaid Cove","cost":"3030"},"41":{"igloo_id":"41","name":"Whale's Mouth","cost":"2700"},"42":{"igloo_id":"42","name":"Trick-or-Treat Igloo","cost":"2000"},"43":{"igloo_id":"43","name":"Deluxe Gingerbread House","cost":"0"},"45":{"igloo_id":"45","name":"Invisible Snowy","cost":"0"},"46":{"igloo_id":"46","name":"Invisible Beach","cost":"0"},"47":{"igloo_id":"47","name":"Invisible Forest","cost":"0"},"48":{"igloo_id":"48","name":"Invisible Mountain","cost":"0"},"49":{"igloo_id":"49","name":"Shipwreck Igloo","cost":"900"},"50":{"igloo_id":"50","name":"Wildlife Den","cost":"900"},"51":{"igloo_id":"51","name":"Medieval Manor","cost":"1200"},"52":{"igloo_id":"52","name":"Warehouse","cost":"950"},"53":{"igloo_id":"53","name":"Pineapple Igloo","cost":"0"},"54":{"igloo_id":"54","name":"Creepy Cavern","cost":"1500"},"55":{"igloo_id":"55","name":"Frost Bite Palace","cost":"0"},"56":{"igloo_id":"56","name":"Fresh Baked Gingerbread House","cost":"2500"},"57":{"igloo_id":"57","name":"Penthouse","cost":"4000"},"58":{"igloo_id":"58","name":"VIP Penthouse","cost":"0"},"59":{"igloo_id":"59","name":"Invisible Age of Dinosaurs","cost":"0"},"60":{"igloo_id":"60","name":"Puffle Tree Fort","cost":"0"},"61":{"igloo_id":"61","name":"Secret Base","cost":"1600"},"62":{"igloo_id":"62","name":"Death Star Igloo","cost":"1000"},"63":{"igloo_id":"63","name":"Beach Party Igloo","cost":"1500"},"64":{"igloo_id":"64","name":"Gymnasium Igloo","cost":"0"},"65":{"igloo_id":"65","name":"Magical Hideout","cost":"1500"},"66":{"igloo_id":"66","name":"Eerie Castle","cost":"2000"},"67":{"igloo_id":"67","name":"Sweet Swirl Igloo","cost":"0"},"68":{"igloo_id":"68","name":"Train Station Igloo","cost":"1100"},"69":{"igloo_id":"69","name":"Main Event Igloo","cost":"1000"},"70":{"igloo_id":"70","name":"CP Airliner","cost":"1200"}}

I need a way to retrieve igloo_id, name and cost.
I've tried the following, but it's not what I want
List<Igloo> igloosList = JsonConvert.DeserializeObject<List<Igloo>>(itemJson);

This is the structure of my class
namespace Canvas
{
    public class Igloo
    {
        public int cost;
        public int igloo_id;
        public string name;

        public int Cost
        {
            get
            {
                return cost;
            }
        }

        public int Id
        {
            get
            {
                return igloo_id;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
        }
    }
}

A: Use the JsonProperty attribute :
[JsonProperty(PropertyName = "cost")]
public int Cost
    {
        get
        {
            return cost;
        }
        private set { cost = value; }
    }

    [JsonProperty(PropertyName = "igloo_id")]
    public int Id
    {
        get
        {
            return igloo_id;
        }
        private set { igloo_id = value; }
    }
    [JsonProperty(PropertyName = "name")]
    public string Name
    {
        get
        {
            return name;
        }
        private set { name = value; }
    }

Basically you need to say for each property what is the Json key that will match. Plus, you will need to have a setter for each of your property, but it can be private.

A: I'm not entirely sure I understand what you want. The code you posted generated an exception when I tried running it,

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[ConsoleApplication2.Program+Igloo]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

It did deserialize correctly if I used:
var igloosList = JsonConvert.DeserializeObject<Dictionary<string, Igloo>>( json );

If you want to loop through it you could then use:
foreach( var igloo in igloosList.Values )


Q: How do I have a web page store changes made by javascript? I have a form on a simple web page that has a series of checkboxes.  These options represent items that may be retrieved from a database upon clicking the submit button.  In addition, there is a place to add an extra option to the page at the bottom.  Here is what I am going for:
I would like to be able to add the new option using javascript, so that it show up quickly and seamlessly to the user, rather than having to send the request back to the server and add it server-side, then have the user reload the page.  However, I also want to make sure that these added fields are preserved so that the next time I load the page, they show up.
Unfortunately, my code is proprietary, so I cannot post it here.  I hope that people can help me this some ideas without having to actually see the code.
Thanks

A: When these checkboxes are added you don't want to go the server but when user presses submit you are anyways going to server, so at that time you can persist this information about new checkboxes on server.
Another option is to call to server asynchronously using AJAX to update the server about the state change.

A: If you still want to store the changes server-side, you can do so quietly in the background.
Just use XmlHttpRequest(), together with a PHP script.

A: You can use the HTML5 local storage API to store your changes.
localStorage.setItem('favoriteflavor','vanilla');

A: If you want session related information to pass thru multiple requests, you can either put the data in a cookie, or with php you can use sessions.
http://php.net/manual/en/features.sessions.php


Q: HTML Meta and Body parts from JSON Is it possible to load html meta attributes from JSON?
for example:
<!DOCTYPE html>

<title>{{title}}</title>
<meta charset="{{charset}}">
<meta name="description" content="{{description}}">
<meta name="keywords" content="{{keywords}}">

{{H1}}

{{some_kind_of_text}}

{{some_kind_of_text2}}

A: Yes.
You can fetch data from a URL using XMLHttpRequest and then use standard DOM methods to change the content of the document.
That said, meta data is generally consumed either as the document loads (so it would be too late to change it for any practical effect by the time JS ran) or is consumed by tools that are likely to not execute JavaScript.

A: Yes as Quentin said, it is possible but any content you change with JS might not be seen by Google or other search engines.
If your purpose is to load content that needs to be read by a search engine you will want to 'build' the HTML on the server side, using a server side language like PHP for instance.


Q: How to echo the results from 2 columns within the same table - PHP I just want to echo out two columns from the same table using php.  What I have below which pulls out all the members first names:

MY DETAILS

        <?php $query = "SELECT * FROM `tblMember`";

        $result = $conn -> query($query);

        while($row = $result -> fetch_assoc())
          {
            echo $row['fldFName']."
";
          }

        $conn -> close();
        ?>

This does give the first names, but I also want the surnames to be pulled out from the same table, called fldSName. Is it a simple AND statement?

A: It is already in the results since you are using a * in the query.
echo $row['fldFName'] . ' ' . $row['fldSName'] . '
';


Q: CKEDITOR - Wordwrap seems to be posted I have a very interesting issue, using CKEDITOR. I'm doing the following:
I have an instance of CKEDITOR, and I have a form with hidden inputs. Before submitting the form, the value of CKEDITOR is entered in a hidden input field. So I have:
$('#form_hidden_input').val(CKEDITOR.instances.editor.getData());

When posting (so submitting the form, I am able, to access the value of the input with $_POST['form_hidden_input']. So far, so good. But when I now try, to insert the value I got into CKEDITOR again, it fails. What I do is
CKEDITOR.instances.editor.insertHtml('<?=$_POST['form_hidden_input'];?>');

When I echo the content of $_POST['form_hidden_input'] everything seems to be fine, but with insertHtml(), I get a "Uncaught SyntaxError: Unexpected token ILLEGAL", in Sources of of Developer Console (or when clicking on the error), the line looks like that:
CKEDITOR.instances.editor.insertHtml('
asfa

');

Be aware, that '); appears in the next line, anyway it should work, but I think, this is the only point, where the problem could appear... The question is, why is there a wordwrap, and how can I prevent that, or get it working anyway?

A: Figured out how to do it:
when I do that:
$content = $_POST['form_old_data'];
$content = str_replace("\n", "", $content);
$content = str_replace("\r", "", $content);
CKEDITOR.instances.editor.insertHtml('<?=$content;?>');

it works.


Q: How to assign a tf.keras.layers.layer to a class without initializing it? I work on a class to create all sorts of symmetric AE's. I now port this class to TF 2.0 and it is more complicated than I thought. However, I use subclassing of layers and models to achieve this. Therefore I want to group several keras layers to one keras layer. But if I want to write something like this:
def __init__(self, name, keras_layer, **kwargs):
    self.keras_layer = tf.keras.layer.Conv2D
    super(CoderLayer, self).__init__(name=name, **kwargs)

I get the following error, because tf wants to use this uninitialized layer:
TypeError: _method_wrapper() missing 1 required positional argument: 'self'

I also tried to wrap this in a list, but it did not work either.
EDIT
Here is a working minimal example and the full traceback:
import tensorflow as tf
print(tf.__version__) # 2.0.0-alpha0

class CoderLayer(tf.keras.layers.Layer):

    def __init__(self, name, keras_layer):
        self.keras_layer = keras_layer
        self.out = keras_layer(12, [3, 3])
        super(CoderLayer, self).__init__(name=name)

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12)
layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D)

layer(inputs)

Traceback:
Traceback (most recent call last):
  File "..\baseline_cae.py", line 24, in <module>
    layer(inputs)
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 581, in __call__
    self._clear_losses()
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\training\tracking\base.py", line 456, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 818, in _clear_losses
    layer._clear_losses()
TypeError: _method_wrapper() missing 1 required positional argument: 'self'

A: The problem is with setting not instantiated class as an attribute in a subclass of tf.keras.layers.Layer. If you remove following line
self.keras_layer = keras_layer
the code would work:
import tensorflow as tf

class CoderLayer(tf.keras.layers.Layer):
    def __init__(self, name, keras_layer):
        super(CoderLayer, self).__init__(name=name)
        self.out = keras_layer(12, [3, 3])

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12)
layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D)
print(layer(inputs))
# Tensor("minimal_example_3/conv2d_12/BiasAdd:0", shape=(12, 198, 198, 12), dtype=float32)

It is probably a bug. This is a similar issue that had been raised (if you put your not instantiated class into list and try to __setattr__() you will get the same exception).
This could be possible workaround if you want to use multiple layers:
class CoderLayer(tf.keras.layers.Layer):
    def __init__(self, name, layername):
        super(CoderLayer, self).__init__(name=name)
        self.layer = layername
        self.out = tf.keras.layers.__dict__[layername](1, 2)

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.random.normal([1, 3, 3, 1])
layer = CoderLayer("mylayer", 'Conv2D')
layer(inputs).numpy()


Q: Extract user input to python from a table created in browser? I want to create a table in a browser that's been created with python. That part can be done by using DataTable of the bokeh library. The problem is that I want to extract data from the table when a user gives his/her input in the table itself.
Any library of python I could use to do this? It would better if I could do this with bokeh though.

A: You can use BeautifulSoup it's great for parse HTML content, see this example

A: If your requirement is to create an application using Python and users will access via browser and update some data into a table?
Use Django or any web framework, basically, you are trying to build a web app!!
or
if you are looking for something else do mention your requirement thoroughly.

A: The slick grid datatable used in bokeh can be edited directly by users:
http://docs.bokeh.org/en/latest/docs/reference/models/widgets.tables.html.
Since the data for each column of a datatable can correspond to a field of a ColumnDataSource, one could create python or javascript callbacks, to detect any changes to the datavalues in the table. You can then access the updated data for your desired use case.
Here is an example using javascript callback when the data is edited. When the data is edited the updated column is printed to the browser console. Note it only detects the data as changed after you edit the value then click out of the cell.
You can do exactly the same with a python callback if you want to run outside python functions based off user input. That does require running a bokeh server to work though.
from datetime import date
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor

output_file("data_table.html")

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        strings=['edit_this' for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="strings", title="Downloads", editor=StringEditor()),
    ]

data_table = DataTable(source=source, columns=columns, width=400, height=280,
                       editable=True)

# callback code to detect user edit of table
code = """
    data = source.data
    console.log('data has been updated!')
    console.log(data['strings'])
"""

callback = CustomJS(code=code,args={'source':source})
source.js_on_change('data', callback)

show(widgetbox(data_table))

edit:
Here is a similar example using a python callback. When you edit the cell all of the cells are replaced in this example. Obviously you could do what ever you wanted this is just an illustration.
You need to set a callback on source that responds to a change in the data. Hence source.on_change('data', update). Read more
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html
from datetime import date
from bokeh.io import curdoc
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        strings=['edit_this' for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="strings", title="Downloads", editor=StringEditor()),
    ]

data_table = DataTable(source=source, columns=columns, width=400, height=280,
                       editable=True)

# callback code to detect user edit of table
def update(attrname, old, new):
    data = source.data
    data['strings'] = ['you just edited the table.']*10
    source.data = data

source.on_change('data', update)

curdoc().add_root(widgetbox(data_table))


Q: (python) how can i split tuple variables? from text file, i could import the result with this code:
with open('filename.txt') as file:

    information = [tuple(line) for line in csv.reader(file)]

print(information)

result:
('   1.1   4.4   7.5   8.9  11.7  15.0  15.3  15.6  13.3  11.1   7.5   5.8        ',)

I want to split this tuple and the result has to be:
('1.1', '4.4', '7.5', '8.9', '11.7', '15.0', '15.3', '15.6', '13.3', '11.1', '7.5', '5.8')

when i use this code,
splitting = information[1].split(' ')

print(splitting)

Error happens with
AttributeError: 'tuple' object has no attribute 'split'

Are there any other methods?

A: it seems that you converted the csv into list of tuples in this line:
information = [tuple(line) for line in csv.reader(file)]

which result in:
[(//...tuple 1...//) , (//...tuple 1...//) , ...etc]

you better just concat them if you dont want nested lists:
data_list= []
for line in csv.reader(file):
    data_list += line.split()
information   = tuple(data_list)


Q: Click facebook like button and be taken to another url Is something like this possible?
I have a client launching an online magazine for his business.  He wants to add a facebook like button (for the magazine fanpage) on his current corporate site and ask users to 'like it' in order to be taken to the magazine website.  Can it be done?  Are there drawbacks to this approach?  For example, the same user will have to 'like it' every time they want to access the magazine site?
Thank you for any suggestion, I'm pretty new to facebook.

A: You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe
FB.Event.subscribe('edge.create', function(response) {

    window.parent.location = 'http://www.google.com';

});

edge.create is called when ever a user likes something on the page
response is the url that has just been liked.
If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button
Here's the full javascript code and a like button

<fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like>


Q: Instantiating objects This may be a dumb question although due to my poor wording i'm having a hard time getting a good understanding from searching up on it. When instantiating an object why is the declared like so.
Object @object = new Object();
// rather than just
Object @object;

Is this simply just to call the objects constructor or is there something i'm missing?

A: Because thats the syntax to make it a new instance.


Q: Google Assistant test app unavailable in my country I've been following this tutorial on using Dialogflow and Firebase so I can control a simple website, but when trying to Talk to <app name> I receive the response

<app name> isn't available on devices set up for your language or
  country. Sorry about that.

I am located in New Zealand, but I did go into the settings for my google assistant and change the search language to English (US) and my search region to United States, although I get the same results, is there any way I can fix this or is there any way around it? Thanks

A: Following Nick Felker's comment, changing my phone's locale to English (US) enabled me to test the app. Thanks Nick!


Q: How to use the Raycaster with a CombinedCamera? I try to use a Raycaster (for selection) that works fine with a PerspectiveCamera but doesn't work with a CombinedCamera.
First it seems that CombinedCamera is not supported by the Raycaster, so among those line of three.js I add this :
if ( camera instanceof THREE.CombinedCamera ) {
    if( camera.inPerspectiveMode ) {
        camera = camera.cameraP;
    } else if ( camera.inOrthographicMode ) {
        camera = camera.cameraO;
    }
}

if ( camera instanceof THREE.PerspectiveCamera ) {

...

So as it refers to the nested camera, however that doesn't do the trick because, I believe, the nested cameras position-quaternion-rotation are not updated ??
How can I achieve this and make Raycaster work with both Ortho and Perspective modes of a CombinedCamera ?

A: The renderer needs world matrix data for the raycasting to work. Make the following modification to the CombinedCamera code:
  // Add to the .toPerspective() method:
  this.matrixWorldInverse = this.cameraP.matrixWorldInverse; //
  this.matrixWorld = this.cameraP.matrixWorld;               //

  // and to the .toOrthographic() method add:
  this.matrixWorldInverse = this.cameraO.matrixWorldInverse; //
  this.matrixWorld = this.cameraO.matrixWorld;               //

r73.


Q: MongoDB hidden node still receiving connections I'm not sure if this question been asked before or if the following behavior of MongoDB is normal. Searching online output no results to this scenario.
Initially, we had a 3 node deployment, 1 Primary, 1 Secondary, and 1 Arbiter.
We wanted to add a ReadOnly replica to the cluster and remove the Arbiter node as well in the process. We added the following to the new node:

*

*priority: 0

*hidden: true

*votes: 1

And removed the Arbiter in the same reconfiguration process so we always have 3 voting members and it leaves us with 1 Primary and 1 Secondary and 1 ReadOnly Node.
The complete process went through smoothly, however, we still end up seeing connections to the ReadOnly replica.
But when checking via db.currentOp(), no queries show up.
Based on the documentation on MongoDB website,

Hidden members are part of a replica set but cannot become primary and are invisible to client applications.

Is there a way to investigate why there are connections coming in? And if this is normal behavior?
EDIT: (for further clarification)
Assuming the following:
MongoDB A (Primary): 192.168.1.50
MongoDB B (Secondary): 192.168.1.51
MongoDB C (Hidden): 192.168.1.52
Client A: 192.168.1.60
Client B: 192.168.1.61
In the logs, we see the following:
2018-03-12T07:19:11.607+0000 I ACCESS   [conn119719] Successfully authenticated as principal SOMEUSER on SOMEDB
2018-03-12T07:19:11.607+0000 I NETWORK  [conn119719] end connection 192.168.1.60 (2 connections now open)
2018-03-12T07:19:17.087+0000 I NETWORK  [listener] connection accepted from 192.168.1.60:47806 #119720 (3 connections now open)
2018-03-12T07:19:17.371+0000 I ACCESS   [conn119720] Successfully authenticated as principal SOMEUSER on SOMEDB

So if the other MongoDB instances were connecting, that would be fine, but my question is regarding why the clients are able to connect even when the hidden option is true and if that behavior is normal.
Thank You


Q: Custom cordova plugin - Get path to file I've created a Cordova plugin for Android, and I've put a file in the src folder:
Plugin.xml
<source-file src="myfile.ext" target-dir="src/com/example"/>

I also can see (in Android Studio) that the file was succesfully added in the src folder:
android
 |-- /src
      |-- com
           |-- example
                |-- myfile.ext
                |-- MyPlugin.java

Now I need to be able to get the path to this file in MyPlugin.java, but I've no clue how to do this. Can anybody help me with this? Thanks!

A: Before you updated your question, it was correct - you should copy the asset file to "assets" not "src":
<source-file src="myfile.ext" target-dir="assets"/>

Then you can reference it via the AssetManager:
AssetManager assetManager = this.cordova.getActivity().getAssets();
InputStream inputStream = assetManager.open("myfile.ext");

In terms of "path" to the file, assets are stored in the APK differently from how your Android project is constructed, so the "path" to your file would be file:///android_asset/myfile.ext, but you most likely wouldn't actually be referencing it like this from MyPlugin.java.


Q: Detect tap touches on CALayer My setup is as follows
- UIView
    - CALayer (container)
        -CAShapeLayer
        -CAShapeLayer
        -..

And i want to detect tap touches on every shapelayer to change its color
I have put a UITapGestureRecognizer on my UIView and have the following code
CGPoint point = [self tapWithPoint:[recognizer locationInView:pieView]];

PieSliceLayer* layerThatWasTapped = (PieSliceLayer *)[_containerLayer hitTest:point];
[(PieSliceLayer *)[layerThatWasTapped modelLayer] setFillColor:UIColor.redColor];

But it seems that it only changes 1 CAShapeLayer always the first that was added.


Q: Do you need License for OS (Windows) inside Docker I am looking at creating a Docker (set) for applications that run on Windows. So, I need the Docker to have Windows OS. What license do I need for it? Or if I run the Docker on a Windows VM, does it make use of the same license from the Host?

A: The container images will use the underlying OS license. Microsoft calls it supplmental license.

You are licensed to use this Supplement in conjunction with the
  underlying host operating system software (“Host Software”) solely to
  assist running the containers feature in the Host Software. The Host
  Software license terms apply to your use of the Supplement. You may
  not use it if you do not have a license for the Host Software. You may
  use this Supplement with each validly licensed copy of the Host
  Software.


Q: Using stream_with_context as async I want to stream a file in telegram using pyrogram, but I can't do it because stream_with_context is not working asynchronously, what can I do?
How can I send a file (bytes) to the user asynchronously via flask? No matter how hard I searched, I could not find the answer to this question, there are always answers for synchronous flasks on the internet.
If I try to use flask synchronously, this time the pyrogram with telegram api starts to cause problems because this api is mainly made for async
from flask import Response

from flask import Flask, send_file
from flask import stream_with_context

app = Flask(__name__)

import asyncio
from pyrogram import Client

api_id = 000
api_hash = ""

tg = Client("aaa", api_id, api_hash)

@app.route('/bigfile')
async def bigfile():
    msg = await tg.get_messages(0674564523, 4564535254)

    async def gnn():
        async for chunk in tg.stream_media(msg):
            chnk = io.BytesIO(chunk)
            yield chnk

    return Response(
        stream_with_context(await gnn()),
        headers={
            'Content-Disposition': f'attachment; filename=asdfasdf.pdf'
        }
    )

import threading

if __name__ == '__main__':
    threading.Thread(target=app.run, daemon=True).start()
    tg.run()


Q: How to update a View without Postback in MVC3 How can I update a dropdownlist in MVC3. I want to refill it with latest data filled by some other view, but I do not want to postback the view and want to achieve it with jquery.
I have a dropdownlist like:
@Html.DropDownListFor(m => m.Department, Model.Departments)
@Html.ValidationMessageFor(m => m.Departments)
<input type="button" value="Refresh" id="btnrefresh" />

I have written jquery code to call controller's method:
 $("#btnrefresh").click(function () {
 var ref = '@Url.Action("RefreshDepartments")';
 var model = '@Model.ToJson()';
 var data = { empModel: model };
 $.getJSON(ref, data, function (result) { alert(result.message); });
        return false;
    });

And Here is the controller method:
public ActionResult RefreshDepartments(EmployeeModel empModel)
    {
        empModel.Departments = GetDepartments();
        empModel.Roles = GetRoles();
        return Json(new { message = "Updated successfully"}, JsonRequestBehavior.AllowGet);
    }

How can I update the dropdownlist with latest values on clicking "Refresh" button without any postback?
Is it a good idea to pass the model to the controller and update the model properties? What other ways are possible ?

A: It doesn't look to me like you need the model to be posted to your controller for what you're doing.  In addition, yes, you absolutely can do this with jquery!  On a side note, you could also do it with an Ajax.BeginForm() helper method, but lets deal with your jquery example.
Rather than complexify your jquery with your @Url.Action, you can simply call the path itself.
$("#btnrefresh").click(function () {
    var ref = 'ControllerName/RefreshDepartments';
    $.each(result, function (index, val) {
        $('#whateverYourRenderedDropdownListHtmlObjectis')
            .append($("<option></option>")
            .attr("value", val.Text)
            .text(val.Text));
    });
});

Now, for your controller...
public JsonResult RefreshDepartments()
{
    return Json(GetDepartments, JsonRequestBehavior.AllowGet);
}

private SelectList GetDepartments
{
    var deparments = GetDepartments;
    SelectList list = new SelectList(departments);
    return list;
}

This is an alternative to returning the model.  It allows you to manipulate the raw JSON instead.  Hope it helps!

A: You almost did it all! Why don't you send the data, I mean list, by RefreshDepartments action? You sent a message to view, so you can send the list similarly and instead of alerting the result you can fill the dropdownlist. something like this:
public ActionResult RefreshDepartments(EmployeeModel empModel)
    {
        return Json(new { departments = GetDepartments()}, JsonRequestBehavior.AllowGet);
    }

$.getJSON(ref, data, function (result) {
    $("#Department").html("");
    for (var i = 0; i < result.departments.length; i++) {
        var item = result.departments[i];
        $("#Department").append(
              $("<option></option>").val(item.Id).html(item.Name);
        );
    });
});


Q: Messed up username and permission on raspberry pi, but still logged in as root through ssh I've gotten myself into a pickle, but perhaps there is still hope.
I've commented out the user "pi" while acting as root after typing the following:
  nano etc/passwd
Saved and exited. Next I literally exit terminal. Now upon opening a new terminal window I get the following message:
  I have no name!@raspberrypi ~ $
Any sudo command I type is returned with the following message:
  sudo: unknown uid #### who are you?
Thing is I still have ssh up on my macbook pro where I'm still logged in as root. Since I'm fairly new to the whole command line bit I figured I'd reach out for a bit a help.
Any ideas how to fix the pi without reinstalling??

A: This is not a huge problem, since the file can be edited like any text document.
If you are at ssh and have root privileges, just nano /etc/passwd (i feel evil typing that haha), otherwise if there is another user with root privileges (other than pi) login in as them and edit the passwd file.
If there are no other users, put your SD card in your mac and edit the file in any text editor.

A: I solved it by uncommenting the line that begins with #pi 1000 1000 (something like that) in the file passwd (access it by typing nano/etc/paswwd) by erasing the #, when I did that, everything returns to normality and I was enable to use sudo commands again.


Q: Radian Console adds random Characters as executed I am facing a problem on a Windows PC using a Radian console for R.
When I execute a line, random characters are added to the end of the line in the console.
As you can see in the image attached, there is a ") added at the end of the line when I try to execute it.
Random Characters added Image

Can somebody help?
Thanks in advance!


Q: How to sort structure C# I've got this structure:
struct kluczyk
    {
        int id;
        char litera;
    }

Making a list:
List<kluczyk> posortuj = new List<kluczyk>();
        for (int i = 0; i < 10; i++)
        {
            kluczyk temp = new kluczyk(some char here, i);
            posortuj.Add(temp);
        }

How to sort this list by litera?

A: There are very simple LINQ methods to accomplish sorting by the property of an object. One is OrderBy:
var sortedEnumerable = unsortedEnumerable.OrderBy(a => a.property);

Likewise, you can use OrderByDescending to ascertain the reverse order of the above:
var sortedEnumerable = unsortedEnumerable.OrderByDescending(a => a.property);

Note that these return a new enumerable and do not sort in place.
If you needed more complex sorting logic, or if you wanted to sort the kluczyk object itself and not any given property, you'd want to create your own object that implements IComparer and establishes less-than/equal/greater relationships between your objects.
Brad Christie included a link to List(T).Sort (IComparer<T>), which I've reproduced here unless he wants to make his own answer.


Q: How to get local language in IE-11 I am trying to get the local language in Angular in IE-11.
I set the local language in the IE-11 browser as french and then trying to get the local language from IE-11 as follows.
this.lang = window.navigator.languages ? window.navigator.languages[0] : null;
    this.lang = this.lang || window.navigator.language || window.navigator['browserLanguage'] || window.navigator['userLanguage'];

it is working fine for all browser but for IE-11 I am not getting the correct local language. it is returning me en-US every time.
can anyone help me with this how to get the correct local for IE-11 in Angular8?

A: Do you set your browser local language in Control Panel like below in win 7?

In this situation, we can get local language in IE 11 using window.navigator.browserLanguage which is "fr-FR". In other modern browsers, we can only use window.navigator.language:

In your app, you could use the code below:
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("Trident");
//check if IE 11
if (Idx > 0) {
   this.lang = window.navigator.browserLanguage;
}
else {
    this.lang = window.navigator.language;
}


Q: Unable to make Google Analytics filter work I wish to create a custom filter on Google Analytics (GA), that would allow me to block all views except the genuine ones onto my webpage.
I want to do this because the google-analytics ID associated with my property (UA-XXXXXXXX-X) is public. Hence in theory, my analytics data is open to attack.
I was trying to follow the instructions here. As suggested I created a custom filter to exclude any hits from Hostnames other than my webpage (or any sub-webpages) - https://ishank-juneja.github.io/. In particular the steps I followed were -
New filter --> custom -->  include --> Choose filter field as Hostname
Then I entered the filter pattern as https://ishank-juneja\.github\.io/. Which I believe is the correct regex corresponding to my site URL/Hostname.
I thought this would be enough to make the filter work, however to be sure, I changed the filter type to exclude instead of include, expecting that if the configuration is correct this filter would start rejecting hits from the url https://ishank-juneja.github.io/ and any of its sub-pages.
However when I clicked the filter verification button available at the bottom of the create-filter page, I received the message-

"This filter would not have changed your data. Either the filter configuration is incorrect, or the set of sampled data is too small."

Since I am certain that all my earlier hits were from the mentioned url, it seems that the filter is not configured correctly even in the include mode.
Any help in correcting the working of the filter, so that only hits from the desired Hostname are recorded, would be appreciated.

A: Try to use this regex for hostname (without protocol and trailing slash):
ishank-juneja\.github\.io


Q: Doubts with Python I have a question. Here you have part of my code for a better understanding:
def client ():
    A=[]
    B = open("clientes.txt", "r")
    user = input("To begin, enter your ID number: ")
    for line in B:
        C = line.split("$")
        A.append(C)
    for i in range (len(A)):
        if A[i][0]==user:

and then I have another function, here is it:
def clientpersonalinfo ():
    A=[]
    B=[]
    C = open("accounts.txt", "r")
    D = open("clients.txt", "r")
    for line in C:
        E=line.split("$")
        A.append(E)
    for line in D:
        F=line.split("$")
        B.append(F)
    for i in range (len(A)):
        ***if user==A[i][1]:***

The question is if there is any method in which i can re-use the first input. As you see if I run this, there will be an error saying that the name "user" is not defined.
So I want to know if I can recall the user input that I first used in clients () and re-use it in my clientpersonalinfo () function.
Thanks for your help!!
Thanks to all those who helped me! Thanks a lot! :)

A: Please review the python docs on how to write functions with arguments: http://docs.python.org/tutorial/controlflow.html#defining-functions
def myFunction1():
    user = "foo"
    return user

def myFunction2(user):
    print user

user = myFunction1()
myFunction2(user)

Ideally you would organize a nice class structure, instead of using globals everywhere which I think is messy. Its a good sign that you should indeed be using a class when all of your functions end up needing to share some kind of state and you think you might need to start defining a ton of globals:
class Client(object):

    def __init__(self):
        self.userId = None

    def getClient(self):
        self.userId = raw_input("To begin, enter your ID number: ")

    def parseClientInfo(self):
        # do something with self.userId
        print self.userId

    def clientPersonalInfo(self):
        # do something with self.userId
        print self.userId

Please note that this class is a really simple example.

A: You can reuse whatever you want, you just have to store it somewhere that is visible to both funcitons. You could make a class and put the information in a field or you could return it from the function and pass it on when you call the other function. Global variables are bad style, but that's doable too.

A: To preserve the content of "user" (which would be better named "user_input" or some such), one way is to return the content of "user" along with whatever else you are returning in client(), perhaps in a tuple, and then passing it to clientpersonalinfo() as an argument, i.e. clientpersonalinfo(user).  Another way is to put the code for getting "user" higher up in the hierarchy so that user exists in the function that calls both client() and clientpersonalinfo(), and then passing it as an argument to both functions.

A: If I understand your question correctly, then I think that the best thing for you to do is to take the input call out of the first function and change the function definitions of both functions to take the user as an argument. The code would look something like:
def client(user):
    clients = []
    with open("clientes.txt",'r') as f:
        for client in f:
            clients.append(client.split('$'))
    for client in clients:
        if client[0] == user:
            ...

user = raw_input("To begin, enter your ID number: ")
client(user)

and the other would be similar. There are a couple of changes from how you handle things. It is recommended that use use the "with open" form since it handles problems better than just opening the file, for instance. Also, naming variables so that the name is relevant to what you are doing makes your code easier to read, so avoid using names like A. Finally, you should use raw_input rather than input in general. The input function evaluates what is input by the user, which means that a user could call some code which is generally not what you want. The raw_input function returns a string which contains what the user put in.


Q: Why is full-laziness a default optimization? Full laziness has been
repeatedly
demonstrated
to
cause
space
leaks.
Why is full laziness on from -O onwards?  I find myself unconvinced by the reasoning in SPJ's The Implementation of Functional Programming Languages.  The claim is that in
f = \y -> y + sqrt 4

sqrt 4 is unnecessarily repeated each time f is entered so we should float it outside the lambda.  I agree in the small, but since we've seen what problems this transformation causes in the large I don't believe it is worth it.  It seems to me that the benefits of this transformation are obtainable unilaterally** with only local code changes and programmers who want it should implement it by hand.
Can you convince me otherwise?  Is full-laziness actually really useful?  I will be especially convinced if you can provide examples which to implement by hand require multilateral cooperation or non-local transformations.
** unlike optimizations like inlining and stream fusion which to implement by hand would require multilateral cooperation between modules and non-local code changes

A: There's at least one common case where full laziness is "safe" and an optimization.
g :: Int -> Int
g z = f (z+1)
  where f 0 = 0
        f y = 1 + f (y-1)

This really means g = \z -> let {f = ...} in f (z+1) and, compiled that way, will allocate a closure for f before calling it. Obviously that's silly, and the compiler should transform the program into
g_f 0 = 0
g_f y = 1 + g_f (y-1)
g z = g_f (z+1)

where no allocation is needed to call g_f. Happily the full laziness transformation does exactly that.
Obviously programmers could refrain from making these local definitions that do not depend on the arguments of the top-level function, but such definitions are generally considered good style...
Another example:
h :: [Int] -> [Int]
h xs = map (+1) xs

In this case you can just eta reduce, but normally you can't eta reduce. And naming the function (+1) is quite ugly.


Q: pip install pods command failed in jupyter with FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log' I tried installing the pods package in jupyter notebook using the below commands:
   pip install pods

   import pods

Installation failed with the following error
       ---------------------------------------------------------------------------
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-3-c6cba4dfa9c3> in <module>
      1 get_ipython().run_line_magic('matplotlib', 'inline')
----> 2 import pods
      3 import matplotlib.pyplot as plt

~\anaconda3\lib\site-packages\pods\__init__.py in <module>
----> 1 from . import datasets
      2 from . import mocap

~\anaconda3\lib\site-packages\pods\datasets.py in <module>
     17 import logging
     18
---> 19 logging.basicConfig(
     20     level=logging.DEBUG,
     21     format="%(asctime)s %(levelname)s %(message)s",

~\anaconda3\lib\logging\__init__.py in basicConfig(**kwargs)
   1974                 mode = kwargs.pop("filemode", 'a')
   1975                 if filename:
-> 1976                     h = FileHandler(filename, mode)
   1977                 else:
   1978                     stream = kwargs.pop("stream", None)

~\anaconda3\lib\logging\__init__.py in __init__(self, filename, mode, encoding, delay)
   1141             self.stream = None
   1142         else:
-> 1143             StreamHandler.__init__(self, self._open())
   1144
   1145     def close(self):

 ~\anaconda3\lib\logging\__init__.py in _open(self)
   1170         Return the resulting stream.
   1171         """
-> 1172         return open(self.baseFilename, self.mode, encoding=self.encoding)
   1173
   1174     def emit(self, record):

 FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log'

I tried to install the pods package with ! pip install pods --user command but still, the issue is the same. Could anyone give your insights for solving the issue?

A: The issue is that the path for the log file is hard coded in the source code, as can be seen on github. The path C:\\tmp does however not exist per default in windows.
Simplest solution is just to create a tmp folder on your C drive


Q: Android/XML: RelativeLayout design basically, I don't understand how to use RelativeLayout. I don't know how to design it. I always use LinearLayout with Table inside of it. Now I use RelativeLayout for my design. I want to know, how to add text "Sorry, no list available" Below is my current code of XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/haha"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyHistoryList">

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:gravity="center"
    android:longClickable="false"
    android:maxLines="1"
    android:textColor="#FFFFFF"
    android:textSize="18sp"
    android:textStyle="bold" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <TextView
            android:id="@+id/tvSuggestion"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".80"
            android:gravity="start"
            android:text="Suggestion"
            android:textAllCaps="true"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorAccent"
            android:textStyle="bold"
            app:fontFamily="@font/anaheim" />

        <TextView
            android:id="@+id/tvStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="start"
            android:text="Status"
            android:textAllCaps="true"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorAccent"
            android:textStyle="bold"
            app:fontFamily="@font/anaheim" />
    </TableRow>
</LinearLayout>

<RelativeLayout
    android:id="@+id/huhu"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylcerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/imgEmpty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:src="@drawable/empty"/>

 </RelativeLayout>
</LinearLayout>

This is how it looks like

(source: fbcdn.net)
But, I want to add text "Sorry, no list available" below of the image (marginTop = 20dp). Can anyone help?

A: <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="20dp"
     android:layout_below="@id/imgEmpty"
     android:text="Sorry, no list available"/>

Insert it below your ImageView of RelativeLayout!

A: Replace your Relative layout with this.
    <RelativeLayout
android:id="@+id/huhu"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recylcerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginBottom="10dp"
    android:visibility="gone" />

<ImageView
    android:id="@+id/imgEmpty"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:src="@drawable/empty"/>

<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="20dp"
     android:layout_below="@id/imgEmpty"
     android:text="Sorry, no list available"/>

A: Add this below imgEmpty. Use android:layout_below to place the text below image,android:layout_centerInParent="true" to move text to center.
 <TextView
            android:layout_marginTop="20dp"
            android:layout_centerInParent="true"
            android:text = "Sorry, no list available"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imgEmpty"/>

Here the output

A: in relative layout you can use below/above to put view below/above its sibling

 <TextView
          android:id="@+id/textView"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/imgEmpty"
          android:layout_marginTop="20dp"
          android:gravity="center_horizontal"
          android:text="TextView"/>


Q: Use of function inside a for loop I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?
Here is the code I tried but I do not get any output.
def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

A: Yes, it is possible but your code would not work because x inside the loop will be unknown:
for i in test_rng:
    my_fun1(i)
    print(x)
    my_fun2(x)

Possibly, you want to do something like:
for i in test_rng:
    x = my_fun1(i)
    print(x)
    my_fun2(x)

You may also want to double-check the code in my_fun1():
def my_fun1(i):
    x=+i
    return x

as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i

A: Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.
def my_fun1(i):
    x=+i#I am assuming you want this x+=i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)


Q: How to find columns of the partition of a master table in postgresql 9.4? In postgresql I have created a master table
CREATE TABLE IF NOT EXISTS table_master(
column_1 text NOT NULL,
column_2 text NOT NULL,
column_3 text NOT NULL
);

and a partition table based on columns: column_1, column_2
CREATE TABLE table_col1_col2 (
CONSTRAINT table_col1_col2_pk PRIMARY KEY (column_1, column_2),
CHECK ( column_1 = 'value_1' AND column_2 = 'value_2')
) INHERITS (table_master);

Is there any select query in order to get the columns of the partition (column_1, column_2)?
UPDATE
In case I know a child table, I may use the below query:
WITH table_id AS (
SELECT oid
FROM pg_class
WHERE relname = 'child_table_name'
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

FINAL QUERY
WITH table_id AS (
SELECT pg_class.oid
FROM pg_class INNER JOIN pg_inherits ON pg_class.relname::text = pg_inherits.inhrelid::regclass::text
WHERE pg_inherits.inhparent = 'master_table'::regclass
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

A: You can get columns of primary key.

This returns the names and data types of all columns of the primary
  key for the tablename table:
SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'tablename'::regclass
AND    i.indisprimary;

(source)
Here used the fact that primary key's uniqueness is handled by Postgres via index, so you can use pg_index table.


Q: Replacing the value of XML attribute I'm trying to replace the "Visible" attribute value of a Field ID=29 that is duplicated across the xml document.
An example of the xml is found below:
<Types>
    <Type ID="4">
        <Fields>
            <Field ID="29" Visible="false"/>
        </Fields>
    </Type>
    <Type ID="5">
        <Fields>
            <Field ID="29" Visible="true"/>
        </Fields>
    </Type>
    <Type ID="6">
        <Fields>
            <Field ID="29" Visible="false"/>
        </Fields>
    </Type>
</Types>

I have tried the following but with no success:
update SF
set [Static_Form_Properties].modify('replace value of (/Field[@ID=29]/@Visible)[1] with ("true")')
from wf_workflow_step_form SF

Any help would be greately appreciated.
thanks

A: It seems you cannot do an update of multiple XML node values in a single UPDATE statement, as mentioned here: How to modify multiple nodes using SQL XQuery in MS SQL 2005
In your query above I think only the first instance found will be updated.


Q: How to Filter array of objects based on a field inside one object? I have an array of this form:
[
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  }
]

And I need to filter based on the infoDate, whether it's in between two specific dates.
I have a function that accepts the object, and the field to search range by and returns :
return resultDate >= fromDate && resultDate <= thruDate;

But how do I filter such array .
I tried
userData.filter(userData => functionthatFiltersDate(userData.moreInfo, {from,thru}, 'infoDate')

The functionthatFiltersDate is a function that accepts an object as input and dates to check range :
functionthatFiltersDate = (
  result,
  { fromDate, thruDate },
  fieldName
) => {
  let resultDate = result[fieldName];
  if (!isDate(resultDate)) {
    resultDate = moment(result[fieldName]).toDate();
  }
  if  (!isDate(fromDate)) {
    fromDate = moment(fromDate).toDate();
  }
  if (!isDate(thruDate)) {
    thruDate = moment(thruDate).toDate();
  }
  return resultDate >= fromDate && resultDate <= thruDate;
};

How do I filter though for an array of objects, based on another object property that's inside?
Any help  is appreciated!

A: call your function this way:
function fooBar(item ){
    // ....
    // return truthy condition
};

var result = arr.filter(fooBar);

-
Passing argument to the filter function:
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * Array filters items based on search criteria (query)
 */
const filterItems = (query) => {
  return fruits.filter((el) =>
    el.toLowerCase().indexOf(query.toLowerCase()) > -1
  );
}

console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']

Source: Mozilla Docs
-
Filtering array based on nested values:
var arr = [
 {foo: 'item1', nested: {nestedFoo: 'returnThis'} },
 {foo: 'item2', nested: {nestedFoo: 'notThis'} },
];

var result = arr.filter(item => item.nested.nestedFoo == 'returnThis');
// result variable now contains an array with one object
console.log(result) // array
console.log(result[0]) // object
console.log(result[0].foo) // 'item1'

Refer to this question for explanation on how to access nested values
-
Making it more clear:
var arr = [
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  },
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  },
 ...
];

const filterItems = (fromDate, thruDate, fieldName) => {
  return arr.filter((item) =>
    item.moreInfo.infoDate >= fromDate && item.moreInfo.infoDate < thruDate
  );
}


Q: How do I start and stop quartz schedular from my class method? Scheduling in spring I am new to spring. I implemented schedular which invokes a method after every 10 sec.
which looks like,
<bean id="bidApprovalJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
      <property name="targetObject" ref="bidApprovalOperations" />
      <property name="targetMethod" value="checkExpiredAuctions" />
      </bean>
     <!--  Simple Trigger -->
     <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
      <property name="jobDetail" ref="bidApprovalJob" />
      <property name="repeatInterval" value="10000" />
     <!--  5second delay mentioned in milliseconds -->
      <property name="startDelay" value="5000" />
      </bean>
     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
     <property name="jobDetails">
     <list>
      <ref bean="bidApprovalJob" />
      </list>
      </property>
     <property name="triggers">
     <list>
      <ref bean="simpleTrigger" />
      </list>
      </property>
      </bean>

But, this schedular runs all the time. I want to start the schedular at run time when user click the button and stop it after certain time.
Can I start the schedular from my class method? Can I create instance of schedular in a class and then start and stop that?
Thank you in advance.

A: Scheduler, created by SchedulerFactoryBean, has standby() and start()  methods, which you can use to control firing of trigger.


Q: How to select element with single class name in Jquery? I have below html and want to get the element based on 'natural' class. The reason is I get t dynamic classes after 'natural'
 <coral-checkbox class="natural coral-Form-field coral3-Checkbox" ></coral-checkbox>

I am trying below code to get hide the element but it is not working.
$("coral-checkbox[class='.natural']").hide();

But it is working when I select entire class like below but I need to do with only 'natural'. Is this possible ?
$("coral-checkbox[class='.natural coral-Form-field coral3-Checkbox']").hide();

A: Use .classname to select based on any of the element's classed. When you use an attribute selector, it matches the entire attribute (unless you use modifiers like *=, but they're not appropriate here, either).
$("coral-checkbox.natural").hide();

A: Use the class the selector instead of the attribute selector:
$("coral-checkbox.natural").hide();


Q: error in the following code near throw IOException import java.io.*;
import java.lang.*;

public class Propogate1
{

String reverse(String name)
{
if(name.length()==0)
    throw IOException("name");

String reverseStr="";
for(int i=name.length()-1;i>0;--i)
{
  reverseStr+=name.charAt(i);

}
return reverseStr;
}

public static void main(String[] args)throws IOException
{
String name;
try
{
        Propogate1 p=new Propogate1();
    p.reverse("java");

}
finally
{
System.out.println("done");
}

}

}

I have to create a class propogate and main method which will call reverse(). In that if the name.length is null, it will throw an exception. If it is not null it will reverse the string. Pls help me

A: You need to declare which exceptions are thrown in a method: the method declaration should be:
String reverse(String name) throws IOException

A: You have to create the exception before throwing it:
if(name.length()==0)
    throw new IOException("name");

Also main must not throw an IOException. Catch it and print the message to System.err.

A: May be this is what you need.
package reversestring;

// import java.io.* is not needed here.
// And if you want to import anything,
// prefer specific imports instead and not entire package.

// java.lang.* is auto-imported. You needn't import it explicitly.

public class Propogate {
  // There's no reason this method should be an object method. Make it static.
  public static String reverse(String name) {
    if (name == null || name.length() == 0) {
      // RuntimeExceptions are preferred for this kind of situations.
      // Checked exception would be inappropriate here.
      // Also, the error message should describe the kind of exception
      // occured.
      throw new RuntimeException("Empty name!");
    }
    // Idiomatic method of string reversal:
    return new StringBuilder(name).reverse().toString();
  }

  public static void main(String[] args) {
    String name;
    try {
      name = Propogate.reverse("java");
      System.out.println("Reversed string: " + name);
    } catch (RuntimeException rx) {
      System.err.println(rx.getMessage());
    } finally {
      // I don't get the point of `finally` here. Control will reach this
      // point irrespective of whether string reversal succeeded or failed.
      // Can you explain what do you mean by "done" below?
      System.out.println("done");
    }
  }
}

/*
Output:-
Reversed string: avaj
done
*/


Q: Chrome message extension : From injected script to background /* My Background */
console.log("Init BackGround ! ");
chrome.runtime.onMessageExternal.addListener(
    (request, sender, sendResponse) => {
        console.log("J'ai bien reçu un truc");
        console.log(request);
        console.log(sender);
    }
);
    // Inject script
chrome.webNavigation.onCompleted.addListener((details) => {
    chrome.tabs.executeScript(details.tabId, {
        file: "include/ts/injectScript.js",
        runAt: "document_end"
    });
}, {url: [{urlPrefix: "https://website.com"}]});
console.log("End Background init");

/* My injected script */
    var extensionID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    chrome.runtime.sendMessage(extensionID, {test : 123},(response) => {
        console.log(response);
    });

/* One part of my manifest.json (with good url) */
"externally_connectable": {
    "matches": [
      "*://*.exemple.com/tests/*"
    ]
 },
 "permissions": [..., "*://*.exemple.com/tests/*",...]

The background automatically injects JS script at page load.
All tests performed in the console (on the current page) work, and the background is receiving messages.
Unfortunately, although the background well injects the script loading the page, it does not receive any messages.
Sorry for my english,
Thank you in advance for your answers
Jérémy-F

A: You have to use chrome.runtime.onMessage.addListener instead of chrome.runtime.onMessageExternal.addListener to receive messages from your own content scripts.
chrome.runtime.onMessageExternal is for messages from other extensions/apps.


Q: casting elements of uint8 vector to stringstream I'm havig some trouble figuring out how to conver my uint8 vector to stringstream.
On input im getting vector of uint8, first 9 bytes are flags which i dont need in my string stream, next 2 bytes are some data i need as string, let's call them "name1", next 2 bytes are another name, lest call it "name2", then comes 4 bytes which are some uint32 number(but writen as 4 uint8 bytes), lets call it just "number". Now i need to pass these data to stringstream but:

*

*name1 and number2 need to be written as bytes (byte 0x52 -> char[2]={"5","2"})

*number needs to be casted to uint32

*all variables need to be seperated by semicolons in final stringstream

so if im getting a vector like this one:
---some 9 bytes---, 0x05, 0x00, 0x01,0x00,0x00,0x00,0x08,0x0E, ---some other data---
i need stringstream to be like this:
"0500;0100;2062;"
i have managed to figure out how to cast number to uint32:
uint8_t tab[4];
for(int i=4; i!=0; --i)
{
    tab[4-i]=data[i+14];
}
uint32_t* var = (uint32_t*)tab;

is there some better way to do this?
EDIT:
How can i pass uint8 values to string as characters?
example:
byte ouput: 0x05
string output: 05
can i put string to stringstream using "<<" operator or is it not recommended?

A: if you have a string, just loop on the string and output the characters to your stringstream
std::string name = "name1";
std::stringstream ss;
for(auto c : name)
  ss << std::static_cast<int>(c);
ss << ";";

As a side note:
uint32_t* var = (uint32_t*)tab;

is totally useless, you don't need a pointer.

A: i'm not sure this will solve your problem, but i would take a different approach.
i would use a struct to describe the underlying protocol and then continue with that. example:
struct dx{
  uint8 _junk0[9];
  char  name1[2];
  char  name2[2];
  uint32 num;
} __attribute__((packed));

uint8 *input;
dx* struct=(dx*)input;
printf("%d",dx->num);


Q: Httpclient throws Timeout waiting for connection from pool exception Now am working on an exception for our uploading image service, the scenario below:
We have a web page, user from all over the world can upload their images to our server, the image normally keep about 3MB. Now we held a promotion, so the images number uploading to our server is extremely huge, which, however caused the server throws the exception as "org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool".
We use apache httpclient as the core uploading middleware, its version is 4.5.*, we correctly handled the response by using the method mentioned in this article.
The code like below:
 if (returnType != StorageHttpResponse.class && response != null) {
        EntityUtils.consumeQuietly(response.getEntity());
        httpRequest.abort();
    }

Also, the max connection pool for the service is 128 and the max connection time out is 50000 ms. We upload the images by using stream mode, not directly upload the image file.
So here, I correctly handled the response entity by consuming it in finally code block, but I still can't stop the service throw connection pool timeout exception.
Any other stuffs that I need to add to my service? Do I really using redis to make a queue to user's uploading requests and post handling?
Whole code here:
 public <T> T excute(Request request, Class<T> returnType) {
    Preconditions.checkState(!isShutDown, "JSSHttpClient is destory!");
    HttpRequestBase httpRequest = new HttpRequestBuild(this.credential).build(request);
    HttpResponse response = null;
    try {
        response = this.client.execute(httpRequest);
        if (errorHandler.hasError(request, response)) {
            int statusCode = response.getStatusLine().getStatusCode();
            log.warn("Unexpected response," + request + " http code [" + statusCode + "]");
            errorHandler.handleError(response);
        }
        if (returnType != null && returnType != StorageHttpResponse.class) {
            return JsonMessageConverter.read(returnType, response);
        }
        if (returnType == StorageHttpResponse.class) {
            return (T) new StorageHttpResponse(response);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } finally {
        if (returnType != StorageHttpResponse.class && response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            httpRequest.abort();
        }
    }
    return null;
}

A: Finally, we solved this not by using code. Because we all know if the response not consumed directly, the connection of a request will not released. So in our code, we offen consume the response first.
We solved this problem not by using better code but slightly modify some parameters like maxconnectionpoolsize, maxconnectionperroute and maxconnectiontimeout based on our business scenario. Then running it and all seems ok now. Hope this helps you.

A: you can set the parameters in either properties or yml file like below.
http:
pool:
size: 100
sockettimeout: 20000
defaultMaxPerRoute: 200
maxPerRoutes:
-
scheme: http
host: localhost
port: 8080
maxPerRoute: 100
-
scheme: https
host: {{URL}}
port: -1
maxPerRoute: 200


Q: TableView sort by distance from current location (parsing locations from JSON) Within xCode, I am trying to sort objects within a TableView so that they appear in order of how close they are to the user. I have seen this question asked, but I can't seem to figure out how to implement it into my project as I am parsing the locations through a JSON file.
What do I need to do to calculate the distance between the user's location and the location of each location object? And how can I then sort the objects within the TableView in ascending order?
Here is the Location.swift model:
import Foundation
import MapKit
import CoreLocation

var currentLocation:CLLocation?

class Location: NSObject {
    var id: String = ""
    var name: String = ""
    var type: String = ""
    var location: String = ""
    var image: String = ""
    var activity: String = ""
    var rating: String = ""
    var latitude: Double = 0.0
    var longitude: Double = 0.0
    var distance: Double {
        get {
            return CLLocation(latitude: latitude, longitude: longitude).distance(from: currentLocation!)
        }
    }

    init(locationInfo:[String:Any]) {
        self.id = locationInfo["id"] as! String
        self.name = locationInfo["name"] as! String
        self.type = locationInfo["type"] as! String
        self.location = locationInfo["location"] as! String
        self.image = locationInfo["image"] as! String
        self.activity = locationInfo["activity"] as! String
        self.latitude = locationInfo["latitude"] as! Double
        self.longitude = locationInfo["longitude"] as! Double
}

    public var coordinate: CLLocationCoordinate2D { get {
        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        return coordinate
        }
    }

}

Here are the relevant parts from LocationTableViewController.swift:
class LocationTableViewController: UITableViewController {

    var locations = [Location]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let locationService: LocationService = LocationService()
        locations = locationService.readLocation()
        locations.sort { $0.distance < $1.distance }
        self.tableView.reloadData()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellIdentifier = "cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LocationTableViewCell

        // Configure the cell
        cell.nameLabel.text = locations[indexPath.row].name
        cell.thumbnailImageView.image = UIImage(named: locations[indexPath.row].image)
        cell.locationLabel.text = locations[indexPath.row].location
        cell.typeLabel.text = locations[indexPath.row].type
        return cell
    }
}

This is what I have implemented in AppDelegate to capture the user's location:
import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var window: UIWindow?
    var locationManager:CLLocationManager!
    private var currentCoordinate:CLLocationCoordinate2D?
    var currentLocation:CLLocation?

    static var locations: Array<Location> = Array()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // Location Manager
        func setupLocationManager() {
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            self.locationManager?.requestAlwaysAuthorization()
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            locationManager?.startUpdatingLocation()
            }
        }

        return true
    }

    // Location Manager
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if currentLocation == nil {
            currentLocation = locations.last
            locationManager?.stopMonitoringSignificantLocationChanges()
            let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
            print("locations = \(locationValue)")
            locationManager?.stopUpdatingLocation()
        }
    }

A: Defined one more property in your Location model called distance. which is distance from user's current location.
var distance: Double {
        get {
            return CLLocation(latitude: latitude , longitude: longitude).distance(from: userLocation)
        }
    }

This returns distance in CLLocationDistance, but you can use it as Double, because it makes easy while sort.
Now you can sort locations in ascending array like this and Reload data
var locations = [Location]()

locations.sort { $0.distance < $1.distance  }

self.tableView.reloadData()


Q: Accessing a variable list through a class instance object I currently develop an SDK and I want to know how to access a list of variables through a class instance object as follow:
MyClass * myObject = [[MyClass alloc] init];

[myObject changeShape : myObject.FORM_SQUARE];
[myObject changeShape : myObject.FORM_CIRCLE];
[myObject changeShape : myObject.FORM_RECTANGLE];
...

These variables ( three dozen ) are static and return just an integer to identify the form.
Do I have to set a @property for each variable or may be there are a more optimized way?

A: If they are not properties then you will have to implement a getter method to access them.
-(String*)getiVar{
     return iVar;
}

A: Finally, the solution is to use NS_ENUM.
Like that:
typedef NS_ENUM(NSUInteger, shape) {

rectangle = 0,
triangle = 1,
square = 1,
    ...
};

-(void)changeShape:(shape)newShape;


Q: error after importing progect from eclipse to android studio I'm getting this error in Android Studio after i've imported a project from eclipse

C:\Users\admn.gradle\caches\transforms-1\files-1.1\actionbarsherlock-4.4.0.aar\9642e2c79c11b0f8f68064f6cbc64e8e\res\values\values.xml
Error:(5, 5) error: resource previously defined here.
C:\Users\admn.gradle\caches\transforms-1\files-1.1\appcompat-v7-25.2.0.aar\65648038dd839bb6dcf32985b0a61b7d\res\values\values.xml
Error:(203, 5) error: duplicate value for resource 'attr/background' with config ''.
  Error:(203, 5) error: duplicate value for resource 'attr/windowMinWidthMajor' with config ''.
Error:(203, 5) error: duplicate value for resource 'attr/windowMinWidthMinor' with config ''.
Error:(203, 5) error: resource previously defined here.
Error:(203, 5) error: resource previously defined here.
D:\pc\andoid-app\apps\infoapps\coloring by number\Coloring Book\studiocoloring\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(165) duplicate value for resource 'attr/background' with config ''.
Error:(12) resource previously defined here.
Error:(190) resource previously defined here.
Error:(357) duplicate value for resource 'attr/windowMinWidthMajor' with config ''.
Error:(357) duplicate value for resource 'attr/windowMinWidthMinor' with config ''.
Error:(190) resource previously defined here.
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
  Error:Execution failed for task ':app:mergeDebugResources'.
Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

build.geadl module:app
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "27.0.3"

defaultConfig {
    applicationId "com.package.name"
    minSdkVersion 8
    targetSdkVersion 17
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.android.support:support-v4:26.0.0-alpha1'
compile 'com.google.android.gms:play-services:+'
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
compile 'com.android.support:support-v4:20.0.0'
compile files('libs/picasso-2.4.0.jar')
}

build.gradl project
// Top-level build file where you can add configuration options common to
all sub-projects/modules.
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
}
}

allprojects {
repositories {
    jcenter()
}
}

manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package.namer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/app_icon"
    android:label="@string/app_name"
    android:theme="@style/Theme.Sherlock.Light" >
    <activity
        android:name="com.package.name.SplashActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.package.name.PicSelect"
        android:configChanges="orientation|keyboardHidden|screenSize" >
    </activity>
    <activity
        android:name="com.package.name.PicItem"
        android:configChanges="orientation|keyboardHidden|screenSize" >
    </activity>
    <activity
        android:name="com.package.name.FloodFillActivity"
        android:configChanges="orientation|keyboardHidden|screenSize" >
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <!-- Activity required to show ad overlays. -->
    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</application>

</manifest>

Does anyone know how to fix it?


Q: How do I recover files using git? I committed 2 days ago.  Then, I made changes to some of the files.
However, inside one specific directory, I didn't make any changes to it recently.
Today, I deleted those files using rm * inside that directory.
How can I restore files to that directory using git?

A: Simply use this:
cd <specific_dir>
git checkout .

It will restore all files and directories in current directory which were tracked by git.
Be aware that this will overwrite uncommitted changes to other files in current directory.


Q: Can not play recorded audio file from android in iOS 5+ I am working on android app which also supports iOS. I want to record the audio & play it in Android as well as in iOS devices.  I am recording audio in android using following settings
MediaRecorder audioRecorder = new MediaRecorder();
audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
audioRecorder.setAudioSamplingRate(44100);
audioRecorder.setAudioChannels(1);
audioRecorder.setAudioEncodingBitRate(12800);
audioRecorder.setOutputFile(<recordedSoundFilePath>);
audioRecorder.prepare();
audioRecorder.start();

On iOS side , settings are as follows
//audioRecorder is object of  AVAudioRecorder

NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
    NSNumber *formatObject;
    formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC ];

    [recordSettings setObject:formatObject forKey: AVFormatIDKey];
    [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];

    NSURL *soundFileURL = [NSURL fileURLWithPath:[self soundFilePath]];

    NSError *error = nil;
    audioRecorder = [[ AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error];

    if ([audioRecorder prepareToRecord] == YES){
        [audioRecorder record];
    }else {
        int errorCode = CFSwapInt32HostToBig ([error code]);
        NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);

    }

I can record the audio & it is playing correctly in android devices.
Now the problem is I can play the recorded audio from iOS in Android device , but iOS device  can't play the audio recorded on Android device. It returns OSStatus error 1937337955. I searched about this error , but I can't find anything.
Can anybody tell me what's going wrong in my code ?
Any kind of help is highly appreciated. Thanks in advance.

A: try this one:
audioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

A: I faced the same issue in which audio that recorded from Samsung's device is not working on all IOS devices and not even on safari browser. But they working fine in all android devices. I have fixed this issue by adding below lines in AudioRecordingUtil class:

recorder?.let{
  it.setAudioSource(MediaRecorder.AudioSource.MIC)
  it.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
  it.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
}

Hope this can help!

A: It is codec issue , the format recorded by iOS is not able decode by android media player , in order to make it work just decode the audio file on IOS side in to android supported format like mp3 or mp4 or 3Gp etc.

A: I also suffered issues with MediaRecorder. At the time of Audio Record, Mime Types are different like
Mac chrome - Mime Type:audio/webm;codecs=opus
Mac Safari - Mime Type:audio/mp4
Windows/Android - Mime Type:audio/webm;codecs=opus
Iphone Chrome - Mime Type:audio/mp4

I was saving the file as M4a but Audio was not running in IOS. After some analysis and Testing. I decided to convert the file after Upload in Server and used ffmpeg and It worked like a charm.
    <!-- https://mvnrepository.com/artifact/org.bytedeco/ffmpeg-platform -->
    <dependency>
        <groupId>org.bytedeco</groupId>
        <artifactId>ffmpeg-platform</artifactId>
        <version>4.3.2-1.5.5</version>
    </dependency>

 /**
 * Convert the file into MP4 using H264 Codac in order to make it work in IOS Mobile Device
 * @param file
 * @param outputFile
 */
private void convertToM4A(File file, File outputFile) {
    try {
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        ProcessBuilder pb = new ProcessBuilder(ffmpeg, "-i", file.getPath(), "-vcodec", "h264", outputFile.getPath());
        pb.inheritIO().start().waitFor();
    }catch (Exception e ){
        e.printStackTrace();
    }
}


Q: undefined method `belongs_to' for ActiveRecord:Module I am getting the following error "undefined method `belongs_to' for ActiveRecord:Module" it is showing the following code for my error in line 1.
class Posting < ActiveRecord::
   belongs_to :user
   validates :content, length: { maximum: 1000 }
end

Also showing an error in this code on line 10
class ProfilesController < ApplicationController

    def show
      if params[:id].nil? # if there is no user id in params, show current one
        @user = current_user
      else
        @user = User.find(params[:id])
      end

      @alias = @user.alias
      @posting = Posting.new
    end

end

The postings controller if it is needed is...
class PostingsController < ApplicationController
  before_action :set_posting, only: [:show, :edit, :update, :destroy]

  # GET /postings
  # GET /postings.json
  def index
    @postings = Posting.all
  end

  # GET /postings/1
  # GET /postings/1.json
  def show
  end

  # GET /postings/new
  def new
    @posting = Posting.new
  end

  # GET /postings/1/edit
  def edit
  end

  # POST /postings
  # POST /postings.json
  def create
    @posting = Posting.new(posting_params)

    respond_to do |format|
      if @posting.save
        format.html { redirect_to @posting, notice: 'Posting was successfully created.' }
        format.json { render action: 'show', status: :created, location: @posting }
      else
        format.html { render action: 'new' }
        format.json { render json: @posting.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /postings/1
  # PATCH/PUT /postings/1.json
  def update
    respond_to do |format|
      if @posting.update(posting_params)
        format.html { redirect_to @posting, notice: 'Posting was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @posting.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /postings/1
  # DELETE /postings/1.json
  def destroy
    @posting.destroy
    respond_to do |format|
      format.html { redirect_to postings_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_posting
      @posting = Posting.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def posting_params
      params.require(:posting).permit(:content, :user_id)
    end
end

A: You need the Posting class to inherit from ActiveRecord::Base and not just ActiveRecord::