text:
Q: Calculate 4 newest comments per post in query I have the following query to get posts with calculated number of likes and calculated user who created the post:
MATCH (post:Post)
WITH post
ORDER BY post.createdAt DESC
MATCH (user:User)-[:CREATED]->(post)
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes
SKIP {skip}
LIMIT {limit}

What I need is to calculate last 4 created comments for every post. If there is 0 comments, I would like to have returned empty array and there is also possibility that post has less then 4 comments, so will just show array of these comments.
I need smth like this (I added imaginary query):
MATCH (post:Post)
WITH post
ORDER BY post.createdAt DESC
MATCH (user:User)-[:CREATED]->(post)
[MATCH (comment:Comment)-[:BELONGS_TO]->(post:Post) ORDER BY comment.timestamp ASC]
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes,
       comment AS comments
SKIP {skip}
LIMIT {limit}

A: This might do what you want:
MATCH (user:User)-[:CREATED]->(post:Post)
WITH user, post
ORDER BY post.createdAt DESC
OPTIONAL MATCH (post)<-[:BELONGS_TO]-(comment:Comment)
WITH user, post, comment
ORDER BY comment.timestamp DESC
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes,
       COLLECT(comment)[0..4] AS latestComments
SKIP {skip}
LIMIT {limit}

It returns the posts (in descending order), and for each post it returns the creator's name, the number of likes, and a collection of (up to) the last 4 comments. It uses OPTIONAL MATCH to ensure that it returns posts that have no comments at all.


text:
Q: Is programming as a profession in a race to the bottom? It seems to me that the programming industry is in a race to the bottom.  If we take the practices of:

*

*Not taking time to implement best practices

*Using other's people code as much as possible (custom code as a liability)

*Using increasingly higher level languages to improve productivity

*GUI based development "tools" that greatly simplify "programming" and do not require people to understand the plumbing behind the code

These things imply to me that we are in a race to becoming like any other office worker. It is in the employer's interest for things to not require skill (easier to replace), for things to be prebuilt (less project time).
My point here is that a) is there a misalignment between skill and the economic interests of the employer? and b) if there is, how do you mitigate it to enforce professional standards?

A: I think you've asked a very poignant question.
Creating GUI coding tools puts programmers out of a job as much as robots put assembly line workers out of a job. In my opinion, while there is a loss of jobs, there is also a shift in where the next jobs are.
The technology to get a task done changes, but the task still needs to be completed: The cars still need to be made/assembled before they can be driven; the code/business logic still needs to be put together for the application to function.
Shifts in technology present choices for programmers: Learn GUI-based programming or program GUI tools ... or ...  something else entirely.
There can be a misalignment between the skills of the employees and the interests of the employer, but not for long, especially if the employer is savvy. It is therefore in the best interest of both employer and employee that they pursue what is to their mutual benefit. But one will inevitably be ahead of the other. Hopefully it is you (-:
Best wishes,
KM

A: To the trends you mention I would add one more, which IMHO explains them:
There is vastly more programmers (needed) than ever.
The amount of tasks which require or include programming is ever increasing, and in an even higher rate than the number of programmers. Nowadays there are several microchips in an average car. In 5 years there may be a chip in your fridge and your toaster. In 10 years, your underwear?... And someone needs to produce all that software to make these work. So there is every possible effort made to automate whatever is automatable, and to improve "productivity" (however it is defined). And more and more fresh brains are recruited.
This implies that the majority of today's active programmers are inexperienced and/or ill prepared for their job. It takes several years to get to an adequate level of experience and it takes constant learning to keep yourself there. The bottom line is, more and more of the programming jobs are becoming less and less challenging. But there is still enough challenges for anyone who is looking for them.
Let me play the devil's advocate against your points above:

Not taking time to implement best practices

A lot of people don't, a lot of people do. Tenish years ago when I first discovered unit testing and the agile approach, none of my colleagues had the slightest idea what it was. Nowadays it is almost standard material at universities, so many fresh graduates already understand it.

Using other's people code as much as possible (custom code as a liability)

As opposed to what? Reinventing the wheel? Or using other people's code to avoid that?
I think it is important to note that we are paid (mostly) to solve problems, and writing code is not the end, only the means to that. If a problem can be solved without writing a single line of code, it still makes the client happy. Especially if this way we manage to produce a more reliable solution faster and cheaper. I don't see any problem with that.

Using increasingly higher level languages to improve productivity

As opposed to coding everything in assembly? ;-)

GUI based development "tools" that greatly simplify "programming" and do not require people to understand the plumbing behind the code

IMHO any tool can be misused. Which is not to say that GUI builders were necessarily perfect or even good - most (or at least some) of them are usable within their limits. But if someone doesn't know those limits, is it a problem of the tool or its user?
In general, I believe (although have no evidence to prove it) that back in the punch card and machine code days, roughly the same proportion of existing code was horrible as now, just both

*

*the overall amount of code, and

*the chances of outsiders ever seeing such code

was much much less.
Now, with the Internet and the Daily WTF, we get exposed to the worst examples day by day. It's a bit like watching all the news about terrorism and earthquakes and divorcing celebs, and crying out how dangerous and immoral this world became.

A: Assembly and FORTRAN programmers probably said the same things when structured programming and widespread interpreters were coming into the picture.
At the end of the day, software is a creation meant to automate something which previously had been done by hand. An accounting department in a moderate corporation would have previously required dozens of people, now all that work can be accomplished by the work of one or two. As a result, the goal posts have moved and we now expect that extra capability standard from an accountant.
It takes Pixar longer to render movies than ever before. Despite the enormous increase in computing speed, along with it, the animators have demanded ever increasing complexity and detail in their scenes. Toy Story caliber animation is not acceptable in 2010 like it was in 1995. As their tools have advanced, so have their capabilities and thus expectations.
When drag and drop or other programming methodologies are common-place, the world will demand solutions to even more challenging and complex problems, and they will need programmers using those newer fancy tools to solve them. The goal posts will move.

A: While I agree with most of the answers that point out that there will still be plenty of work to do I will give a different answer for you to consider:
Yes it is, and it SHOULD be
I am here to design a solution to problems that others cannot.  Anything in the toolset that takes my time away from solving problems to deal with all the small details of how to implement my design is waste.
The only reason I would fear going to a higher level language or a simpler and more abstracted tool is that those tools often make assumptions that get in my way and require my time to work around the assumptions to get the desired implementation.
There are always more problems to solve than there are good problem solvers.  Even if the entire dev chain became so simple preschoolers could use it most of the solutions designed would be insufficient or inefficient enough that people would pay for a better solution because most people are just bad at seeing the correct solution to issues with all the edge cases and what-ifs that you need to consider to make a good solution.
Our jobs are to solve problems better than most of the rest, the toolchain complexity is not terribly relevant in the big picture view as long as it gets out of the way and lets you build and you build something good.

A: You summarize the situation correctly, but completely misinterpret the meaning.
As software becomes more powerful, the tasks it takes on scale with it.  So sure, it may not be necessary nowadays to be a database programmer to create a phone contact database when you can use Access.  And it may not be necessary to be a web programmer to set up a blog when you can just go to wordpress.  But, while 15 years ago it would be necessary to be a programmer to do those things, what programmers do now is orders of magnitude greater than what could be done 15 years ago.
Let me put it this way, 100 years from now, it will be trivial to set up a system as complex as facebook or google.  I'm not talking their web pages, I mean their data centers.  Anyone will be able to do it.  It'll be built into phones, assuming we even still use them.  BUT, there will still be programmers, and while they may not be working on such 'trivial' systems 100 years from now, they will be working on systems so much more complex and sophisticated that no one here can even begin to comprehend their scope and scale.  And those systems, like the ones now, will be far out of reach of the average office worker because some people, called programmers, will chose to specialize in pushing the technology of that era to its extremes.

A: I've read that sort of thing for forty years now, and I wasn't in on the beginning of the predictions.  It hasn't happened yet.
COBOL was the original development tool intended to remove the need for business programmers, and was a much higher-level language than assembler.  Code libraries (to avoid having to write one's own code) are of similar antiquity.
Every so often, something comes up that allows nonprogrammers to do something more like programming work.  There were the 1980s "fourth-generation languages", fancy spreadsheets like Excel, report generators, and the like.  What they have uniformly done, if successful, is remove some of the scutwork from programming and allow programmers to do other, more interesting, things.
This pattern won't last forever, but I'm going to need something more than theoretical arguments and predictions to convince me that programming is indeed going downhill.
The issue from COBOL to modern development tools is that they don't replace the ability to take an inexact specification and turn it into something precise and useful.  That is the fundamental ability of programmers, and why we're not going away for a long time.

A: Even though programming technologies may change, the underlying complexity of a software product is still there.  If software could be written completely using diagrams or flow charts (or some other 'simple' way), all of the complexity of the software still needs to be understood and addressed.  For that reason, it is important for employers to have programmer(s) who know the company's products inside-out in order to update them or add new features.  And it can take quite a while for employees to learn a software product.

A: No matter what you can automate or pull off the shelf, most packaged software falls into two categories:

*

*It's simple to use, but it doesn't quite match what the business really needs

*It's highly customizable, but it takes a specialist to understand and leverage the customization

I guess I forgot the third It's standard productivity software (email, browser, word proc, etc. The software in category one leads to businesses hiring software developers to customize the off the shelf software (if that's possible). The category 2 software, well they might as well hire a developer because the person who knows that customizable system inside and out is either highly sought after (think SAP, PeopleSoft, etc.) or a dying breed (think any system similar to SAP and PeopleSoft that doesn't quite have the same market penetration).
There will always be a need for developers. What I am seeing is that more of what used to be manual, tedious, repetitive work has become automated (think writing code for data access by hand versus using an O/RM). This allows developers to deliver more value to the business with less effort.

A: I don't take your arguments:

*

*Not taking time to implement best practices

except that.

*

*Using other's people code as much as possible (custom code as a liability)

Code reuse is a best practice. Used code is tested. Of course you should use code from good sources, which is maintained and used by many.

*

*Using increasingly higher level languages to improve productivity

Productivity isn't bad per se - is it?

*

*GUI based development "tools" that greatly simplify "programming" and do not require people to understand the plumbing behind the code

If the tool does the job: Use it. If not: refuse it. If the promise holds, and people really don't need to understand the code - well done! You seem to tell that this is a promise which doesn't hold?
(The numbers here are automatically rerendered wrong. :) )

