text:
Q: If $\sin\theta+\cos\theta=1$ prove that $\cos\theta-\sin\theta=\pm1$ So my work,
Squaring both sides $$(\sin\theta+\cos\theta)^2=1$$
$$1+2\sin\theta\cos\theta=1\ \ \ \ \ \text{-------(i)}$$
$$\sin\theta\cos\theta=0 \ \ \ \ \ \text{------(ii)}$$
So reverting back to $(i)$,
$$\sin^2\theta+\cos^2\theta+2\sin\theta\cos\theta-4\sin\theta\cos\theta=1-4\sin\theta\cos\theta$$
$$(\cos\theta-\sin\theta)^2=1-4\sin\theta\cos\theta$$
$$\cos\theta-\sin\theta=\pm1$$

But my teacher says that there is a shorter solution than that, so please can someone help me find that?

A: After ii), you can say that one of the $\sin \theta$ and $\cos \theta$ has to be $0$, and this implies the other one to be $\pm 1$.
So also the difference $\sin \theta - \cos \theta = \pm 1$.

A: Notice, we have $$\cos \theta+\sin\theta=1$$
$$(\cos \theta+\sin\theta)^2=1$$$$\cos^2\theta+\sin^2\theta+2\sin \theta\cos \theta=1$$ $$1+2\sin \theta\cos \theta=1$$
$$\iff \sin\theta\cos \theta=0\tag 1$$
Now, we have
$$(\cos \theta-\sin\theta)^2=\cos^2\theta+\sin^2\theta-2\sin \theta\cos \theta$$
$$=(\cos^2\theta+\sin^2\theta+2\sin \theta\cos \theta)-4\sin \theta\cos \theta$$
$$=(\cos \theta+\sin\theta)^2-4\sin \theta\cos \theta$$
Substituting the corresponding values
$$=(1)^2-4(0)=1$$ $$\cos\theta-\sin\theta=\pm\sqrt 1=\pm 1$$

A: Let $x = \cos\theta$ and $y = \sin\theta$. Then $(x,y)$ is a point on
the unit circle. But the equation
$$\sin \theta + \cos \theta = 1$$
says that $x + y = 1$. So $(x,y)$ must be on the line given by $x + y = 1$,
that is, the line that intersects the unit circle at $(1,0)$ and $(0,1)$.
In fact, since $(x,y)$ is on that circle and on that line,
it must be one of those two points.
Case 1: $(x,y) = (0,1)$.
\begin{align}
\cos \theta &= 0 \\ \sin \theta &= 1 \\ \cos\theta - \sin\theta &= -1
\end{align}
Case 2: $(x,y) = (1,0)$
\begin{align}
\cos \theta &= 1 \\ \sin \theta &= 0 \\ \cos\theta - \sin\theta &= 1
\end{align}
And those are the only two possible cases that can occur.

A: $\cos \theta + \sin \theta=1$ is easily solved for $\theta$ in a graphical way, since it describes the intersection between a line and the goniometric circle:
$$
\begin{cases}
X+Y=1\\
X^2+Y^2=1,
\end{cases}
$$
where $X=\cos\theta$, $Y=\sin\theta.$
So either $\cos\theta =0$, $\sin\theta=1$, or viceversa. Plugging this into $\cos\theta-\sin\theta$ you either get $+1$ or $-1$.


text:
Q: Minimize parameters for createSelector in reselect Reactjs I am using reselect in my ReactJs code. Here is the code snippet. Due to large file, i am ommitting out unnecessary code from it.
import { createSelector } from 'reselect';

const todoSelector = state => state.todo.todos;
const searchTermSelector = state => state.todo.searchTerm;
const searchViewSelector = state => state.todo.userView

export const filteredTodos = createSelector(
  [todoSelector, searchTermSelector, searchViewSelector],
  (todos, searchTerm, searchView) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchTerm, 'i')));
  }
);

As you can notice the paramters for createSelector. As we know createSelector expects 2 arguments: an array of input selector(s) as the 1st argument and a function as the 2nd argument
In this case, array of input selectors is 3. ([todoSelector, searchTermSelector, searchViewSelector])
But in my actual code, array of input selectors are 9. I need to reduce the count from 9 to less than 4 due to sonar issues.
How can i minimize the array of input selectors and still make it work as expected. I search a lot online but i didnt find any ifno related to it. Please any suggestions ?

A: If you want to reduce the number of arguments per selector functions, you can separate logic into multiple pieces and use createSelector function result as an argument for another createSelector function. Something like this:
const todoSelector = state => state.todo.todos;
const searchTermSelector = state => state.todo.searchTerm;
const searchViewSelector = state => state.todo.userView

export const filteredTodosByTerm = createSelector(
  [todoSelector, searchTermSelector],
  (todos, searchTerm) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchTerm, 'i')));
  }
);

export const filteredTodosByView = createSelector(
  [filteredTodosByTerm, searchViewSelector],
  (todos, searchView) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchView, 'i')));
  }
);
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple 1 Page PHP Login Not Working NOTE: Before we get started, YES I understand this is not the most secure type of login. I am comfortable using this. However if you can modify this to work with MySql I will use that instead, but I cannot seem to get this script to work anymore after I added the cookies to it. What did I do wrong? Thanks in advance.
<?php
 if(isset($_COOKIE['user']) && isset($_COOKIE['pass'])) {
  $user = $_COOKIE['user'];
  $pass = $_COOKIE['pass'];
  }
else {
 $user = $_POST['user'];
 $pass = $_POST['pass'];
}

if($user == "user" && $pass == "pass") {
  setcookie("user", $user, time() + (86400 * 30), "/"); // 86400 = 1 day
  setcookie("pass", $pass, time() + (86400 * 30), "/"); // 86400 = 1 day
  echo 'Logged In';
}
else {
  if(isset($_POST))
    {?>

        <form method="POST" action="test.php">
        User <input type="text" name="user"></input>

        Pass <input type="password" name="pass"></input>

        <input type="submit" name="submit" value="Go"></input>
        </form>
<?php}
}
?>

The content I am securing with this, is just basic PHP forms. Nothing that can be used to harm my site if someone did get into this. Just don't want everyone accidentally accessing it.

A: I strongly advise against you using this in any kind of production environment, but if it's what you want to use then that's fine too.
I'll be showing you how to implement sessions instead of cookies here.
The very first step: Whenever you use sessions, the very first thing you need to do on every script that uses those sessions is to start the session with:
session_start();

Now for session the session, that's simple. All you need to do is add an index to the $_SESSION superglobal:
$_SESSION['user'] = $user;

The trick though is not to force your user to login through the procedure you currently have. A session means the user is authenticated, so you don't want to force them to login again. What you want to do is add a check at the top of your file like this:
<?php
session_start(); // start the session

if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
    die(header("Location: admin.php")); // user is logged in, send them to admin/user only page...
}

Which ends up leaving your "Login" script looking like this:
<?php
session_start(); // start the session

if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
    die(header("Location: admin.php")); // user is logged in, send them to admin/user only page...
}

if(isset($_POST['submit'])) {
    if($user == "user" && $pass == "pass") {
        $_SESSION['user'] = $user;
        die(header("Location: admin.php"));
    } else {
        // add some sort of error handling here because the user had invalid credentials.
    }
} else {
 ?>
    <form method="POST" action="">
        User <input type="text" name="user"></input>

        Pass <input type="password" name="pass"></input>

        <input type="submit" name="submit" value="Go"></input>
    </form>
<?php
}
?>

A: Here you go.  Not sure why this mattered but it worked for me.  (I changed the cookie duration too, but that wasn't part of the fix.)
<?php
 if(isset($_COOKIE['user']) && isset($_COOKIE['pass'])) {
  $user = $_COOKIE['user'];
  $pass = $_COOKIE['pass'];
  }
else {
 $user = $_POST['user'];
 $pass = $_POST['pass'];
}

if($user == "user" && $pass == "pass") {
  setcookie("user", $user, time() + (1800), "/"); // 86400 = 1 day
  setcookie("pass", $pass, time() + (1800), "/"); // 86400 = 1 day
  echo 'Logged In';
}
else {
  if(isset($_POST))
    {?>

        <form method="POST" action="test.php">
        User <input type="text" name="user"></input>

        Pass <input type="password" name="pass"></input>

        <input type="submit" name="submit" value="Go"></input>
        </form>
<?php
}}
?>

I changed your:
<?php}
}
?>

to:
<?php
}}
?>


text:
Q: Print out date (declared as a character) as a string i have this code that i need to print out the values without changing the char sizes.
#include <stdio.h>
#include <string.h>
typedef struct studentData
{
int ID;
char lastName[10];
char firstName[10];
char birthMonth[2];
char birthDay[2];
char birthYear[4];
}
studentData;

int main()
{
 studentData admin={12345,"John","Doe","07","12","1990"};

printf("ID: %d\n",admin.ID);
printf("Last Name: %s\n",admin.lastName);
printf("First Name: %s\n",admin.firstName);
printf("Birth Month: %s\n",admin.birthMonth);
printf("Birth Day: %s\n",admin.birthDay);
printf("Birth Year: %s\n",admin.birthYear);

return 0;
}

my results
ID: 12345
Last Name: John
First Name: Doe
Birth Month: 07121990
Birth Day: 121990
Birth Year: 1990

What i want
ID: 12345
Last Name: John
First Name: Doe
Birth Month: 07
Birth Day: 12
Birth Year: 1990

I want to keep the Date as 2 bytes, month as 2 bytes so the \0 won't work here

A: Use a precision specifier with "%s" to not print more than the array size.  In this way admin.birthMonth does not need to be null character terminated.  Yet if code is later working with strings, using a wider array is judicious, only a tad memory expensive.

the maximum number of bytes to be written for s conversions.  C11dr §7.21.6.1 4

printf("Birth Month: %.2s\n",admin.birthMonth);
// or
printf("Birth Month: %.*s\n", (int) (sizeof admin.birthMonth), admin.birthMonth);

