text:
Q: Python: variable with multiple lists concatenate into one list I'm relatively new to Python and am working on a problem where I'm looking to create a variable that contains every word in a text file without period marks and commas. I have the variable with each word correctly edited, however the variable prints as a list for each word (in this case, this one variable contains 280 lists, each list with a word).
The code I'm working with is such:
import string

with open("pythonhow1.txt",'r') as file:

    content=file.read()
    s=content.split()
    for words in s:
        v=string.replace(words,',','')
        w=string.replace(v,'.','')
        z=w.split()
        print(z)

variable s provides one list with each word in the text file before the editing, and the for loop removes '.' and ',' marks. However when I print z, I get output that looks like this:
['Aenean']

['commodo']

['ligula']

['eget']

['dolor']

['Aenean']

['massa']

where each word is its own list, stored in variable z. Alternatively, I would like z to print 1 list with each word, looking something like this:
['Aenean','commodo','ligula','eget','dolor','Aenean','massa']

I've tried using itertools as some other posts have suggest, however that makes the problem worse by breaking each letter into a string, looking something like this: ['A','e','n','e','a','n']
Would anyone have an idea on what to do to solve this? Thank you ahead of time!

A: The last split is redundant. Moreover, the whole thing can be done much more elegantly with a list comprehension:
z = [w.replace(',.', '') for w in s]
print(z)


text:
Q: MySQL foreign key question Does defining a foreign key also defines a index? I have mysql v5.1.46 & I am looking at the MySQL Administrator tool and its shows the foreign key as an index, so I wanted to confirm?

A: *

*If there already is a usable index (an index where the foreign key columns are listed as the first columns in the same order) then a new index is not created.

*If there is no usable index then creating a foreign key also creates an index.

This is covered in the documentation.

InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.

A: Yes, MySQL 5.1 automatically creates an index on the referencing table when you define a foreign key constraint. MySQL requires an index on both the referencing table and referenced table for foreign keys.
Note however that the index is created automatically only on the referencing table, and not on the referenced table. MySQL won't allow you to create a foreign key that references a field in the referenced table that cannot use an index:
CREATE TABLE orders (
  id int PRIMARY KEY,
  code int,
  name varchar(10)
) ENGINE=INNODB;

CREATE TABLE order_details (
  detail_id int PRIMARY KEY,
  order_code int,
  value int,
  FOREIGN KEY (order_code) REFERENCES orders(code)
) ENGINE=INNODB;

ERROR 1005 (HY000): Can't create table 'test.order_details'