A: Visual programming is no less valid or deserving of scorn than text based programming.
There are certain deficits and challenges when programming visually, but the underlying component plumbing being potentially perilous when ignored is not monopolized by visual components and more relevantly, visual designers.  Underlying plumbing being ignored is a risk to any development.
If you get a chance to try Labview, you might see the potential (or even a specialized variant in the Lego NXT environment).  While not without flaws or shortcomings, there are inherit benefits.  Seeing is believing.

A: Programming practices not only increase productivity and reduce costs for certain types of development (your race to the bottom), but increase application capabilities and customer expectations (thus encouraging a race to the top).  Witness the bonuses that Goole and Facebook are paying to get top technologists.

A: There's no other profession that deals with existence engineering that strives towards change as much as programming. As soon as you simplify something, you just open a can to new problems that breed new ideas.
So I wouldn't soil other people's endeavors to share code and solutions in order to help us move towards novel challenges, ideas and user experiences with the individual practitioner's bad practices, bad habits and manners devoid of humanism.

A:  If we take the practices of:

*

*Not taking time to implement best practices

*Using other's people code as much as possible (custom code as a liability)

WTF?  Did you mean for this list to be inconsistent?  Lists should come from the same side for each element rather than switching back and forth without warning.  Thus your list should read:
 If we take the practices of:

*

*Not taking time to implement best practices

*Not using other's people code as much as possible (custom code as a liability)

redpajama_set_name: RedPajamaStackExchange


text:
Q: using a non literal as a template string in javascript Given this?
var v = 10;
var template = "testing ${v}...";

How do I achieve the same result as the following template string.
var result = `testing ${v}...`;

The template string is stored in a variable, and not a literal template string.
Is there a method to apply a template string when the template string is stored in a variable, and not literal?

A:

var v = 10;
var template = "testing ${v}...";

var output = template.replace("${v}", `${v}`);

alert(output);


text:
Q: DataTables: re-render table dynamically with new data? I'm using DataTables v1.10.15 as part of a single-page JavaScript application, and would like to update the table with new data (loaded via Ajax) when the user changes a dropdown.
This is my code:
 custname.on("change", function(e) {
        $('#titles').DataTable().rows().invalidate('data');
        $('#titles').DataTable({
            "ajax":{
              "url": "data/" + e.added.slug + ".geojson",
              "dataSrc": "features"
            },
            "columns": [
              { data: "properties.name" },
              { data: "properties.address" }
            ],
            "deferRender": true
        });
        $('#titles').DataTable().draw();
});

But the table always shows No data available in table.
The same code works fine if I just call the $('#titles').DataTable({... line immediately on page load, with a specified GeoJSON file, so I know the problem isn't anything to do with the Ajax or column loading.
How can I fix this?
I'm wondering if perhaps I need to totally empty the HTML element and re-create it each time.

A: According to the Documentation the correct way to do this would be something like:
custname.on("change", function(e) {
    $("#titles")ajax.url("data/" + e.added.slug + ".geojson").load();
});

Hope this helps :)


text:
Q: Is there a way to prevent Visual Studio's find (Ctrl+F) from searching through certain directories in the solution? I've included a huge open source javascript framework that has thousands of files in it into my solution. It would be nice to include only what I need, but the classes are interdependent, and not in an obvious way either. These files really slow down the find option in VS 2013 just because there are so many of them.
Anyhow, these files are all in one directory. Right now, I just search 'current project', 'current document', or 'all open documents' if/because that option doesn't contain the huge directory. But I miss using 'entire solution' especially because I have so many projects in it now.
It would be worth my while to add this huge directory to a do-not-search list if such a thing exists. Does it exist?


text:
Q: Is there any library in flutter ,that can scan details of other applications in the device? I am trying to build a project in which we will create a report according to screen time of all the applications present in the device ,is there any suitable library present for flutter that can helps us out .
(if not library then any possible way to reach our need)


text:
Q: Bluez4 get device name during agent pair I am implementing a custom Bluetooth pairing agent in Python using Bluez via DBUS.  The agent needs to return one of a number of fixed PIN codes (legacy PINs, not simple pair mode requests) depending on which type of device is trying to pair.  The devices are Bluetooth enabled medical monitors (blood pressure, scales etc) of which I have no control.
Originally, I was looking at the first bit of the devices Mac address and returning a PIN based on the manufacture prefix.  This was working well.  But the device I am now trying to add support for uses the same prefix (I assume it has the same BT chip) but a different PIN as one of the other devices I need to support.  The only thing unique about the devices are their names which are always constant (such as "AND 1234" or "IEM 5678") so I tried to change by agent to look at the first bit of the name instead
knownPins = {
    "aandd": "12345",
    "iem ": "5678",
    "default": "98689"
}

@dbus.service.method("org.bluez.Agent", in_signature="o", out_signature="s")
def RequestPinCode(self, device):
    pprint("RequestPinCode ({})", device)
    dbdevice = dbus.Interface(bus.get_object("org.bluez", device),
        "org.bluez.Device")

    bits = device.split('/')
    mac = bits[-1].replace("dev_","").replace("_",":").lower()
    props = dbdevice.GetProperties()
    if not props["Name"]:
        raise Rejected()
    try:
        for name, pin in knownPins.items():
            if props["Name"].startswith(name):
                return pin

        return knownPins["default"]
    except:
        raise Rejected()

But, in most cases props["Name"] is simply empty - i assume this is because the pair request is being initiated by the remote party and since I have not done a discover, I dont know its name.
So my question is, how can I force a inquiry at this point in the process so I can get the device name?  I have tried
adapter.CreateDevice(mac)

Which gives org.bluez.Error.AlreadyExists
I have tried
adapter.RemoveDevice(device)
adapter.CreateDevice(mac)

Which gives org.bluez.Error.DoesNotExist: Device creation in progress
I assume in both instances this is because Bluez is in the middle of trying to create the device
Thanks


text:
Q: How to set collection view alpha = 0.5 but header alpha = 1.0 Is it possible to set collection view (all items) alpha = 0.5 but header set alpha = 1.0?

A: If your collection have some interitem or interline spacing and collection view have a background color other than clear or systemBackgroundColor, Then you need to set alpha for background color like this :
yourCollectionView.backgroundColor = UIColor.green.withAlphaComponent(0.5)

you can also use backgroundView of collectionView depending upon the need , like this :
    let aView = UIView(frame: yourCollectionView.frame)
    aView.backgroundColor = .green
    aView.alpha = 0.1
    yourCollectionView.backgroundView = aView

and then in cellforItemAt:
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellID", for: indexPath)
        cell.contentView.alpha = 0.5
        return cell
    }

A: here you can set items alpha:
override func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell",
                                                      for: indexPath
        cell.alpha = 0.5
 }

here you can set header alpha:
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        switch kind {

        case UICollectionView.elementKindSectionHeader:

            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)

            headerView.backgroundColor = UIColor.blue
            headerView.alpha = 1.0 //by default its also 1 just showing here
            return headerView

        case UICollectionView.elementKindSectionFooter:
            break
        default:
            assert(false, "Unexpected element kind")
        }
    }


text:
Q: CodeIgniter, active records, JOIN help? I am trying to figure out why my JOIN is not working on a database query, I have two tables with a user_ID column, but when I return this it returns everything, not just the selected ones per user. What am I messing up any thoughts? Thank you!
function user_apps()
{
    $this->db->select('*');
    $this->db->from('apps');
    $this->db->join('members', 'members.user_ID = apps.user_ID');

    $query = $this->db->get();

    return $query;

}

Here is an image of the DB tables, and goal is to basically get the urls from the apps table of each user,
http://cl.ly/516bd1e8aae62bd11773

A: You haven't specified a WHERE clause in your query. At the moment it is returning everything because you only have two users and they both have entries in the 'apps' table.
If you add:
$this->db->where('members.first_name', $first_name);

And pass a first name as a parameter to the function then it will only return results for that user.
function user_apps($first_name)
{
$this->db->select('*');
$this->db->from('apps');
$this->db->join('members', 'members.user_ID = apps.user_ID');
$this->db->where('members.first_name', $first_name);

$query = $this->db->get();

return $query;

}


text:
Q: Pointers to stack I am sorry that I cannot support my question with some code (I didnt understand how to structure it so it would be accepted here), but I try anyway.
If I understand correctly, a struct that references a struct of same type would need to do this with contained pointer for reference. Can this pointer reference to allocated space on the stack (instead of the heap) without creating segmentation fault? -
how should this be declared?

A: You didn't say what language you are working in, so assuming C for now from the wording of your question... the following code is perfectly valid:
typedef struct str_t_tag {
   int foo;
   int bar;
   struct str_t_tag *pNext;
} str_t;

str_t str1;
str_t str2;
str1.pNext = &str2;

In this example both str1 and str2 are on the stack, but this would also work if either or both were on the heap. The only thing you need to be careful of is that stack variables will be zapped when they go out of scope, so if you had dynamically allocated str1 and passed it back out of a function, you would not want str1->pNext to point to something that was on the stack within that function.
In other words, DON'T DO THIS:
typedef struct str_t_tag {
   int foo;
   int bar;
   struct str_t_tag *pNext;
} str_t;

str_t *func(void)
{
    str_t *pStr1 = malloc(sizeof(*pStr1));
    str_t str2;
    pStr1->pNext = &str2;

    return pStr1; /* NO!! pStr1->pNext will point to invalid memory after this */
}

A: Yes, you can use pointers to variables on the stack, but only when the method that provides that stack frame has not returned.  For example this will work:
typedef struct
{
    int a;
    float b;
} s;

void printStruct(const s *s)
{
    printf("a=%d, b=%f\n", s->a, s->b);
}

void test()
{
    s s;
    s.a = 12;
    s.b = 34.5f;
    printStruct(&s);
}

This will cause an error however, as the stack frame would have disappeared:
s *bad()
{
    s s;
    s.a = 12;
    s.b = 34.5f;
    return &s;
}

EDIT: Well I say it will cause an error, but while calling that code with:
int main()
{
    test();
    s *s = bad();
    printStruct(s);
    return 0;
}

I get a warning during compilation:
s.c:27:5: warning: function returns address of local variable [enabled by default]