A: The assignment operation just fails to put a NULL character in the end for birthMonth, birthDay and birthYear because sizes of what you are trying to assign (i.e. "07", "12" or "1990") are same as sizes of the arrays (i.e. birthDay, birthMonth, birthYear). Make their corresponding array size atleast 1byte wider to make them able to contain a NULL-terminated string.
typedef struct studentData
{
    int ID;
    char lastName[10];
    char firstName[10];
    char birthMonth[3];
    char birthDay[3];
    char birthYear[5];
}
studentData;

As the size was exactly same as the size of what you want to assign, it fails to put a NULL in the end which results to printing Garbage characters.
Or
You can print using Precision Specifier i.e. by specifying how many characters you want to print like following
printf("Birth Month: %.2s\n", admin.birthMonth);
printf("Birth Day: %.2s\n", admin.birthDay);
printf("Birth Year: %.4s\n", admin.birthYear);

Look into this to read more about Width & Precision Specifiers.

A:

typedef struct studentData
{

    int ID;
    char lastName[10];
    char firstName[10];
    char birthMonth[3];
    char birthDay[3];
    char birthYear[5];

}

studentData;

int main()
{

    studentData admin={12345,"John","Doe","07","12","1990"};
    printf("ID: %d\n",admin.ID);
    printf("Last Name: %s\n",admin.lastName);
    printf("First Name: %s\n",admin.firstName);
    printf("Birth Month: %s\n",admin.birthMonth);
    printf("Birth Day: %s\n",admin.birthDay);
    printf("Birth Year: %s\n",admin.birthYear);
    return 0;

}

birthmonth, birthdate and birthyear should have size 3,3 & 5 so that the last space occupy the null character. In your code, the size is equal to the no. of character you want.
Thank You


text:
Q: JRuby on Rails vs. Ruby on Rails, what's difference? I'm looking to try out JRuby and JRuby on Rails. I'm having trouble finding information on what's difference between JRuby on Rails and Ruby on Rails.
What's the differences I need to look out for?

A: I may be wrong, but I think you can package a JRuby on Rails app in a way you can't do with normal RoR - look at Mingle or similar. Makes it possible to sell without dropping your pants / opening the komono.
That said, I'm not familiar enough with RoR packaging, so dont hold me to it :)

A: I'm surprised there's a crucial thing missing in all answers to this question, related  to GIL.
The main difference you should care about esp. in web-applications such as ones built with Rails is true concurrency ("Global Interpreter Lock" free). When two threads are running (e.g. serving 2 user requests) with JRuby they are capable of running concurrently within a single process, while in MRI there's the GIL (even with 1.9's native threads) that avoids executing Ruby code in parallel.
For an application developer this is the first thing to keep in mind while considering JRuby, as it really shines with config.threadsafe! but requires you to make sure your code (and your gems code) to be "truly" thread-safe.

A: mostly it should work the same. in jRoR you can access stuff you wouldn't have in RoR. Usually its mainly a deployment concern.
However, if your RoR app uses native libraries that don't have an equivalent that runs on the JVM, that can be a pain. However most libs have a non native version available (at least the popular ones I have come across).

A: There are some great answers here already.
eebbesen already covered the basics, and kares (himself!) has told us JRuby has no GIL.
I'll add from a more practical perspective, I've launched apps on Ruby on Rails, and then migrated to JRuby for performance reasons.
There were two main performance benefits: JRuby is (or was) simply faster than Ruby in some circumstances, and two, the lack of the Global Interpreter Lock kares mentions allowed me to do multithreading, which, while tricky, unlocked orders of magnitude performance benefits.
A very large Ruby on Rails app ported and ran in an hour, gems and all. The only actual glitch was that Java's regexes are slightly different than Ruby's. That's a monumental achievement on JRuby's part.

A: JRuby is the Ruby implementation that runs on a JVM whereas Matz's Ruby is a C implementation.
Key features to note are:

*

*JRuby runs on Java VM's and it's either compiled or interpreted down to Java byte code.

*JRuby can integrate with Java code. If you have Java class libraries (.jar's), you can reference and use them from within Ruby code with JRuby. In the other direction you can also call JRuby code from within Java. JRuby can also use the JVM and application server capabilities.

*JRuby is usually hosted within Java application servers such as Sun's GlassFish or even the Tomcat web server.

*Although you cannot use native Ruby gems with JRuby there are JRuby implementations for most of the popular Ruby libraries.

There are other differences which are listed at the JRuby wiki:

*

*Differences between JRuby and Ruby (MRI)

*JRuby On Rails


text:
Q: Activity monitor is unable to execute queries against server Is there any fix to get SSMS activity monitor working?
Problem:
SQL Server Activity Monitor fails with an error dialog:

TITLE: Microsoft SQL Server Management
  Studio The Activity Monitor is
  unable to execute queries against
  server [SERVER]. Activity Monitor for
  this instance will be placed into a
  paused state. Use the context menu in
  the overview pane to resume the
  Activity Monitor.
ADDITIONAL INFORMATION: Unable to
  find SQL Server process ID [PID] on
  server [SERVER]
  (Microsoft.SqlServer.Management.ResourceMonitoring)

I have this problem on SQL Server 2008 R2 x64 Developer Edition, but I think it is found in all 64bit systems using SQL Server 2008, under some yet unidentified conditions.
There is a bug report on this in Microsoft Connect, but it is not solved yet.

A: OK, I think I have found a solution.
The issue seems to be with the mix of 32bit and 64bit apps that need to query each-other.
If you enable the service Performance Counter DLL Host in the Services control panel, the Activity Monitor should now work.

A: Check if SQLServer performance counters exist in the Performance Monitor. If not, manually rebuild all performance counters running lodctr /R command with administrative priviledges:
cd \windows\system32
lodctr /R

A: In the simplest case all you need to do is to restart the SSMS. I just had this problem with SSMS 2008 R2 running against 2005 server after I had lost network connection while the Activity Monitor was running. I tried a couple of tricks before I decided to try restarting SSMS and that's what helped.

A: If SQL is running on a Windows 2008 R2 server or cluster, go to the Performance Monitor application, expand the Data Collection Sets, then select the System Performance, if the arrow is green on the line below the menu just click on it. This will restart the counters, you may wish to do same for System Diagnosis collection set.
Then just refresh or open new connection to the SQL instance you wish to open SSMS Activity Monitor for, this should have solved your problem.
I just stumbled into this today. Of course, the error message saying Use the context menu in the overview pane to resume the Activity Monitor didn't help me in the least.
Hope this helps someone.

A: I thought I would post my experience with this issue.
Symptoms - SQL Server 2008 R2, on Dell machine, suddenly suffered huge performance degradation. User applications became very slow when performing queries. Activity monitor would start - but the above process timeout error would occur if you tried to open the process list.
Restored backups of the databases performed fine on a second server with half the memory. Restoring these same backups to the original server did not resolve the problem.
I ran dbcc's on all databases, rebuilt indices. Forced re-create of the Windows page file. Tried restarting SQL server. Tried rebooting the server. None of these worked. Reset the performance counters as described above - this improved the server CPU usage but did not resolve any problems.
Our network admin wanted to rule out hardware issues. He updated the device drivers for the RAID controllers, then powered down the server. He used a power sequence from Dell to purge memory, this involved disconnecting from the power supply. After restarting, the server performed fine.
We believe the power cycle resolved the issue, and that the underlying problem was with the hardware memory.

A: I was getting the same error message and viewed the Technical Details.  That led me to the Microsoft.SqlServer.Management.ResourceMonitoring.dll.  I decompiled the method that was throwing the error and after a bit of tracing through the code I found an area where a PerformanceCounter in the "Process" group was trying to be instantiated.  Well I checked in Perfmon and that group wasn't there.  Other counters were working but that one wasn't there.  Looks like that group got disabled somehow.
How to fix it:
Use regedit to find HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
there is a key in there called Disable Performance Counters , delete it or set it to 0  You may need a restart after you change the key.

A: I can't comment yet hence the new answer...
I tried EightVans suggestion first

How to fix it: Use regedit to find HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance there is a key in there called Disable Performance Counters , delete it or set it to 0 You may need a restart after you change the key.

And i still experienced the problem. Then i tried renaud's suggestion:

If you enable the service Performance Counter DLL Host in the Services control panel, the Activity Monitor should now work.

And i still experienced the problem. Then I tried Mika's suggestion:

Check if SQLServer performance counters exist in the Performance Monitor. If not, manually rebuild all performance counters running lodctr /R command with administrative priviledges:

Now the activity monitor is working!

A: I just do
EightVans suggestion first
How to fix it: Use regedit to find HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance there is a key in there called Disable Performance Counters , delete it or set it to 0 You may need a restart after you change the key.
and  Mika's suggestion:
Check if SQLServer performance counters exist in the Performance Monitor. If not, manually rebuild all performance counters running lodctr /R command with administrative priviledges:
And activity monitor is now running in my system!


text:
Q: React/ React Web Component/ is it possible to fetch data? I have introduced a React Component in my html website and have been trying to fetch data from a data.js file or data.json file to no result.
I have already tried:
import {data} from './data' when it was a data.js file and import data from './data.json' when it was a json file. I have also tried data = require("./data.js"). Each time it generates a RefferenceError: require is not defined.
I was hoping to bring data for posts to be generated with each data value. Maybe it is not possible in a simple React Web Component and without creating a whole React App. Not much I have found online to read about React Web Components and their ways.
The component:
const names = [
  {
    name: "name",
  },
  "Ada Lovelace",
  "Grace Hopper",
  "Margaret Hamilton",
];

class TitleAddition extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: "",
      name: "",
    };
  }

  render() {
    return (
      <>
        {names.forEach((item) => {
          console.log(item);
        })}
        {`${this.props.name}`}
        {
          //some HTML
        }
      </>
    );
  }
}

And I was hoping to take the names array into a separate file - without any result.