This is not very common, since you'd often be creating foreign key constraints that reference the primary key of the referenced table, and primary keys are indexed automatically. However it is probably worth keeping in mind.
Creating an index on the code field of the orders table would solve the problem:
CREATE INDEX ix_orders_code ON orders(code);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validation failed for one or more entities. See EntityValidationErrors property for more details I have the following two domain Models.
[Table("tblActual_AgencyProfile")]
public class AgencyModel
{
    public AgencyModel()
    {
        CategoryItemList = new List<CategoryModel>();
        user = new UserProfile();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string UniqueURL { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
    public string Email { get; set; }
    public string ABN { get; set; }
    public string CAN { get; set; }
    public string PhotoURL { get; set; }
    public string Summary { get; set; }
    public string Specialities { get; set; }
    public string LocationsServices { get; set; }
    public DateTime? ImportedDateTime { get; set; }
    public int? UserID { get; set; }

    [ForeignKey("UserID")]
    public UserProfile user { get; set; }

    public ICollection<CategoryModel> CategoryItemList { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    public UserProfile()
    {
        Actual_Category_List = new List<CategoryViewModel>();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    [Required]
    public string UserType { get; set; }
    [RequiredIfAttribute("UserType", "Agency")]
    public string AgencyName { get; set; }
    public string Title { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public string Suburb { get; set; }
    [Required]
    public string State { get; set; }
    [Required]
    public string PostCode { get; set; }
    [Required]
    public string Phone { get; set; }
    public string Fax { get; set; }
    public string Mobile { get; set; }
    [EmailAddress]
    [Required]
    public string EmailAddress { get; set; }
    public ICollection<CategoryViewModel> Actual_Category_List { get; set; }
}

Then I have an Update method in my Repository class
public void EditDetails(AgencyViewModel model)
{
    try
    {
        using (WebScrapperDBContext contex = new WebScrapperDBContext())
        {
            using (TransactionScope scope = new TransactionScope())
            {
                AgencyModel agency = (from tb in contex.agencies where tb.ID == model.ID select tb).SingleOrDefault();
                agency.Address = model.Address;
                agency.Email = model.Email;
                agency.Fax = model.Fax;
                agency.LocationsServices = model.LocationsServices;
                agency.Name = model.Name;
                agency.Phone = model.Phone;
                if (!string.IsNullOrEmpty(agency.PhotoURL))
                    agency.PhotoURL = model.PhotoURL;
                agency.Specialities = model.Specialities;
                agency.Summary = model.Summary;

                agency.user.Address = model.Address;
                agency.user.AgencyName = model.Name;
                agency.user.EmailAddress = model.Email;
                agency.user.Fax = model.Fax;
                agency.user.Mobile = model.Mobile;
                agency.user.Phone = model.Phone;
                agency.user.PostCode = model.PostCode;
                agency.user.State = model.State;
                agency.user.Suburb = model.Suburb;

                contex.SaveChanges();

                scope.Complete();
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

As you can see, I don't want to update all the fields in UserProfile (Ex: FirstName, LastName). When I run the EditDetails() method it throws an exception

Validation failed for one or more entities. See
  'EntityValidationErrors' property for more details.

This could be because I'm skipping some required fields in the domain model. How can I solve this issue?

A: The error suggests the values of the properties of user are not being included in your the model you query is returning. You can force these to be populated by adding .Include(x => x.user) to your query. Then it is only necessary to update those properties you need.

A: You can use this configuration to ignore the validation when update. In your case you only need to update some properties instead of all.
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();


text:
Q: Generating .ovpn Config for android phone I'm using an Ubuntu Server and I wanted to use OpenVpn  for my server and my android phone. I installed OpenVpn connect for my phone and the software needs *.ovpn file from my server. How can I generate this file? And how can I enable authentication? I've use OpenVpn Access Server but it gives only two users licensee to authenticate but I need more. I've searched through internet but all training I've found was how to generate client.key , client.crt and ca.crt but I can't use them for my android phone.

A: This is how you create a .ovpn file:
Create a new txt file and rename as yourname.ovpn. Paste the following in into the txt file and replace with your domain name:
client
dev tun
proto udp
remote YOUR.DOMAIN 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
tls-client
remote-cert-tls server
auth-user-pass
comp-lzo
verb 1
reneg-sec 0

a reference is here: http://lukasz.cepowski.com/devlog/32,sample-openvpn-client-config-ovpn
Otherwise if you are using OpenVPN Access Server (which I would recommend), once you've set up your profile, you can get the .ovpn file in your similar directory of: C:\Program Files (x86)\OpenVPN Technologies\OpenVPN Client\etc\profile


text:
Q: Save a WPF Web Browser's Content to an Excel File I wanted to know if there is a way I can get the content of a Web Browser control and save it in a format that would open in Excel?  Currently I have an application that gets data from the user and converts it to a table and displays it in html in a WPF Web Browser control.  I can export this controls content successfully as a PDF document as follows:
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";

File.WriteAllText(fileName, generateHtml());

//Creates a new instance of the Microsoft office interop for using MS Word
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = false;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(fileName);
doc.SaveAs("C:\\Temp\\testExport.pdf", 17);
app.Quit();

This works fine for exporting a PDF file, the issue I am having is that I can't for the life of me get this to work with an excel file.  So far I am trying to do it like so:
  string filePath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";

  File.WriteAllText(filePath, generateHtml());

  //Creates a new instance of Microsoft office interop for using MS Excel
  Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
  //Create a new instance of a workbook
  Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();
  //Don't Show MS Excel
  excelApp.Visible = false;
  //Open a file at location
  Microsoft.Office.Interop.Excel.Workbook excelWorkBook2 = excelApp.Workbooks.Open(filePath);
  //Convert that file to an XLSX document
  excelWorkBook2.SaveAs("C:\\Temp\\testExport.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
  //Close excel
  excelApp.Quit();

However when I try and open the file that this generates I get the following error:

A: Have you tried changing the filename to .xls? I believe that Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet exports to xls, not xlsx
All the types can be found here


text:
Q: What is the main difference between Numba Pro and Theano/pyautodiff for GPU calculations? Both Numba Pro and pyautodiff based on Theano supports conversion of Python code into GPU machine code. Theano will also allow symbolic derivation of the resulted syntax tree, but this is outside the scope of my question.
My question is whether there are technical limitations in one or the other framework, which would make the code less efficient.


text:
Q: Is there a Bootstrap plugin that provides a combination of a dropdown menu and list box? For my website, I require to have a select box. I am using Bootstrap, but it only provides a dropdown menu, which is not exactly what I need.
Is there a plugin available that provides a select box?
Here is a GIF showing exactly what I am trying to achieve: https://gyazo.com/2d16dba01cd3eb5860618b35909b9885
So basically it's a combination of the Bootstrap's Drop-down menu and HTML list box.

A: yes , select box available in bootstrap go through this link in and finds multipal select box https://silviomoreto.github.io/bootstrap-select/examples/

A: Here i will show you some plug in for Bootstrap - Select
Github : Bootstrap - Select


text:
Q: How to change scale of a plot with Maplotlib and add increments? I am making a simple plot in Python with Matplotlib that shows populations of different regions over time.  I have a CSV file that has columns of each region's population over the years, so the years is on the x-axis and population is on the y-axis. The plot looks okay except the y-axis. As you can see in the image, every single population value is included on the y-axis, which is too many values and is unnecessary. I would like to y-axis to have some increments (such as 100 million). Is there a simple way to do that or would I have to manually add my own increments?
And I tried to scale it linearly and logarithmic but I would still prefer to have increments on the y-axis.
This is what the plot looks like right now.

(I took out unnecessary code such as legend and formatting):
data2 = pd.read_csv('data02_world.csv')

for region in data2:
    if region != 'Year':
        plt.plot(data2.Year, data2[region], marker='.', label=region)

plt.xlabel('Year')
plt.ylabel('Population')

plt.show()

A: I think you can simply do with pandas:
data2 = pd.read_csv('data02_world.csv')
data2.set_index('Year', inplace=True)
data2.plot()

if you would like to adopt matplotlib plt.yticks is what you need


text:
Q: Is std::string's default constructor no-throw? Can
    std::string s;
throw under any circumstances? Is this regulated by the standard (interested in C++03, in case there are differences)?

A: In C++11, the default constructor actually takes one (defaulted) argument, namely the allocator (21.4.2):
explicit basic_string(const Allocator& a = Allocator());

This constructor is not declared as noexcept. (I suppose that would require the allocator to have a non-throwing copy constructor.) As Jonathan and Bo point out, the allocator's copy constructor must not throw any exceptions, but the string's constructor is allowed to perform throwing operations (e.g. allocate an initial piece of memory). It should certainly be possible to write a string-like class that as a no-throwing, constexpr constructor, but the standard library string is not specified to be like that.

A: This was changed by WG21/N4002. The first working paper contains it I see is WG21/N4296:

// 21.4.2, construct/copy/destroy:
basic_string() noexcept : basic_string(Allocator()) { }

A: Sure if allocation isn't possible for any reason it would throw


text:
Q: What is the value in hiding the details through abstractions? Isn't there value in transparency? Background
I am not a big fan of abstraction. I will admit that one can benefit from adaptability, portability and re-usability of interfaces etc. There is real benefit there, and I don't wish to question that, so let's ignore it.
There is the other major "benefit" of abstraction, which is to hide implementation logic and details from users of this abstraction. The argument is that you don't need to know the details, and that one should concentrate on their own logic at this point. Makes sense in theory.
However, whenever I've been maintaining large enterprise applications, I always need to know more details. It becomes a huge hassle digging deeper and deeper into the abstraction at every turn just to find out exactly what something does; i.e. having to do "open declaration" about 12 times before finding the stored procedure used.
This 'hide the details' mentality seems to just get in the way. I'm always wishing for more transparent interfaces and less abstraction. I can read high level source code and know what it does, but I'll never know how it does it, when how it does it, is what I really need to know.
What's going on here? Has every system I've ever worked on just been badly designed (from this perspective at least)?
My philosophy
When I develop software, I feel like I try to follow a philosophy I feel is closely related to the ArchLinux philosophy:

Arch Linux retains the inherent complexities of a GNU/Linux system, while keeping them well organized and transparent. Arch Linux developers and users believe that trying to hide the complexities of a system actually results in an even more complex system, and is therefore to be avoided.

And therefore, I never try to hide complexity of my software behind abstraction layers. I try to abuse abstraction, not become a slave to it.
Question at heart

*

*Is there real value in hiding the details?

*Aren't we sacrificing transparency?

*Isn't this transparency valuable?

A:
Is there real value in hiding the details?

Yes.  By presenting abstractions we can think and program at a higher level.
Imagine modeling physical systems without calculus or matrix algebra.  It's completely impractical.  Similarly, if we can only program at a scalar level, we will be unable to solve interesting problems.  Even relatively simple web applications can benefit greatly from abstractions like tag libs.  It is much easier to insert a tag that means "address entry fields" than to repeatedly create four text fields and a select box.  And if you decide to expand overseas, you can just modify the tag definition, rather than fixing every form to handle international addresses.  Effective use of abstraction is what makes some programmers ten times as effective as others.
Humans have a limited working memory.  Abstraction allows us to reason about large systems.
Aren't we sacrificing transparency?

No.  If abstractions are not used, then the purpose of a software component is buried in repeated details.  Developers spend their days wading through code like this:
for (i = 0; i < pilgrim.wives.size(); ++i) {
  wife = pilgrim.wives[i];
  for (j = 0; j < wife.sacks.size(); ++j) {
     sack = wife.sacks[i];
     for (k = 0; j < sack.cats.size(); ++j) {
        cat = sack.cats[k];
        for (m = 0; m < cat.kits.size(); ++m) {
           ++count;
        }
     }
  }
}

and thinking "oh yes another four-level loop over the kits", instead of seeing
pilgrim.kits.each { ++count; }

Isn't this transparency valuable?

As you pointed out, there is a cost to indirection.  There is no point in creating layers "just in case".  Use abstraction to reduce duplication and clarify code.

A: When people say that abstractions hide implementation details, they don't actually mean "hide" in the sense to make it hard to find. What they mean is separate implementation details from public interface, to keep the interface simple, concise, and manageable. Just like a car "hides" most of its vital parts, and only offers a fairly rudimentary set of controls to operate them, a software module "hides" most of its functionality deep in its bowels and only exposes a limited number of access methods to drive it. Imagine a car where you had to manually operate all the engine's internals (and there's a whole freaking lot of them), you'd have a really hard time keeping an eye on the traffic and finding the way.
But keeping the interface simple is not merely an aesthetic thing; it can make the difference between a successful project and a Death March. Let's play devil's advocate for a minute; imagine a software project without any abstractions at all. If you need to keep a value around, you use a global variable. If you need to use functionality more than once, you copy-paste it. If you need two different versions of a certain code section, you copy-paste, wrap it in an if statement, and modify both branches. Technically speaking, it works, but a few months down the road, you'll be fighting a few really nasty problems:

*

*When you find and fix a bug, it is likely to also exist in other copy-pasted instances of similar code, so on top of finding and fixing the bug, you also have to go hunting for other occurrences and fix them, too.

*In order to find a bug or implement a change, a maintenance programmer must be able to understand the relevant code. The difficulty in doing this increases with the size of the relevant code section, but even more with its scope. Keeping half a dozen variables in your head while mentally stepping through some code is doable; but if you have a few hundred of them, your productivity is severely impacted (I like to compare the thought process with a program that runs out of physical RAM and has to dip into the swapfile: instead of reading through the code fluently in one go, the programmer has to jump back and forth to look things up).

*The scope of a piece of code also impacts the size of the codebase one has to dig through in order to find the bug. If you have a ten-line function with two parameters, and no globals, and you know the values of the input and the line at which it crashes, finding the bug is usually trivial and often requires nothing more than looking at the code. If it's a few hundred lines, twenty parameters, fifteen globals, and calls a few other functions of similar nature, you're in for some serious pain.

*Without proper abstraction, any change can potentially impact large parts of the codebase, as practically anything may depend on the code to be changed. A typical symptom with such codebases is that you make a small, seemingly innocent change, and a completely unrelated feature suddenly breaks. With abstraction, you can limit the amount of damage a change can do, and you make the impact more predictable. If you change the name of a private field, you only have one source file to check; if you change the name of a global variable, you need to run through the entire codebase.

In a badly-abstracted codebase, the impact typically grows exponentially with the size of the codebase, that is, adding a constant amount of code increases the maintenance effort by a constant factor. To make matters worse, adding more programmers to a project does not increase productivity linearly, but logarithmically at best (because the larger your team, the more overhead is required for communication).

A: The reason for hiding the details isn't to keep the details hidden; it's to make it possible to modify the implementation without breaking dependent code.
Imagine that you've got a list of objects, and each object has a Name property and other data.  And a lot of times, you need to find an item in the list whose Name matches a certain string.
The obvious way is to loop over each item one by one, and check to see if Name matches the string.  But if you find that that's taking far too much time, (as it would if you have several thousand items in the list,) you might want to replace it with a string-object dictionary lookup.
Now if all of your lookups were done by retrieving the list and looping over it, you've got a huge amount of work to do to fix this.  It's even tougher if you're in a library and third-party users are using it; you can't go out and fix their code!
But if you had a FindByName method to encapsulate the process of the name lookup, you can simply change the way it's implemented and all the code that calls it will continue working, and get a lot faster for free.  That's the real value of abstraction and encapsulation.

A: I think you should understand how it works if needed. Once you've determined it does what you thought it would do, then you have peace of mind. I never thought the goal was to hide it for ever and ever.
Once you set an alarm on a clock that you are confident will work, you can get some sleep knowing it will go off at the corret time. Waking up an hour early just so you can watch the seconds tick away is a waste.

A: To answer your questions specifically:

Is there real value in hiding the details?

Yes. As you acknowledge in the first line of your question.

Aren't we sacrificing transparency?

Not really.  A well written abstraction will make it easy to understand the details if needed.

Isn't this transparency valuable?

Yes. Abstractions should be designed and implemented to make understanding the details easy when needed/desired.

A: I just finished reading the section in Code Complete about abstraction, so that's where most of this sources.
The point of abstraction is to remove the need to ask "how is this implemented?". When you call user.get_id(), you know that an id is what you're going to get back. If you have to ask "how does this get the user id?" then you probably either don't need an id, or get_id() returns something that is unexpected and is poorly designed.
You use abstraction to allow you to design:
a house with doors and windows

not design
a box with four walls,
    with 3 holes,
        two of which fit panes of glass surrounded by wood frames,
        one that fits a large plank of wood with hinges and a metal knob,
etc.

A: I would say that hiding the details is great when the stuff that's hidden works.
For instance, say we develop an interface which defines behaviors (i.e. GetListItems, SendListItem), which are two features that are initiated by the user via some button click or something.. NOW, each user can have their own "ListItemStore".. say one's on facebook, ones on myspace.. (for instance)..  and say it's saved as a user property / setting somewhere in the app via user prefrences.. and say it's possible for the App developers to add additional ListItemStore's over the course of time (mybook, facespace, etc..)
now there's a lot of details in connecting to facebook and getting them items.. and there's equally as much details when connecting to to myspace.. and so on...
now, after the initial "store access" code is written, it may not need to be modified (well in facebooks case we probably need a fulltime developer to keep up with the changes, zing..) ,
so when you use the code it's something like:
    new ItemManager(user) //passes in user, allowing class to get all user properties
    ItemManager.GetListItems()

and now you've got the User's data from wherever they've stored it, and since all i'm worried about is getting the list of items and doing something with it, and since it only took 2 lines which will work no matter how many more stores are added i can get back to answering / posting questions on stack... lol..
So, all the plumbing to make that happen is "hidden" and who really cares how it does it as long as i get the correct list of items.. if you have unit tests, then you can even rest easier because the results should've been quantified already..

A: What you refer to as "Hiding", many see as a separation of concerns (e.g. Implementation vs. Interface).
In my opinion, one major benefit of abstraction is to reduce the clutter of unneeded details from the developer's limited brainspace.
If implementation code were obfuscated, I could see that as hindering transparency, but abstraction as I see it, is just good organization.

A: First off, anything beyond a single machine code instruction is essentially abstraction--a while...do loop is an consistent symbolic way of representing the comparisons and address calls required to repeat a set of instructions until a condition is met.  Likewise the int type is an abstraction for X number of bits (depending on your system).  Programming is all about abstraction.
You'd probably agree that those primitive abstractions are mighty useful.  Well, so is being able to build your own.  OOAD and OOP are all about.
Suppose you've got a requirement where the users want to be able to export the data from a screen in a variety of formats: delimited text, excel, and pdf.  Isn't it handy that you can create an interface called "Exporter" with a method export(data), based on which you can build a  DelimitedTextExporter, an ExcelExporter, and a PDFExporter, each of which knows how to create it's particular output? All the calling program needs to know is that it can call the export(data) method, and whichever implementation is used will do its thing.  Moreover, if the delimited text rules change, you can change the  DelimitedTextExporter without having to mess with the ExcelExporter, possibly breaking it.
Pretty much all of the well known design patterns used in OO programming depend on abstraction.  I'd recommend reading Freeman and Freeman's Head First Design Patterns to get a better feeling for why abstraction is a good thing

A: I think I understand your feeling about this, and I think I have a similar opinion.
I have worked with Java developers who turn 50 code line class into 3 classes and 3 interfaces because it's easy to understand. And I couldn't stand it.
The thing was awfully hard to understand, almost impossible to debug and never ever needed to "switch the implementation".
On the other hand, I've also seen code where multiple objects share similar behavior and are used in one place, and could really use common sorting/processing loops if the methods would have been exposed through common interface.
So, IMHO, core objects that are likely to be used in similar scenarios usually benefit from common behavior which should be accessible through interface. But that's pretty much it, abstracting simple things because it's right, or makes it possible to switch implementations is just a way to make code messy.
Then again, I prefer longer smarter classes over explosive amount of small classes with all the lifetime management issues, and hard to see relationships, and spaghetti call graphs. So some people will disagree with me.

A: The guiding purpose of hiding and abstraction should be decoupling the user from the implementation so they can be changed independently If the consumer is coupled with the implementation details, due to fiddling with their internals both are cast in stone and it becomes harder to introduce new features or better algorithms in the future.
When writing a module, hidden parts of the implementation gives you the piece of mind to be able to change them without risking breaking other code you can't think of.
Another advantage to providing opaque interfaces is that they significantly reduce the surface area between subsystems. By reducing the amount of ways they can interact they can become more predictable, easier to test and have fewer bug. Interactions between modules also increase quadratically with the number of modules so there is a value in trying to control this growth of complexity.

That said, it is of course possible to hide too much and nest interfaces too deep. It is the job of the programmer, as an intelligent human, to design the system so that it is maximally useful while also minimizing complexity and maximizing maintainability.

A: In so many cases you simply don't need to know how things are implemented.  I can almost guarantee that you'll write code like this people.Where(p => p.Surname == "Smith") so many times a day yet you will hardly ever think "how does this Where() method actually work?"  You just don't care - you know this method is there and that it gets you the results you want.  Why would you care how it works?
This is exactly the same for any in-house software; just because it's not written by Oracle, Microsoft, etc doesn't mean that you should have to go hunting into how it's implemented.  You can reasonably expect that a method called GetAllPeopleWithSurname(string name) to return you a list of people who have that surname.  It might iterate over a list, it might use a dictionary, it might do something completely crazy but you just shouldn't care.
There is an exception to this rule of course (it wouldn't be a rule without one would it!) and that is if there is a bug in the method.  So in the above example, if you have a list with 3 people in it and you know that one of them has the surname Smith and they aren't returned in the list then you care about the implementation of that method because it is clearly broken.
Abstraction, when done correctly, is wonderful because it allows you to filter out all of the stuff that isn't useful when you have to read it at a later date.  Don't forget that much more time is spent reading code than is spent writing it, therefore the emphasis must be on making that task as easy as possible.  You might also be thinking that abstraction means a hierarchy of objects as long as your arm but it can be as simple as refactoring a 100 line method into 10 methods, each 10 lines long.  So what was once 10 steps all bundled together is now 10 separate steps allowing you to go straight to the place where this pesky bug is hiding.

A: Abstractions result in information hiding. This should end up in lower coupling. This should lead to fewer risks in change. This should lead to happy programmers, not getting nervous when touching code.
Those ideas are expressed through three essential laws in software architecture:
Simon's Law:
"Hierarchies reduce complexity." (Hierarchies introduce abstraction)
Parna's Law:
"Only what is hidden can be changed without risk."
Constantin's Law:
Robust programs need low coupling and high cohesion

A: I am in the enterprise application business too, and this question grabbed my attention because I have the same question myself. I had some insight regarding the abstraction issue over the course of my career thus far, but my insight is by no means the universal answer. I am continuing to learn/listen to new ideas and thoughts, so what I believe now may change.
When I was a maintaining a large and complex healthcare application, just liked you, I hated all the abstractions there. Figuring where the all the code goes was pain in the neck. Jumping around different classes made me dizzy. So I said to myself "abstraction sucks, I will minimize abstraction when I design stuff".
Then, it came to the time I had to design an application (relative small web service component) from ground up. Remembering all the pain, I had a pretty flat design of the component. Problem was, when requirements changed I had to made change to many different places (requirements were quite fluid, and I couldn't do anything about that). It was so bad, I basically throw away my initial design and re-design with abstraction, and things got better - I didn't have to make changes to many places when requirements changed anymore.
I delivered the application, sat around for few weeks then was told to start maintaining the application. I had been a while, I didn't remember everything so I struggled a little bit to understand my own code, and the abstraction was not helping.
I was put on many other different projects afterwards and had the chance to play around with the abstraction levels a little bit more. What I actually find is, and this is just my personal opinion, abstraction helps a lot in development but has negative impact when you didn't write the code and are trying to understand everything to the deepest level of an application; you will spend more time jumping around different classes, and trying to make the connections.
My feeling is that abstraction is so valuable during development time that the trouble we go through as maintainer when trying to understand the code is worth while. Software exist to solve business problems, business problems evolve over time; hence, software has to evolve over time. Without abstraction, evolving the software is very hard. One can design abstraction in a way that the maintainer can navigate around the code base easily once they see the pattern of the code structure, so that only the initial learning curve is frustrating.

A: As others have said, "hiding details" behind an abstraction enables them to be changed without affecting users. This idea comes from Parnas' On the Criteria to Be Used in Decomposing Systems Into Modules (1972), and is related to the idea of abstract data types (ADT) and object oriented programming.
At around the same time, Codd's A Relational Model of Data for Large Shared Data Banks (1970) was motivated (see the abstract and intro) by wanting to change the internal storage representation of databases, without affecting users of the database. He had seen programmers regularly taking days, modifying pages of code, to cope with minor storage changes.
That said, an abstraction isn't very useful if you have to see what's inside it to be able to use it.  It can be very difficult to design it well. An example of a good abstraction is addition - when was the last time you had to think about what happens inside? (but at times you do, e.g. for overflow).
The essential problem (IMHO) is that to design modules well (in Parnas' sense), you need to predict what will change and what won't.  Predicting the future is difficult - but if you have a lot of experience with something, and understand it clearly, then you can do a pretty good job of predicting.  And therefore, you can design a module (abstraction) that works well.
However, it does seem the fate of all abstractions - even the very best - that eventually there will be unforeseen (and arguably, unforeseeable) changes that require breaking the abstraction.  To address this, some abstractions have an escape, where you can get access to a deeper level if you really need it.
This all seems very negative. But I think the truth is we are surrounded by abstractions that work so well that we don't notice them, or realize what they are hiding. We only notice the poor abstractions, so we have a jaundiced view of them.

A: Abstractions are mostly for the benefit of their consumers (e.g., application programmers). The system (designer) programmers have more work to do to make them beautiful and useful, which is why good design is not usually done by beginners.
Maybe you don't like abstractions because they always add complexity? Maybe the systems you've worked on had abstractionitis (over use of abstractions)? They're not a panacea.
The extra work and complexity of a useful abstraction should pay off, but it's hard to know for sure. If you think of an abstraction as a pivot point, then the software design can flex on either side: implementations of the abstraction can be modified without breaking client code, and/or new clients can easily re-use the abstraction to make new things.
You could almost measure the return-on-investment of abstractions by showing that they've been "flexed" over time in one or both of these directions: relatively painless implementation changes and additional new clients.
For example: Using the abstraction of the Socket class in Java, I'm sure my application code from Java 1.2 still works fine under Java 7 (although their may be some performance changes). Since Java 1.2, there have definitely been a lot of new clients that used this abstraction, too.
As for unhappiness with abstractions, if I talked to the developers who maintained the code behind the Socket class, then maybe their lives are not as peachy and rosy as the clients who used Socket to write fun applications. Working on the implementation of an abstraction surely is more work than using it. But that doesn't make it bad.
As for transparency, in a top-down design strategy, total transparency makes for bad design. Smart programmers tend to make the most out of the information they have at their disposal, and the system then becomes tightly coupled. The smallest change of detail (e.g., changing the order of bytes in a data structure) in a module might break some code somewhere else, because a smart programmer used that information to do something useful. David Parnas pointed it out this problem in articles as old as 1971 where he proposed hiding information in designs.
Your reference to ArchLinux makes sense to me if you consider the "inside" of the operating system as being the complex implementation of the abstraction that are the OS to the applications that run on it. Keep it simple in the guts of the abstraction.

A: I'll answer your question with a question; when you drove to work this morning (I'll assume you did in fact do so), did you care exactly how the engine opened valves to let in fuel-air mixtures, and then ignited them? No. You don't care how your car's engine works when you're driving down the road. You care that it does work.
Suppose, one day, your car fails to work. Doesn't start, throws a rod, breaks a belt, inexplicably plows into that concrete barrier through no fault of your own while you were busy texting. Now, you need a new car (at least temporarily). Do you care exactly how this new car works? No. What you care about is first that it does work, and second that you can use the same knowledge and skills that you used to drive your old car to drive the new one. Ideally, it should appear to you that there has been no change in the car you are driving. Realistically, the way this new car works should give you as few "surprises" as possible.
These basic tenets are the core principle behind encapsulation and abstraction. Knowledge of how an object does what it does should not be a requisite to using it to do what it does. Even in computer programming, the details of electrical paths within the CPU running your program are abstracted behind at least half a dozen layers of I/O instructions, drivers, OS software and runtime. Many very successful software engineers write perfectly good code without once worrying about the exact hardware architecture, or even OS build, that will run it. Including me.
Encapsulation/information hiding allows the "don't care how it does, just care that it does" mentality. Your object should expose what is useful to the consumer, in a way that the consumer can easily consume. Now, back in the real world, this doesn't mean that a car shouldn't give the user any information about the inner workings, or that the car should only allow the user the most basic of functionality like the ignition, steering wheel, and pedals. All cars have speedometers and fuel gauges, tachometers, idiot lights, and other feedback. Virtually all cars also have switches for various independent subsystems, like headlights, turn signals, the radio, seat adjustment, etc. Some cars allow for some pretty esoteric user input, like the sensitivity of the limited-slip center differential. In all cases, if you know enough, you can open it up and change things to make it work a slightly different way. But, in most cases, maybe, just maybe, the user shouldn't be able to directly and independently control the fuel pumps from inside the cabin? Maybe, just maybe, the user shouldn't be able to activate their brake lights without actually depressing the brake pedal?
Abstraction allows the "this isn't the same as that, but because they are both X I can use them as I would any X" mentality. If your object inherits or implements an abstraction, your consumers should expect your implementation to produce the same or similar result as other known implementations of the abstraction. A Toyota Camry and a Ford Fusion are both "cars". As such, they have a common set of expected functionality, such as a steering wheel. Turn it counterclockwise, car goes left. Turn it clockwise, car goes right. You can get in any car in the United States and expect the car to have a steering wheel and at least two pedals, the one on the right being the "car goes" pedal and the one in the center being the "car stops" pedal.
A corollary of abstraction is the "theory of least astonishment". If you got behind the wheel of a new car for a test drive, rotated the steering wheel clockwise and the car turned left, you'd be pretty astonished to say the least. You'd accuse the dealer of peddling a POS, and would be unlikely to listen to any of his reasons why the new behavior is "better" than what you're used to, or how well this behavior is "documented" or how "transparent" the control system is. Despite this new car and all the other ones you've driven still being "cars", when driving this car you have to change some fundamental concepts of how a car is supposed to be driven in order to drive the new car successfully. That's typically a bad thing, and it only happens when there is an intuitive advantage to the new paradigm. Perhaps the addition of seat belts is a good example; 50 years ago you just got in and went, but now you have to buckle up, the intuitive advantage being that you don't go through the windshield or into the passenger seat if you get in an accident. Even then, drivers resisted; many car owners cut the seat belts out of the car until laws were passed mandating their use.


text:
Q: AWS SDK V3 SecretsManager: Value null at 'secretId' Below is the code that I'm running via a Lambda function with full SecretsManagerReadWrite permission on its role:
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');

exports.handler = async () => {
  const secretsManagerClient = new SecretsManagerClient({
    region: 'eu-west-2'
  });

  const params = {
    secretId: 'Realitex/APIAccount'
  }
  const command = new GetSecretValueCommand(params);

  try {
    const data = await secretsManagerClient.send(command);
    console.log(data);
  } catch (error) {
    console.log(error, error.stack);
  } finally {
    console.log("Done getting");
  }
}

You can see clearly that I am passing secretId as a parameter to the command sent via the secrets manager client, however this error occurs:
2021-03-17T15:20:39.963Z    0bd9bc3a-47ce-4c57-b583-0df9d9d70b34    INFO    ValidationException: 1 validation error detected: Value null at 'secretId' failed to satisfy constraint: Member must not be null
    at deserializeAws_json1_1GetSecretValueCommandError (/var/task/node_modules/@aws-sdk/client-secrets-manager/dist/cjs/protocols/Aws_json1_1.js:770:41)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async /var/task/node_modules/@aws-sdk/middleware-serde/dist/cjs/deserializerMiddleware.js:6:20
    at async /var/task/node_modules/@aws-sdk/middleware-signing/dist/cjs/middleware.js:12:24
    at async StandardRetryStrategy.retry (/var/task/node_modules/@aws-sdk/middleware-retry/dist/cjs/defaultStrategy.js:56:46)
    at async /var/task/node_modules/@aws-sdk/middleware-logger/dist/cjs/loggerMiddleware.js:6:22
    at async Runtime.exports.handler (/var/task/index.js:14:18) {
  __type: 'ValidationException',
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: 400,
    requestId: '7b22cb52-0345-4c49-bd41-33aa3a1be707',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  }
}

I don't know where else it could be expecting the member 'secretId' as I've tried passing it as a configuration param when initialising SecretsManager, and the docs for API V3 don't suggest anywhere else either.
Any help would be greatly appreciated!

A: I've solved the issue (typical that it's minutes after posting)
The error states that it's expecting a member with key 'secretId', however it needs to be passed as 'SecretId' - note the uppercase first character
After changing the param passed to the constructor of the command to be the latter key, it now works...

A: For future reference - AWS SDK V3 SecretsManager code examples can be found here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/secrets


text:
Q: Bug in the C++ standard library in std::poisson_distribution? I think I have encountered an incorrect behaviour of std::poisson_distribution from C++ standard library.
Questions:

*

*Could you confirm it is indeed a bug and not my error?

*What exactly is wrong in the standard library code of poisson_distribution function, assuming that it is indeed a bug?

Details:
The following C++ code (file poisson_test.cc) is used to generate Poisson-distributed numbers:
#include <array>
#include <cmath>
#include <iostream>
#include <random>

int main() {
  // The problem turned out to be independent on the engine
  std::mt19937_64 engine;

  // Set fixed seed for easy reproducibility
  // The problem turned out to be independent on seed
  engine.seed(1);
  std::poisson_distribution<int> distribution(157.17);

  for (int i = 0; i < 1E8; i++) {
    const int number = distribution(engine);
    std::cout << number << std::endl;
  }
}

I compile this code as follows:
clang++ -o poisson_test -std=c++11 poisson_test.cc
./poisson_test > mypoisson.txt

The following python script was used to analyze the sequence of random numbers from file mypoisson.txt:
import numpy as np
import matplotlib.pyplot as plt

def expectation(x, m):
    " Poisson pdf "
    # Use Ramanujan formula to get ln n!
    lnx = x * np.log(x) - x + 1./6. * np.log(x * (1 + 4*x*(1+2*x))) + 1./2. * np.log(np.pi)
    return np.exp(x*np.log(m) - m - lnx)

data = np.loadtxt('mypoisson.txt', dtype = 'int')

unique, counts = np.unique(data, return_counts = True)
hist = counts.astype(float) / counts.sum()
stat_err = np.sqrt(counts) / counts.sum()
plt.errorbar(unique, hist, yerr = stat_err, fmt = '.', \
             label = 'Poisson generated \n by std::poisson_distribution')
plt.plot(unique, expectation(unique, expected_mean), \
         label = 'expected probability \n density function')
plt.legend()
plt.show()

# Determine bins with statistical significance of deviation larger than 3 sigma
deviation_in_sigma = (hist - expectation(unique, expected_mean)) / stat_err
d = dict((k, v) for k, v in zip(unique, deviation_in_sigma) if np.abs(v) > 3.0)
print d

The script produces the following plot:
You can see the problem by bare eye. The deviation at n = 158 is statistically significant, it is in fact a 22σ deviation!

Close-up of the previous plot.

A: My system is set up as follows (Debian testing):
libstdc++-7-dev:
  Installed: 7.2.0-16

libc++-dev:
  Installed: 3.5-2

clang:
  Installed: 1:3.8-37

g++:
  Installed: 4:7.2.0-1d1

I can confirm the bug when using libstdc++:
g++ -o pois_gcc -std=c++11 pois.cpp
clang++ -o pois_clang -std=c++11 -stdlib=libstdc++ pois.cpp
clang++ -o pois_clang_libc -std=c++11 -stdlib=libc++ pois.cpp

Result:


text:
Q: Add a people group attribute in list programatically I want to add a attribute (Person or Group)  in List through coding,
does any one know how to do it.
thanks

A: [Saboor's comment re-posted as an answer, with minor modifications]
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
  SPListCollection lists = web.Lists;
  SPList list = lists['Guid for List'];
  list.Fields.Add("people", SPFieldType.User, false);
  list.Update();
}

A: Itm["AssignedTo"] = new SPFieldLookupValue(Vti, "");

here vti is USserID or GroupID


text:
Q: How to create C++ template class with 2 datatype parameters based on 2 enum values checking? I have a template class which contains 2 type parameters. While I create the class instance, I need check 2 other enum value to decide the this class type parameter.
enum DataType_t
{
    DATA_TYPE_INT32 = 1,
    DATA_TYPE_FLOAT = 2,
    DATA_TYPE_DOUBLE = 3
    // totally more then 10 type enum value,
};

class MyClassBase
{};

template<typename InputDataType, typename OutputDataType>
class MyClass:public MyClassBase
{
private:
    InputDataType inputData;
    OutputDataType outputData;
public:
    MyClass() {};
    ~MyClass() {};

};

MyClassBase* make_instance(DataType_t inputDataType, DataType_t outputDataType)
{

    switch (inputDataType)
    {
    case DATA_TYPE_INT32:
        switch (outputDataType)
        {
        case DATA_TYPE_INT32:
            return new MyClass<int, int>();
        case DATA_TYPE_FLOAT:
            return new MyClass<int, float>();
        case DATA_TYPE_DOUBLE:
            return new MyClass<int, double>();
        }
        break;
    case DATA_TYPE_FLOAT:
        switch (outputDataType)
        {
        case DATA_TYPE_INT32:
            return new MyClass<float, int>();
        case DATA_TYPE_FLOAT:
            return new MyClass<float, float>();
        case DATA_TYPE_DOUBLE:
            return new MyClass<float, double>();
        }
        break;
    case DATA_TYPE_DOUBLE:
        switch (outputDataType)
        {
        case DATA_TYPE_INT32:
            return new MyClass<double, int>();
        case DATA_TYPE_FLOAT:
            return new MyClass<double, float>();
        case DATA_TYPE_DOUBLE:
            return new MyClass<double, double>();
        }
        break;
    default:
        break;
    }

    return NULL;
}

I can write make_instance function like above, but I feel it is not an elegant way.  Actually, the enum DataType_t define more than 10 data types, If I list them all inside switch case, it will be too complex to maintain.
I wonder whether there is a better approach to handle the scenario? And my project is using C++98, not upgrade to C++11 yet.Thanks.
Regards,
Yanhua

A: This code of yours will force the compiler to implement 100 or more variations of your class, for no gain in performance or readability. This is plain crazy, if you ask me.
One could wonder why you need dynamic instanciation in the first place, but surely you have a pretty good reason...
You could use doubles for your data, of maybe make a specialization for integer values if you require perfect integer precision.
Then you could store the data types, assuming you require some specific processing like displaying the numbers according to the original type, which might not even be necessary.
Forget about C++ magicking your design problems away, that's my advice. This is the kind of language that can produce monstruosities even with careful design, and only more so if you ask it to on purpose.

A: EDIT
I didn't know that's for runtime since your comment, so the solution below does not work for you. (But I let it here is case where it inspires you for a different implementation.
You have to know something: Templates are evaluated a COMPILE time and are therefore not an efficient tool since you are trying to evaluate type at RUNTIME.
You will need to define every possibilities.
Deprecated answer
Solution 1
In this case, why don't you just use using keyword ?
using DATA_TYPE_FLOAT = float;
using DATA_TYPE_INT32 = int;

const auto my_c = MyClass<DATA_TYPE_INT32, DATA_TYPE_FLOAT>();

Solution 2
Change the purpose of your make_ function. Just like the STL does, you should build your object passing parameters which are going to be hold by your MyClass. In your case, you are doing wrong. Here is my solution:
#include <type_traits>

template <typename I, typename O>
class MyClass {

    private:
        I input;
        O output;

    public:

        MyClass(const I& new_input, const O& new_output)
        : input(new_input), output(new_output) {}
};

template <typename I, typename O>
auto make_instance(I input, O output) -> MyClass<typename std::decay<I>::type, typename std::decay<O>::type> {
    return MyClass<typename std::decay<I>::type, typename std::decay<O>::type>(input, output);
}

int main() {
    const auto c = make_instance(4, 3.2);
    return 0;
}


text:
Q: Subtotal=Quantity*Unit_price Typescript I have the form  addProductForm , in this form I want to calculate Subtotal=Quantity*Unit_price.
this.addProductForm = this.fb.group({
      'product_id': new FormControl('', Validators.required),
      'Quantity': new FormControl('', Validators.required),
      'Unit_price': new FormControl('', Validators.required),
      'Subtotal': new FormControl('', Validators.required)
    });

Html Code.
In html code, I want to display subtotale when I write unit_price and Quantity.
<form [formGroup]="addProductForm" (ngSubmit)="onAddProduct()" class="col s12" materialize style="text-align:center">

      <select formControlName="product_type_id" id="product_type_id" materialize="material_select" [materializeSelectOptions]="producttype">
        <option value="" disabled selected>ProductTye*</option>
        <option *ngFor="let item of producttype; let i=index;" [value]="item.product_type_id">{{item.product_type_name}}</option>
      </select>

      <input formControlName="Quantity" id="Quantity " type="number" class="validate">

      <input formControlName="Unit_price" id="Unit_price" type="number" class="validate">

      <input formControlName="Subtotal" id="Subtotal" type="number" class="validate">

    <button id="add_contrat_button" type="submit" class="button button1">
      SUBMIT
    </button>

</form>

Thanx in advance

A: write a common change event for Quantity  and Unit_price input box. In the event, do the computation
this.addProductForm.Subtotal= this.addProductForm.Quantity* this.addProductForm.Unit_price


text:
Q: Pass the_post() as a parameter I would like to take the following code sample
<?php while ( have_posts() ) : the_post(); ?>

<?php the_field('title'); ?>

<?php the_field('desc'); ?>

<?php endwhile; ?>

and convert it to use a function rather than putting all my code in my archive file. I would like to pass the the_post() as a parameter so I have access to all of the fields for a given content type.
function formatMyCustomPost($thePost) {
    $html = "
" . get_field('title') . "
";
    $html .= "
" . get_field('desc') . "
";
    return $html;
}

and call it like this
<?php while ( have_posts() ) : the_post(); ?>
    <php echo formatMyCustomPost(the_post()); ?>
<?php endwhile; ?>

Is this possible?

A: You may not need to pass in the_post(). Calling the_post() sets up the global $post object, and get_field() may also be accessing the global $post object


text:
Q: How to simply deploy Java/JavaFX applicartion on Max OS? I designed a Java application with some JavaFX features, whose ideal target is the Java 8 JRE. The application works fine, and has to be ran on several OS, like Windows, Mac OS or Linux.
The application is designed with Eclipse and JavaFX scene builder.
Thought I manage in installing manually it on Mac OS, I would need a more automated process for end-users: so far, I must copy the files, run a JRE installer if needed and finally launch the application.
Now what I need is some kind of script that would do the job in one click:
- Check whether the appropriate JRE is available or not
- Install or upgrade the appropriate JRE
- Copy the needed files
- Set a shortcut on the desktop
- Launch the application.
Does anybody know which tool I should try ?
Thanks!


text:
Q: AngularJS watch list exclude How do you run a digest loop on manual selected watches? For example I want a directive that displays the current time (with seconds), but I do not want to trigger the digest loop every second. One solution is to update the value outside of angular's digest loop (using jQuery). Other solutions?
Thanks.

A: Your clock directive will probably use $timeout or $interval, which have the following signature:
$timeout([fn], [delay], [invokeApply], [Pass]);
$interval(fn, delay, [count], [invokeApply], [Pass]);

Notice the invokeApply parameter. If you set it to false, angular will skip dirty-checking.

A: One approach to "restrict" the digest effect is to run the digest only on the current scope and its children. This is done with $scope.$digest().
In contrast, $scope.$apply() calls the digest from the root scope, so in that sense it is the same as doing $rootScope.$digest().
EDIT:
If you are using $timeout/$interval, then make sure to set the invokeApply parameter to false, otherwise it will trigger a digest from the root.

A: Use angulars $interval() instead of javascripts setInterval for your clock.
$interval will take care of digest.
https://docs.angularjs.org/api/ng/service/$interval
update:
I actually have a clock directive in the project I'm currently working on:
Directive:
app.directive('clock', ['$interval', 'dateFilter',function($interval, dateFilter) {

return {
  restrict:   'E',
  scope:      {
    format:   '=',
  },
  link: function (scope, element, attrs) {
    var format;
    var stopTime;

    // set the time in the directive
    function setTime() {
      element.text(dateFilter(new Date(), format));
    }

    // update the UI on change.
    scope.$watch(attrs.format, function(value) {
      format = value;
      setTime();
    });

    format = attrs.format;
    updateTime();
    stopTime = $interval(setTime, 1000);

    element.on('$destroy', function() {
      $interval.cancel(stopTime);
    });
  }
};

}]);

Usage:
<clock format="'H:mm'"></clock>

A: I would suggest wrapping your watcher with a debounce utility function.
David Walsh has provided a quite sweet solution.
Here is a simple demo:
angular.module('watchApp', []).controller('watchCtrl', function ($scope) {
    $scope.count = 0;
    $scope.b = Date.now();

    $scope.$watch("b", _debounce(function (b) {

        $scope.$apply(function () {
            $scope.b = Date.now();
            $scope.count += 1;
        })
    }, 1000));
});


text:
Q: Issues with Boom Beach and Clash of Clans My dad and I share an Apple ID (even though I've asked him time and time again to get his own for this reason). I accidentally clicked on both games my dad's account that is on his iPad and now I can't get to my own account. I have tried logging out of the Game Center and logging back in but neither will prompt to switch to my game. I also tried deleting it off my iPhone 6 and clearing it from the Game Center then re-download them and they both just pop up under my dad's account. Any advise to get my account back? Or start a new one?

A: Apps such as Boom Beach and Clash of Clans use Game Center by default, the only way to force it to not use the Game Center account is to temporarily sign out of Game Center then start the app after a clean install. If your old account was not bound to either Facebook or Game Center, there is no definite way to recover it, but you can try by following these steps: http://clashofclans.wikia.com/wiki/Recovering_a_lost_village_that_wasn%27t_linked_to_GC_or_GPlus


text:
Q: $E=mc^2$ explanation needed My question is pretty standard and easy,I wonder all my life how Einstein get energy equation $E=mc^2$.
Also I some videos about that equation on YouTube and some of the peoples said there that the equation $E=mc^2$ isn't full.
Any help will be appreciated.


text:
Q: Ionic PopUp : TypeError: Cannot read property 'confirm' of undefined I would like to code a simple "confirm ionic pop up", but I had this issue that I can't solve. I'm sure if you take a look you'll find it out, because now it's like I was totally blind against it ...
TypeError: Cannot read property 'confirm' of undefined
Here is my code :

// Here is the start of my "directive.js" file, I have one directive and 3 controllers

var myApp = angular.module('app.directives', [])

myApp.directive('activePageHighlight', ['$rootScope', '$state', function($rootScope, $state){

// Something else

}]);

// Here is my controller

myApp.controller('MainCtrl', ['$scope', function ($scope, $ionicPopup, $timeout) {

$scope.info = function(){

var confirmPopup = $ionicPopup.confirm({
    // Here I tried to add $scope, but I'm not sure if is it usefull
    scope:$scope,
    title: 'Consume Ice Cream',
    template: '<button class="button button-primary" ng-click="info()">Confirm</button>'
   });

   confirmPopup.then(function(res) {
     if(res) {
       console.log('You are sure');
     } else {
       console.log('You are not sure');
     }
   });
 };

}]);
<div ng-controller="MainCtrl">

    <button ng-click="info()" class="calm button-block">Info 1</button>

</div>

Thank you !

A: This line:
myApp.controller('MainCtrl', ['$scope', function ($scope, $ionicPopup, $timeout) {

You forgot to inject the $ionicPopup and $timeout service:
myApp.controller('MainCtrl', ['$scope', '$ionicPopup', '$timeout', function ($scope, $ionicPopup, $timeout) {

A: You're only injecting $scope as dependency for your controller, add the rest too and it should work.
myApp.controller('MainCtrl', ['$scope', '$ionicPopup', '$timeout', function ($scope, $ionicPopup, $timeout) {
// ...
}])


text:
Q: Apache Commons CLI 1.3.1: Option coming after another option with multiple arguments is consumed as ARGUMENT I'm using Apache Commons CLI 1.3.1 to process some options and some of the options can take one to unlimited number arguments. A trivia example with two options would be like this
usage: myProgram -optionX <arg1> <arg2> <arg3> < ... > [-optionY]
-optionX <arg1> <arg2> <arg3> < ... >   optionX takes one to unlimited
                                        number of arguments.
-optionY                                optionY is optional

What I found is that the second option optionY is always recognized as an ARGUMENT of the optionX instead of being recognized as an OPTION by itself. That means if you type
myProgram -optionX arg1 arg2 -optionY in the command line, you will get three arguments (arg1, arg2, and -optionY) associated with optionX.
Here is the code that anyone can use to reproduce the problem.
import org.apache.commons.cli.*;

public class TestCli {

public static void main(String[] args) {

    Option optObj1 = Option.builder("optionX")
                            .argName("arg1> <arg2> <arg3> < ... ")
                            .desc("optionX takes one to unlimited number of arguments.")
                            .required()
                            .hasArgs()
                            .build();

    Option optObj2 = new Option("optionY", "optionY is optional");

    Options optsList = new Options();
    optsList.addOption(optObj1);
    optsList.addOption(optObj2);

    CommandLineParser commandLineParser = new DefaultParser();

    try {

        CommandLine cmd = commandLineParser.parse(optsList, new String[]{"-optionX", "arg1", "arg2", "-optionY"});

        System.out.println("--------------------------");
        System.out.println("argument list of optionX: ");
        for (String argName : cmd.getOptionValues(optObj1.getOpt())) {
            System.out.println("arg: " + argName);
        }

        System.out.println("--------------------------");
        System.out.println("value of optionY: " + cmd.hasOption(optObj2.getOpt()));

    } catch (ParseException e) {
        System.out.println("Unexcepted option: " + e.getMessage());
    }

}
}

This is the output you'll see.
--------------------------
argument list of optionX:
arg: arg1
arg: arg2
arg: -optionY
--------------------------
value of optionY: false

Do I miss something here?
Any suggestion will be really appreciated.

A: The problem is that you are putting the long name in the short name of the option.
When you use Option optObj1 = Option.builder("optionX").... or new Option("optionY", "optionY is optional"), you're setting the short name of the option, which is supposed to be only 1 character long.
That work well until you have a multi arguments option. In this case, the parser cannot find "o" (the first letter of your option) in his short option list and you don't have a long name set, so the parser determines that -optionY is just another argument for -optionX.
To solve your problem, just set the long option name of your option and it should work alright.
Example
Option.builder("x").longOpt("optionX")....

Option optObj2 = new Option("y", "optionY", hasArgs, "optionY is optional");


text:
Q: Do integration constants depend on initial/boundary conditions? I am going through an example in my textbook, which solves the boundary value problem
$$u_{x} + xu_{y} = x^{2}$$ such that $u(0,y) = y$.
The author finds the characteristics $\frac{dy}{dx} = x \implies y(x) = \frac{x^{2}}{2} + y_{0}$. Along the curves $(x, y(x))$, we have the ODE:
$$\frac{d}{dx} u(x,y(x)) = x^{2}$$
whose solution is $u(x,y(x)) = u(0, y_{0}) + \frac{x^{3}}{3}$
My problem: why does the solution to the ODE $\frac{d}{dx} u(x,y(x)) = x^{2}$ have integration constant given by $u(0,y_{0})$?

A: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=1$ , letting $x(0)=0$ , we have $x=t$
$\dfrac{dy}{dt}=x=t$ , letting $y(0)=y_0$ , we have $y=\dfrac{t^2}{2}+y_0=\dfrac{x^2}{2}+y_0$
$\dfrac{du}{dt}=x^2=t^2$ , letting $u(0)=f(y_0)$ , we have $u(x,y)=\dfrac{t^3}{3}+f(y_0)=\dfrac{x^3}{3}+f\left(y-\dfrac{x^2}{2}\right)$
$u(0,y)=y$ :
$f(y)=y$
$\therefore u(x,y)=\dfrac{x^3}{3}-\dfrac{x^2}{2}+y$


text:
Q: Gitlab 6.9.2 access denied for deploy key I am trying to clone repository via SSH. Public key for my user is set as deploy key in a project.
I got this error message:
Access denied.
fatal: The remote end hung up unexpectedly

Here is my /var/log/secure for this attempt
Jul 16 11:09:54 gitlab sshd[32217]: Accepted publickey for git from <IP> port 55499 ssh2
Jul 16 11:09:54 gitlab sshd[32217]: pam_unix(sshd:session): session opened for user git by (uid=0)
Jul 16 11:09:54 gitlab sshd[32219]: Received disconnect from <IP>: 11: disconnected by user
Jul 16 11:09:54 gitlab sshd[32217]: pam_unix(sshd:session): session closed for user git

And here is /var/log/gitlab/gitlab-shell/gitlab-shell.log
[2014-07-16T11:09:54.407037 #32220] ERROR -- : API call <GET https://gitlab//api/v3/internal/allowed?action=git-upload-pack&ref=_any&project=group%2Fproject&forced_push=false&key_id=5> failed: 404 => <{"message":"404 Not found"}>.W,
[2014-07-16T11:09:54.407161 #32220]  WARN -- : gitlab-shell: Access denied for git command <git-upload-pack 'group/project.git'> by user with key key-5.

Can you please help me to figure out what's wrong?
For many other deploy keys specified everything works just well.

A: Today I run into the same behavior as you describe. I found an open issue in gitlabhq(https://github.com/gitlabhq/gitlabhq/issues/6908).
The problem is that it can happen that the same public key are two times listed in /home/git/.ssh/authorized_keys. In my case I deleted the deploy key and recreate it to have a better name. In this case the key was not remove from the authorized_keys file.
After I deleted the deploy key and the corresponding lines in the authorized_keys file and recreate the deploy key in my project the access is working.


text:
Q: Is There A Reason lepton flavor violation (LFV) In $B^+$ Meson Decays Can't Be Explained By $K+πº$ Decays? Physicists at Moriond 2021 reported New results on theoretically clean observables in rare $B$-meson decays from LHCb 3.1 sigma away from the SM prediction of lepton universality in the $B+→K+μ+μ- $vs. $B+→K+e+e-$ comparison (i.e. there is apparent lepton flavor universality violation (LFV)). Muons are less common than electrons in the decay products. The ratios seem to be coming up at about 86% of the expected Standard Model number of muon pair decays relative to electron-positron decays.
The simplest answer in the Standard Model would seem be that there are two processes.
One produces equal numbers of electron-positron and muon pair decays together with a positively charged kaon in each case, as expected.  The pre-print linked above states this about this process:

The B+ hadron contains a beauty antiquark, b, and the K+ a strange
antiquark, s, such that at the quark level the decay involves a b → s
transition. Quantum field theory allows such a process to be mediated
by virtual particles that can have a physical mass larger than the
mass difference between the initial- and final-state particles. In the
SM description of such processes, these virtual particles include the
electroweak-force carriers, the γ, W± and Z bosons, and the top quark.
Such decays are highly suppressed and the fraction of B+ hadrons that
decay into this final state (the branching fraction, B) is of the
order of 10−6.

A second process with a branching fraction of about 1/6th that of the primary process produces a positively charged kaon together with an electromagnetically neutral particle that has more than about 1.22 MeV of mass (enough to decay to a positron-electron pair), but less than about 211.4 MeV mass necessary to produce a muon pair when it decays.
It turns out that there is exactly one such known particle fundamental or composite, specifically, a neutral pion, with a mass of about 134.9768(5) MeV. About 98.8% of the time, a πº it decays to a pair of photons and that decay would be ignored as the end product doesn't match the filtering criteria. But about 1.2% of the time, it decays to an electron-positron pair together with a photon, and all other possible decays are vanishingly rare by comparison.
So, we need a decay of a B+ meson to a K+ meson and a neutral pion with a branching fraction of about (10-6) * (1/6) * (1/0.012)= 1.4 * 10-5.
It turns out that B+ mesons do indeed decay to K+ mesons and neutral pions with a branching fraction of 1.29(5) * 10-5 which is almost exactly what it needs to be to produce the apparent violation of lepton universality.
It also appears to me that the theoretical calculation of the K+µ+µ- to K+e+e- ratio isn't considering this decay, although it seems mind boggling to me that so many physicists in such a carefully studied process would somehow overlook the B+ --> K+πº decay channel impact on their expected outcome, which is the obvious way to reverse engineer the process.
I looked at the methodology section of the paper on event selection and didn't see anything showing any kind of event selection that would weed out πº decays to electron-positron pairs.
Does this make sense, or am I missing something?

A: I am not an expert in this area, but I see that they apply a cut on the invariant mass-squared of the two leptons: $$1.1 < q^2 < 6.0\,\mathrm{GeV}^2/c^4.$$
The pion mass (squared) is way outside this cut, and so I suppose that the contribution from that decay mode doesn't pollute their measurement, though they don't say so explicitly. [Note that on page 3 they do discuss the value of the cut for excluding other resonances such as the $J/\psi$ or $\phi(1020$)]


text:
Q: Lasagne dropoutlayer does not utilize GPU efficiently I am using theano and lasagne for a DNN speech enhancement project. I use a feed-forward network very similar to the mnist example in the lasagne documentation (/github.com/Lasagne/Lasagne/blob/master/examples/mnist.py). This network uses several dropout layers. I train my network on an Nvidia Titan X GPU. However, when I do not use dropout my GPU utilization is approximately 60% and one epoch takes around 60s but when I use dropout my GPU utilization drops to 8% and each epoch takes approximately 600s. This is regardless of the dropout rate is set to 20% or 0.1%.
Initially I thought it was due to the random number generator (RNG) used to generate the dropout mask, that did not run on the GPU. However, in the code (https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/noise.py) it seems like rng_mrg is used, which should be running on the GPU based on this link: http://deeplearning.net/software/theano/tutorial/examples.html#other-implementations
Running the theano profiler shows that "theano.sandbox.rng_mrg.mrg_uniform" takes up 86.7% of the execution time, which I do not understand.
If anyone has an idea of what kills my GPU utilization I would appreciate it.

A: If you look at the code for mrg_uniform, you can see that it is a pure python CPU implementation of the random generator. You can also see that there is a GPU version of that same generator, but the code you are running apparently does not use it.
So the answer isn't that your GPU utilisation is going down so much as your CPU utilisation is greatly increasing because you are using a pure Python random generator. The solution would obviously be to work out how to switch to a GPU accelerated random generator.

A: As pointed out by talonmies the problem was that lasagne was using the CPU version of the RNG (mrg_uniform) and not the GPU version (GPU_mrg_uniform).
I have not yet found an elegant solution but the following two hacks solves the problem.
Either change line 93 cuda_enabled = False to cuda_enabled = True in
https://github.com/Theano/Theano/blob/master/theano/sandbox/cuda/__init__.py

or
Change line 57
self._srng = RandomStreams(get_rng().randint(1, 2147462579))
to
self._srng = "RandomStreams(get_rng().randint(1, 2147462579),use_cuda = True) in https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/noise.py
I also believe you should be able to do the same by simply typing theano.sandbox.cuda.use(enable_cuda=True) directly in the main script. However, this did not for some reasons not work for me.


text:
Q: How to implement ParaUnity plugin? I'm trying to implement this Paraview plugin for Unity. I've spent the whole day just trying to get through the dev setup steps listed on that page. I've never used cmake before, have only taken a few comp sci classes, and have limited experience using the command prompt.  I'm hoping that someone can help me get through these instructions on my windows 10 machine.
So far on step 1 I've changed the first command from

./configure.exe -prefix "C:\Qt\4.8.5" -debug-and-release -nomake
  examples -nomake tests -nomake demos -opensource -confirm-license

to

C:\Qt\4.8.5\configure.exe -debug-and-release -nomake examples -nomake
  tests -nomake demos -opensource -confirm-license

Subbing the first command because I was getting an error that '.' is not a valid command and removing the -platform option because I couldn't find a valid platform that the command accepted.  When I entered 'nmake' I got the following errors:

c:\qt\4.8.5\src\corelib\codecs\qisciicodec_p.h(56): fatal error C1083:
  Cannot open include file: 'QtCore/qtextcodec.h': No such file or
  directory qlatincodec.cpp
c:\qt\4.8.5\src\corelib\codecs\qlatincodec_p.h(56): fatal error C1083:
  Cannot open include file: 'QtCore/qtextcodec.h': No such file or
  directory qsimplecodec.cpp
c:\qt\4.8.5\src\corelib\codecs\qsimplecodec_p.h(56): fatal error
  C1083: Cannot open include file: 'QtCore/qtextcodec.h': No such file
  or directory qtextcodec.cpp
c:\Qt\4.8.5\mkspecs\win32-msvc2003\qplatformdefs.h(53): fatal error
  C1083: Cannot open include file: 'qglobal.h': No such file or
  directory qtsciicodec.cpp
c:\qt\4.8.5\src\corelib\codecs\qtsciicodec_p.h(85): fatal error C1083:
  Cannot open include file: 'QtCore/qtextcodec.h': No such file or
  directory qutfcodec.cpp
c:\qt\4.8.5\src\corelib\codecs\qutfcodec_p.h(56): fatal error C1083:
  Cannot open include file: 'QtCore/qtextcodec.h': No such file or
  directory
Generating Code...
NMAKE : fatal error U1077: '"C:\Program
  Files (x86)\Microsoft Visual
  Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.EXE"'
  : return code '0x2' Stop.
NMAKE : fatal error U1077: '"C:\Program
  Files (x86)\Microsoft Visual
  Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\nmake.exe"'
  : return code '0x2' Stop. NMAKE : fatal error U1077: 'cd' : return
  code '0x2'
  Stop.

Note that I did add C:\Qt\4.8.5\bin into the PATH environment variable like he recommended.  Since this step was optional, I moved on to step 2 to see if I could get through that.
I ran mkdir build and cd build inside of C:\Program Files\ParaView 5.5.1-Qt5-Windows-64bit and then ran

C:\Program Files\ParaView 5.5.1-Qt5-Windows-64bit\build>cmake -G "Visual Studio 15 2017" -DQT_QMAKE_EXECUTABLE="C:\Qt\4.8.5\bin\qmake.exe" ..

Changing the original command which had "Visual Studio 12 2013"
I got the error

CMake Error: The source directory "C:/Program Files/ParaView 5.5.1-Qt5-Windows-64bit" does not appear to contain CMakeLists.txt.

Searched around online, found nothing I could understand on how to fix this error, and fixed it by making a copy of "CMakeLists.txt" in the ParaView 5.5.1-Qt5-Windows-64bit directory.  Ran it again and got the errors

CMake Error at CMakeLists.txt:56 (include):   include could not find load file:
C:/Program Files/ParaView 5.5.1-Qt5-Windows-64bit/Source/Checks/cm_c11_thread_local.cmake

CMake Error at CMakeLists.txt:68 (include):   include could not find
  load file:
C:/Program Files/ParaView 5.5.1-Qt5-Windows-64bit/Source/Checks/cm_cxx17_check.cmake

CMake Error at CMakeLists.txt:86 (include):   include could not find
  load file:
CompileFlags.cmake

CMake Error at CMakeLists.txt:89 (include):   include could not find
  load file:
C:/Program Files/ParaView 5.5.1-Qt5-Windows-64bit/Source/Checks/cm_cxx_features.cmake

CMake Error at CMakeLists.txt:92 (message):   The C++ compiler does
  not support C++11 (e.g.  std::unique_ptr).

Which is where I now stand.  Any help on any of these issues would be greatly appreciated.

A: I'm facing similar problems building and compiling ParaView and the ParaUnity-Plugin.
I was not able to build Qt aswell. As a workaround I downloaded and installed Qt 4.8.7 from Anaconda.
Have you succeeded in building the plugin?


text:
Q: Cant save SQL output to a File in Apache Camel I been trying this camel-sql example to fetch some rows from the back-end oracle.
Datasource definition:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@localhost:port:sid"/>
    <property name="username" value="username"/>
    <property name="password" value="password"/>
</bean>

Routes Definition:
<route id="QueryTable">
    <from uri="timer:foo?period=5s"/>
    <to uri="sql:{{sql.selectOrder}}"/>
    <to uri="file:target/data/?fileName=data.txt"/>
</route>

It seems to fetch the row properly, but, does not create the file and reports the following exceptions. Any help would be highly appreciated.

at org.apache.camel.impl.converter.BaseTypeConverterRegistry.mandatoryConvertTo(BaseTypeConverterRegistry.java:198)
      at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:105)
      ... 16 more

A: http://camel.apache.org/sql-component.html

For select operations, the result is an instance of List<Map<String, Object>> type, as returned by the JdbcTemplate.queryForList() method.

You received List<Map<String, Object>> as result of the query. If you like to save this results to file, you have to split list by records (use splitter), convert one record to string (maybe you can use some sort of template, or just join to string fields values) and save (append) this string to file.

A: Thanks for the kind help. Here is what I used to save the resultSet to a file.

<from uri="timer:foo?repeatCount=1" />
    <to uri="sql:{{sql.selectOrder}}"/>
    <marshal>
     <csv delimiter="|" />
    </marshal>
 <to uri="file://target/test.csv?fileName=data.txt" />

And of course, pom.xml has to have the following dependency added.

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-csv</artifactId>
 </dependency>


text:
Q: Can only log in via service name in SQL developer [Oracle DB] So I dl and installed Oracle Db 21c, the latest version. I connect to it via SQL developer using the default system account. The SID was XE when I connected using SQL developer, when I tried to make a new user I encounter an error. After searching it seems I had to alter my session to a plugable database so I alter my session to XEPDB1 and was able to successfully create the user.
Now I can connect to the DB with that user but if I use the SID of XE it says invalid login information but if I switch to service name and put XEPDB1 it works. However I have a program that populate it with the data I need but the program only takes SID for the connection. So do I find the SID I should be using to log into the new account I created?
Tried using XEPDB1 as SID but that doesn't work. I expect to be able to connect to this new user I created with an SID instead of the service name.


text:
Q: Cannot Intospect reference token by other client I have IDS4 (resource ids) with users on single host
options.ApiName = "ids";
options.ApiSecret = "secret";

and client (clientId cl1) with PasswordFlowCredentials.
Client has scope ids.
When I get JWT token with login-password by cl1 I have access to controllers on ids. But if I get reference token I cannot access.
Introspection endpoint return 401 because client_id=ids but token from cl1.
token=15cf93dd255db79a46141c9403f86a71f81d797b2e7649bdd56e10f860c9afde&client_id=ids&token_type_hint=access_token&client_secret=secret
Token content from PersistedGrants (short)

    {"CreationTime":"2019-01-11T11:12:37Z","Lifetime":900000,"AccessToken":
    {"Audiences":
    ["https://localhost:5000/resources","ids"],
    "Issuer":"https://localhost:5000","CreationTime":"2019-01-11T11:12:37Z",
    "Lifetime":90000,"Type":"access_token","ClientId":"cl1",
    "AccessTokenType":1,"Claims":
    [{"Type":"client_id","Value":"cl1","ValueType":"http://www.w3.org/2001/XMLSchema#string"},
    {"Type":"scope","Value":"ids","ValueType":"http://www.w3.org/2001/XMLSchema#string"},
    {"Type":"sub","Value":"5eb745a6-21ab-4f69-941d-0295f9a9e468","ValueType":"http://www.w3.org/2001/XMLSchema#string"},

Where is error?
How can I validate reference token?

A: client_id in introspection request is not client_id. There is must be Resource Id from [dbo].[ApiResources] and secret from [dbo].[ApiSecrets]


text:
Q: Activity not opens on notification clicked I am new to android programming please help me out what I am missing.
I receive notification but my messageActivity is not opened
NotificationManager notificationManager = (NotificationManager)
                                    getSystemService(NOTIFICATION_SERVICE);
                            NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(getApplicationContext())
                                    .setContentTitle("Message from " + name)
                                    .setContentText(message)
                                    .setAutoCancel(true)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setSound(soundUri);
                            if (strVibratePreference)
                                mbuilder.setVibrate(new long[]{100, 100});
                            notificationManager.notify(110, mbuilder.build());
                            Intent intent=new Intent(MessageService.this,MessageActivity.class);
                            intent.putExtra("name",name);
                            intent.putExtra("phno",_from);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            PendingIntent pendingIntent = PendingIntent.getActivity(MessageService.this,0,intent,0);
                            mbuilder.setContentIntent(pendingIntent);

A: add this end code
Notification n = mbuilder.build();
notificationManager.notify(YOUR_NOTIF_ID, n);

A:   Intent intent = new Intent(MessageService.this, MessageActivity.class);
                            intent.putExtra("name",name);
                            intent.putExtra("phno",_from);
                            PendingIntent pIntent = PendingIntent.getActivity(MessageService.this, (int) System.currentTimeMillis(), intent, 0);

                            // Build notification
                            // Actions are just fake
                            Notification noti = new Notification.Builder(MessageService.this)
                                    .setContentTitle("New mail from " + "test@gmail.com")
                                    .setContentText("Subject")
                                    .setContentIntent(pIntent)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .build();

                            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            // hide the notification after its selected
                            noti.flags |= Notification.FLAG_AUTO_CANCEL;

                            notificationManager.notify(0, noti);


text:
Q: Extend size of Ubuntu on Flash Ubuntu 18.04.02 LTS was installed on 64GB flash disk.
When boot for that flash disk and check the size of the partition, it is only 6.4 GB.
What is the procedure to follow so could use all the disk?


text:
Q: List sudo users in centos How do I list all sudo users at CentOS server?
There are many groups(root, wheel, adm etc) at server, and have users in it. I am looking an easy way/command to find users in all groups who have sudo access.
Note: My user also have sudo access. And I am using 64-bit CentOS release 5.2 (Final).

A: Try this:
for USER in `cut -d: -f1 /etc/passwd`
do
  sudo -U $USER -l
done

A: What is wrong with sudo cat /etc/sudoers and maybe getent group <groupname> to get usernames of group members?

A: When adding users with sudo permissions on centos7, its advised to add them to the wheel usergroup which by default has sudo permissions with
sudo gpasswd -a <user_name> wheel

Following @Sven 's answer, does the trick for centos7.
getent group wheel


text:
Q: SHA-256 Hash and base64 encoding With the string "123456Adrian Wapcaplet" I need to

*

*generate the SHA-256 hash

*take the least significant 128 bits of the hash

*represent these bits in base64 encoding

I need help with #1 and #3. Below is how I generate this in Linux
$ echo -n "123456Adrian Wapcaplet" | shasum -a 256 | cut -c33-64 | xxd -r -p | base64

jNWe9TyaqmgxG3N2fgl15w==

A: Install the pgcrypto extension:
create extension pgcrypto;

Then you can use the digest function to do sha256. The rest of the functions you'll need are built in:
select encode(substring(digest('123456Adrian Wapcaplet', 'sha256') from 17), 'base64');

Note that there's an implicit cast from text to bytea performed here when calling digest. It will use the default encoding for the database. To avoid problems due to environmental differences you can specify the encoding for the conversion:
digest(convert_to('123456Adrian Wapcaplet', 'utf8'), 'sha256')


text:
Q: Other ways of customizing Unity web player I'm using the free version of Unity. I saw that there's a way around custom in-game loading screens with "Application.GetStreamProgressForLevel" instead of "Application.LoadLevelAsync".
I know you can change it in Unity Pro; is there a method of changing the screen in the free version?

A: From the docs:

"[M]odifying the loader images is only possible with Unity Pro."

Unfortunately, there's no way around it with the free version.


text:
Q: Реализация алгоритма Ли Есть ошибка в коде(acces violation),не понимаю почему она выскакивает.Портировал код с вики с си++ на делфи.
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, StdCtrls;

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
const
  W=10;
  H=10;
  wall=50;
  blank=0;

var
  Form1: TForm1;
  Px:array [0..W*H{+1}] of Integer;          //убрал в коммы до того,как скинуть тебе,но не помогло
  Py:array [0..W*H{+1}] of Integer;
  len:Integer;
  grid:array [0..H{+1},0..W{+1}] of Integer;

implementation

{$R *.dfm}

function Proverka(ax,ay,bx,by:Integer):Boolean;
const
  dx:array[0..7] of Integer = (1,1,-1,-1,0,1,-1,0);
  dy:array[0..7] of Integer = (1,-1,-1,1,1,0,0,-1);
var
  d, x, y, k, iy, ix:integer;
  stop:Boolean;
begin

  if ((grid[ay,ax] = wall) or (grid[by,bx] = wall)) then Result:= false;

  d := 0;
  grid[ay,ax] := 0; //стартовая ячейка

  repeat
    stop := true;
    for  y := 0 to H do
      for  x := 0 to W do
        if  grid[y,x] = d then
           for  k := 0 to 8 do
           begin
             iy:=y + dy[k];
             ix:=x + dx[k];
             if  ((iy >= 0) and (iy < H) and (ix >= 0) and (ix < W) and (grid[iy,ix] = BLANK )) then
               stop := false;
               grid[iy,ix] := d + 1;

           end;
        Inc(d);
  until ((not stop) and  (grid[by,bx] = BLANK));

  if (grid[by,bx] = BLANK) then Result:= false;

  len:=grid[by,bx];
  x := bx;
  y := by;
  d := len;

   while ( d > 0 ) do
   begin
     px[d] := x;
     py[d] := y;                   // ?????????? ?????? (x, y) ? ????
     Dec(d);

     for k := 0 to 8 do
       iy:=y + dy[k];
       ix := x + dx[k];

       if ( (iy >= 0) and (iy < H) and (ix >= 0) and (ix < W) and (grid[iy,ix] = d)) then
         x := x + dx[k];
         y := y + dy[k];
         break;
    end;

  px[0] := ax;
  py[0] := ay;
  Result:=True;

end;
procedure TForm1.Button1Click(Sender: TObject);
var
  i,j:Integer;
begin
  for i:=1 to StringGrid1.ColCount-1 do
  begin
    StringGrid1.Cells[0,i]:=IntToStr(i);
    StringGrid1.Cells[i,0]:=IntToStr(i);
  end;

  for i:=1 to StringGrid1.ColCount-1 do
    for j:=1 to StringGrid1.RowCount-1 do
      StringGrid1.Cells[i,j]:='0';

  with StringGrid1 do
  begin
    Cells[4,4]:='50';
    Cells[4,5]:='50';
    Cells[5,5]:='50';
    Cells[5,6]:='50';
    Cells[6,6]:='50';
    Cells[6,7]:='50';
    Cells[7,7]:='50';
    Cells[7,8]:='50';
  end;

 for i:=1 to 10 do
   for j:=1 to 10 do
     grid[i,j]:=StrToInt(StringGrid1.Cells[i,j]);

  Proverka(8,3,3,6);
end;

end.


text:
Q: How to deploy basic java application I am quite new to java applications in a production environment and have never deployed.
I have an application that connects to a mysql database, reads in data, preforms some NLP and other data manipulation, then saves the data back to the mysql DB.
The application is to be deployed on a rackspace cloud server and run every couple of hours (maybe with a cron job?).
I've been looking into using maven to help with the build for deployment, but I have no idea if that is the right tool to use or if to build a .war or .jar.

A: Basics - Deploy as an executable Jar if at all possible (or some kind of executable container).  Will simply make your life simpler when it comes to things like setting up the class path.
I've not used Maven before, but we are looking into to help us manage a rather large and cumbersome dependency chain.  As I understand, Maven's build process is rather good, but again, I've never used it.

A: If your project is simple, better go with a small Apache Ant script to build it. Use the generated jar and put it in a location in the server. Use a small unix shell script to trigger the main class in the jar. Add this script to the cronjob.
PS: Since this is production, please have a deployment plan ready with all the steps to follow. Example:

*

*Login to server with so and so username

*cd /path/to/the/jar

*cp xxx.jar /deployment/path/bin

*crontab ... etc etc..


text:
Q: How to get only the exact list of events using the core_calendar_get_calendar_monthly_view The response using this function is not ideal for getting just the events, the response will return all the data you want if you will create the UI for the calendar, I just want the response to be like the response using the core_calendar_get_calendar_events just the list of the events.

Just like this, but this will return all the events regardless of the date. It's not accepting year and month parameters like in core_calendar_get_calendar_monthly_view
I tried doing this. Is there any other way?

A: Found it. You can use core_calendar_get_calendar_events
https://moodle.org/mod/forum/discuss.php?d=253940
just add these paremeters if you want to specify the date range.
&options[timestart]=1391212800&options[timeend]=1409529599


text: Q: With ArcGIS Solutions, what is the difference between Jupyter Notebooks and the Notebook Server? Several solutions now require Notebook server Several solutions now require a Notebook Server as Part of your Portal environment.  Is it truly a requirement or can Jupyter Notebooks work as well?