and the program appears to work fine:
$ ./s
a=12, b=34.500000
a=12, b=34.500000

But it is, in fact, broken.

A: Not sure if this is specifically a C/C++ question, but I'll give C/C++ code as example in anyway.
The only way you can declare it: (with minor variations)
typedef struct abc
{
  struct abc *other;
} abc;

other can point to an object on the stack as follows:
abc a, b; // stack objects
b.other = &a;

This is not a question about scope, so I'll skip commenting on possible issues with doing the above.
If, however, you want to assign it to a dynamically created object, there's no way this object can be on the stack.
abc b;
b.other = malloc(sizeof(abc)); // on the heap


text:
Q: Team working on Drupal - Tips I am working on a Drupal site with a few friends. Obviously we can Version control the code... but what do we do to keep each others databases in check?
I have managed to get all the theming into files (contemplate etc), but ideally my views settings, menu settings would be in line also... (Not worried about Content either way as we're just building the framework)
Any suggestions?

A: Using Features along with Context is very powerful.  Context lets you create a "section" for your site. It's best illustrated through an example:
Lets say we define the "Forum" context as anything with the url of forums/*.  Context lets us say: "I want to show these three views in the right side bar, only when I am in the "Forums" context.
Now, using Features, we can create "module" define by the context.  So, we will end up with a module called "youSite_forums", which will include all the views, blocks, etc. that was define in your Forums context.  It also will determine the correct dependencies, as well as Content Types used in the context.  All will be bundled up nicely in a module.

As for versioning content such as node, you can user either Node Export, or just do a DB dump using Backup and Migrate.  We use these occasionally, but we never have every node versioned in SVN.

Links:
Features
Context
Backup and Migrate

A: Problem Solutions in Database Migration from Development to Live Sites

A: You can find some more opinions on this here: Drupal DATABASE deployment strategies?


text:
Q: how to limit the data shown in react-infinite-scroll I try to use react-infinite-scroll-component to show some data cards but I don't understand how to show some data only in view in this case I display all data, how to solve this
here is my code
  const AllTrainingEvent = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const nextData = () => {
    if (loading) return;
    setLoading(true);

    setTimeout(() => {
      const newData = dataCard.slice(0, data.length + 1);
      setData([...dataCard, ...newData]);
      setLoading(false);
    }, 1000);
  };

  return (

here is the use of react-infinite-scroll
        <InfiniteScroll
                  dataLength={data.length}
                  hasMore={data.length < 5}
                  next={nextData}
                  loader={
Loading...
}
                  endMessage={

                      <Divider>Yay! You have seen it all</Divider>

                  }
                  style={{
                    maxHeight: 350,
                    overflow: "inherit",
                  }}
                >

              <List
                dataSource={dataCard}
                renderItem={(item) => (
                  <List.Item>
                    <Row justify="space-between">
                      <Col>
                        <CardTrainingEvent {...item} />
                      </Col>
                    </Row>
                  </List.Item>
                )}
              />
            </InfiniteScroll>
 );
};


text:
Q: Safemode Startup Issues on Vista 64 Bit Before i ask the question, let me point out that this is not a hardware issue. I have a clean install of vista on another hd that runs on same hardware, i am pretty sure its a corruption of a drive or a file, i presume it might be video driver.
When windows wont start via normal boot i just get black screen after initial load up of os, so i boot into savemode, I end up having black screen with a mouse pointer visible, after initial load of os. The shut down button is responsive.
Of course, I can install clean copy of os, and prior to that can retrieve all other files that i need by accessing hd itself, i can restore my pc from my external back up as well.
Although i have all these options, i was wondering if there anything else i can do that can help me fix this issue.
In save mode, it looks like I am capable of logging in after initial load of os, even though i cant see the process it self, i do see the mouse pointer. By visual memory i navigated to password field, and entered my password, hit enter, I get the loading mouse pointer, nothing really changes, same black screen and mouse pointer, but when i tried to access task manager for a second i got a safemode watermark at all four corners.
Any help would be appriciated. Thank you in advance.

A: If disk checks seem to be making it worse, and it seems things are working in slow-mo (like the watermarks showing up) if they do work, then it sounds like a failing drive.
Go to the drive manufacturer's website and get a bootable set of diagnostics and use them to test the drive.
Most manufacturers' diagnostic tools have both 'quick' and 'extended' type tests.  The Quick tests are mainly testing drive operations like head positioning, cache checks, and disk spin (etc.).  If the quick tests detect a problem they will either fail outright and tell you to replace the drive, or say the error is 'repairable' and offer to run the extended tests to attempt the repair.
The Extended tests that can fix problems do a surface scan and remap bad sectors to spare areas on the drive (amongst other things).
A potential problem is that the extended tests generally don't try to resurrect the data before remapping.   So if the quick test tells you there's a 'repairable' problem, and you want to keep as much data as possible, then I'd say check out Spinrite and perhaps run that to attempt to resurrect the data from any bad blocks before going back and using the manufacturer's tool to 'repair' the drive.
That's my best suggestion based on what I can 'see'. ;)


text:
Q: Intellij Idea and Eclipse and JDK 7 and Android I start to develop application for Android using Intellij Idea because it is preferable IDE for last year.
I've smashed my face with two fatal error with both IDE:
Intellij Idea
1. I created custom view:
public class ImageOverlayView extends View implements View.OnTouchListener {

private static final String TAG = "ImageOverlayView";
private Bitmap image;

private float x, y, sX, sY;

private final Paint paint = new Paint();
private float scaleFactor;

private int getScaledWidth()
{
    return (int)(image.getWidth() * scaleFactor);
}

private int getScaledHeight()
{
    return (int)(image.getHeight() * scaleFactor);
}

public ImageOverlayView(Context context) {
    super(context);
}

public ImageOverlayView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(R.styleable.ImageOverlayView);
    this.setOnTouchListener(this);
}

public void setImage(Bitmap bm) {
    image = bm;
    invalidate();
}

public void setDrawable(Drawable drawable) {
    image = BitmapUtils.drawableToBitmap(drawable);
    invalidate();
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (canvas != null && image != null) {
        canvas.drawBitmap(image, null, paint);
    } else {
        Log.d(TAG, "Canvas is NULL");
    }
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE: {
            sX = event.getX();
            sY = event.getY();

            break;
        }

    }
    return super.onTouchEvent(event);
}

public void loadImageBitmap(String fileName) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    image = BitmapFactory.decodeFile(fileName, options);
    if (image == null) {
        throw new NullPointerException("The image can't be decoded.");
    }

    scaleFactor = 1;

    // center image on the screen
    int width = getWidth();
    int height = getHeight();
    if ((width != 0) || (height != 0)) {
        int scrollX = (image.getWidth() < width ? -(width - image.getWidth()) / 2 :    image.getWidth() / 2);
        int scrollY = (image.getHeight() < height ? -(height - image.getHeight()) / 2 : image.getHeight() / 2);
        scrollTo(scrollX, scrollY);
    }
    invalidate();
}

public void loadImageDrawable(int resourceId) {
    Resources resources = getResources();
    Drawable drawable = resources.getDrawable(resourceId);
    image = BitmapUtils.drawableToBitmap(drawable);
    invalidate();
}
}

Then, i've tried to see result in UI Designer in Idea:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

<ru.lookmyway.customview.ImageOverlayView
    android:id="@+id/imageOverlayView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

And idea gives me NPE:
java.lang.NullPointerException
at ru.lookmyway.customview.ImageOverlayView.onDraw(ImageOverlayView.java:65)
at android.view.View.draw(View.java:13712)
at android.view.View.draw(View.java:13596)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13594)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13594)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13715)
at android.view.View.draw(View.java:13596)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13715)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:570)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:334)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:325)
at org.jetbrains.android.uipreview.RenderService.createRenderSession(RenderService.java:127)
at org.jetbrains.android.uipreview.RenderUtil.renderLayout(RenderUtil.java:154)
at com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel$8.run(AndroidDesignerEditorPanel.java:346)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:289)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

But at the same time in Eclipse (JUNO) everything is OK!
Than, i decided develop using Eclipse. I installed it and try to build my project.
But Eclipse said me that i'm using java 1.7, and Android wants 5.0 or 6.0.
Some google search says that i can not use jdk 1.7 cause there are no support it yet in Android, but Idea works fine with android and jdk 1.7!!
Some questions:

*

*Why my custom view working fine in Eclipse, but Idea gives me NPE?

*Why Eclipse could not work with jdk 1.7, but Idea works fine with
    jdk 1.7?

*What i have to do? :D

*Which IDE i have to choose?

UPDATED ANSWER:
Because i've got small reputation, i can not answer my self, so answer in question:
My custom view was in package com.example.customview.ImageCustomView.
When i try use it in other project, i placed it in com.example and it work, than i refactored this view to name ImageCustomView, moved it ot com.example and again it work fine.
I've tried to repeat my bug - but unsuccess, in all packages, with different names it works.
Thanks!

UPDATED UPDATED:
I repeat my bug.
I add Geasture listener, remove constructor with AttributeSet and i got NPE again. But when i discard all my changes - NPE wont dissapear. So i dont know now what's wrong, so i need some versions or answer. I fix it again: i move my custom view class in other package.

MORE INFORMATION:
NPE appear when i removed on of constructor:

    public ImageCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(R.styleable.ImageCustomView);
    a.recycle();

    }

And it even if i add it back - NPE wont disappear, but after refactor name of this class - it works. So, my version this is after refactor Idea refresh pre-compiled classes, coz pre-compile files it is one of the feature Intellij Idea.
After some expirements i've got new NPE:
java.lang.NullPointerException
at android.graphics.Canvas.throwIfRecycled(Canvas.java:1025)
at android.graphics.Canvas.drawBitmap(Canvas.java:1065)
at ru.lookmyway.ImageCustomView.onDraw(ImageCustomView.java:63)
at android.view.View.draw(View.java:13712)
at android.view.View.draw(View.java:13596)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13594)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13594)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13715)
at android.view.View.draw(View.java:13596)
at android.view.ViewGroup.drawChild(ViewGroup.java:2928)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2797)
at android.view.View.draw(View.java:13715)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.render(RenderSessionImpl.java:570)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:334)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:325)
at org.jetbrains.android.uipreview.RenderService.createRenderSession(RenderService.java:127)
at org.jetbrains.android.uipreview.RenderUtil.renderLayout(RenderUtil.java:154)
at com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel$8.run(AndroidDesignerEditorPanel.java:346)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
at com.intellij.util.Alarm$Request$1.run(Alarm.java:289)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

Updated custom view:
public class ImageCustomView extends View implements View.OnTouchListener {

private static final String TAG = "ImageCustomView";
private Bitmap image;

private float x, y, sX, sY;

private final Paint paint = new Paint();
private float scaleFactor;
private GestureDetector gestureDetector;

private int getScaledWidth()
{
    return (int)(image.getWidth() * scaleFactor);
}

private int getScaledHeight()
{
    return (int)(image.getHeight() * scaleFactor);
}

public ImageCustomView(Context context) {
    super(context);
    this.setOnTouchListener(this);
    paint.setFilterBitmap(true);
    paint.setDither(false);
    gestureDetector = new GestureDetector(context, new MyGestureListener());
}

public void setImage(Bitmap bm) {
    image = bm;
    invalidate();
}

public void setDrawable(Drawable drawable) {
    image = BitmapUtils.drawableToBitmap(drawable);
    invalidate();
}

@Override
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(image, 0, 0, paint);
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_MOVE: {
            sX = event.getX();
            sY = event.getY();
            Log.d(TAG, "x: " + sX + " y: " + sY);
            break;
        }

    }
    return super.onTouchEvent(event);
}

private class MyGestureListener extends GestureDetector.SimpleOnGestureListener
{
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        scrollBy((int)distanceX, (int)distanceY);
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        int fixedScrollX = 0, fixedScrollY = 0;
        int maxScrollX = getScaledWidth(), maxScrollY = getScaledHeight();

        if (getScaledWidth() < getWidth())
        {
            fixedScrollX = -(getWidth() - getScaledWidth()) / 2;
            maxScrollX = fixedScrollX + getScaledWidth();
        }

        if (getScaledHeight() < getHeight())
        {
            fixedScrollY = -(getHeight() - getScaledHeight()) / 2;
            maxScrollY = fixedScrollY + getScaledHeight();
        }

        boolean scrollBeyondImage = (fixedScrollX < 0) || (fixedScrollX > maxScrollX) || (fixedScrollY < 0) || (fixedScrollY > maxScrollY);
        return !scrollBeyondImage;

    }
}

public void loadImageBitmap(String fileName) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    image = BitmapFactory.decodeFile(fileName, options);
    if (image == null) {
        throw new NullPointerException("The image can't be decoded.");
    }

    scaleFactor = 1;

    // center image on the screen
    int width = getWidth();
    int height = getHeight();
    if ((width != 0) || (height != 0)) {
        int scrollX = (image.getWidth() < width ? -(width - image.getWidth()) / 2 : image.getWidth() / 2);
        int scrollY = (image.getHeight() < height ? -(height - image.getHeight()) / 2 : image.getHeight() / 2);
        scrollTo(scrollX, scrollY);
    }
    invalidate();
}

public void loadImageDrawable(int resourceId) {
    Resources resources = getResources();
    Drawable drawable = resources.getDrawable(resourceId);
    image = BitmapUtils.drawableToBitmap(drawable);
    invalidate();
}

}
I removed second construcor - got NPE, refactor name of class - got works, added some changes - got NPE (about canvas, second NPE) do refactor name(or place) of class - got works... i dont know...
One more detail - this view has no reactions on Touch my image, breakpoint wont go in method onTouch... may be it is key information.
My target it is move image on screen and redraw image where i place image by my finger.

A: Your code is working fine for me(IntelliJ IDEA aka Android Studio). Double check your project setup.

A: Android Studio save my ass. It shows me errors. So, about Eclipse and JDK 1.7 i have no answer, but about Custom view the answer is:

*

*Custom View requires two default constructors:

    public CustomView(Context context) {
         super(context);
    }

    public CustomView(Context context, AttributeSet attrs) {
         super(context, attrs);
    }

*

*onDraw method have to contain check entire data for null:

if (bitmap == null) {
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.CYAN);
    canvas.drawRect(mImagePosition, paint);
    return;
}
Rect rect = new Rect(0, 0, this.getWidth(), this.getHeight());
canvas.drawBitmap(bitmap, rect, mImagePosition, null);

*There are no need make:
super.onDraw(canvas);

in onDraw method.


text:
Q: Sign up in php not working and redirecting to same page with blank screen I am developing Login system in php.I have one file for sign up named as signup1.php when I put details in sign up form and click on sign up button
it show same file signup1.php with blank screen.
I want to redirect myprofile.php when signup the user.
I put this code.
$user->redirect('myprofile.php');

code from the comment:
<?php
require_once 'dbconfig.php';
if($user->is_loggedin()!="") {
    $user->redirect('myprofile.php');
}
if(isset($_POST['btn-signup'])) {
    else{
        try {
            $stmt = $DB_con->prepare("SELECT name,email FROM customer WHERE email=:umail");
            $stmt->execute(array(':umail'=>$umail));
            $row=$stmt->fetch(PDO::FETCH_ASSOC);
            if($row['email']==$umail) {
                $error[] = "sorry email id already taken !";
            } else {
                if($user->register($fname,$lname,$uname,$umail,$uphone,$upass)) {
                    $user->redirect('myprofile.php');
                }
            }
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }
}
?>

Redirect function:
class User {
    public function redirect($url) {
        header("Location: $url");
    }
}

A: From the little information you provide I can see one problem. This:
if(isset($_POST['btn-signup'])) {
    else{
    }
}

Is not going to work, it will throw this error:

PHP Parse error:  syntax error, unexpected 'else' (T_ELSE)

An if clause works like this:
if( $condition ) {
    // do something if $condition is TRUE
}
else{
    // do something else if $condition is FALSE
}

If I understood your code correctly you should just remove the else { line along with its corresponding closing bracket.
Common note: If you encounter the white screen of death in PHP, without any error message, error reporting is usually disabled (wich is normal in production environments). You can activate it with these lines:
ini_set('display_errors',true);
error_reporting(E_ALL);

Alternatively you can look at the error log of your web server (if your hoster provides one, not all do).


text:
Q: Сохранение текста, введенного в поле формы на html странице без использования php input type="text" id="txt" value=""
input type="button" onclick="" id="b" value="Сохранить"

Можно ли при нажатии на кнопку 'Сохранить' сохранять значение текстового поля? Допустим, я ввёл в текстовое поле текст "777", и мне нужно сохранить это не в отдельный файл, а в этот же. И в итоге после сохранения должно получится это:
input type="text" id="txt" value="777"
input type="button" onclick="" id="b" value="Сохранить"

Это для использования только на одном конкретном компьютере - без доступа к сети.

A: Вот то что Вы хотите, но сразу хочу сказать - так никто не делает, так как злоумышленник может это эксплуатировать на свое усмотрение.
Если отправлять серверу только измененные данные а не всю страницу целиком, можно этому препятствовать, но это совсем другая история и кода в ней будет на порядок больше.
PS: запускал из idea, html файл должен лежать в корне проекта и называться index.html
—-
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.*;
import java.net.InetSocketAddress;

public class Server {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8087), 0);
        server.createContext("/save", new Save());
        server.createContext("/", new Serve());
        server.start();
        System.out.println("http://localhost:8087/index.html");
    }

    static abstract class Handler implements HttpHandler {
        @Override
        public void handle(HttpExchange http) throws IOException {
            OutputStream outputStream = http.getResponseBody();
            byte[] result;
            int code = 200;
            try {
                result = process(http);
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                result= sw.getBuffer().toString().getBytes();
                code = 500;
            }
            http.sendResponseHeaders(code, result.length);
            outputStream.write(result);
            outputStream.close();
        }

        abstract byte[] process(HttpExchange http) throws Exception;
    }

    static class Save extends Handler {
        @Override
        byte[] process(HttpExchange http) throws Exception {
            FileWriter fw = new FileWriter(new File("index.html"));
            fw.write(new String(read(http.getRequestBody()).toByteArray()));
            fw.close();
            return "saved".getBytes();
        }
    }

    static class Serve extends Handler {
        @Override
        byte[] process( HttpExchange http) throws Exception {
            String path = "." + http.getRequestURI().getRawPath();
            return read(new FileInputStream(path)).toByteArray();
        }
    }

    static ByteArrayOutputStream read(InputStream is) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead = is.read(data, 0, data.length)) != -1)
            buffer.write(data, 0, nRead);
        buffer.flush();
        return buffer;
    }
}

<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>
    <input type="text" id="txt" value="">
    <input type="button" onclick="save()" value="Сохранить">
    <script>
        function save() {
            txt.setAttribute('value', txt.value);

            return fetch('/save', {
                method: 'POST',
                body: document.documentElement.innerHTML,
            }).then(resp => {
                console.log(resp)
            }).catch(err => {
                console.error(resp)
            })
        }
    </script>
</body>


text:
Q: How to pass table name as a parameter in update procedure in Oracle? I am new to Oracle so please sorry the question that seems to be very easy for you.
I need to get the following procedure with UPDATE query with replace function
CREATE OR REPLACE PROCEDURE proc_replace_space_1
(
    p_table user_tables.table_name%TYPE,
    p_search IN varchar2,
    p_replace IN varchar2
)
IS
BEGIN
    EXECUTE IMMEDIATE
            'update ' || p_table ||
            'set docnum = replace(docnum, :2, :3 )'
            USING p_search, p_replace;
END;

This procedure removes all spaces.
But when I call it
BEGIN
    proc_replace_space_1('cm_risk.fct_loans_temp', ' ', '');
END;

I've got the following error
SQL Error [971] [42000]: ORA-00971: missing SET keyword
ORA-06512: at "CM_RISK.PROC_REPLACE_SPACE_1", line 9
ORA-06512: at line 2

How can I modify my code to handle the problems?
Thank you.

A: Dynamic SQL is hard because it turns compilation errors into runtime errors. So I urge you to acquire the good habit of assembling your dynamic SQL as string variables which you can persist to a log table if you have such a thing (and if you don't it would be another good habit to acquire) or display using dbms_output.put_line.
So your procedure would look like this:
CREATE OR REPLACE PROCEDURE proc_replace_space_1
(
    p_table user_tables.table_name%TYPE,
    p_search IN varchar2,
    p_replace IN varchar2
)
IS

  l_sql varchar2(32767);

BEGIN

  l_sql := 'update ' || p_table ||
            'set docnum = replace(docnum, :2, :3 )';

    EXECUTE IMMEDIATE
            l_stmt
            USING p_search, p_replace;

exception
  when others then
    dbms_output.put_line(l_sql);
    raise;
END;

This approach allows you to see the actual SQL your procedure executed. Probably you'll be able to spot the syntax error immediately (in this case it's the missing space between table name and set). Otherwise you can try to run the statement for yourself and see what the SQL compiler highlights.

NB: depending on your environment you may need to enable DBMS_OUTPUT before you can see the message.

A: You just need to add a space before set. Currently your table name is appended to set keyword and it is assuming it as a table name i.e MyTableSet
CREATE OR REPLACE PROCEDURE proc_replace_space_1
(
    p_table user_tables.table_name%TYPE,
    p_search IN varchar2,
    p_replace IN varchar2
)
IS
BEGIN
    EXECUTE IMMEDIATE
            'update ' || p_table ||
            ' set docnum = replace(docnum, :2, :3 )'
            USING p_search, p_replace;
END;


text:
Q: How to require a Dropdown that has a value no longer in the Dropdown Options? I'm using Angular 6 and have a required <select> element with the current options of a, b, c:
<select class="form-control" name="mySelect" [(ngModel)]="vm.mySelect" #mySelect="ngModel" required>
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

However, lets say d was a valid option previously and is what is saved to my back-end database. So when I load my page, I'm setting mySelect to what is stored in the database and if I inspect mySelect with Chrome devtools, it has a  ng-relfect-model="d" but the select element is empty because d isn't an option anymore.
When I check my NgForm's .valid property, I would expect it to return false. However, it returns true.
How can make it so my select element is invalid if it has a value that is not a valid option?

A: An easy solution would be add pattern="['a' | 'b' | 'c']" to your select:
<select class="form-control"
        name="mySelect"
        [(ngModel)]="vm.mySelect"
        #mySelect="ngModel"
        pattern="['a' | 'b' | 'c']"
        required>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

or, if you have an array of options, you could construct a pattern in your ts file and pass it to HTML.
ts file:
pattern = new RegExp(['a','b', 'c'].join('|'));

HTML file:
<select [patern]="patern"...>...

STACKBLITZ (enter invalid value in the input box)
NEW UPDATE
In case of vm.options as array of objects having value property try following:
in your ts file:
vm = {
  options: [
    {
      description: 'a1',
      value: 'a'
    },
    {
      description: 'b1',
      value: 'b'
    },
    {
      description: 'c1',
      value: 'c'
    }
  ],
  mySelect: null
};
pattern = new RegExp('^[' + this.vm.options.map(o => o.value).join('') + ']$');

in your HTML file:
<select class="form-control"
        name="mySelect"
        [(ngModel)]="vm.mySelect"
        #mySelect="ngModel"
        required
        [pattern]="pattern">
  <option *ngFor="let option of vm.options"
          [value]="option.value">{{option.description}}</option>
</select>

STACKBLITZ is updated as well


text:
Q: Only show menu if the current page is in menu Is it possible to conditionally display a menu based on whether the current page is present in the menu?

A: You can use the following code. Loop through every item, in every menu, and check if the item exists. If it does, display the menu and move on to the next menu.
    <?php
    // get array of nav menus
    $menus = wp_get_nav_menus();

    //get current page URL
    $uri = $_SERVER['REQUEST_URI'];

    //loop through each menu looking for current page
    foreach($menus as $menu)
    {
        //get menu items from ith menu in loop
        $items = wp_get_nav_menu_items( $menu->term_id );

        //loop through each item in menu to check for
        foreach($items as $item)
        {
            if( strpos($item->url, $uri) !== false )
            {
                //display menu
                wp_nav_menu( array('menu'=>$menu->term_id) );

                //current menu done, check next menu
                break;
            }
        }
    }
    ?>

All relevant Wordpress functions usage can be found in the codex, or via Google Search.


text:
Q: Deriving a text string from a date I could use some help deriving a year quarter from a text string that represents a date. I have a string, say '20121230', to represent 12/30/2012. Somehow, someway, I need to convert this value into '4Q12.' I get stuck after converting the 20121230 into a date:
CONVERT(date,datestringfield,111)

I need help deriving the quarter and year from this date and then converting the quarter and year to a string format 4Q12. Any help would be greatly appreciated

A: If you are using SQL Server, then the particular format of datestringfield can be used as a date unambiguosly. So, you can do:
SELECT  DATENAME(QUARTER,datestringfield) + 'Q' +
        RIGHT('00'+DATENAME(YEAR,datestringfield),2)


text:
Q: Creating a function that returns an array of strings I'm trying to create a string parser that breaks a string up into an array of strings using a delimiter. I'm using the function "strtok" which I understand how to use. What I don't understand is how to get my parsing fuction to return an array of the different words in my string. It's been quite some time since I've used C, so this is proving to be quite difficult.
char ** parseString(char * inString){

    char **ptr; //What I want to return, an array of strings
    int count = 0;

    ptr[count] = strtok(inString, " ");
    count++;
    while(inString!=NULL){
         ptr[count]=strtok(NULL, " ");
         count++;
    }
    return ptr;
}

I know that this above code won't work. I vaguely remember how to use malloc, and I know that my above code will result in a seg fault since I haven't malloced, but above is essentially what I want to have happen. How do I appropriately malloc if I don't even know how many words I need to have in my array of strings?

A: For allocating the vector since you don't know from the start its size there are a couple of strategies:

*

*you can first parse inString to get the number of words, allocate then parse again.

*you can reallocate for each word.

*you can reallocate with a geometric growth.

In the first variant you do the parsing twice, making it the worst of them
The second has the disadvantage of multiple reallocations, but could be acceptable on small strings and if the function is not critical.
The third one is the best and is what std::vector in C++ does.
I show you the 2nd variant here.
You also need to keep the size of the vector in a separate variable.
char** parseString(char* inString, size_t* tokensLen)
{
    char **tokens = NULL; // realloc on NULL acts like malloc so we simplify the code
    size_t i = 0;

    // parse the first word
    char* inToken = strtok(inString, " ");

    while (inToken)
    {
        // allocate for one more pointer
        tokens = realloc(tokens, (i + 1) * sizeof *tokens);
        assert(tokens);

        // point to word
        tokens[i] = inToken;

        // parse the next word
        inToken = strtok(NULL, " ");
        ++i;
    }

    // set size
    *tokensLen = i;

    return tokens;
}

int main()
{
    char str[] = "here we go";
    size_t len;
    char** tokens = parseString(str, &len);

    for (size_t i = 0; i < len; ++i)
    {
        printf("%s\n", tokens[i]);
    }
}


text:
Q: Errors in solving coupled pdes I am trying to solve following coupled PDEs:

I am not sure about suitable BCs.
 ClearAll[V, Rho, T]
gamma = 5/3; ep = 0.05; d = 0.01; L = 1; H = 1.1; gpara = 0.38;
System = {D[V[x, t],t] == -1/gamma/exp[-x/H]*{D[Rho[x, t], x] + D[T[x,
t],x]} + Rho[x, t]/exp[-x/H]*gpara + 1.3*ep*D[V[x, t], {x, 2}],
D[Rho[x, t], t] == - D[{exp[-x/H]*V[x, t]}, x],
D[T[x, t], t] == D[{exp[-x/H]*V[x, t]}, x] - V[x, t]*Rho[x, t]*gpara -
gamma*exp[-x/H]*D[V[x, t], x] + gamma*d*D[T[x, t], {x, 2}],
V[x, t] == 0 /. x -> 0,
V[x, t] == 0 /. x -> 1,
Rho[x, t] == 0 /. x -> 0,
Rho[x, t] == 0 /. x -> 1,
T[x, t]   == 0 /. x -> 0,
T[x, t]   == 0 /. x -> 1,
D[T[x, t], x] == 0 /. x -> 1,
V[x, 0] == Sin[Pi*x/L],
Rho[x, 0] == 0,
T[x, 0] == 0};
{V, Rho, T} = NDSolveValue[System, {V, Rho, T}, {x, 0, 1}, {t, 0, 5}]
Plot3D[{V[x, t], Rho[x, t], T[x, t]}, {x, 0, 1}, {t, 0, 5}]

General::ivar: 3 is not a valid variable.
........
Also, how i can import variable gpara in .txt format to this code?

A: Here is a version that fixes the syntax errors but there is a warning message indicating instability you should look into:
ClearAll[V, Rho, T]
gamma = 5/3; ep = 0.05; d = 0.01; L = 1; H = 1.1; gpara = 0.38;
System = {
   D[V[x, t],
     t] == -1/gamma/Exp[-x/H]*(D[Rho[x, t], x] + D[T[x, t], x]) +
     Rho[x, t]/Exp[-x/H]*gpara + 1.3*ep*D[V[x, t], {x, 2}],
   D[Rho[x, t], t] == -D[Exp[-x/H]*V[x, t], x],
   D[T[x, t], t] ==
    D[Exp[-x/H]*V[x, t], x] - V[x, t]*Rho[x, t]*gpara -
     gamma*Exp[-x/H]*D[V[x, t], x] + gamma*d*D[T[x, t], {x, 2}],
   V[0, t] == 0, V[1, t] == 0, V[x, 0] == Sin[Pi*x/L],
   Rho[0, t] == 0, Rho[1, t] == 0, Rho[x, 0] == 0,
   T[0, t] == 0, T[1, t] == 0, Derivative[1, 0][T][1, t] == 0,
   T[x, 0] == 0};
{V, Rho, T} = NDSolveValue[System, {V, Rho, T}, {x, 0, 1}, {t, 0, 5}]

Plot3D[{V[x, t], Rho[x, t], T[x, t]}, {x, 0, 1}, {t, 0, 5}]


text:
Q: Regular Expression to eleminate pattern I have strings in a pattern such as
1. ABC No 5
2. PQR - XYZ
3. ABC (PQR)

Can somebody specify a regular expression which only and only removes numerical and period at the start of the screen and maintains the rest of the screen as it is?

*

*remove 1. from 1. ABC No 5

*remove 2. from 2. PQR - XYZ
etc.

A: Here is a substitution expression that should work.
 s/^\d+\.//

You didn't mention what language you are using so implementation will vary depending on how the language/API exposes regex search and replace. For example, if you're processing one input line at a time, in PHP, you could do this:
$myVar = preg_replace('/^\d+\./', '', $myVar);

In java you could do this:
myVar = myVar.replaceFirst("^\\d+\\.", "");

A: Regex: ^[0-9]+\.
^ # Matches the start of the line

[0-9]* # Matches one or more digits

\. # Matches the period (escaped as . matches anything in regex) and the space

Using sed:
$ cat file
1. ABC No 5
2. PQR - XYZ
3. ABC (PQR)

$ sed -E 's/^[0-9]+\. //' file
ABC No 5
PQR - XYZ
ABC (PQR)

Regex is not necessarily needed here however -
Using cut:
$ cut -d' ' -f2- file
ABC No 5
PQR - XYZ
ABC (PQR)

Using Awk:
$ awk -F. '{print $2}' file
 ABC No 5
 PQR - XYZ
 ABC (PQR)

A: in Perl
$cadena ="1111. ABC No 5";
$cadena =~ s/^[\d\.]+//;
print $cadena;

A: Perl:
while(<>) {
  print $_ unless /[^-0-9]/
}


text:
Q: Create MQTT topics on AWS Can someone please suggest me how can I create topics on AWS server? I knew that it will create topic automatically when I publish a message by giving the topic name but is there any way I can add all possible topics on server?

In the above image I am able to send message on a topic (test_topic) and it create that automatically on server. Is there any way I created all topics at one time on a server?

A: Topics are meaningless until a message is published to it.
There is nothing to create in advance, you can subscribe to any topic you want even if no messages have ever been published to.
Also ACLs to control access to topics do not depend on a topic "existing" before they are created.


text:
Q: WPF GradientBrush? How Many type of gradient brushes are available like LinearGradientBrush, SolidColorBrush?
and when we create a GradientStop how the offset works?
        LinearGradientBrush LGB = new LinearGradientBrush();
        LGB.StartPoint = new Point(0, 0);
        LGB.EndPoint = new Point(0, 1);
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(255,251,255) , 0));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(206,207,222), 1));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(0, 247, 0), 2));
        rect.Fill = LGB;

Why the third one "Color.FromRgb(0, 247, 0)" is not reflecting?
Please suggest,where i am wrong?

A: The GradientStop.Offset property is a value which ranges from 0.0 to 1.0. From the MSDN documentation:

A value of 0.0 specifies that the stop is positioned at the beginning of the gradient vector, while a value of 1.0 specifies that the stop is positioned at the end of the gradient vector.

Change your second stop's offset to 0.5 and your third's to 1.0 and it should work.


text:
Q: Oracle Select query help please SELECT  id
      FROM    (
 SELECT  id
      FROM   table
      WHERE
      PROCS_DT is null
      ORDER BY prty desc, cret_dt ) where rownum >0 and rownum <=100

The above query is giving me back 100 records as expected
 SELECT  id
          FROM    (
     SELECT  id
          FROM   table
          WHERE
          PROCS_DT is null
          ORDER BY prty desc, cret_dt ) where rownum >101 and rownum <=200

why is the above query returning me zero records?
Can some one help me how i can keep on. I am dumb in oracle...

A: Try this:
SELECT id
FROM
  (SELECT id,
          rownum AS rn
   FROM
     (SELECT id
      FROM TABLE
      WHERE PROCS_DT IS NULL
      ORDER BY prty DESC, cret_dt) )
WHERE rn >101
  AND rn <=200

If you are comfortable using the ANALYTIC functions, try this:
SELECT id
  FROM
    (
        SELECT id,
                ROW_NUMBER() OVER(ORDER BY prty DESC, cret_dt ) rn
            FROM table
        WHERE procs_dt IS NULL
    )
 WHERE rn >101 and rn <=200

A: ROWNUM values are assigned to rows as they are returned from a query (or subquery).  If a row is not returned, it is not assigned a ROWNUM value at all; so the ROWNUM values returned always begin at 1 and increment by 1 for each row.
(Note that these values are assigned prior to any sorting indicated by the ORDER BY clause.  This is why in your case you need to check rownum outside the subquery.)
The odd bit of logic you have to understand is that when you have a predicate on ROWNUM, you are filtering on a value that will only exist if the row passes the filter.  Conceptually, Oracle applies any other filters in the query first, then tentatively assigns ROWNUM 1 to the first matching row and checks it against the filter on ROWNUM.  If it passes this check, it will be returned with that ROWNUM value, and the next row will be tentatively assigned ROWNUM 2.  But if it does not pass the check, the row is discarded, and the same ROWNUM value is tentatively assigned to the next row.
Therefore, if the filter on ROWNUM does not accept a value of 1, no rows will ever pass the filter.
The use of the analytic function ROW_NUMBER() shown in the other answers is one way around this.  This function explicitly assigns row numbers (distinct from ROWNUM) based on a given ordering.  However, this can change performance significantly, as the optimizer does not necessarily realize that it can avoid assigning numbers to ever possible row in order to complete the query.
The traditional ROWNUM-based way of doing what you want is:
SELECT  id
          FROM    (
  SELECT rownum rn, id
    FROM (
     SELECT  id
          FROM   table
          WHERE
          PROCS_DT is null
          ORDER BY prty desc, cret_dt
     ) where rownum <=200
  ) where rn > 101

The innermost query conceptually finds all matching rows and sorts them.  The next layer assigns ROWNUMs to these and returns only the first 200 matches.  (And actually, the Oracle optimizer understands the significance of a sort followed by a ROWNUM filter, and will usually do the sort in such a way as to identify the top 200 rows without caring about the specific ordering of the other rows.)
The middle layer also takes the ROWNUMs that it assigns and returns them as part of its result set with the alias "rn".  This allows the outermost layer to filter on that value to establish the lower limit.
I would experiment with this variant and the analytic function to see which performs better in your case.


text:
Q: Ansible - How maintain a dynamic list of data I'm building a system to deploy an entire environment in AWS. However, in the case of failure, I want to tear down everything that's already been built. Since I was planning to deploy multiple, different environments, I figured it would be better to just keep a running list of what I've made in AWS up to that point.
So I want a way to store just a simple array of the names of each component, appending the names as each part is spun up in turn,  so that at the error stage, I can just terminate everything, but this is proving to be quite head-scratching for me.
As it stands, my code looks something like this:
top-level-playbook
- hosts: localhost
  connection: local
  roles:
    - { role: make_ec2, when: "ansible_failed_task is undefined" }
         --Fails Here--
    - { role: make_ec2, when: "ansible_failed_task is undefined" }
    - { role: make_ec2, when: "ansible_failed_task is undefined" }
  post_tasks:
    - name: "do a teardown"
      *iterate through list and tear down environment*
      when: ansible_failed_task is defined

make_ec2 (This is in a block/rescue)
---
- name: "spin up EC2
     --all the variables you need to spin up the EC2"
  register: EC2

- name: "Append List"
- set_fact:
     ec2_list: "{{ ec2_list | default | -Append ec2.string.value- }}"

In addition, if there are any better ways to do the tear down, please let me know as well!

A:
So I want a way to store just a simple array of the names of each
  component, appending the names as each part is spun up in turn....

You can create a temp file in pre_task and write data into it, so if something failed, you know what to delete.   Alternatively you can replace file with DB, but the mechanics would still be the same.

if there are any better ways to do the tear down, please let me know
  as well!

I personally wouldn't reinvent the wheel and would just use CloudFormation which is a template for your AWS resources.  You can use libraries like troposphere to help you manage JSON structure.  So in other words if something failed, cloudformation will revert it back, and cleanup all the resources.


text:
Q: Elements of a localization
How does a localization at a prime look like, for example if we have $R:=\mathbb Z[\sqrt{-3}]$ and let the ideal $\mathfrak p:=\left(\sqrt{-3}\right)$ in $R$, what are the elements of $R_{\mathfrak p}$ ?

I have to find an easier expression than $\mathfrak pR$, for example $3\mathbb Z$ is contained in $\mathfrak p$, or otherwise is it superfluous to determine whether the localization is for example a local ring or a PID ?

A: We have $$\mathbb Z[\sqrt{-3}]\subset\mathbb Z\left[\dfrac{1+\sqrt{-3}}{2}\right]\subset\mathbb Z[\sqrt{-3}]_{(\sqrt{-3})}\subset\mathbb Q[\sqrt{-3}].$$ (For the second containment notice that $2\notin(\sqrt{-3})$.) If $z\in\mathbb Q[\sqrt{-3}]$ is integral over $\mathbb Z[\sqrt{-3}]_{(\sqrt{-3})}$, then there is $a\in\mathbb Z[\sqrt{-3}]-(\sqrt{-3})$ such that $az$ is integral over $\mathbb Z[\sqrt{-3}]$. Thus we get $az\in\mathbb Z\left[\dfrac{1+\sqrt{-3}}{2}\right]$, so $az\in\mathbb Z[\sqrt{-3}]_{(\sqrt{-3})}$ which entails $z\in\mathbb Z[\sqrt{-3}]_{(\sqrt{-3})}$.
This shows that $\mathbb Z[\sqrt{-3}]_{(\sqrt{-3})}$ is integrally closed, so it is a DVR with $\sqrt{-3}$ as uniformizer.


text:
Q: Using Facebook Login safely on an insecure page Suppose I have two URLs:
http://example.com/createinsecureaccount
https://example.com/accesssecureaccount
A possible user flow is as follows:
1.  User visits insecure page and creates an account via FB. My site tells the user they are logged in(*).
2A.  User visits secure page to access account details via FB.
2B.  Man-in-the middle visits secure page and uses credentials stolen during #1 to impersonate the user.
Is there a means for me to differentiate between a login token created on an insecure page and one created on a secure page? My current thinking is that I could use attach a nonce to Facebook's redirect_uri state parameter (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3#logindialog ), but I'm unsure if this is reasonable/safe.
(*) This is a half-truth to make the user happy.  The site pretends the user is fully logged in until they attempt to access protected content, at which point they will be asked to login again.  Sites like Amazon have similar behavior.


text:
Q: Transforming matrix diagonals to ragged array? I'm trying to come up with a non brute-force solution to the following problem. Given a matrix of arbitrary size:
[6  0  3  5]
[3  7  1  4]
[1  4  8  2]
[0  2  5  9]

Transform its diagonals to a list of vectors, like so:
(0)
(1, 2)
(3, 4, 5)
(6, 7, 8, 9)
(0, 1, 2)
(3, 4)
(5)

(Working from bottom left to top right in this example)
Is there an elegant way to do this short of iterating up the left column and across the top row?

A: I would just write a little function to transform the vector indices into matrix indices.
Say the matrix is NxN square, then there will be 2N-1 vectors; if we number the vectors from 0 to 2N-2, element k of vector n will be at row max(N-1-n+k,k) and column max(n+k-N+1,k) (or in reverse, the matrix element at row i, column j will be element min(i,j) of vector N-1+j-i). Then whenever you need to access an element of a vector, just convert the coordinates from k,n to i,j (that is, convert vector indices to matrix indices) and access the appropriate element of the matrix. Instead of actually having a list of vectors, you'll wind up with something that emulates a list of vectors, in the sense that it can give you any desired element of any vector in the list - which is really just as good. (Welcome to duck typing ;-)
If you're going to access every element of the matrix, though, it might just be quicker to iterate, rather than doing this computation every time.

A: (non-checked code)
Something like this (java code):
// suppose m is the matrix, so basically an int[][] array with r rows and c columns
// m is an int[rows][cols];

List result = new ArrayList(rows + cols - 1);
for (int i = 0; i < (rows + cols - 1))
{
  int y;
  int x;
  if (i < rows)
  {
    x = 0;
    y = rows - i - 1;
  }
  else
  {
    x = i - rows + 1;
    y = 0;
  }
  Vector v = new Vector();
  while (y < rows && x < cols)
  {
    y++;
    x++;
    v.add(new Integer(m[y][c]));
  }
  result.add(v);
}
// result now contains the vectors you wanted

Edit: i had x and y mixed up, corrected now.

A: Mathematica:
m = {{6, 0, 3, 5},
     {3, 7, 1, 4},
     {1, 4, 8, 2},
     {0, 2, 5, 9}};

Table[Diagonal[m, i], {i, 1 - Length@m, Length@m[[1]] - 1}]

Which gives a list of the i'th diagonals where the 0th diagonal is the main diagonal, i = -1 gives the one below it, etc.  In other words, it returns:
{{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {0, 1, 2}, {3, 4}, {5}}

Of course using the built-in Diagonal function is kind of cheating.  Here's an implementation of Diagonal from scratch:
(* Grab the diagonal starting from element (i,j). *)
diag0[m_,i_,j_] := Table[m[[i+k, j+k]], {k, 0, Min[Length[m]-i, Length@m[[1]]-j]}]

(* The i'th diagonal -- negative means below the main diagonal, positive above. *)
Diagonal[m_, i_] := If[i < 0, diag0[m, 1-i, 1], diag0[m, 1, i+1]]

The Table function is basically a for loop that collects into a list.  For example,
Table[2*i, {i, 1, 5}]

returns {2,4,6,8,10}.


text:
Q: What is the right place to start a service in MVVM architecture Android I just started using MVVM architecture on Android. I have a service which basically fetches some data and updates the UI and this is what I understood from MVVM:

*

*Activity should not know anything about the data and should take care of the views

*ViewModels should not know about activity

*Repository is responsible for getting the data

Now as ViewModels should not know anything about the activity and Activities should not do anything other than handling views, Can anyone please tell where should I start a service?

A: In MVVM, ideally, the methods to start a service should be defined in Repository since it has the responsibility to interact with Data Source. ViewModel keeps an instance of Repository and is responsible for calling the Repository methods and updating its own LiveData which could be a member of ViewModel. View keeps an instance of ViewModel and it observes LiveData of ViewModel and makes changes to UI accordingly. Here is some pseudo-code to give you a better picture.
class SampleRepository {
    fun getInstance(): SampleRepository {
        // return instance of SampleRepository
    }

    fun getDataFromService(): LiveData<Type> {
        // start some service and return LiveData
    }
}

class SampleViewModel {
    private val sampleRepository = SampleRepository.getInstance()
    private var sampleLiveData = MutableLiveData<Type>()

    // getter for sampleLiveData
    fun getSampleLiveData(): LiveData<Type> = sampleLiveData

    fun startService() {
        sampleLiveData.postValue(sampleRepository.getDataFromService())
    }
}

class SampleView {
    private var sampleViewModel: SampleViewModel

    // for activities, this sampleMethod is often their onCreate() method
    fun sampleMethod() {
        // instantiate sampleViewModel
        sampleViewModel = ViewModelProviders.of(this).get(SampleViewModel::class.java)
        // observe LiveData of sampleViewModel
        sampleViewModel.getSampleLiveData().observe(viewLifecycleOwner, Observer<Type> { newData ->
            // update UI here using newData
    }
}

A: As far as I know, Services are Android related so, they could be started from View (Activity/Fragment/Lifecycleowner).


text:
Q: obtaining info about facebook likes - strange issue I've developed some facebook application (wrote in php) that should allow users to use it only if they liked some fanpage.
Everything worked good till today when i received some feedback from users about blocked access to the application.
It seems like application doesnt let them in because they didnt liked the fanpage, but the point is that those users already like that fanpage (I tested it many times).
Im checking if user like a fanpage with the standard graph request like /USER_ID/likes?target_id=PAGE_ID
This mostly returns some array if user likes that page or empty array if he doesnt. In my case for those users it was always empty array.
I also checked /USER_ID/likes - for list of all likes of user, and for normal users i got response with json array of pages they like, in case of "bugged" users i again got empty array.
Im using PHP with phpsdk, so all requests are made with $facebook->api(...)
I have like 2 users with that problem now, others are fine.
I'm not sure if im doing something wrong or it is some of facebook bug.
I would be glad to hear opinion about that of anyone experienced with facebook api.
Thanks in advance.

A: The problem might be from the user not authorizing the app to access the user information. You can use the signed request from the Facebook API to see if the user has liked the page, which will be much more reliable.
require 'facebook.php';
$app_id = "app_id";
$app_secret = "app_secret";
$facebook = new Facebook(array(
    'appId' => $app_id,
    'secret' => $app_secret,
    'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
if($signed_request["page"]["liked"] != 1) {
    // Render the blocker page
}else{
    // Business as usual
}


text:
Q: accessing CSS static resource in Lighting Web Component How do you access (referencing) CSS static resource file in Lightning Web Component (LwC) html?   I have included the css under the "staticresources" folder and its uploaded in the salesforce static resource section.
I am referring this help doc but don't see how to reference css -
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_resources

A: I ran into a similar issue. The Salesforce docs show how to reference numerous resources except css, lol. There are a few details worth pointing out that the Salesforce doc doesn't explicitly mention:
I'll assume you are writing this in VSCode and have the default file structure (e.g. force-app\main\default etc.). Let's pretend you have your desired css in a file called myStaticStyles.css. Add myStaticStyles.css to your staticresources folder. Then, create a new file called myStaticStyles.resource-meta.xml file.
And here is what the code will look like:
controller.js
import { loadStyle } from 'lightning/platformResourceLoader';
import myStaticStyles from '@salesforce/resourceUrl/myStaticStyles'
/* notice that it's just myStaticStyles, not myStaticStyles.css.
The LWC framework will automatically compile your .css and .resource-meta.xml files
into the necessary css resource.
*/
export default class Controller extends LightningElement {
    connectedCallback() {
        loadStyle(this, myStaticStyles);
        //you can add a .then().catch() if you'd like, as loadStyle() returns a promise
    }
}

myStaticStyles.resource-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
    <contentType>text/css</contentType>
</StaticResource>

There are other tags you can add to configure your settings, but this is all you need to get things working. A .resource-meta.xml file is necessary in order to successfully deploy from source to org.
And your myStaticStyles.css will just have normal css.
Make sure you SFDX: Deploy source to org the static resources folder. Sometimes I would only deploy my component code and not realize the static resources were left behind.

A: You will most likely need to utilize loadStyle(self, fileUrl): Promise
 from lightning/platformResourceLoader. You can find a sample on Use Third-Party JavaScript Libraries

The platformResourceLoader module has two methods,  loadScript and loadStyle. Both methods return promises, which can be chained or used in parallel. You control the load sequence of your scripts or styles.

import resourceName from '@salesforce/resourceUrl/resourceName';
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';

loadStyle(this, resourceName + '/yourstyle.css')


text:
Q: Error running make - array type has incomplete element type I am trying to install libbow library. When i run make file the following error is generated
gcc -c   -Ibow -I. -I./argp -DHAVE_LIBNSL=1 -DHAVE_STRERROR=1 -DHAVE_GETTIMEOFDAY=1 -DHAVE_RANDOM=1 -DHAVE_SRANDOM=1 -DHAVE_SETENV=1 -DHAVE_STRCHR=1 -DHAVE_STRRCHR=1 -DHAVE_ALLOCA_H=1  -g -O -Wall -Wimplicit -o array.o array.c
In file included from array.c:22:
./bow/libbow.h:2128: error: array type has incomplete element type
make: *** [array.o] Error 1

The Source of libbow is :http://www.cs.cmu.edu/~mccallum/bow/src/
(The latest version)
Search results showed it as a compiler problem. How to resolve this? Or is there any other source for libbow?

A: The error points line 2128 of bow/libbow.h
extern struct argp_child bow_argp_children[];

It means that struct argp_child is not defined.
I noticed that in line 1346 there is a forward declaration of the structure.
struct argp_child;      /* forward declare this type */

The full declaration of the structure is in line 245 of argp/argp.h
To resolve this issue you can either

*

*Use include of argp.h in libbow.h
i.e #include "../argp/argp.h"

*Copy struct argp_child definition in libbow.h (not recommended)
An other thought is that you might compiling array.c from wrong directory and -Ibow -I. -I./argp does not point to the correct directories.


text:
Q: Dialog box name Does any one know the dialog below like a lower third?

A: It's called the Component Tray.

Non-visual components added to the Windows Forms Designer are placed on the Component Tray, located below the design surface, so that they are easily accessible without cluttering the visual design space.


text:
Q: retrieving data from sql database using C# with stored procedure Whenever I try to retrieve data from my database i keep getting null. The code i'm using is below:
protected void Button2_Click(object sender, EventArgs e)
 {
    SqlConnection myConnection = new SqlConnection(GetConnectionString());
    SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection);
    cmd.CommandType = CommandType.StoredProcedure;
    myConnection.Open();

    SqlParameter custId = cmd.Parameters.Add("@CustomerId", SqlDbType.Int);
    custId.Direction = ParameterDirection.Input;
    custId.Value = 10;

    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}