A: The problem is React when called a script on a standard HTML page doesn't have access to the filesystem. When you deploy a React app using create-react-app, it runs on a Node.js server, and the app has access to its own server root. If you want to do this as a web component, you'll need to create some sort of back-end API to fetch your data via fetch() function.
Now, if this is the only dynamic data your site is going to display, then I'd say go that route. If you plan to have other pages with dynamic data, then I highly recommend deploying your site as a full React app. Actually, I would recommend you use Next.JS, which is a layer on top of React. NextJS is more comprehensive and is production ready out of the box. And another huge bonus is you can deploy your app via the next-cli or automatically via Github commits to Vercel, the makers of Next.JS.
In addition to all standard React libraries, Next.JS handles routing for you via the pages directory, so a URL on your site like https://example.com/blog would automatically route to /pages/blog/index.js. You can also have dynamic routes as easily as https://example.com/blog/some-blog-slug => /pages/blog/[slug].js.
Lastly, Next.JS has a built-in back-end express server API with the same filesystem-based routing as the pages directory.
Next.JS also does static site generation and can automatically rebuild portions of the site when the data sources changes. I highly recommend you check it out.


text:
Q: how can i solve this error: no rule to make target 'Button icon.qml' needed by 'all-am'.stop this is the error when i am trying to make navit in ubuntu10.10
   error: no rule to make target 'Button icon.qml' needed by 'all-am'.stop.

i dont know how to solve it.somebody help me

A: Try running sudo apt-get build-dep navit, then run ./configure && make again.

A: If you are trying to build the source from this files you must get the missing .qml files from the SVN repository (https://navit.svn.sourceforge.net/svnroot/navit/trunk/navit) and place them under navit/gui/qml/skins/navit/


text:
Q: Getting value from DataView class in google chart to a javascript array I'm trying to get the values from the DataView class of google chart into a javascript array and I can't seem to figure it out. Any help is greatly thankful.
Image of Data
Here is my code:
    <html>
    <head>
      <script type="text/javascript" src="https://www.google.com/jsapi"></script>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script type="text/javascript">
      google.load('visualization', '1', {'packages': ['table', 'corechart','controls']});
      google.setOnLoadCallback(initialize);

    function initialize() {
              // The URL of the spreadsheet to source data from.
              var query = new google.visualization.Query(
                'https://docs.google.com/spreadsheets/d/11w3bG72wkWpqAneTRNwQWKzPsMaQgveYCe5OPvbq9CA/edit#gid=0');
              query.setQuery("select A, D");
              query.send(draw);
             }
             function draw(response) {
                if (response.isError()) {
                    alert('Error in query');
                }
                var frequency = response.getDataTable();
                var format1 = new google.visualization.DateFormat({pattern: "Hms"});
                format1.format(frequency, 0);
                var view = new google.visualization.DataView(frequency);
                var table = new google.visualization.Table(document.getElementById('table_div'));
                view.setColumns([0]);
                // to get the values from the view to array arr
                var i;
                var arr = [];
                for(i in view){
                    arr [i] = view.getValue(i, 0);
                }
                var x;
                for(x in arr){
                    document.write(arr[x]);
                }
             }
            </script>
           </head>
           <body>
            <div id="table_div">
            </div>
           </body>
           </html>

A: try this...
var i;
var arr = [];
for (i = 0; i < view.getNumberOfRows(); i++) {
  arr.push(view.getValue(i, 0));
}


text:
Q: Require boolean attribute on model to be false or empty How can I use annotations to require a boolean model property to be either false or empty?
Example:
// model
public class MyModel
{
  public string StringProperty { get; set; }
  public bool BoolProperty { get; set; }
}

OK:
POST /someEndpoint
{
  "stringProperty": "foobar"
}

POST /someEndpoint
{
  "stringProperty": "foobar",
  "boolProperty": false
}

400:
POST /someEndpoint
{
  "stringProperty": "foobar",
  "boolProperty": true
}

I want to validate the model using ModelState.IsValid. So far, I've tried using [Range(typeof(bool), "false", "false")] but ModelState.IsValid returns true even if boolProperty is set to true. Any help?

A: I created a custom validation attribute and it works for me
    public class AllowedOnlyFalse : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null) return true;
            bool val = Convert.ToBoolean(value);
            return !val;
        }
    }

    // model
    public class MyModel
    {
        public string StringProperty { get; set; }

        [AllowedOnlyFalse]
        public bool BoolProperty { get; set; }
    }


text:
Q: Priority Queue remove complexity time What is the complexity (big-oh) for the remove() function on the Priority Queue class in Java? I can't find anything documented anywhere, I think it's O(n), considering you have to find the element before you remove it and then reshuffle the tree. but I've seen others that disagree and think it's O(logn). Any ideas?

A: The confusion is actually caused by your "remove" function. In java, there are two remove functions.

*

*remove() -> This is to remove the head/root, it takes O(logN) time.

*remove(Object o) -> This is to remove an arbitrary object. Finding this object takes O(N) time, and removing it takes O(logN) time.

A: The complexity for remove is O(N) since the complexity for contains is O(N) (in java's priority queue class)
One way this can be made O(logN) in your own Priority Queue implementation is to maintain an auxiliary data structure like a HashMap that maintains the mappings from a value in the priority queue to its position in the queue. So, at any given time - you would know the index position of any value.
Note that this modification does not affect the running time of any of the existing operations - you would only need to update the mappings during the heapify operations.

A: According to Oracle documentation:
"Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size)."
Link here to Oracle Doc

A: Please check:
http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
"this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods"
Thus for poll() and remove(), that' log(N)
But for remove(object), that log(N)


text:
Q: Trying to make a simple Sql query in PHP Hello can you help me with this script?
Im trying to pull information on my slider from database.
$query = "SELECT * FROM `slider1`";
$select_from_slider1 = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_from_slider1)){
    $slider1_title = $row['slider1_title'];
    $slider1_content = $row['slider1_content'];
    $slider1_moreinfo = $row['slider1_moreinfo'];
    ?>

<?php echo $slider1_title ?>

<?php echo $slider1_content ?>

    <?php echo $slider1_moreinfo ?>
<?php } ?>

This is the error i get:

Lol im sorry i figured it out myself, the reason for the error was that i dublicated many times include "database"....
Thanks guys for the fast replies.!

A: Looks like the var $connection isn't a mysqli connection. You'll need the following somewhere this script can access it.
$connection = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

http://php.net/manual/en/mysqli.construct.php


text:
Q: How to resolve HA: px ≠ py? I have two samples:
allprogrammers <- subset(df, job == "programmer")
sampleprogrammers <- sample(1:523, 50, replace=FALSE)
allprogrammers_sample = allprogrammers[sampleprogrammers]

and
allanalysts <- subset(df, job == "analysts")
sampleanalysts <- sample(1:482, 50, replace=FALSE)
allanalysts_sample = allanalysts[sampleanalysts]

I need to proof that HA: px ≠ py (so allprogrammers ≠ allanalysts) with 2%.
All the info the teacher gave us before starting to work at home is this, but I really don't understand how to use this to resolve the problem.
Cas de deux populations
Exemple 9.5
H0: px=py contre HA: px != py
prop.test(x = c(54, 108), n = c(300, 450), alternative="two.sided", conf.level=0.90)


text:
Q: looking for help call a perl script with arguments from java class I have to call a Perl script from a Java class. I am able to do that using
final ProcessBuilder builder = new ProcessBuilder("perl", "/home/abc.pl");

I am wondering if I can pass parameters something like
new ProcessBuilder("perl", "/home/abc.pl  x y");

But it's throwing an error.
Could someone please suggest how this could be done?

A: From the documentation:

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");

Each argument to the program you are calling needs to be a separate argument to the ProcessBuilder constructor.
new ProcessBuilder("perl", "/home/abc.pl", "x", "y");

Otherwise you are calling the equivalent of perl "/home/abc.pl x y" and it will be unable to find a file called "/home/abc.pl x y" (since x and y are different arguments, not part of the file name).

A: Use following code to execute your perl code from java.
final List<String> commands = new ArrayList<String>();

commands.add("perl");
commands.add("/home/abc.pl");
commands.add("x");
commands.add("y");
ProcessBuilder pb = new ProcessBuilder(commands);


text:
Q: How do I replace backspace characters (\b) using sed? I want to delete a fixed number of some backspace characters ocurrences ( \b ) from stdin. So far I have tried this:
echo -e "1234\b\b\b56" | sed 's/\b{3}//'

But it doesn't work. How can I achieve this using sed or some other unix shell tool?

A: You can use tr:
echo -e "1234\b\b\b56" | tr -d '\b'
123456

If you want to delete three consecutive backspaces, you can use Perl:
echo -e "1234\b\b\b56" | perl -pe 's/(\010){3}//'

A: sed interprets \b as a word boundary. I got this to work in perl like so:
echo -e "1234\b\b\b56" | perl -pe '$b="\b";s/$b//g'

A: With sed:
echo "123\b\b\b5" | sed 's/[\b]\{3\}//g'
You have to escape the { and } in the {3}, and also treat the \b special by using a character class.
[birryree@lilun ~]$ echo "123\b\b\b5" | sed 's/[\b]\{3\}//g'
1235

A: Note if you want to remove the characters being deleted also, have a look at ansi2html.sh which contains processing like:
printf "12..\b\b34\n" | sed ':s; s#[^\x08]\x08##g; t s'

A: You can use the hexadecimal value for backspace:
echo -e "1234\b\b\b56" | sed 's/\x08\{3\}//'

You also need to escape the braces.

A: No need for Perl here!
# version 1
echo -e "1234\b\b\b56" | sed $'s/\b\{3\}//' | od -c

# version 2
bvar="$(printf '%b' '\b')"
echo -e "1234\b\b\b56" | sed 's/'${bvar}'\{3\}//' | od -c


text:
Q: CakePHP Auth: How to authenticate with email having multiple emails on the same account? I'm starting with CakePHP. I've build an users table logging with email instead of username...
Problem is that i wan't to have, not one, but many emails for each user so they can login into the same account using any of their emails, almost like facebook does.
My question, once that CakePHP doesn't allows me to create dynamicly multiple attributes (see my previous question), what is the best way to do this?

A: My advice would be to setup two tables in your database:

*

*USERS

*USER_EMAILS

In your USERS table, you store whatever you want about your users:

*

*id

*username

*fname

*lname

*telephone

*etc...

Then you setup your USER_EMAILS table to reference the USERS table with a foreign key:

*

*user_id (foreign key)

*email

Make the "email" a unique index to prevent duplicates.
Now whenever you lookup an email address in the USER_EMAILS table (say at login), you will get a reference to the USER you are supposed to be working with.
Does that make sense?