private static string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["Lab3ConnectionString"].ConnectionString;
}

A: You need to call Read before you can access data, Your code should be
While (dr.Read())
{

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

//close DataReader
dr.Close();

A: Before you read column values from DataReader you must invoke Read() method from data reader.
if (dr.Read())
{
    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

You can also try:
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);

A: You are missing a call to Read() on your reader. I also suggest you wrap your IDisposable objects in using statements as below.
You also seem to be using a strange combination of column names and ordinal positions when retrieving your values from the SqlDataReader.
protected void Button2_Click(object sender, EventArgs e)
{
    using (SqlConnection myConnection = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            myConnection.Open();

            SqlParameter custId = cmd.Parameters.AddWithValue("@CustomerId", 10);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    Label1.Text = dr["FirstName"].ToString();
                    Label2.Text = dr["LastName"].ToString();
                    Label3.Text = dr[3].ToString();
                    Label4.Text = dr["Email"].ToString();
                }
            }
        }
    }
}

A: SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
//Implicitly closes the connection because CommandBehavior.CloseConnection was specified.

Documentation: SqlCommand.ExecuteReader Method


text:
Q: When I try to post data an error message is generated "Internal Server Error" This is part my database schema
var commentSchema = new mongoose.Schema({
    comment: {
        type: String,
        required: true
    },
    commentOwner: {
        type: String,
        required: true
    }
});

and this is part of my angularjs controller
vm.addComment = function () {
        var id = $routeParams.id;
        var comment = vm.myComment;
        console.log(comment);
        var postData = {
            comment: comment,
            commentOwner: own
        };
        console.log(postData);
            postFactory.postComment(id, postData).then(function (response) {
            if (response.status === 200) {
                $route.reload();
                toastr["success"]("Basic Info Saved Successfully");
            }
        }).catch(function (error) {
            // console.log(error);
            toastr["error"]("unsuccessful.Please try again!");
        });

    }

this is my factory
function postComment(postId, comment){
        return $http.post('http://localhost:8080/api/posts/' + postId + '/comments', comment).then(complete).catch(failed);
    }
    function complete(response) {
        return response;
    }

    function failed(error) {
        console.log(error);
    }

and my the html part is like this
<form name="vm.commentForm" ng-submit="vm.addComment()">

            <input type="text" class="form-control" placeholder="Add your comment here"  required
                ng-model="vm.myComment" aria-label="comment" aria-describedby="sizing-addon1">

        <button style="margin:15px;" type="submit" class="btn btn-outline-primary">
             Send
        </button>
    </form>

and this is my express route controller
module.exports.addOneComment = function (req, res) {
    var id = req.params.postId;

    console.log('Add new comment', id);

    Post
        .findById(id)
        .select('comments')
        .exec(function (err, doc) {
            var response = {
                status: 200,
                message: doc
            };
            if (err) {
                console.log("Error finding the post");
                res.status(500).json({ "message": err });
            } else if (!doc) {
                console.log("PostId not found in database", id);
                res.status(404).json({ "message": "PostId not found in database" });
            }
            if (doc) {
                _addComment(req, res, doc);
            } else {
                res
                    .status(200)
                    .json({ "message": "Comment Added!" });
            }
        });
}
var _addComment = function (req, res, doc) {
    doc.comments.push({
        comment: req.body.comment,
        commentOwner: req.body.commentOwner
    });
    doc.save(function (err, postUpdated) {
        if (err) {
            res
                .status(500)
                .json(err);
        } else {
            res
                .status(200)
                .json(postUpdated.comments[postUpdated.comments.length - 1]);
        }
    });
}