A: You probablly need to do what @Petar answered... in order to store multiple emails for each user.
To authenticate the users, you migth need to create a custom authentication object where you'll have to create an authenticate() method that makes the query and returns true if the email-password is correct.
Dont forget to set this new authentication object in your AppController. It should be something like:
AppController.php
// Pass settings in $components array
public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'MultipleEmails'
        )
    )
);

Component/Auth/MultipleEmailsAuthenticate.php
class MultipleEmailsAuthenticate extends BaseAuthenticate {
    public function authenticate(CakeRequest $request, CakeResponse $response) {
        //make your query here and return true or false
    }

If you want some examples on how to write a BaseAuthenticate class, you could read the source files: BaseAuthenticate and FormAuthenticate.
Hope this helps


text:
Q: Getting rid of "static" references in C# I've recently begun learning C# but have encountered an annoying problem. Every variable I want available to all functions in my program I have to put a "static" in front of and also every function. What I'd like to know is how to avoid this, if possible?
Also, small side question: creating public variables inside functions?
This is what my program looks like right now, and I want to basically keep it like that, without having to add "static" everywhere:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace NetworkExercise
{
class Client
{
    public IPAddress addr;
    public int port;
    public string name;
    public Thread thread;
    public TcpClient tcp;
    public NetworkStream stream;

    public Client(IPAddress addr, int port, string name, NetworkStream stream)
    {
    }
}
class Program
{
    //NETWORK
    TcpListener tcpListener;
    Thread listenThread;
    ASCIIEncoding encoder = new ASCIIEncoding();
    //DATA
    byte[] buffer = new byte[4096];
    string servIp;
    int servPort;
    //CLIENT MANAGEMENT
    int clientNum;

    static void Main(string[] args)
    {
        beginConnect();
    }
    public void beginConnect()
    {
        Console.Write("Server IP (leave blank if you're the host): ");
        servIp = Console.ReadLine();
        Console.Write("Port: ");
        servPort = Console.Read();

        tcpListener = new TcpListener(IPAddress.Any, servPort);
        listenThread = new Thread(new ThreadStart(listenForClients));
        listenThread.Start();
    }
    public void listenForClients()
    {
        tcpListener.Start();

        Console.WriteLine("Listening for clients...");

        while (true)
        {
            Client cl = new Client(null, servPort, null, null);
            cl.tcp = tcpListener.AcceptTcpClient();
            ThreadStart pts = delegate { handleClientCom(cl); };
            cl.thread = new Thread(pts);
            cl.thread.Start();
        }
    }
    public void handleClientCom(Client cl)
    {
        cl.stream = cl.tcp.GetStream();
    }

}

}

A: Try creating an instance of Program class in the main function. Like:
Program program = new Program();

Then you can access the member functions, like:
program.beginConnect();

A: Using global variables is generally considered bad practice as they increase coupling and damage maintainability, so you should rethink your approach if you find yourself using them often. If all of your code uses the same few variables, you can have a very difficult time debugging it, since you have to track the global state of the system and you've no idea which part of the program has been modifying it.
Also, you should almost never use public fields in classes, for similar reasons. Doing so allows client code to become tied directly into the implementation of your class such that if you change the class's internal mechanics then the client code breaks. What you should be using is properties.
To answer your question, though: no, if you want a member to be globally accessible, it must be static. Otherwise it exists only on an object, to which you would need a reference in order to access it.
Some key ideas you might want to read about here are dependency injection and encapsulation.

A: You have hit on something fundamental that is really important to understand, what does the 'static' keyword mean and how do I use it correctly? You will be surprised how many people cannot answer this question correctly.
As Rakesh has mentioned, the compiler is asking you to mark your 'beginConnect' method as static because beginConnect is an instance method, ie you require an instance of the object in order to call the method. His example works (same as tafa's answer), I would just add that it doesn't 'feel' right to create an instance of Program, put the logic (methods and properties) into a separate class, create an instance of that class then call the method.
While you are researching and getting an understanding of 'static' I strongly recommend also getting a solid understanding of the difference between a static type and a reference type.

A: Write this in Main:

static void Main(string[] args)
{
 Program myProgram = new Program();
 myProgram.beginConnect();
}


text:
Q: Layout is not working for iPhone 6 The calendar displays for iPhone 5 but does not work for iPhone 6.In iPhone 6 the layout is changed
this is my code:
 calendar = [[DSLCalendarView alloc]initWithFrame:CGRectMake(10, 64, 320, 320)];

this is image for iPhone 6 its not working
This the image for iPhone 5 is working.

A: You need to adopt auto-layout in order to make your Calendar responsive. Also you have fixed width of calendar. Change
CGRectMake(10, 64, 320, 320)

to
CGRectMake(10,64,self.view.frame.width, self.view.frame.height)


text:
Q: Can Polymodel classes be used with Basemodel in the Google App Engine Django Helper? The Django Helper for Google App Engine creates BaseModel to allow a model to exist both in Django and App Engine. Does the helper provide a way to use Polymodels with Django?

A: I'm not aware of any functionality in the helper to incorporate Polymodel.   I think you're going to have to change BaseModel to inherit from Polymodel and test it out to see if anything breaks.
There was a question about this here, but no one responded.  There's been some activity lately on the mailing list, so you might want to raise it again: http://groups.google.com/group/app-engine-django/browse_thread/thread/cdaba1ed81a9d958


text: Q: Можно ли переставить ssd на другой ноут Суть такова, есть два ноутбука. 1 - мой, 2 - не мой, но я им пользуюсь, и на нём хард повреждённый. Хочу переставлять ssd из моего ноута туда-сюда, по мере использования, потому что второй попросту мощнее, но к нему нет доступа 24/7. Винда на ссд стоит 11я, она сможет подтягивать необходимые драйвера при перестановки ssd из системы в систему?


text:
Q: How to generate the "create table" sql statement for an existing table in postgreSQL I have created a table in postgreSQL. I want to look at the SQL statement used to create the table but cannot figure it out.
How do I get the create table SQL statement for an existing table in Postgres via commandline or SQL statement?

A: Even more modification based on response from @vkkeeper. Added possibility to query table from the specific schema.
CREATE OR REPLACE FUNCTION public.describe_table(p_schema_name character varying, p_table_name character varying)
  RETURNS SETOF text AS
$BODY$
DECLARE
    v_table_ddl   text;
    column_record record;
    table_rec record;
    constraint_rec record;
    firstrec boolean;
BEGIN
    FOR table_rec IN
        SELECT c.relname, c.oid FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                WHERE relkind = 'r'
                AND n.nspname = p_schema_name
                AND relname~ ('^('||p_table_name||')$')
          ORDER BY c.relname
    LOOP
        FOR column_record IN
            SELECT
                b.nspname as schema_name,
                b.relname as table_name,
                a.attname as column_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
                CASE WHEN
                    (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                     FROM pg_catalog.pg_attrdef d
                     WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
                    'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                                  FROM pg_catalog.pg_attrdef d
                                  WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
                ELSE
                    ''
                END as column_default_value,
                CASE WHEN a.attnotnull = true THEN
                    'NOT NULL'
                ELSE
                    'NULL'
                END as column_not_null,
                a.attnum as attnum,
                e.max_attnum as max_attnum
            FROM
                pg_catalog.pg_attribute a
                INNER JOIN
                 (SELECT c.oid,
                    n.nspname,
                    c.relname
                  FROM pg_catalog.pg_class c
                       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                  WHERE c.oid = table_rec.oid
                  ORDER BY 2, 3) b
                ON a.attrelid = b.oid
                INNER JOIN
                 (SELECT
                      a.attrelid,
                      max(a.attnum) as max_attnum
                  FROM pg_catalog.pg_attribute a
                  WHERE a.attnum > 0
                    AND NOT a.attisdropped
                  GROUP BY a.attrelid) e
                ON a.attrelid=e.attrelid
            WHERE a.attnum > 0
              AND NOT a.attisdropped
            ORDER BY a.attnum
        LOOP
            IF column_record.attnum = 1 THEN
                v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
            ELSE
                v_table_ddl:=v_table_ddl||',';
            END IF;

            IF column_record.attnum <= column_record.max_attnum THEN
                v_table_ddl:=v_table_ddl||chr(10)||
                         '    '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
            END IF;
        END LOOP;

        firstrec := TRUE;
        FOR constraint_rec IN
            SELECT conname, pg_get_constraintdef(c.oid) as constrainddef
                FROM pg_constraint c
                    WHERE conrelid=(
                        SELECT attrelid FROM pg_attribute
                        WHERE attrelid = (
                            SELECT oid FROM pg_class WHERE relname = table_rec.relname
                                AND relnamespace = (SELECT ns.oid FROM pg_namespace ns WHERE ns.nspname = p_schema_name)
                        ) AND attname='tableoid'
                    )
        LOOP
            v_table_ddl:=v_table_ddl||','||chr(10);
            v_table_ddl:=v_table_ddl||'CONSTRAINT '||constraint_rec.conname;
            v_table_ddl:=v_table_ddl||chr(10)||'    '||constraint_rec.constrainddef;
            firstrec := FALSE;
        END LOOP;
        v_table_ddl:=v_table_ddl||');';
        RETURN NEXT v_table_ddl;
    END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

A: Here is a single statement that will generate the DDL for a single table in a specified schema, including constraints.
SELECT 'CREATE TABLE ' || pn.nspname || '.' || pc.relname || E'(\n' ||
   string_agg(pa.attname || ' ' || pg_catalog.format_type(pa.atttypid, pa.atttypmod) || coalesce(' DEFAULT ' || (
                                                                                SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
                                                                                FROM pg_catalog.pg_attrdef d
                                                                                WHERE d.adrelid = pa.attrelid
                                                                                AND d.adnum = pa.attnum
                                                                                AND pa.atthasdef
                                                                                ),
                                                                                '') || ' ' ||
              CASE pa.attnotnull
                  WHEN TRUE THEN 'NOT NULL'
                  ELSE 'NULL'
              END, E',\n') ||
   coalesce((SELECT E',\n' || string_agg('CONSTRAINT ' || pc1.conname || ' ' || pg_get_constraintdef(pc1.oid), E',\n' ORDER BY pc1.conindid)
            FROM pg_constraint pc1
            WHERE pc1.conrelid = pa.attrelid), '') ||
   E');'
FROM pg_catalog.pg_attribute pa
JOIN pg_catalog.pg_class pc
    ON pc.oid = pa.attrelid
    AND pc.relname = 'table_name'
JOIN pg_catalog.pg_namespace pn
    ON pn.oid = pc.relnamespace
    AND pn.nspname = 'schema_name'
WHERE pa.attnum > 0
    AND NOT pa.attisdropped
GROUP BY pn.nspname, pc.relname, pa.attrelid;

A: Generate the create table statement for a table in postgresql from linux commandline:
Create a table for a demo:
CREATE TABLE your_table(
    thekey   integer NOT NULL,
    ticker   character varying(10) NOT NULL,
    date_val date,
    open_val numeric(10,4) NOT NULL
);

pg_dump manual, can output the table create psql statement:
pg_dump -U your_user your_database -t your_table --schema-only

Which prints:
-- pre-requisite database and table configuration omitted
CREATE TABLE your_table (
    thekey integer NOT NULL,
    ticker character varying(10) NOT NULL,
    date_val date,
    open_val numeric(10,4) NOT NULL
);
-- post-requisite database and table configuration omitted

Explanation:
pg_dump helps us get information about the database itself.  -U stands for username.  My pgadmin user has no password set, so I don't have to put in a password.  The -t option means specify for one table.  --schema-only means print only data about the table, and not the data in the table.
pg_dump is elite C code that tries to play nicely with the evolving sql standards, and takes care of the thousand details that arise between postgresql's query language, and its representation on a disk.  If you want to roll your own "psql disk to create statement" arrangement, ye be dragons: https://doxygen.postgresql.org/pg__dump_8c_source.html
Another option to get around pg_dump is to save the table-create SQL statement when you create the table.  Keep it somewhere safe and retrieve it when you need it.
Or get the table name, column name and datatype information from postgresql with SQL:
CREATE TABLE your_table(  thekey integer NOT NULL,
                          ticker character varying(10) NOT NULL,
                          date_val date,
                          open_val numeric(10,4) NOT NULL
);

SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = 'your_table';

Which prints:
┌────────────┬─────────────┬───────────────────┐
│ table_name │ column_name │     data_type     │
├────────────┼─────────────┼───────────────────┤
│ your_table │ thekey      │ integer           │
│ your_table │ ticker      │ character varying │
│ your_table │ date_val    │ date              │
│ your_table │ open_val    │ numeric           │
└────────────┴─────────────┴───────────────────┘

A: If you have PgAdmin4, then open it. Go to your database--> schema---> table--> right click on table name whose create script you want---> Scripts---> CREATE SCRIPT

A: pg_dump -t 'schema-name.table-name' --schema-only database-name

More info - in the manual.

A: If you want to find the create statement for a table without using pg_dump, This query might work for you (change 'tablename' with whatever your table is called):
SELECT
  'CREATE TABLE ' || relname || E'\n(\n' ||
  array_to_string(
    array_agg(
      '    ' || column_name || ' ' ||  type || ' '|| not_null
    )
    , E',\n'
  ) || E'\n);\n'
from
(
  SELECT
    c.relname, a.attname AS column_name,
    pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
    case
      when a.attnotnull
    then 'NOT NULL'
    else 'NULL'
    END as not_null
  FROM pg_class c,
   pg_attribute a,
   pg_type t
   WHERE c.relname = 'tablename'
   AND a.attnum > 0
   AND a.attrelid = c.oid
   AND a.atttypid = t.oid
 ORDER BY a.attnum
) as tabledefinition
group by relname;

when called directly from psql, it is usefult to do:
\pset linestyle old-ascii

Also, the function generate_create_table_statement in this thread works very well.

A: Here is a bit improved version of shekwi's query.
It generates the primary key constraint and is able to handle temporary tables:
with pkey as
(
    select cc.conrelid, format(E',
    constraint %I primary key(%s)', cc.conname,
        string_agg(a.attname, ', '
            order by array_position(cc.conkey, a.attnum))) pkey
    from pg_catalog.pg_constraint cc
        join pg_catalog.pg_class c on c.oid = cc.conrelid
        join pg_catalog.pg_attribute a on a.attrelid = cc.conrelid
            and a.attnum = any(cc.conkey)
    where cc.contype = 'p'
    group by cc.conrelid, cc.conname
)
select format(E'create %stable %s%I\n(\n%s%s\n);\n',
    case c.relpersistence when 't' then 'temporary ' else '' end,
    case c.relpersistence when 't' then '' else n.nspname || '.' end,
    c.relname,
    string_agg(
        format(E'\t%I %s%s',
            a.attname,
            pg_catalog.format_type(a.atttypid, a.atttypmod),
            case when a.attnotnull then ' not null' else '' end
        ), E',\n'
        order by a.attnum
    ),
    (select pkey from pkey where pkey.conrelid = c.oid)) as sql
from pg_catalog.pg_class c
    join pg_catalog.pg_namespace n on n.oid = c.relnamespace
    join pg_catalog.pg_attribute a on a.attrelid = c.oid and a.attnum > 0
    join pg_catalog.pg_type t on a.atttypid = t.oid
where c.relname = :table_name
group by c.oid, c.relname, c.relpersistence, n.nspname;

Use table_name parameter to specify the name of the table.

A: This is the variation that works for me:
pg_dump -U user_viktor -h localhost unit_test_database -t floorplanpreferences_table --schema-only
In addition, if you're using schemas, you'll of course need to specify that as well:
pg_dump -U user_viktor -h localhost unit_test_database -t "949766e0-e81e-11e3-b325-1cc1de32fcb6".floorplanpreferences_table --schema-only
You will get an output that you can use to create the table again, just run that output in psql.

A: pg_dump -h XXXXXXXXXXX.us-west-1.rds.amazonaws.com -U anyuser -t tablename -s

A: Like the other answers mentioned, there is no built in function that does this.
Here is a function that attempts to get all of the information that would be needed to replicate the table - or to compare deployed and checked in ddl.
This function outputs:

*

*columns (w/ precision, null/not-null, default value)

*constraints

*indexes

CREATE OR REPLACE FUNCTION public.show_create_table(
  in_schema_name varchar,
  in_table_name varchar
)
RETURNS text
LANGUAGE plpgsql VOLATILE
AS
$$
  DECLARE
    -- the ddl we're building
    v_table_ddl text;

    -- data about the target table
    v_table_oid int;

    -- records for looping
    v_column_record record;
    v_constraint_record record;
    v_index_record record;
  BEGIN
    -- grab the oid of the table; https://www.postgresql.org/docs/8.3/catalog-pg-class.html
    SELECT c.oid INTO v_table_oid
    FROM pg_catalog.pg_class c
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE 1=1
      AND c.relkind = 'r' -- r = ordinary table; https://www.postgresql.org/docs/9.3/catalog-pg-class.html
      AND c.relname = in_table_name -- the table name
      AND n.nspname = in_schema_name; -- the schema

    -- throw an error if table was not found
    IF (v_table_oid IS NULL) THEN
      RAISE EXCEPTION 'table does not exist';
    END IF;

    -- start the create definition
    v_table_ddl := 'CREATE TABLE ' || in_schema_name || '.' || in_table_name || ' (' || E'\n';

    -- define all of the columns in the table; https://stackoverflow.com/a/8153081/3068233
    FOR v_column_record IN
      SELECT
        c.column_name,
        c.data_type,
        c.character_maximum_length,
        c.is_nullable,
        c.column_default
      FROM information_schema.columns c
      WHERE (table_schema, table_name) = (in_schema_name, in_table_name)
      ORDER BY ordinal_position
    LOOP
      v_table_ddl := v_table_ddl || '  ' -- note: two char spacer to start, to indent the column
        || v_column_record.column_name || ' '
        || v_column_record.data_type || CASE WHEN v_column_record.character_maximum_length IS NOT NULL THEN ('(' || v_column_record.character_maximum_length || ')') ELSE '' END || ' '
        || CASE WHEN v_column_record.is_nullable = 'NO' THEN 'NOT NULL' ELSE 'NULL' END
        || CASE WHEN v_column_record.column_default IS NOT null THEN (' DEFAULT ' || v_column_record.column_default) ELSE '' END
        || ',' || E'\n';
    END LOOP;

    -- define all the constraints in the; https://www.postgresql.org/docs/9.1/catalog-pg-constraint.html && https://dba.stackexchange.com/a/214877/75296
    FOR v_constraint_record IN
      SELECT
        con.conname as constraint_name,
        con.contype as constraint_type,
        CASE
          WHEN con.contype = 'p' THEN 1 -- primary key constraint
          WHEN con.contype = 'u' THEN 2 -- unique constraint
          WHEN con.contype = 'f' THEN 3 -- foreign key constraint
          WHEN con.contype = 'c' THEN 4
          ELSE 5
        END as type_rank,
        pg_get_constraintdef(con.oid) as constraint_definition
      FROM pg_catalog.pg_constraint con
      JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
      JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
      WHERE nsp.nspname = in_schema_name
      AND rel.relname = in_table_name
      ORDER BY type_rank
    LOOP
      v_table_ddl := v_table_ddl || '  ' -- note: two char spacer to start, to indent the column
        || 'CONSTRAINT' || ' '
        || v_constraint_record.constraint_name || ' '
        || v_constraint_record.constraint_definition
        || ',' || E'\n';
    END LOOP;

    -- drop the last comma before ending the create statement
    v_table_ddl = substr(v_table_ddl, 0, length(v_table_ddl) - 1) || E'\n';

    -- end the create definition
    v_table_ddl := v_table_ddl || ');' || E'\n';

    -- suffix create statement with all of the indexes on the table
    FOR v_index_record IN
      SELECT indexdef
      FROM pg_indexes
      WHERE (schemaname, tablename) = (in_schema_name, in_table_name)
    LOOP
      v_table_ddl := v_table_ddl
        || v_index_record.indexdef
        || ';' || E'\n';
    END LOOP;

    -- return the ddl
    RETURN v_table_ddl;
  END;
$$;

example
SELECT * FROM public.show_create_table('public', 'example_table');

produces
CREATE TABLE public.example_table (
  id bigint NOT NULL DEFAULT nextval('test_tb_for_show_create_on_id_seq'::regclass),
  name character varying(150) NULL,
  level character varying(50) NULL,
  description text NOT NULL DEFAULT 'hello there!'::text,
  CONSTRAINT test_tb_for_show_create_on_pkey PRIMARY KEY (id),
  CONSTRAINT test_tb_for_show_create_on_level_check CHECK (((level)::text = ANY ((ARRAY['info'::character varying, 'warn'::character varying, 'error'::character varying])::text[])))
);
CREATE UNIQUE INDEX test_tb_for_show_create_on_pkey ON public.test_tb_for_show_create_on USING btree (id);

A: YOu can also use a free DB management tool, such as DBeaver, which allows you to view DDL for the tables, here's an example:

A: Dean Toader Just excellent!
I'd modify your code a little, to show all constraints in the table and to make possible to use regexp mask in table name.
CREATE OR REPLACE FUNCTION public.generate_create_table_statement(p_table_name character varying)
  RETURNS SETOF text AS
$BODY$
DECLARE
    v_table_ddl   text;
    column_record record;
    table_rec record;
    constraint_rec record;
    firstrec boolean;
BEGIN
    FOR table_rec IN
        SELECT c.relname FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                WHERE relkind = 'r'
                AND relname~ ('^('||p_table_name||')$')
                AND n.nspname <> 'pg_catalog'
                AND n.nspname <> 'information_schema'
                AND n.nspname !~ '^pg_toast'
                AND pg_catalog.pg_table_is_visible(c.oid)
          ORDER BY c.relname
    LOOP

        FOR column_record IN
            SELECT
                b.nspname as schema_name,
                b.relname as table_name,
                a.attname as column_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
                CASE WHEN
                    (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                     FROM pg_catalog.pg_attrdef d
                     WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
                    'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                                  FROM pg_catalog.pg_attrdef d
                                  WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
                ELSE
                    ''
                END as column_default_value,
                CASE WHEN a.attnotnull = true THEN
                    'NOT NULL'
                ELSE
                    'NULL'
                END as column_not_null,
                a.attnum as attnum,
                e.max_attnum as max_attnum
            FROM
                pg_catalog.pg_attribute a
                INNER JOIN
                 (SELECT c.oid,
                    n.nspname,
                    c.relname
                  FROM pg_catalog.pg_class c
                       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                  WHERE c.relname = table_rec.relname
                    AND pg_catalog.pg_table_is_visible(c.oid)
                  ORDER BY 2, 3) b
                ON a.attrelid = b.oid
                INNER JOIN
                 (SELECT
                      a.attrelid,
                      max(a.attnum) as max_attnum
                  FROM pg_catalog.pg_attribute a
                  WHERE a.attnum > 0
                    AND NOT a.attisdropped
                  GROUP BY a.attrelid) e
                ON a.attrelid=e.attrelid
            WHERE a.attnum > 0
              AND NOT a.attisdropped
            ORDER BY a.attnum
        LOOP
            IF column_record.attnum = 1 THEN
                v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
            ELSE
                v_table_ddl:=v_table_ddl||',';
            END IF;

            IF column_record.attnum <= column_record.max_attnum THEN
                v_table_ddl:=v_table_ddl||chr(10)||
                         '    '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
            END IF;
        END LOOP;

        firstrec := TRUE;
        FOR constraint_rec IN
            SELECT conname, pg_get_constraintdef(c.oid) as constrainddef
                FROM pg_constraint c
                    WHERE conrelid=(
                        SELECT attrelid FROM pg_attribute
                        WHERE attrelid = (
                            SELECT oid FROM pg_class WHERE relname = table_rec.relname
                        ) AND attname='tableoid'
                    )
        LOOP
            v_table_ddl:=v_table_ddl||','||chr(10);
            v_table_ddl:=v_table_ddl||'CONSTRAINT '||constraint_rec.conname;
            v_table_ddl:=v_table_ddl||chr(10)||'    '||constraint_rec.constrainddef;
            firstrec := FALSE;
        END LOOP;
        v_table_ddl:=v_table_ddl||');';
        RETURN NEXT v_table_ddl;
    END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.generate_create_table_statement(character varying)
  OWNER TO postgres;

Now you can, for example, make the following query
SELECT * FROM generate_create_table_statement('.*');

which results like this:
CREATE TABLE public.answer (
     id integer DEFAULT nextval('answer_id_seq'::regclass) NOT NULL,
     questionid integer  NOT NULL,
     title character varying  NOT NULL,
     defaultvalue character varying  NULL,
     valuetype integer  NOT NULL,
     isdefault boolean  NULL,
     minval double precision  NULL,
     maxval double precision  NULL,
     followminmax integer DEFAULT 0 NOT NULL,
CONSTRAINT answer_pkey
     PRIMARY KEY (id),
CONSTRAINT answer_questionid_fkey
     FOREIGN KEY (questionid) REFERENCES question(id) ON UPDATE RESTRICT ON DELETE RESTRICT,
CONSTRAINT answer_valuetype_fkey
     FOREIGN KEY (valuetype) REFERENCES answervaluetype(id) ON UPDATE RESTRICT ON DELETE RESTRICT);

for each user table.

A: DataGrip has the same functionality as pgAdmin. You can right click on a table and you will see option to auto-generate create table statement.

A: The easiest method I can think of is to install pgAdmin 3 (found here) and use it to view your database.  It will automatically generate a query that will create the table in question.

A: (NOTICE - this solution is not working with PostgreSQL v12+)

My solution is to log in to the postgres db using psql with the -E option as follows:
psql -E -U username -d database

In psql, run the following commands to see the sql that postgres uses to generate
the describe table statement:
-- List all tables in the schema (my example schema name is public)
\dt public.*
-- Choose a table name from above
-- For create table of one public.tablename
\d+ public.tablename

Based on the sql echoed out after running these describe commands, I was able to put together
the following plpgsql function:
CREATE OR REPLACE FUNCTION generate_create_table_statement(p_table_name varchar)
  RETURNS text AS
$BODY$
DECLARE
    v_table_ddl   text;
    column_record record;
BEGIN
    FOR column_record IN
        SELECT
            b.nspname as schema_name,
            b.relname as table_name,
            a.attname as column_name,
            pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
            CASE WHEN
                (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                 FROM pg_catalog.pg_attrdef d
                 WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
                'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                              FROM pg_catalog.pg_attrdef d
                              WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
            ELSE
                ''
            END as column_default_value,
            CASE WHEN a.attnotnull = true THEN
                'NOT NULL'
            ELSE
                'NULL'
            END as column_not_null,
            a.attnum as attnum,
            e.max_attnum as max_attnum
        FROM
            pg_catalog.pg_attribute a
            INNER JOIN
             (SELECT c.oid,
                n.nspname,
                c.relname
              FROM pg_catalog.pg_class c
                   LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
              WHERE c.relname ~ ('^('||p_table_name||')$')
                AND pg_catalog.pg_table_is_visible(c.oid)
              ORDER BY 2, 3) b
            ON a.attrelid = b.oid
            INNER JOIN
             (SELECT
                  a.attrelid,
                  max(a.attnum) as max_attnum
              FROM pg_catalog.pg_attribute a
              WHERE a.attnum > 0
                AND NOT a.attisdropped
              GROUP BY a.attrelid) e
            ON a.attrelid=e.attrelid
        WHERE a.attnum > 0
          AND NOT a.attisdropped
        ORDER BY a.attnum
    LOOP
        IF column_record.attnum = 1 THEN
            v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
        ELSE
            v_table_ddl:=v_table_ddl||',';
        END IF;

        IF column_record.attnum <= column_record.max_attnum THEN
            v_table_ddl:=v_table_ddl||chr(10)||
                     '    '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
        END IF;
    END LOOP;

    v_table_ddl:=v_table_ddl||');';
    RETURN v_table_ddl;
END;
$BODY$
  LANGUAGE 'plpgsql' COST 100.0 SECURITY INVOKER;

Here is the function usage:
SELECT generate_create_table_statement('tablename');

And here is the drop statement if you don't want this function to persist permanently:
DROP FUNCTION generate_create_table_statement(p_table_name varchar);

A: If you want to do this for various tables at once, you meed to use the -t switch multiple times (took me a while to figure out why comma separated list wasn't working). Also, can be useful to send results to an outfile or pipe to a postgres server on another machine
pg_dump -t table1 -t table2 database_name --schema-only > dump.sql

pg_dump -t table1 -t table2 database_name --schema-only | psql -h server_name database_name

A: Here is another solution to the old question. There have been many excellent answers to this question over the years and my attempt borrows heavily from them.
I used Andrey Lebedenko's solution as a starting point because its output was already very close to my requirements.
Features:

*

*following common practice I have moved the foreign key constraints outside the table definition. They are now included as ALTER TABLE statements at the bottom. The reason is that a foreign key can also link to a column of the same table. In that fringe case the constraint can only be created after the table creation is completed. The create table statement would throw an error otherwise.

*The layout and indenting looks nicer now (at least to my eye)

*Drop command (commented out) in the header of the definition

*The solution is offered here as a plpgsql function. The algorithm does however not use any procedural language. The function just wraps one single query that can be used in a pure sql context as well.

*removed redundant subqueries

*Identifiers are now quoted if they are identical to reserved postgresql language elements

*replaced the string concatenation operator || with the appropriate string functions to improve performance, security and readability of the code.
Note: the || operator produces NULL if one of the combined strings is NULL. It should only be used when that is the desired behaviour. (check out the
usage in the code below for an example)

CREATE OR REPLACE FUNCTION public.wmv_get_table_definition (
    p_schema_name character varying,
    p_table_name character varying
)
    RETURNS SETOF TEXT
    AS $BODY$
BEGIN
    RETURN query
    WITH table_rec AS (
        SELECT
            c.relname, n.nspname, c.oid
        FROM
            pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE
            relkind = 'r'
            AND n.nspname = p_schema_name
            AND c.relname LIKE p_table_name
        ORDER BY
            c.relname
    ),
    col_rec AS (
        SELECT
            a.attname AS colname,
            pg_catalog.format_type(a.atttypid, a.atttypmod) AS coltype,
            a.attrelid AS oid,
            ' DEFAULT ' || (
                SELECT
                    pg_catalog.pg_get_expr(d.adbin, d.adrelid)
                FROM
                    pg_catalog.pg_attrdef d
                WHERE
                    d.adrelid = a.attrelid
                    AND d.adnum = a.attnum
                    AND a.atthasdef) AS column_default_value,
            CASE WHEN a.attnotnull = TRUE THEN
                'NOT NULL'
            ELSE
                'NULL'
            END AS column_not_null,
            a.attnum AS attnum
        FROM
            pg_catalog.pg_attribute a
        WHERE
            a.attnum > 0
            AND NOT a.attisdropped
        ORDER BY
            a.attnum
    ),
    con_rec AS (
        SELECT
            conrelid::regclass::text AS relname,
            n.nspname,
            conname,
            pg_get_constraintdef(c.oid) AS condef,
            contype,
            conrelid AS oid
        FROM
            pg_constraint c
            JOIN pg_namespace n ON n.oid = c.connamespace
    ),
    glue AS (
        SELECT
            format( E'-- %1$I.%2$I definition\n\n-- Drop table\n\n-- DROP TABLE IF EXISTS %1$I.%2$I\n\nCREATE TABLE %1$I.%2$I (\n', table_rec.nspname, table_rec.relname) AS top,
            format( E'\n);\n\n\n-- adempiere.wmv_ghgaudit foreign keys\n\n', table_rec.nspname, table_rec.relname) AS bottom,
            oid
        FROM
            table_rec
    ),
    cols AS (
        SELECT
            string_agg(format('    %I %s%s %s', colname, coltype, column_default_value, column_not_null), E',\n') AS lines,
            oid
        FROM
            col_rec
        GROUP BY
            oid
    ),
    constrnt AS (
        SELECT
            string_agg(format('    CONSTRAINT %s %s', con_rec.conname, con_rec.condef), E',\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype <> 'f'
        GROUP BY
            oid
    ),
    frnkey AS (
        SELECT
            string_agg(format('ALTER TABLE %I.%I ADD CONSTRAINT %s %s', nspname, relname, conname, condef), E';\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype = 'f'
        GROUP BY
            oid
    )
    SELECT
        concat(glue.top, cols.lines, E',\n', constrnt.lines, glue.bottom, frnkey.lines, ';')
    FROM
        glue
        JOIN cols ON cols.oid = glue.oid
        LEFT JOIN constrnt ON constrnt.oid = glue.oid
        LEFT JOIN frnkey ON frnkey.oid = glue.oid;
END;
$BODY$
LANGUAGE plpgsql;

A: Use this and get your output in ddl.out file
~/bin/pg_dump -p 30000 -d <db_name> -U <db_user> --schema=<schema_name> -t <table_name> --schema-only >> /tmp/ddl.out

So this will generate DDL in the path: /tmp/ddl.out

A: Here is a solution if you don't want to create a function and just want the query to create a basic table structure.
select 'CREATE TABLE ' || table_name ||'(' ||STRING_AGG (
    column_name || ' ' || data_type ,
        ','
       ORDER BY
        table_name,
        ordinal_position
    ) ||');'
    from
information_schema.columns
where table_schema = 'public'
group by
table_name

A: A simple solution, in pure single SQL.
You get the idea, you may extend it to more attributes you like to show.
with c as (
SELECT table_name, ordinal_position,
 column_name|| ' ' || data_type col
, row_number() over (partition by table_name order by ordinal_position asc) rn
, count(*) over (partition by table_name) cnt
FROM information_schema.columns
WHERE table_name   in ('pg_index', 'pg_tables')
order by table_name, ordinal_position
)
select case when rn = 1 then 'create table ' || table_name || '(' else '' end
 || col
 || case when rn < cnt then ',' else '); ' end
from c
order by table_name, rn asc;

Output:
create table pg_index(indexrelid oid,
 indrelid oid,
 indnatts smallint,
 indisunique boolean,
 indisprimary boolean,
 indisexclusion boolean,
 indimmediate boolean,
 indisclustered boolean,
 indisvalid boolean,
 indcheckxmin boolean,
 indisready boolean,
 indislive boolean,
 indisreplident boolean,
 indkey ARRAY,
 indcollation ARRAY,
 indclass ARRAY,
 indoption ARRAY,
 indexprs pg_node_tree,
 indpred pg_node_tree);

 create table pg_tables(schemaname name,
 tablename name,
 tableowner name,
 tablespace name,
 hasindexes boolean,
 hasrules boolean,
 hastriggers boolean,
 rowsecurity boolean);

A: Another easy option was to use [HeidiSQL client][1] for PostgreSQL database.
How to go into the database tab where all the databases and tables are listed.
Click on any of the table/View which you wanted to see the DDL/create a statement of the particular table.
Now there this client do the following jobs for you for that table, on the right-hand side windows:
The first window would be for data of table
Second for your SQL Host information
Third for database-level information like which tables and what is the size

Forth which we are more concern about table/view information tab will have the create table statement readily available for you.

I can not show you in the snapshot as working with confidential data, Try it with yourself and let me know if any issues you guys found.

A: To generate the SQL (DDL) behind the creation of a particular table.
We can simply use this SQL query -
SHOW TABLE your_schema_name.your_table_name

A: In pgadminIII database>>schemas>>tables>> right click on 'Your table'>>scripts>> 'Select any one (Create,Insert,Update,Delete..)'

A: Here is a query with some edits,
select 'CREATE TABLE ' || a.attrelid::regclass::text || '(' ||
string_agg(a.attname || ' ' || pg_catalog.format_type(a.atttypid,
a.atttypmod)||
        CASE WHEN
            (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
             FROM pg_catalog.pg_attrdef d
             WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
            ' DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                          FROM pg_catalog.pg_attrdef d
                          WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
        ELSE
            '' END
||
        CASE WHEN a.attnotnull = true THEN
            ' NOT NULL'
        ELSE
            '' END,E'\n,') || ');'
FROM pg_catalog.pg_attribute a join pg_class on a.attrelid=pg_class.oid
WHERE a.attrelid::regclass::varchar =
'TABLENAME_with_or_without_schema'
AND a.attnum > 0 AND NOT a.attisdropped  and pg_class.relkind='r'
group by a.attrelid;


text:
Q: How do I add ads to my local site which I host on my local area connection of my college campus? I have a website that runs in my college LAN and I want to add some revenue making ads. Its a website that offers downloads and tech blogs. However I have no interest of putting it up online and just host it locally. How do I do so?
What I have tried:
I have gone through different ad sites but I didnt get any proper results.

A: Do a google search for a free adsense clone script.
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=free%20adsense%20clone
You can run the clone script and charge to run ads on it or ppc. As for other ad networks like adsense, I'm not sure they allow that type of advertising or not, so if it were me, I'd just grab a free script and run it that way or find an affiliate program that would allow LAN ads.


text:
Q: Sitecore 8.2 : All Indexes are not listed in Index manager I am using Sitecore 8.2 update 5.
Now switching from Lucene Solr using the steps mentioned in: https://sitecorerockz.wordpress.com/2018/08/01/lucene-to-solr/
After doing all the changes when i tried to build the index the Index manager is empty as shown in this image Indixing manager
Below is the my all configuration using the .../sitecore/admin/showconfig.aspx
Link: https://gist.github.com/FirozNaimAnsari/45dce0167aa608b9e14a6815270709a9

A: In your config there is 1 index, a Lucene index, a custom one named mymywebsite_assets
<contentSearch>
      <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
        <indexes hint="list:AddIndex">
          <index id="mymywebsite_assets" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider">

Check if the following step is done correctly:
Navigate to the website Include folder: wwwroot\{sitename}\App_Config\Include\
Enable the Sitecore.ContentSearch.Solr.*.config files by removing .example from the file name.
Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config.example

Sitecore.ContentSearch.Solr.Index.Analytics.config.example

Sitecore.ContentSearch.Solr.Index.Core.config.example

Sitecore.ContentSearch.Solr.Index.Master.config.example

Sitecore.ContentSearch.Solr.Index.Web.config.example

In your config I see currently only the "Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config"
Also on the doc.sitecore there is an walktrough specific to Sitecore 8.2 see https://doc.sitecore.com/developers/82/sitecore-experience-platform/en/walkthrough--setting-up-solr.html

A: All Indexes are visible in Sitecore Index Manager if you can see their configs. in ShowConfig.aspx, Just make sure that you are able to see all the required configs. If not then try Configuring it properly. I hope this Help.

A: I am getting the below exception while debugging

Solr Indexes Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type ISolrOperations`1, key "sitecore_analytics_index" ---> Ninject.ActivationException: Error activating ISolrOperations{Dictionary{string, Object}} No matching bindings are available, and the type is not self-bindable. Activation path: 1) Request for ISolrOperations{Dictionary{string, Object}} Suggestions: 1) Ensure that you have defined a binding for ISolrOperations{Dictionary{string, Object}}. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct. at Ninject.KernelBase.Resolve(IRequest request) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 376 at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, String name, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 164 at MyLibrary.test.Infrastructure.NinjectServiceLocator.DoGetInstance(Type serviceType, String key) in C:\test_Git\Sitecore\src\test\Infrastructure\NinjectServiceLocator.cs:line 15 at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 49 --- End of inner exception stack trace --- at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 53 at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService](String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:line 103 at Sitecore.ContentSearch.SolrProvider.SolrSearchIndex.Initialize() at ASP._Page_sitecore_admin_solr_diagnostic_cshtml.Execute() in c:\test_Git\Sitecore\build\25Sep2019\Website\sitecore\admin\solr-diagnostic.cshtml:line 29


text:
Q: Passing a Jquery value to PHP Query I have a JQGrid with a OndblClickRow function as follows:
    ondblClickRow: function(rowid)
    {
        rowData = $("#bookings").getRowData(rowid);
                    var brData = rowData['bookref'];
                    console.log(brData);

        getGridRow(brData);

        //$("#cp-bookings-dialog").dialog({ hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});
    },

This is being passed to the following function:
function getGridRow(brData) {

    $.post("bookings-dialog.php", { 'rowdata': brData } );
               $("#cp-bookings-dialog").load('bookings-dialog.php').dialog({ show: "slide", hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});
    ,

Which loads the bookings.dialog.php page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<?php

set_include_path($_SERVER['DOCUMENT_ROOT'] . "/onlinebookingv4/scripts/php/");
require_once('models/sql.php');

require_once('models/bookingdocket.php');

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    try {
           $rowdata = $_POST['rowdata'];
           $query = ("SELECT * FROM tblbookings WHERE bookref = '$rowdata'");

        $stmt = $dbh->prepare($query);

        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_BOTH);

           BookingDocket::set_id($row['id']);
           BookingDocket::set_bookref($row['bookref']);
           BookingDocket::set_bookdate($row['bookingdate']);
           BookingDocket::set_returndate($row['returndate']);
           BookingDocket::set_journeytype($row['journeytype']);
           BookingDocket::set_passtel($row['passengertel']);
           BookingDocket::set_returndate($row['returndate']);

        $stmt->closeCursor();

    }

    catch (PDOException $pe) {
        die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
    }

    $dbh = null;

?>

Booking Date:  Booking Reference is = <? echo BookingDocket::get_bookref(); ?>

Query =   <? echo $query; ?>

Journey:

Passenger Tel:

E-mail:

What I am trying to do is pass 'brData' which is the booking reference to bookings-dialog.php so that I can select all bookings from the database by booking reference.
At the moment, when I double click a row, in firebug console I get the following:
POST bookings-dialog.php which is showing SELECT * FROM tblbookings WHERE bookref = 'BR1278' which is correct
But it is also showing:
GET bookings-dialog.php which is showing SELECT * FROM tblbookings WHERE bookref = ''
To me it looks like this is being overridden somehow, I'm probably wrong.
Anybody have any idea how I can get this to work?

A: We don't want to send back HTML, we want to send back something like JSON. our #cp-bookings-dialog element should have a HTML structure that looks like ->

Then we send our data to the server. Your existing code is actually fine, my comment was assuming a different type of action.
$.post("bookings-dialog.php", { 'rowdata': brData } );

This is where I have to make assumptions. After you do your set_var($_POST['var']) on your BookingDocket class, we should just return a JSON encoded array of key:value pairs to be parsed in our browser, and used to update the information in the dialog.
//for example, only showing the last two...
BookingDocket::set_passtel($row['passengertel']);
BookingDocket::set_returndate($row['returndate']);

//create a scope of variables to prepare and return
$booking_date = BookingDocket::get_bookref();
//query is already set, omitting it.
//making assumptions about data I cannot see
$journey = BookingDocket::get_journey();
$pass_tel = BookingDocket::get_tel();
$email = BookingDocket::get_email();

//formatting here is for example and not live usage
return json_encode(array("date" => $booking_data,
                         "query" => $query,
                         "journey" => $journey,
                         "pass_tel" => $pass_tel,
                         "email" => $email
                         )
                  );

So now we're returning a JSON encoded array, let's go back to the $.post method and see what we can do now.
//I prefer to write things out with $.ajax
$.ajax({
  url: 'booking-dialog.php',
  data: {'rowdata' : brData },
  dataType: 'json', //this is what we expect our returned data as
  success: function(data){
    //empty our dialog so we don't end up with duplicate content
    $('.cp-booking-info').empty();
    //we have told the browser to expect JSON back, no need to do any parsing
    //the date
    $('.cp-booking-info').append('
Booking Date: '+data.date+'
');
    //the query
    $('.cp-booking-info').append('
Query: '+data.query+'
');
    //the journey
    $('.cp-booking-info').append('
Journey: '+data.journey+'
');
    //thepassenger tel
    $('.cp-booking-info').append('
Passenger Tel: '+data.pass_tel+'
');
    //the email
    $('.cp-booking-info').append('
Email: '+data.email+'
');

    //now let's manipulate our dialog and open it.
    $("#cp-bookings-dialog").dialog({
      show: "slide",
      hide: 'slide',
      height: 625,
      width: 733,
      title: 'Booking Reference: - '+ brData
    });
  }

});

This is the quickest mockup I could make of how I would imagine your system to work.


text:
Q: SAS PROC SQL to join two tables by comparing date Good day everyone. I am trying to join two datasets by comparing the dates.
Suppose I have two datasets as such:
---Table A---      ---Table B---
ID  Date1          ID  Date2
01  29/1/2010      01  28/1/2011
01  29/1/2011      01  28/1/2012
01  29/1/2012      01  28/1/2013
01  29/1/2013      01  28/1/2014
01  29/1/2014      01  28/1/2015
01  29/1/2015      01  28/1/2016

I am trying to join the table A and table B by comparing date 1 and date 2. If date2 < date1 then join.
The intended result should like this (table 3):
---Table C---
ID  Date1      Date2
01  29/1/2010  .
01  29/1/2011  28/1/2011
01  29/1/2012  28/1/2012
01  29/1/2013  28/1/2013
01  29/1/2014  28/1/2014
01  29/1/2015  28/1/2015

But when I tried using this code
PROC SQL;
    CREATE TABLE TABLE_C AS
    SELECT TABLE_A.*, TABLE_B.DATE2
    FROM TABLE_A LEFT JOIN TABLE_B
    ON
        TABLE_A.ID = TABLE_B.ID AND
        TABLE_A.DATE1 < TABLE_B.DATE2;

I ended up with this result:
---Table C---
ID  Date1      Date2
01  29/1/2010  .
01  29/1/2011  28/1/2011
01  29/1/2012  28/1/2011 *
01  29/1/2013  28/1/2011 *
01  29/1/2014  28/1/2011 *
01  29/1/2015  28/1/2011 *
01  29/1/2012  28/1/2012
01  29/1/2013  28/1/2012 *
01  29/1/2014  28/1/2012 *
01  29/1/2015  28/1/2012 *
01  29/1/2013  28/1/2013
01  29/1/2014  28/1/2013 *
01  29/1/2015  28/1/2013 *
01  29/1/2014  28/1/2014
01  29/1/2015  28/1/2014 *
01  29/1/2015  28/1/2015

How can I remove the ones that are labelled (*)? Can anybody help? Thanks!

A: Based on your expected result it looks like you would only need to replace
TABLE_A.DATE1 < TABLE_B.DATE2;

with
TABLE_A.DATE1 > TABLE_B.DATE2 and /* date2 < date1 */
YEAR(TABLE_A.DATE1) = YEAR(TABLE_B.DATE2);


text:
Q: Minimal binding TextBlock to property It's been sometime since I coded something in XAML, and, trying to update an old app, I stopped at an issue with binding. I stripped everything to come up to a minimal example.
Here is my XAML body:
<Grid>
    <TextBlock Text="{Binding Path=PageTitle, ElementName=page, Mode=OneWay}"></TextBlock>
</Grid>

My code behind has this:
Public ReadOnly Property PageTitle As String
    Get
        Return "My page"
    End Get
End Property

I believe this is the minimal code (ok, exluding the Mode=OneWay part, since we are talking about a TextBlock) required to bind this TextBlock content to a property on its underlying page, yet it doesn't work and I come up with an empty TextBlock. The Get code of my PageTitle property is never called.
I even went as far as implementing INotifyPropertyChanged by declaring:
Public Event PropertyChanged As PropertyChangedEventHandler Implements  INotifyPropertyChanged.PropertyChanged

and then raising RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("PageTitle")) in my OnNavigatedTo code, but to no avail.
So, what's the simple thing I'm missing here?

A: Did you set the Name of the Page?
However, if the property is defined in the code-behind of the view, you could use x:Bind without setting the DataContext:
<TextBlock Text="{x:Bind PageTitle, Mode=OneWay}" />


text:
Q: Generic Type with namespace restriction Everyone knows
public class Test<T> where T : SomeBaseClass

But is there a way to restrict T to classes that exists in a namespace like
public class Test<T> where T in SomeNamespace

Best regards

A: Namespace constrains are not possible. Anyway it does not makes any sence because everyone can create classes which are located in the target namespace. It maybe would only make sence if you can restrict it to a specific assembly.
Would make more sence if you can restrict it to n types like the following lines( doesn't work ):
public T Create<T>() where T : { MyClass1, MyClass2 }

See constraints
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

A: No. There's no way to constrain a generic type to a namespace.

A: No. Constraints are about specifying behaviour - whether that is as simple as being a class, implementing a given interface or whatever. It's not about which namespace a class is defined in - that says nothing about its behaviour.
See Constraints on Type Parameters for a constraint summary

A: You could sort of do this by creating an interface with internal scope and using that in your generic where clause (generic class/method would need to be in the same assembly).  Then you would only be able to use it with classes in the same assembly that implement that interface.
If you needed to pass classes from another assembly, you could add a global::InternalsVisibleToAttribute('other assemblys name') to the AssemblyInfo file.
All that being said, it still doesn't sound like the sort of thing to try and achieve.


text:
Q: Minimizing variance of sequence of independent but not identically distributed random variable I tried to work on the problem

Let $(X_n)$ be a sequence of independent random variables with $E[X_n]=\mu$ and $Var[X_n]=n$ for every $n \in \mathbb{N}$. Find the statistic of the form $\sum_{i=1}^nw_iX_i$, where $w_1,\cdots,w_n$ are non-negative numbers that add up to 1, that has the smallest possible variance.

I really have no idea how to solve this problem. I know that if $X_n$ are iid, then $\bar{X}_n$ has the smallest variance but in this case $X_n$ are not iid.

A: Since $X_i$s are independent of each other,
$$
\begin{align}
Var{\sum_{i=1}^n w_i X_i} &= \sum_{i=1}^n w_i^2 Var X_i \\
&=\sum_{i=1}^n iw_i^2
\end{align}
$$
Apply Cauchy's inequality,
$$
\sum iw_i^2 \sum \frac1i \ge \left(\sum w_i \right)^2 = 1
$$
which implies
$$
Var\sum w_i X_i \ge \frac{1}{\sum\limits_{i=1}^n \frac1i}
$$