when I try to post using postman it works fine, but I cannot post data from the application it self and generates an error message "Internal server error".So can you guys tell me what my mistake is? thank you very much!

A: In this code, only possibility I see is doc.save. Try adding a console.error(err) in your doc.save callback for more info.


text:
Q: PlantUML object layout control is not working, how to deal with that? @startuml
rectangle "System Architecture" as map {
    rectangle "Problem" as problem {
        rectangle "Quantity" as quantity {

        }

    }
    rectangle "Soluation" as solution {
        rectangle "Flow 1" as flow_1 {

        }
        rectangle "Flow 2" as flow_2 {

        }
        flow_1 -down[hidden]-> flow_2
        rectangle "Flow 3" as flow_3 {

        }
        flow_2 -down[hidden]-> flow_3
        rectangle "Flow ..." as flow_ {

        }
        flow_3 -down[hidden]-> flow_
        rectangle "Flow N" as flow_n {

        }
        flow_ -down[hidden]-> flow_n

    }
    problem -right[hidden]- flow_3
}

@enduml

I want problem laying left of solution, so I think problem -right-> solution can make it, but it turns out neither -left-  nor -right- can make any change, problem lays right anyway, what should I do?
SO tells me there mostly code out there, so here I am forced to make some bullshit, I think layout control of PlantUML is horrible, no one knows what is the result during development, OK, here it is

A: When I defined the rectangles in the other order and adjusted the arrow between problem and flow_3 it looks OK to me.
@startuml
rectangle "System Architecture" as map {

    rectangle "Soluation" as solution {
        rectangle "Flow 1" as flow_1 {

        }
        rectangle "Flow 2" as flow_2 {

        }
        flow_1 -down[hidden]-> flow_2
        rectangle "Flow 3" as flow_3 {

        }
        flow_2 -down[hidden]-> flow_3
        rectangle "Flow ..." as flow_ {

        }
        flow_3 -down[hidden]-> flow_
        rectangle "Flow N" as flow_n {

        }
        flow_ -down[hidden]-> flow_n

    }
    rectangle "Problem" as problem {
        rectangle "Quantity" as quantity {

        }

    }
    problem -[hidden]> flow_3
}
@enduml

Result in the plantuml web service:
http://www.plantuml.com/plantuml/uml/VP71JWCX48RlFCMazzsaoztKYqUZyMYCmOAM18OAGvh6xBkBYCkQmCvfXdp_nmGEWOIdQ0tpwaW2Fuo2tTCraB9mwuydJUauUhK34S2ACtmn1gdMj3DHa7QOcP2cdo61K6h5tXbtWNq6trFxka_OmitTn5GJKpjHR8Dq5tm-QIaLlWmt9TBrykhb6zwfxULTxpYErRmXvcrnrtjVhRYXRLkHiSgkp0_UlHbbi_hysxS_xp4A94tNJ7wMuVyQzOP5DVpjiRpQp0uAPRJc6m00
Maybe a source of some ideas:

*

*PlantUml define relative position of components

*How to correct PlantUML Line Path


text:
Q: Get data in AJAX I creating APP with SMS function and I want to display text messages and their details. I tried do something like this but this doesn't work.
Here is format data from SMS API:
object(stdClass)#30 (1) {
  ["items"]=>
  array(2) {
    [0]=>
    object(stdClass)#31 (7) {
      ["id"]=>
      int(396629)
      ["type"]=>
      string(2) "nd"
      ["phone"]=>
      string(12) "123456789"
      ["recived"]=>
      string(19) "2016-01-16 16:36:42"
      ["blacklist"]=>
      bool(false)
      ["text"]=>
      string(19) "Vrs wifi nie dziala"
      ["contact"]=>
      object(stdClass)#32 (10) {
        ["id"]=>
        string(9) "272075197"
        ["first_name"]=>
        string(6) "FirstName"
        ["last_name"]=>
        string(5) "LastName"
        ["company"]=>
        string(0) ""
        ["phone"]=>
        string(12) "123456789"
        ["email"]=>
        string(0) ""
        ["tax_id"]=>
        string(0) ""
        ["city"]=>
        string(0) ""
        ["address"]=>
        string(0) ""
        ["description"]=>
        string(0) ""
      }
    }
    [1]=>
    object(stdClass)#33 (7) {
      ["id"]=>
      int(396609)
      ["type"]=>
      string(2) "nd"
      ["phone"]=>
      string(12) "123456789"
      ["recived"]=>
      string(19) "2016-01-16 14:36:53"
      ["blacklist"]=>
      bool(false)
      ["text"]=>
      string(3) "vrs"
      ["contact"]=>
      object(stdClass)#34 (10) {
        ["id"]=>
        string(9) "272075197"
        ["first_name"]=>
        string(6) "FirstName"
        ["last_name"]=>
        string(5) "LastName"
        ["company"]=>
        string(0) ""
        ["phone"]=>
        string(12) "123456789"
        ["email"]=>
        string(0) ""
        ["tax_id"]=>
        string(0) ""
        ["city"]=>
        string(0) ""
        ["address"]=>
        string(0) ""
        ["description"]=>
        string(0) ""
      }
    }
  }
}

I do somethink like this:
$result = $serwersms->messages->recived('eco|nd|ndi|pre');

    $output = array();
    foreach ( $result->items as $key ) {
        $row = array();
        $row[] = $key->id;
        //var_dump RETURN: int(396609), etc.
        $row[] = $key->phone;
        $row[] = $key->text;
        $output[] = $row;

    }

    $output = array( "data" => $output );
    echo json_encode($output);

And AJAX:
$.ajax({
        url : "MY_URL_TO_FUNCTION",
        type: "GET",
        dataType: "JSON",
        success: function(data) {

            console.log(data.id);

        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Error');
        }
});

But I don't getting data, only 'undefined' in console.
AJAX response:
{"data":[[396629,"123456789","Vrs wifi nie dziala"],[396609,"123456789","vrs"]]}

What is wrong?


text:
Q: Windows 10 Home: is it possible to switch to Semi-Annual Channel instead of Semi-Annual Channel (Targeted)? Unlike Pro/Enterprise edition of Windows 10, Home edition does not have UI to select preferred update channel. Here is the options available in Pro edition:

Based on MSFT documentation Home edition only allows use of Semi-Annual Channel (Targeted) and Insider channels, but I'm wondering if we can force it to use Semi-Annual Channel (formerly known as CBB)?