text:
Q: Possible to regularly export MS-SQL tables to another DB format on Linux without complete dumps? We have a production server running SQL-Server, which holds our backend data, e.g., customer information, sales invoices etc. The nature of this data is that "old" data can change, e.g., a customer updating their address.
Currently we use a Windows Server 2008 instance as a research server, so that we can have an MS-SQL slave running on it, which replicates from the live server in a transactional way. We then do daily flat-file exports from the slave into our research schema, which happens to be a MySQL DB. We do this by reading in slave data into some algorithms, which modify and write the data to the MySQL research db. We drop all the tables in the research db and do clean imports each day to deal with the "old" data that may have changed in the production and slave DBs.
So, essentially, to go from the the live DB to our research schema always involves a complete dump and re-import every day, which is fine for us because it's all done locally.
Unfortunately, we have a lot of issues with both the MS-SQL replication and the Windows server; the source for these issues is actually mostly human-based rather than technical. However, we do have added problems that we have to use other Linux application servers because running some of the platforms/stacks we need in other areas is hard on Windows...
I want to move our research server to a Linux box, which I'm much more familiar with, and capable of managing and configuring correctly, but I don't know the best plan of action, for getting from the live MS-SQL DB to our research MySQL schema, given we now won't have the option of having live replication to a slave.
Basically:

*

*there are around 5 SQL-Server tables totalling ~3GB

*our IT guys are worried about the IO load on the production server if we do 3GB exports every day (currently we do transaction replication to a slave and then do 3GB exports from the slave).

Our update processes for getting the SQL-Server data into our research schema are expecting to do entire imports each day, but of course it doesn't matter whether they import from flat-files/SQL files or tables.
So, we know, one way or another, we will be doing flat-file imports of the SQL-Server data, but, the question is - is there a smart way to do exports from the MS-SQL tables daily, without having to do an entire dump?
I'm not talking about replication, because there won't be a MS-SQL instance on the receiving end, due to it being a Linux server. But, is it, say, possible to export from the MS-SQL server only rows which have had fields modified? That is, without modifying the SQL-Server tables' schemas of course to mark edited rows... :-)
Can SQL-server keep a log of modified rows or anything?
Failing all that, does anyone have an inkling about whether an under-provision SQL-Server instance would be expected to fall over every time you did a 3GB export???? That bit I don't really buy... We're talking about minimal load on the DB in the early hours of the morning (we are a small B2B internet retailer so wouldn't expect much to be going on in those hours).
Thanks!

A: If you wanted to keep that "slave" SQL Server, I would suggest forgetting about replication just loading a daily backup onto the server, or fiddling with restore transaction log backups. The DBAs should have those handy, you would just have to convince them to help you get an automated restore of the production data onto the "slave" box. BUT, it sounds to me that you would rather that the slave box goes away.
I would look in detail at the "Change Tracking" and "Change Data Capture" features. From what I have read, "Change Tracking" identifies rows that have changed in monitored tables by providing a list of primary key values. "Change Data Capture" provides more information, including capturing actual before and after values, for full auditing. The hand-wavy blurb is that you would read from SQL Server tables that describe what's changed and then update your mysql database. No fancy replication, or agents, or anything. Here is MS's landing page for those features.
It sounds to me that you could just use Change Tracking and overwrite whatever is in mysql with the currently-good value from the SQL Server. I would expect that Change Data Capture would put more load onto the box than Change Tracking.
As far as the daily 3GB extract goes:
I have seen "over-provisioned" servers with poorly performing SAN storage. Having lots of cores doesn't fix every problem.
Overnight periods often have other stuff going on, like backups, defrags, other extracts, large report runs, etc.
To me, "internet retailer" implies that you could have traffic at any time.
The DBAs might simply be wary of adding any load that the don't have to.

A: If the research server only contains data based on the production DB, why not run SQL Server on your linux servers instead of MySQL?  If your production database is less than 4GB (which it sounds like it is), you could run SQL Server Express edition for free.
You would not need a separate export step.  IT guys should already be making full and transaction log backups of the production DB, so they've already paid that I/O cost.  SQL Server Express would easily be able to read and restore from those backups onto your Linux server.
I personally have never used SQL Server DB replication, but it sounds like you have that.
 So you'd also have the option of replicating from production to the research DB as well.
SQL Server 2017 on Linux
And now there's SQL Server 2019, which is bound to be better!
SQL Server 2017 Express capacity limits

A: I know that you mentioned you did not want to modify the tables, but have you thought about adding an update/insert trigger on the table to write a drop file that your linux box can then pick up and update the MySQL server with?
Something like
USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[trig_WriteDropfileOnChange] ON [dbo].[tableName]
FOR INSERT, UPDATE
AS

-- declare vars
DECLARE @RecordId bigint,
    @RetCode int,
    @FileSystem int,
    @FileHandle int,
    @MyDate varchar(255),
    @FileName varchar(255)

-- build filename
SET @MyDate = getDate()
SET @MyDate = REPLACE(@MyDate, ':', '')
SET @MyDate = REPLACE(@MyDate, ' ', '')
SET @MyDate = REPLACE(@MyDate, '-', '')
SET @MyDate = REPLACE(@MyDate, '.', '')

SELECT @RecordID = myfield
FROM INSERTED

SET @FileName = '\\path\to\drop\directory\' + @MyDate + '.txt'

EXECUTE @RetCode = sp_OACreate 'Scripting.FileSystemObject', @FileSystem OUTPUT
    IF (@@ERROR|@RetCode > 0 Or @FileSystem < 0)
        RAISEERROR('could not create FileSystemObject', 16, 1)

EXECUTE @RetCode = sp_OAMethod @FileSystem, 'OpenTextFile', @FileHandle OUTPUT, @FileName, 2, 1
    IF (@@ERROR|@RetCode > 0 Or @FileHandle < 0)
        RAISEERROR('Could not open file.', 16, 1)

EXECUTE @RetCode = sp_OAMethod @FileHandle, 'WriteLine', NULL, CONVERT(varchar, @RecordId)
    IF (@@ERROR|@RetCode > 0 Or @FileHandle < 0)
        RAISEERROR('Could not write to file.', 16, 1)

EXECUTE @RetCode = sp_OAMethod @FileHandle, 'Close', NULL
    IF (@@ERROR|@RetCode > 0)
        RAISEERROR('Could not close file.', 16, 1)

EXEC sp_OADestroy @FileSystem


text:
Q: Manual JOIN on CakePHP I'm trying to do manual join because I expected to get better query result than CakePHP did.
This is my controller's coding
$this->ClinicWishList->contain();
$this->set('recordSets', $this->ClinicWishList->find('all', array(
  'fields' => array('ClinicWishList.*', 'ApplicantIssue.issue_desc', 'User.nickname', 'User.role'),
  'joins' => array(
    array(
      'table' => 'applicant_issues',
      'alias' => 'ApplicantIssue',
      'type' => 'left outer',
      'foreignKey' => false,
      'conditions' => array('ClinicWishList.issue_id' => 'ApplicantIssue.id')
    ),
    array(
      'table' => 'users',
      'alias' => 'User',
      'type' => 'left outer',
      'foreignKey' => false,
      'conditions' => array('ApplicantIssue.user_id' => 'User.id')
    )),
    'conditions' => array('ClinicWishList.user_id' => $this->Auth->user('id')),
    'order' => 'ClinicWishList.created DESC'
  )));

CakePHP produced the SQL like this.

There is no error but I got empty result from the joined table like this.

I copied the SQL and tried to execute on the GUI tool, I got this warning.

How to modify coding in CakePHP to get SQL like

instead of this

Please help, thanks.

A: You should change this line:
'conditions' => array('ClinicWishList.issue_id' => 'ApplicantIssue.id')

to:
'conditions' => array('`ClinicWishList`.`issue_id` = `ApplicantIssue`.`id`')

and change this line:
  'conditions' => array('ApplicantIssue.user_id' => 'User.id')

to:
  'conditions' => array('`ApplicantIssue`.`user_id` = `User`.`id`')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using StringWriter for XML Serialization I'm currently searching for an easy way to serialize objects (in C# 3).
I googled some examples and came up with something like:
MemoryStream memoryStream = new MemoryStream ( );
XmlSerializer xs = new XmlSerializer ( typeof ( MyObject) );
XmlTextWriter xmlTextWriter = new XmlTextWriter ( memoryStream, Encoding.UTF8 );
xs.Serialize ( xmlTextWriter, myObject);
string result = Encoding.UTF8.GetString(memoryStream .ToArray());

After reading this question I asked myself, why not using StringWriter? It seems much easier.
XmlSerializer ser = new XmlSerializer(typeof(MyObject));
StringWriter writer = new StringWriter();
ser.Serialize(writer, myObject);
serializedValue = writer.ToString();

Another Problem was, that the first example generated XML I could not just write into an XML column of SQL Server 2005 DB.
The first question is: Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards? I never found a result using StringWriter when googling.
The second is, of course: If you should not do it with StringWriter (for whatever reasons), which would be a good and correct way?

Addition:
As it was already mentioned by both answers, I'll further go into the XML to DB problem.
When writing to the Database I got the following exception:

System.Data.SqlClient.SqlException:
  XML parsing: line 1, character 38,
  unable to switch the encoding

For string
<?xml version="1.0" encoding="utf-8"?><test/>

I took the string created from the XmlTextWriter and just put  as xml there. This one did not work (neither with manual insertion into the DB).
Afterwards I tried manual insertion (just writing INSERT INTO ... ) with encoding="utf-16" which also failed.
Removing the encoding totally worked then. After that result I switched back to the StringWriter code and voila - it worked.
Problem: I don't really understand why.
at Christian Hayter: With those tests I'm not sure that I have to use utf-16 to write to the DB. Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

A: One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:
public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }
}

Or if you only need UTF-8 (which is all I often need):
public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

A: First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.
Here's an example of serializing an object into an XML column:
public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

A: When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.
SQL Server works on a similar principle; any string passed into an xml column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.
Bearing this in mind, here are some utility methods for doing the conversion.
public static string Serialize<T>(T value) {

    if(value == null) {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
        Indent = false,
        OmitXmlDeclaration = false
    };

    using(StringWriter textWriter = new StringWriter()) {
        using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

public static T Deserialize<T>(string xml) {

    if(string.IsNullOrEmpty(xml)) {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlReaderSettings settings = new XmlReaderSettings();
    // No settings need modifying here

    using(StringReader textReader = new StringReader(xml)) {
        using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
            return (T) serializer.Deserialize(xmlReader);
        }
    }
}

A: public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

A: <TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).
The fix should have been as simple as:

*

*In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.

*In the second case, when adding the declaration stating encoding="utf-16": either

*

*simply don't add the XML declaration, OR

*simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)

All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.
It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve "unable to switch the encoding" error when inserting XML into SQL Server, but the basics are:

*

*The XML declaration is optional

*The XML datatype stores strings always as UCS-2 / UTF-16 LE

*If your XML is UCS-2 / UTF-16 LE, then you:

*

*pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".

*if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)

*If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:

*

*need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database

*you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".

*Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.

*The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.
On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.
For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:
-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ሴ</string>';
SELECT @Xml;
-- <string>Test ሴ</string>

As you can see, it even handles characters beyond standard ASCII, given that ሴ is BMP Code Point U+1234, and  is Supplementary Character Code Point U+1F638. However, the following:
-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ሴ</string>';

results in the following error:
Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:
You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:
-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ሴ</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

A: For anyone in need of an F# version of the approved answer:
type private Utf8StringWriter() =
    inherit StringWriter()
    override _.Encoding = System.Text.Encoding.UTF8

A: It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.
using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
    try
    {
        bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
        bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
        tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed.  What you see in the resulting record is just
<test></test>

Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string> tag.
The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard.  The five parameters to the Insert method map to fields in a SQL Server table.


text: Q: Making stored procedure with input parameter I need to make a stored procedure that takes an input parameter. That parameter is name of a patient. All i want is to get that name's ID and add these ID and name to a new table. Is it possible?


text:
Q: How to make WinInet HTTPS subsequent requests to reuse connection? I'm sending a few subsequent http-requests on my server using wininet, and until I use TLS (INTERNET_FLAG_SECURE flag in HttpOpenRequestA) the connection is being reused ok. Now I want to use TLS, set the mentioned flag, and  also flags INTERNET_FLAG_IGNORE_CERT_CN_INVALID and INTERNET_FLAG_IGNORE_CERT_DATE_INVALID (to skip self-signed cert verification) - now a new connection is established for every HttpOpenRequest call. How to reuse conn with tls?
p.s. INTERNET_FLAG_EXISTING_CONNECT has no effect

A: Each new connection does a separate TCP handshake and a separate TLS handshake.In case of session reuse no key exchange is performed, that is the same symmetric key is re-used.
See How does SSL/TLS work?


text:
Q: How do I deploy my H2O wave app (e.g. with heroku)? Is there a way to deploy an app created using H2O wave?
I recently made a data visualization app and would like people to be able to demo it really quickly and easily.
I have tried following this thread: Deploy H2O Wave application to Heroku? but the problem seems to be unresolved thru previous replies.
In addition, H2O's docs (https://wave.h2o.ai/docs/deployment) don't really explain this in much detail. Not many articles about this exist elsewhere, so any help would be extremely appreciated!

A: H2O Wave maintainer here. You can see this or this blog post on how to do it on Heroku specifically.
The deployment is no different from deploying any other server/software in general. All you need is a dedicated server (e.g. Heroku/AWS EC2) to which you upload your code, start the server, make sure the correct ports are exposed etc. If that sounds like too much work, I would recommend having a look at enterprise - appstore solution.


text:
Q: Ubuntu 20.04 - iMac late 2009. Nvidia Geforce 9400 freezes I have been trying to run Ubuntu 20.04 on an old iMac (late 2009).
With a fresh install, it randomly freezes once resizing windows, changing the background wallpaper, or while opening a browser.
I have read a few posts describing the same problem, pointing to changing the graphics driver to the legacy-nvidia driver:
Help needed with Ubuntu 20.04 on iMac late 2009
Following the first part of the post:
sudo add-apt-repository ppa:kelebek333/nvidia-legacy
sudo apt update
sudo apt install nvidia-340
sudo reboot

It seems to work fine at first, however, I can't add the brightness control described in the linked topic. The monitor will stay black on the next reboot.
I have the same issue the monitor stays black after a few restarts.
Could you give a Linux beginner some pointers?

A: We have Ubuntu 20.04 working on a Late 2009 imac (in December 2021) and ran into these same kinds of issues but were able to successfully work through them. 3 things are critical in the install

*

*The first critical point is that the install must be done on a BIOS partition (not an EFI one). I followed the "Option B" procedure in this post: https://ubuntuforums.org/showthread.php?t=2209602. You basically start with an EFI install procedure from the liveboot disk and then convert it to a BIOS one. If you do it on an EFI partition, you will have all kinds of problems with the video card, even if you install the right drivers. At least we did.

One minor point is 3/4 of the way down the page, you need to add "sudo" to one of the lines:
sudo mount --bind /dev /mnt/dev
sudo mount --bind /dev/pts /mnt/dev/pts
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys
sudo chroot /mnt
sudo update-grub
exit

*You need to install the proper NVIDIA drivers for the video card on your machine. For us, it was the NVIDIA "GeForce 9400". So you skip the last steps in the post in #1 above, and instead follow this second procedure here: Help needed with Ubuntu 20.04 on iMac late 2009. It looks pretty similar to what you tried, so I think maybe your problem is you didn't do step 1.

*Finally, I installed mbpfan so the fans were not always running on high, using the procedure in this post. Imac with Ubuntu (Lubuntu 20.04) - Controlling fan speed
Yes, this may seem a bit tedious, but after installing a fresh 250GB SSD and with this Ubuntu 20.04 install procedure, our 2009 imac is running impressively well - almost too good to be true, really. The only remaining issue I have is I can't get it to suspend when on the login screen, but its such a minor issue compared to where the machine was before!!!


text:
Q: Getting error 413 Request Entity Too Large when using SSL, after a few minutes of inactivity This past Monday we pushed out a new ASP.NET website to our production server for use by the public. One section of the site provides a wizard type interface, each step requesting a fairly small amount of input from the user. Each step of the wizard is it's own user control. As the user moves through the steps, their input is saved to the viewstate, the current control is hidden, and the next is made visible. They of course can go back if need be.
Overall, everything is running smooth given the amount of use we're seeing, but we have had two users call in to say that as they tried to move from one step to the next, they were given the message "Request Entity Too Large". I gathered all of their input, and  went through myself trying to recreate the problem.
In both cases I went through several times, and everything worked without issue. During another test run, I got a phone call, and was sidetracked for about 5 minutes. When I went to pick up where I left off, I then got the same error. I then tried again, purposely waiting for a few minutes at one step in the process, and got the error again. This was a different step then where I had paused the last time.
I'm wondering if inactivity can actually contribute to the problem, and if increasing the "uploadReadAheadSize" value in IIS is the correct solution, or if we can somehow correct the problem in the application itself. Thanks.

A: We experienced a similar problem recently, and we made the following changes:

*

*Increased the uploadReadAheadSize (as you mentioned)

*Updated IIS7 SSL Settings to Ignore the Client Certificate.


text:
Q: MediaLauncher on emulator(virtual device) Is it possible to play and record speech on android emulator? or it must require physical device?

A: Sorry, but its require a physical device... At least to recording:

Note that the emulator doesn't have hardware to capture audio or video, but actual mobile devices are likely to provide these capabilities
  http://developer.android.com/guide/topics/media/index.html


text:
Q: boost::program_options ignore options in config file Could you please help me with boost::program_options?
I want the parser to ignore unknown options that are saved in config file.
I know that allow_unregistered() can be used for cmd line options, how do I proceed with text files?
Here is stripped code:
namespace po = boost::program_options;
try {
    string config_file;
    string gps_source;
    int op_baud;

    po::options_description generic("Generic options");
    generic.add_options()

        ("ssdvpacksize", po::value<int>(),
              "ssdv packets size in bytes")
        ("ssdvdir", po::value<string>()->default_value("/ARY1/ssdv"),
              "ssdv image dir")

        //unused
        //I have to specify these even if they're unused
        ("ssdvproc_dir", po::value<string>(), "")
        ;

    po::options_description file_options;
    file_options.add(generic);

    po::options_description cli_options("command line interface options");
    cli_options.add(generic);
    cli_options.add_options()
        ("config", po::value<string>(&config_file)->default_value("/boot/ary-1.cfg"), "name of a file of a configuration.");

    po::variables_map vm;
    store( po::command_line_parser(ac, av).options(cli_options).allow_unregistered().run(), vm );
    //store( po::basic_command_line_parser<char>(ac, av).options(cli_options).allow_unregistered().run(), vm );

    notify(vm);

    ifstream ifs(config_file.c_str());
    if (!ifs)
    {
        cout << "Can not open config file: " << config_file << "\n";
    }
    else
    {
        // probably smth. to do here ?
        //store(parse_config_file(ifs, file_options).allow_unregistered(), vm); // does not work
        store(parse_config_file(ifs, file_options), vm);
        notify(vm);
    }

    // ...
    // rest of program

}

A: OK, the solution is embarrassingly easy.
Line 44 should be:
store(parse_config_file(ifs, file_options, true/*allow unregistered*/), vm);


text:
Q: Passing an C# array of structs with array of double member to C DLL by reference We have the following code marshalling between c# and c dll. However, when print the value within the C dll function, the values associated with the double array properties are all 0.0000000.  I have put some in line comments for the code having problems.
Did we miss any thing to configure the marshalling behaviour?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            MonteCarlo montecarlo = new MonteCarlo();
            montecarlo.RunMonteCarlo();
        }
    }
    class MonteCarlo
    {

        [DllImport("MonteCarloCUDA.dll")]
        public static extern int MonteCarloPrint([In, Out]PurchaseOrder[] purchaseorders, int length);

        public void RunMonteCarlo()
        {

            PurchaseOrder[] purchaseorders = new PurchaseOrder[3];

            purchaseorders[0] = new PurchaseOrder();
            purchaseorders[0].Value1 = "AAAAA";
            purchaseorders[0].Value2 = 0.111;
            purchaseorders[0].Value3 = new double[2]; // Assign the values to array of double
            purchaseorders[0].Value3[0] = 0.11111;
            purchaseorders[0].Value3[1] = 0.22222;

            purchaseorders[1] = new PurchaseOrder();
            purchaseorders[1].Value1 = "BBB";
            purchaseorders[1].Value2 = 0.222;
            purchaseorders[1].Value3 = new double[2];
            purchaseorders[1].Value3[0] = 0.33333;
            purchaseorders[1].Value3[1] = 0.44444;

            purchaseorders[2] = new PurchaseOrder();
            purchaseorders[2].Value1 = "CCC";
            purchaseorders[2].Value2 = 0.333;
            purchaseorders[2].Value3 = new double[2];
            purchaseorders[2].Value3[0] = 0.55555;
            purchaseorders[2].Value3[1] = 0.66666;

            int result = MonteCarloPrint(purchaseorders, purchaseorders.Length);

            Console.ReadKey();
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
        public unsafe struct PurchaseOrder
        {
            public string Value1;

            public double Value2;

            public double[] Value3; // Array of double member
        }
    }
}

// C Code
#include <stdio.h>

typedef struct PurchaseOrder
{
   char* Value1;
   double Value2;
   double* Value3;
 };

__declspec(dllexport) int __stdcall MonteCarloPrint(PurchaseOrder *hostPurchaseOrders, int length)
{
    printf("\nSize of PurchaseOrder: %d",sizeof(PurchaseOrder));

    for (int i = 0; i < length; i++)
    {
        printf("\n\nAddress: %u",hostPurchaseOrders+i);
        printf("\nValue1: %s",(hostPurchaseOrders+i)->Value1);
        printf("\nValue2: %f",(hostPurchaseOrders+i)->Value2);
        printf("\nValue3[0]: %f",(hostPurchaseOrders+i)->Value3[0]);
        printf("\nValue3[1]: %f",(hostPurchaseOrders+i)->Value3[1]);

    }
}}

The print result from the C dll function

Size of PurchaseOrder: 24

Address: 13180880
Value1: AAAAA
Value2: 0.111000
Value3[0]: 0.000000 // No value are marshalled
Value3[1]: 0.000000

Address: 13180904
Value1: BBB
Value2: 0.222000
Value3[0]: 0.000000
Value3[1]: 0.000000

Address: 13180928
Value1: CCC
Value2: 0.333000
Value3[0]: 0.000000
Value3[1]: 0.000000

A: Remove the Pack property from the [DllImport] declaration, it is wrong.  You are not using a #pragma pack directive in your C code, the default value for Pack is appropriate.  If it would have been in effect then your C code would have reported 16.
You are seeing 24 because there's 4 bytes of padding to align the double and 4 bytes of padding at the end of the structure to make the double align when the structure is used in an array.  4 + 4 + 8 + 4 + 4 = 24.  The packing in effect is 8, the default.
You can make it more efficient by swapping Value2 and Value3 to get a struct of 16 bytes, no padding necessary.  In case it matters.  That's what the JIT compiler does.

The next problem is tougher, the P/Invoke marshaller will marshal the embedded array as a SAFEARRAY.  You can solve that on the unmanaged side by using this code:
#include "stdafx.h"
#include <stdio.h>
#include <objidl.h>

struct PurchaseOrder
{
    char* Value1;
    double Value2;
    LPSAFEARRAY Value3;
    int fence;
};

extern "C"
__declspec(dllexport) int __stdcall MonteCarloPrint(PurchaseOrder *hostPurchaseOrders, int length)
{
    printf("\nSize of PurchaseOrder: %d",sizeof(PurchaseOrder));

    for (int i = 0; i < length; i++)
    {
        printf("\n\nAddress: %u",hostPurchaseOrders+i);
        printf("\nValue1: %s",(hostPurchaseOrders+i)->Value1);
        printf("\nValue2: %f",(hostPurchaseOrders+i)->Value2);
        double* arrayPtr;
        if (S_OK == SafeArrayAccessData((hostPurchaseOrders+i)->Value3, (void**)&arrayPtr)) {
            printf("\nValue3[0]: %f", arrayPtr[0]);
            printf("\nValue3[1]: %f", arrayPtr[1]);
        }
    }
    return 0;
}

I wrote the code using the C++ compiler, you may have to tweak.


text:
Q: Algorithm to determine international calling code from phone number I'm able to retrieve contact's phone number from the device using Address Book framework on iOS. How can I separate or identify which is country code and which is actual phone number?
Is it possible?

A: Country codes are a fairly messy topic but standard enough that with some programmer maintenance you can solve it.
You can identify a country code by its initial subsequence.  Do the following algorithm:

*

*Build a simple database - can even store as a flat file and load into a dictionary in memory - of country codes.

*Recursively from n = 1 to 3, check if the first n digits of the phone number match any country code.  If so, that's your country code.  If it fails by try 3, it's not a valid country code.

*If you like deal with quasi-ambiguities.  If you ever see overlap between country codes, e.g. if you see "1340" for Virgin Islands, it's because in some probably irrelevant sense it's a subset of the country code "1" for U.S.  Country codes sometimes reflect geopolitical situations and usually this is expressed by splitting the country code to the next digit.  "1" will be the official country code but which is of more interest to you depends on your application.
Note: This takes maintenance when thinks like the Soviet Union breakup happen.

Now, things get messier when you have to deal with the fact that some #s already have country codes on them and some don't and such.  The only country code I've found in which the country code can also occur as a leading area code is Singapore - I think it was +65-65....  With decent accuracy you can use business logic along the lines of:

*

*Watch for U.S. number format: (xxx) xxx-xxxx and such.

*Use the fact that only certain digits lengths can occur in given countries.  There are documents on this if you search hard enough.  e.g., all U.S. numbers are length 10, Japanese numbers can be length 9 or 10.  This can give you added information.

*Ignore leading 0's for most countries.  Italy and Ivory Coast are the only two exceptions I've found, these can have valid leading 0's.  Otherwise it's just a local telecom convention for staying within the country, usually.

A: What I did was to create an array of all the country calling codes on wikipedia. Then, when I have a phone number, I try to match the first four digits with one of the country calling codes. If none match, try the first three digits and so on. Eventually I find the calling code.

A: Country calling codes are fairly easy to detect from phone number.
The first thing you need to do is to parse calling codes into a tree where each digit is representing a branch.
Then, finding a country code is as easy as traversing the tree, digit by digit, until the last branch which is a country code match.
At this moment (July 2016.), the longest country calling code has 5 digits, so your tree should not have more than 5 levels of branches.

A: After some researches I found this lib which seems to do the work:
https://github.com/iziz/libPhoneNumber-iOS

A: To add to @unobic answer, here's a working code sample you could use to do that without a library in JavaScript (because that's what I do, and needed, don't hate me ^^):
// Get the international dialing code (with region code)
// from a given phone number
const getDialingCode = (phoneNumber) => {
  const maxDialingCodeLength = 5
  const start = phoneNumber
    ?.replace(/^(\+|00)/, "")
    .slice(0, maxDialingCodeLength)
  if (start) {
    const tree = start.split("")
    let testedDialingCode = tree.join("")
    let match = countriesMap.get(testedDialingCode)
    while (!match && tree.length) {
      tree.pop()
      testedDialingCode = tree.join("")
      match = countriesMap.get(testedDialingCode)
    }

    if (match && testedDialingCode) {
      return testedDialingCode
    }
  }
}

This requires you to have a countries map, which you can generate from https://gist.github.com/daformat/b3bf879b1df325c77999fdd742f1d63f
by doing the following:
// Because some countries can have multiple regional codes
// we first create a flattened list (still using an array
// for the regional code, though this time of length 1 if any
const flattenedCountries = iso3166_1_countries
  .flatMap((country) => {
    return country.dial_region_codes
      ? country.dial_region_codes.map((dial_region_code) => ({
        ...country,
        dial_region_codes: [dial_region_code]
      }))
      : [country]
  })
  .sort((a, b) => a.name.localeCompare(b.name))

// We also build a map to make the prefix lookup easier / cheaper
const countriesMap = new Map(
  flattenedCountries.map((country) => [
    country.dial_country_code +
    (country.dial_region_codes ? country.dial_region_codes.join() : ""),
    country
  ])
)

If you need to get the full Country info, you can then use the following to get the entry from the countries map:
const getCountryFromPhoneNumber = (
  phoneNumber
) => {
  const dialingCode = getDialingCode(phoneNumber)
  if (dialingCode) {
    return countriesMap.get(dialingCode)
  }
}

You can find a fully working typescript implementation of this here:
https://gist.github.com/daformat/ea94d3be630d2039f479ca774e276578

A: We cannot identify the country code from the phone number.


text:
Q: Why all bolt acked but the spout fail? I'm using JmsSpout and BaseBasicBolt.
All bolts acked, but a lot(about half) of spout fail.
What's the possible reason?
or how can I log why the message fail? the JmsSpout just print which message fail, without error info.

A: If you do not actively fail() tuples in bolts, the only reason for failing tuples is a timeout. The default timeout in Storm is 30 seconds (you can configure it via TOPOLOGY_MESSAGE_TIMEOUT_SECS). If a tuples get emitted, Storm wait for the timeout duration to receive an ack. If not ack is received within this duration, Strom fails the tuple.
Increasing the timeout can fix the problem (you should set the timeout to a larger value than your expected processing latency).
If your expected processing latency is already lower then the timeout value, it indicates that you have a bottleneck in you topology. Thus, one (or multiple) operators cannot process incoming tuples fast enough. Therefore, incoming tuples get buffered in input queues increasing there latency as the queue is growing over time. You need to increase the parallelism for those bottleneck operators to resolve the issue.


text:
Q: array counter in java not counting correctly Using the code below I have a 3x3 array.  Every other check I've designed has been sucessful however counter seems to stop outputting/counting at the 3rd or 4th input I have no idea as to why it would do that.
sorry I left some info out (Thanks tom)
the board is a tic-tac-toe board and there's a method to input the value into the array as listed below
 public void inputMove(int inRow, int inCol, String inMove){
    board[inRow][inCol] = inMove;
}

 private boolean checkFill(){
    boolean test = false;
    int counter = 0;

    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            if(!(board[i][j].equals("-"))){
                counter++;
            }
        }
    }
    System.out.println(counter);
    return test;

}

A: You haven't provided the full code, where board[][] is created. However, I can suggest two things:

*

*You are not setting the test variable.

*Verify your board[][] input for 3rd and 4th inputs.

Rest looks good.

A: Your are using fixed lengths, change it from a fixed 3 to the .length property of the board array with something like
for(int i = 0; i < board.length; i++) { // board.length instead of 3
    for(int j = 0; j < board[i].length; j++) {
        if(!(board[i][j].equals("-"))){


text:
Q: how to force all browsers to not store your site's cache? When you are in the development stage it's a bit embarrassing to constantly remind your clients to clear the cache or to ask them to "refresh the page a bunch of times."
Is there a setting that I, the developer, can set in nginx or as a meta tag in the HTML to force all browsers to stop caching my page?

A: Theoretically, according to Difference between Pragma and Cache-control headers? and also http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32, the following may be sufficient, in nginx:
add_header  Cache-Control   no-cache;

In practice, you might have to specify some extra directives; it would seem like using the expires directive should be sufficient, which will automatically add the Cache-Control header as above, too:
expires -1;

A: Try setting these headers:
"Cache-control: no-store, no-cache, must-revalidate"
"Expires: Mon, 26 Jun 1997 05:00:00 GMT"
"Pragma: no-cache"
"Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"

This will prevent the browsers from cashing the pages.


text:
Q: SQL Server: migrate one table to discrete DB server SQL Server 2012 Standard
We have one table that is highly transactional (tons of inserts, no updates), that contains a BLOB object of 5kb-300kb per row. The whole table is about 31GB in size (table and indexes), and has 450K rows. There is a primary key (it is a clustered table), and there is a record creation timestamp col.
We want to move table to its own db server. We have already updated the application to reference this table via its own ADO connection string. Yes, we can take the app offline during a maint window to do this.
What is the best strategy to migrate a single table to another DB server?
Options we have considered:
 - Log shipping , but this replicates whole db... if we could log ship one table, we would do it for sure, we like log shipping
 -  Transactional replication... we do NOT like transactional replication because it is such a monster.
One thought is to bring the app down briefly, and do a tsql command to
insert into <new db server.db.table> select from <source db server and table>

*

*Can that work? Can we do a tsql command across discrete db servers?

*What other method we should consider?

A: If it is one time, then you should use bcp out and bulk insert .. much better and faster than the linked server approach that you are thinking, since in the linked server approach if you run the query on the source server then you are pushing the data from source server to destination server which is an expensive operation. Alternatively, you can use SSIS as well.
If you need to keep the data in the new server sync with the old one, then your only option is to use transactional replication.
Also, refer to my answer on : Which one is more efficient: select from linked server or insert into linked server?

A: *

*Yes it could. however...

*I would use SSIS.

Depending upon the size of the table you could create an SSIS (.dtsx) package and execute in on the target server. This would also avoid the use of the linked server.
You could create this with the import wizard in SSMS and save the package.
If the table is massive, there are a few options and features within SSIS that will help you break the job into more manageable chunks. SSIS can also handle bulk insert.
If this table is the only object in the target database you could also consider putting the database into simple recovery mode or bulk logged. That may help minimize logging while you are copying data.
Provided you are correct that the source table is only inserted to, and not updated this should be relatively straight forward. After the copy you could use a linked server query to compare. (outer join on primary key)
BCP may have better performance, but db->db has the advantage of 1 less step and the storage requirements that go with it. The biggest advantage is that the ssis approach can be interrupted and you could easily resume where you left off.


text:
Q: How can I write vim mappings to stdout? I would like to write the output of :map to stdout from the vim cli so I can read my vim keymaps from a script and do something with them. How can I accomplish this?
I've tried vim -c map > out.txt and vim -c "map|q" > out.txt as text cases, but neither work. :map opens a pager while inside vim, I think I may need a way to bypass this.

A: Based on https://stackoverflow.com/a/33190693/355325 I came up with this:
vim -e +"redir>>/dev/stdout | map | redir END" -scq


text:
Q: Wordpress insert javascript into page text area I'm trying to add some JavaScript into one of my Wordpress pages. When I change the text area to HTML mode and paste in the JavaScript then save my changes. It does not appear on the page itself. Can someone please help me allow JavaScript in the default Wordpress page text editor?
The JavaScript that I am trying to input is:
<script type="text/javascript">
    jQuery(function($){
        $.supersized({
            random : 1,
            slide_interval : 3000,
            transition : 3,
            transition_speed : 900,
            slide_links : 'blank',
        });
    });
</script>

A: WordPress is really picky about how you do the newlines and it will sometimes place <p> tags in there which will mess up JavaScript code.  I would recommend looking at the source after you make the post and see if any of the <p> tags got incorporated.  If so, go back and delete the white-spacing in that area and try again.
In the worst case, you can always use the Raw HTML plugin which will render the raw code for you:
http://wordpress.org/extend/plugins/raw-html/

A: You, or others viewing this question, might also want to try my plugin which enables support for inline JavaScript and JavaScript code blocks in the HTML editor tab.  You don't have to use a shortcode or special markup and you can continue to use the TinyMCE wysiwyg editor without worrying too much about losing the content... If you delete everything in the Visual editor, you'll lose the code block, but edits, additions and targeted deletions of content are fully compatible.
It also preserves whitespace and indentation of HTML code when you switch between the HTML and Visual tabs among a few other minor features.
http://wordpress.org/extend/plugins/preserved-html-editor-markup/


text:
Q: Mid point with set square?
Is it possible to construct the midpoint of a segment in the hyperbolic plane
  using the set square only?

With the set square one can

*

*draw the line through the given two points and

*drop the perpendicular from the given point to the given line.

The following construction produce the point $X'$ which is centrally symmetric to the point $X$ with respect to point $O$.

*

*Draw line $(OX)$ and let $m$ be the line perpendicular to $(OX)$ through $O$.

*Draw yet two perpendicular lines $l$ and $l'$ through $O$.

*Find the foot point $Y$ of $X$ on $l$.

*Draw the line through $Y$ perpendicular to $m$ and let $Z$ be its intersection with $l'$.

*Finally, $X'$ is the footpoint of $Z$ on $l$.

A: I can do it if I am allowed to cheat - in axiom one for the set square (which is the axiom for the straight-edge) I'll allow one of the points to be ideal: that is, on the Gromov boundary of $H^2$.  Also, I assume that the set square produces infinite geodesic rays.  In particular, this means, in the second axiom, that the given point can be on the given line.
Suppose the segment $[x,y]$ is given.  Draw the geodesic ray $P$, based at $x$ and perpendicular to $[x,y]$.  Do the same at $y$ to get the ray $Q$, on the same side of $[x,y]$.  Connect the ideal endpoint of $P$ to $y$ and the ideal endpoint of $Q$ to $x$.  These new rays cross at $z$.  Drop a perpendicular from $z$ to $[x,y]$ and we are done.

A: Finally, I realized that the answer is NO.
Let us think of hyperbolic plane as about subset of projective plane for $\mathbb R^{2,1}$.
Note that in this model, the set square tool is the same as hyperbolic-cross-product tool;
i.e. for any two vectors $u$ and $v$
you can construct the vector
$$w=J(u\times v),$$
where
$$ J\begin{pmatrix}x\\y\\z\end{pmatrix}=\begin{pmatrix}x\\y\\-z\end{pmatrix}$$
If the end points of the segment are given by rational vectors then so are all the hyperbolic-cross-products.
On the other hand, it is easy to construct two rational vectors such that their hyperbolic bisector goes in an irrational directin.
Hence the result follows.

In spherical geometry, the same question has also answer NO.
It is easier to visualize since in spherical geometry the set square tool is equivalent to the cross-product tool.

A: Here's another construction that works in the Euclidean plane.  Suppose we want the midpoint of $A$ and $B$.  Take any $C$ between $A$ and $B$, and draw some $D$ off of $\overline{AB}$ such that $\overline{CD}$ and ${AB}$ are perpendicular.   You can construct a line parallel to $\overline{AD}$ that goes through $B$ by drawing a perpendicular to $\overline{AD}$ and then another perpendicular to that new line.  You can also draw a parallel to $\overline{BD}$ through $A$.  These two parallels intersect at $E$.  Then $ADBE$ forms a parallelogram, and you can intersect the diagonals to find the midpoint $F$ of $AB$.
Now, in the hyperbolic plane, the parallel you find isn't unique, so there are multiple ways to do this same construction.  And when you do, $F$ is not going to be a midpoint.  However, $F$ will be closer to the midpoint than $C$ (I believe).  Hence, repeating the construction, you could construct maybe construct a sequence of points that converge to the midpoint.  Obviously that sort of thing isn't allowed in a construction, but it's at least going in the right direction =).


text:
Q: Get context id corresponding to the current period I'm trying to parse a list of xbrl instance files. The filings (10-Q) correspond to different companies from different industries, reporting under us-gaap.
I'm trying to extract the values of Revenue for the current 3-month period. In order to do that I'm trying to get the value of "us-gaap:Revenues" element.
The problem is that there're many "us-gaap:Revenues" elements corresponding to different contexts. How do I let the parser know which context corresponds to the current period and is for the whole company (not for the segments)?

A: Without knowing more details about your work, I believe you need some basic XBRL processor to help working with XBRL easier. There are many open-source and proprietary processors.
Coming back to your question, I think the ideal way would be to fetch all the contexts matching the period you are looking for. Then querying for the us-gaap:Revenue facts for each of those contexts.
On your question "How do I let the parser know which context is for the whole company (not for the segments)?" - I believe there is a dimension (or axis) that you are looking for. Usually the dimension member corresponding to the whole company is the default one (confirm this by looking at the taxonomy). And since contexts usually omit the default dimension values, you have to look for the contexts that don't have that dimension in their segment (or scenario).
You can browse the us-gaap taxonomy in the online Taxonomy Viewer tool provided by FASB.
One thing to make sure is, there can be Revenue facts in the extension taxonomy as well and you might be interested in those as well. This is a big issue with US-GAAP taxonomy, even though allowing extensions adds flexibility, it degrades the data quality of the filings.


text:
Q: GSAP 3 ScrollTrigger not working with dynamically changing value (not refresh / recalculated) I have a problem when using GSAP's ScrollTrigger.
I set the height of a pinned element in different viewport widths, and it works fine when resizing the window.
But now I want to change hight of the pinned element by clicking the button. I use ScrollTrigger.refresh(); but nothing happens.
Can somebody tell me how to fix it?

ScrollTrigger.create({
  trigger: '.box',
  pin: true,
  start: 'top center',
  end: () => `+=${$('.h-500').height() - $('.box').height()}`,
  markers: true,
  id: "box",
  onRefreshInit: () => {
  },
  onRefresh: () => {
  }
});

function resizeBox(){
  $('.box').css('height', '50px');
  ScrollTrigger.refresh();
}
body{
  margin: 0;
}
.space {
  width: 100%;
}
.h-500 {
  height: 500px;
  background: yellow;
}
.h-1000 {
  height: 1000px;
}
.box {
  width: 100px;
  height: 100px;
  background: red;
}
button {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 999;
  font-size: 20px;
}

@media only screen and (max-width: 600px) {
  .box {
    height: 5vw;
  }
}

<button onclick="resizeBox()">resizeBox</button>

A: This is somewhat of a tricky situation because you're resizing the same element that you're pinning. ScrollTrigger automatically caches the dimensions and such so when the refresh happens ScrollTrigger clears all inline styles (which just happens to clear the new value that you set) and then reverts to its cached state. Whether or not that is a bug or not we (GreenSock) have not determined yet :)
As for how to work around the situation for now, you can create an empty container around your box and pin that instead:

trigger: ".pin-container"

Demo


text:
Q: Calculate statistics for number of clicks per week so i have a small application, that registers how many clicks are on certain statements.
I have a table called ClickStatistics
Which stores the ID for the specific statement clicked, and a Datetime "LogDate".
I want to create a graph that tells me how many clicks there has been each week.
I have made something similar with months, but i am unable to figure out a way to do it for weeks.
var months = new[]{
                "Januar",
                "Februar",
                "Marts",
                "April",
                "Maj",
                "Juni",
                "Juli",
                "August",
                "September",
                "Oktober",
                "November",
                "December"
            };
var MonthlyCountQuery = from c in ClickStatistics
                                    where c.LogDate.Year == selectedYear && c.Statement.Deleted == false
                                    group c by c.LogDate.Month into grp
                                    select new
                                    {
                                        Month = grp.Key,
                                        Clicks = grp.Count(),
                                    };

            var monthlyCount = MonthlyCountQuery.ToList().Select(i => new { Month = months[i.Month - 1], i.Clicks});

Any tips would be welcome!

A: You can make an extension for DateTime and then group by that method.
An extension I use (not quite sure, but I think I found it here on SO):
public static int? GetIso8601WeekOfYear(this DateTime? dt)
{
    if (!dt.HasValue) return null;

    // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll
    // be the same week# as whatever Thursday, Friday or Saturday are,
    // and we always get those right
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(dt.Value);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        dt = dt.Value.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dt.Value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

But be aware, like Stefan mentioned in a comment above, you need to check which standard you need. You might to write a different extension method.
Update: extension method is from this post:
Get the correct week number of a given date
Upvotes for @il_guru please ;)

A: So, something like:
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

//just to make formatting on SO better
var whereClause = ClickStatistics
         .Where(i => i.LogDate.Year == selectedYear && i.Statement.Deleted == false).ToList();

var WeekCountQuery = from c in whereClause
                     group c by
                     cal.GetWeekOfYear(c.LogDate, dfi.CalendarWeekRule, dfi.FirstDayOfWeek)
                     into grp
                     select new
                     {
                          Week = grp.Key,
                          Clicks = grp.Count(),
                     };

Or of course one of the other extension methods mentioned in the comments.
e.g.:
var WeekCountQuery = from c in whereClause
                     group c by
                     //make sure you have the extension method
                     c.LogDate.GetIso8601WeekOfYear()
                     into grp
                     select new
                     {
                          Week = grp.Key,
                          Clicks = grp.Count(),
                     };


text:
Q: Store output of subprocess.Popen call in a string I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")

I've tried a few things including some of the suggestions here:
Retrieving the output of subprocess.call()
but without any luck.

A: In Python 2.7 or Python 3
Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:
from subprocess import check_output
out = check_output(["ntpq", "-p"])

In Python 2.4-2.6
Use the communicate method.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

out is what you want.
Important note about the other answers
Note how I passed in the command. The "ntpq -p" example brings up another matter. Since Popen does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"].

A: This worked for me for redirecting stdout (stderr can be handled similarly):
from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]

If it doesn't work for you, please specify exactly the problem you're having.

A: I wrote a little function based on the other answers here:
def pexec(*args):
    return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()

Usage:
changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))

A: Python 2: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, Popen

command = "ntpq -p"
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
output = process.communicate()[0]
print output

In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
command = ["ntpq", "-p"]
process = Popen(command, stdout=PIPE, stderr=None)

If you need to read also the standard error, into the Popen initialization, you should set stderr to PIPE or STDOUT:
command = "ntpq -p"
process = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
output, error = process.communicate()

NOTE: Starting from Python 2.7, you could/should take advantage of subprocess.check_output (https://docs.python.org/2/library/subprocess.html#subprocess.check_output).

Python 3: https://docs.python.org/3/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, Popen

command = "ntpq -p"
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
    output = process.communicate()[0].decode("utf-8")
    print(output)

NOTE: If you're targeting only versions of Python higher or equal than 3.5, then you could/should take advantage of subprocess.run (https://docs.python.org/3/library/subprocess.html#subprocess.run).

A: In Python 3.7+ you can use the new capture_output= keyword argument for subprocess.run:
import subprocess

p = subprocess.run(["echo", "hello world!"], capture_output=True, text=True)
assert p.stdout == 'hello world!\n'

A:  import os
 list = os.popen('pwd').read()

In this case you will only have one element in the list.

A: Assuming that pwd is just an example, this is how you can do it:
import subprocess

p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result

See the subprocess documentation for another example and more information.

A: import subprocess
output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE,
stderr = subprocess.STDOUT).communicate()[0])

This is one line solution

A: for Python 2.7+ the idiomatic answer is to use subprocess.check_output()
You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....
If args is just single command with no args of its own (or you have shell=True set), it can be a string.  Otherwise it must be a list.
for example... to invoke the ls command, this is fine:
from subprocess import check_call
check_call('ls')

so is this:
from subprocess import check_call
check_call(['ls',])

however, if you want to pass some args to the shell command, you can't do this:
from subprocess import check_call
check_call('ls -al')

instead, you must pass it as a list:
from subprocess import check_call
check_call(['ls', '-al'])

the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses...
like this:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))

A: This works perfectly for me:
import subprocess
try:
    #prints results and merges stdout and std
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error and merges stdout and stderr
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output # contains stdout and stderr together

A: This was perfect for me.
You will get the return code, stdout and stderr in a tuple.
from subprocess import Popen, PIPE

def console(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    out, err = p.communicate()
    return (p.returncode, out, err)

For Example:
result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]

A: The accepted answer is still good, just a few remarks on newer features. Since python 3.6, you can handle encoding directly in check_output, see documentation. This returns a string object now:
import subprocess
out = subprocess.check_output(["ls", "-l"], encoding="utf-8")

In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :
import subprocess
p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
p2.stdout

A: The following captures stdout and stderr of the process in a single variable.  It is Python 2 and 3 compatible:
from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True
except CalledProcessError as e:
    output = e.output.decode()
    success = False

If your command is a string rather than an array, prefix this with:
import shlex
command = shlex.split(command)

A: Use check_output method of subprocess module
import subprocess

address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])

Finally parse the string
for line in res.splitlines():

Hope it helps, happy coding

A: For python 3.5 I put up function based on previous answer. Log may be removed, thought it's nice to have
import shlex
from subprocess import check_output, CalledProcessError, STDOUT

def cmdline(command):
    log("cmdline:{}".format(command))
    cmdArr = shlex.split(command)
    try:
        output = check_output(cmdArr,  stderr=STDOUT).decode()
        log("Success:{}".format(output))
    except (CalledProcessError) as e:
        output = e.output.decode()
        log("Fail:{}".format(output))
    except (Exception) as e:
        output = str(e);
        log("Fail:{}".format(e))
    return str(output)

def log(msg):
    msg = str(msg)
    d_date = datetime.datetime.now()
    now = str(d_date.strftime("%Y-%m-%d %H:%M:%S"))
    print(now + " " + msg)
    if ("LOG_FILE" in globals()):
        with open(LOG_FILE, "a") as myfile:
            myfile.write(now + " " + msg + "\n")


text:
Q: How do i round to the nearest whole number I am calling ToMinutes() on a nullable DateTime, this returns a double butI wish to convert it to the nearest whole number if it is not null.
example: From 1534488.74496255 to 1534489
How can I do this ?

A: Could it be something like the following you are after? This returns the closest lower integer.
int timeAsWholeMinute = (int) Math.Floor(timeInMinutes);

or if you just want the closest integer:
int timeAsWholeMinute = (int) Math.Round(timeInMinutes);

A: When you want to round, just round:
  double source = 1534488.74496255;

  // if you want double (i.e. floating point result)
  double result = Math.Round(source);

  // if you want integer outcome (and source is positive)
  int minutes = (int) (source + 0.5);

  // if you want integer outcome (general case)
  int minutes = (int) (source > 0 ? source + 0.5 : source - 0.5);


text:
Q: Alternative of XML Starlet Is there any alternative to XML starlet for XML processing in bash? My typical usage is:

*

*pretty formatting;

*selecting data by XPath.

A: Take a look at xmllint.
To format xml:
$ xmllint --format file.xml

To evaluate an XPath:
$ xmllint --format --shell file.xml <<< "cat /some/xpath/expression"


text:
Q: TV screen not detected anymore I have had a dual monitor (one tv, one monitor) setup for a few month on Ubuntu 16.04.3 LTS. And I've had this setup before for a few years on xubuntu 14 and older.
Whenever I've watched some MP4 videos with Totem on Ubuntu 16 sometimes the screens started reconfiguring and sometimes one of the screens wasn't recognized anymore. This all reconfigured itself usually. However, this time the tv screen (LG32LC52) isn't detected anymore even if I restart the pc.
The tv screen is connected to HDMI-0. Unplugging and plugging the hdmi cable has no effect. I checked the hdmi cable and the tv screen on another pc device. They are working.
Additionally all videos played with Totem and Youtube now play in double speed, although normal speed is activated.
I rebooted the pc and switched to Kubuntu 14 and Win 7. No HDMI as well.
I replaced the graphic card with another one and still no HDMI. Might this be a motherboard issue?
xrandr --current
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
VGA-0 disconnected (normal left inverted right x axis y axis)
HDMI-0 disconnected (normal left inverted right x axis y axis)
DVI-0 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 510mm x 287mm
   1920x1080     60.00*+
   1600x1200     60.00
   1680x1050     59.88
   1280x1024     60.02
   1440x900      59.90
   1280x960      60.00
   1280x800      59.91
   1024x768      60.00
   800x600       60.32    56.25
   640x480       60.00

My graphics card:
lspci | grep VGA
05:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RV730 PRO [Radeon HD 4650]

I used the hdmi port of my monitor - this works! So the monitor works via hdmi port, but only the tv is not, although the tv works on my notebook
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
DVI-I-1 disconnected (normal left inverted right x axis y axis)
HDMI-1 disconnected (normal left inverted right x axis y axis)
VGA-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 160mm x 90mm
   1920x1080     60.00*+  50.00    59.94
   1920x1080i    60.00    50.00    59.94
   1600x1200     60.00
   1680x1050     59.88
   1280x1024     60.02
   1440x900      59.90
   1280x960      60.00
   1280x800      59.91
   1280x720      60.00    50.00    59.94
   1024x768      60.00
   800x600       60.32    56.25
   720x576       50.00
   720x480       60.00    59.94
   640x480       60.00    59.94

Funny how this states the VGA port is connected.
I freshly installed Ubuntu 16, but the problems persist.
I switched to the aforementioned other graphics card, which is the following:
lspci | grep VGA
05:00.0 VGA compatible controller: NVIDIA Corporation G86 [GeForce 8400 GS] (rev a1)

I turned on the nvidia-304 drivers (304.137) in the Applications & Updates -> Additional drivers section. I would have the option to switch to nvidia-340 (340.104) or Nouveau. Those do not recognize the tv at all though.
It recognizes the tv. But only as a vga device with a resolution of 800x600, although it is still connected via hdmi.
xrandr --current
Screen 0: minimum 8 x 8, current 2720 x 1080, maximum 8192 x 8192
DVI-I-0 disconnected (normal left inverted right x axis y axis)
HDMI-0 disconnected (normal left inverted right x axis y axis)
DVI-I-1 connected primary 1920x1080+800+0 (normal left inverted right x axis y axis) 510mm x 287mm
   1920x1080     60.00*+
   1680x1050     59.95
   1600x1200     60.00
   1440x900      59.89
   1280x1024     60.02
   1280x960      60.00
   1280x800      59.81
   1024x768      60.00
   800x600       60.32    56.25
   640x480       59.94
VGA-0 connected 800x600+0+480 (normal left inverted right x axis y axis) 0mm x 0mm
   800x600       60.32*+

I have the feeling the Totem crash caused an EDID corruption and only Windows still can recognize the tv(?).
I still have my old 16.04 distribution aside. When I boot it, I can see the following message several times in the kern.log:
kernel: [  519.320215] nouveau 0000:05:00.0: DRM: DDC responded, but no EDID for VGA-1

I have no clue as to how to debug this behavior any further.

Update:
In the meantime I tried different TVs and different graphic cards (also a current one: Palit NE5105T018G1H).
With other TVs I have a video signal. With the new graphics card, I had a video signal as well, but not up to the highest resolution (720p) but only to 1280x*.
I am using another TV now and the video signal usually shows 1080p. However, the TV "randomly" loses its video signal. Turning it off and on again normally brings it back.
But sometimes individual web sites viewed via Firefox seem to crash the signal and the TV loses it. Turning it off and on again is of no help then. Closing the web site does help. Viewing the web site in Chrome for instance does give a more stable result, but not to 100%.


text:
Q: Databases (RDBMS, NoSQL) difficulty with terminology I have some difficulty in understanding the terminology of NoSQL, RDBMS (where they belong, category etc).
From my understanding, you have a 'Database Management System', which has many types such as the relational and ER model.
A RDBMS is based on the relational model.
Now you have NoSQL, which is a type of Database management system, which also has many types (key/value, document store etc.)
So basically, a DBMS and NoSQL are, term wise, on the same level but have different data models?
Am I correct?

A: The Wikipedia article on NoSQL is very appropriate, please read it.
The short answer is that a relational database management system is any system that manages data by...relations.   NoSQL is far less descriptive.  It's a host of very different approaches for managing data.  They really don't have much in common with one another other than that they're not RDBMS.  To further confuse things, NoSQL may actually use SQL, hence why people now call it "Not Only SQL" instead of actually "No SQL".


text:
Q: Validation of only one form On a page with two forms I need a script that will validate only the one that is being submitted.
I have made a simple page that shows the problem
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function validateForm() {
var checks = document.getElementsByName("tjek");
var checksChecked = false;

var i = 0;
while (!checksChecked && i < checks.length) {
    if (checks[i].checked) checksChecked = true;
    i++;
}

if (!checksChecked) {
    alert("Select something!")
    return false;
}
}

</script>
</head>

<body>
<form onSubmit='return validateForm()' action="" method="get">
<input name="tjek" type="checkbox" value="" />
<input name="" type="submit" />
</form>
<form onSubmit='return validateForm()' action="" method="get">
<input name="tjek" type="checkbox" value="" />
<input name="" type="submit" />
</form>
</body>
</html>

http://jsbin.com/duqotobi/1/edit
But it doesn't work. Why?

A: Here goes: live demo: http://jsbin.com/duqotobi/2/edit?html,output.
The code:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Demo</title>
<script>
function validateForm(caller) {
    var checks = caller.querySelectorAll('input[type="checkbox"]');
    for (var i=0; i<checks.length; i++) {
        if (checks[i].checked == false) {
            alert("Select something.");
            return false;
        }
        else {
            caller.submit();
        }
    }
}
</script>
</head>
<body>
    <form name="firstForm" action="form_handler.php" method="get">
        <input name="tjek" type="checkbox" value="" />
        <input type="button" value="Send" onclick="validateForm(this.parentNode)" />
    </form>

    <form name="secondForm" action="form_handler.php" method="get">
        <input name="tjek" type="checkbox" value="" />
        <input type="button" value="Send" onclick="validateForm(this.parentNode)"  />
    </form>
</body>
</html>

If it's not fully self-explanatory, let me know. Do realize however, that it is tricky to give checkboxes the same names, even if it concerns different forms. Only radio inputs belonging to the same group should have the same name. This script is not critical in that aspect, but just so you know.
I rewrote it in my style of JS validation scripting; other styles are possible as well.


text:
Q: Embedding Icons in Rails text_field placholder with HAML I am working on a rails project and it is using bootstrap and I want to embed an icon from awesome font into the placeholder of a text field. The code looks like this:
#search
  = form_for :search, url: topic_search_path do |f|
    = f.text_field :search_query, placeholder: "Search for topics..."

I know that I'm supposed to normally make an italic tag with the class being the icon I want to reference, but I'm lost on how exactly I'm supposed to embed that in the placeholder let alone in a rails form_for block written with HAML. Any help is greatly appreciated.

A: You can specify the character in the value of the plaeholder the old–fashioned way using an entity, as long as you first set the style of the input so that the font is FontAwesome (or at least the first font in the stack is FontAwsome.
For example, if you want to use the icon-search icon, which is at code point F002 (the codepoint is on the icons web page), then you want to generate something like this (assuming you have Font Awesome set up for the page):
<style>
input /* be more selective here if you want */ {
  font-family: FontAwesome;
}
</style>

<input placeholder=" Search for topics...">

To generate this from the text_field method, just pass the entity as part of the value of the placeholder key in the options hash (you may need to use .html_safe here, I haven't tested this last bit):
= f.text_field :search_query, placeholder: " Search for topics..."

(You'll still need to style the input so that it uses the right font, as above.)


text:
Q: The line between a person asking a genuine question and not doing research Stack Overflow is an incredible resource for asking questions and receiving prompt answers from the users.
However sometimes (and I know we have seen it) we get questions which seem insidiously stupid and obvious that the person hasn't put in the research.
Other times I, personally (maybe you too) have noticed that a question will be asked in such a way that the user indicates that he has no familiarity with the subject whatsoever.
For example, "How can you do..."
Answer: "There's absolutely no way and you clearly don't get what you're asking"
And these questions are nearly always closed under the heading "Not A Real Question".
However, this ends up leaving the user confused when he could have been helped by someone explaining instead why the question couldn't be solved.
This happened to me with an old question of mine:
Mutidimensional Array Of Checkboxes?
And though now I clearly understand why that wouldn't work at the time the reason was not apparent and the question was closed before anyone could tell me so.
I'm not saying that we should close vague questions but instead maybe adopt a policy of leniency or try to explain why particular questions were closed
Brilliant Stack Overflow Community!!
Well, you reopened my question above and thanks to you, I in fact did get a very interesting answer to it.
Again, I reiterate that at the time my concepts were flawed, and I should have done a little more research before I posted. (And maybe it deserved closure over an exact duplicate. As said by @ircmaxell.)
However
But saying that I still believe that often when a question is declared to be ambiguous or vague the tagline itself is rather vague to a user that has a genuine question but unfortunately completely misunderstands the concept.

A: I personally see no problem with your question and I wouldn't have voted to close it (I don't know javascript so I can't comment on the triviality of it) Sometimes the effort put into writing the question in terms of formatting, tagging and title ect can't have just as large an impact as the question itself. I think you were just unlucky with that one.
Edit: Seems your post had a positive effect and the question is now re-opened but it does seem to divide opinion as it also have 2 close votes.
Some users are too quick to tear apart a question and vote to close instead either editing the question to improve clarity or comment with suggestions. This goes against the community spirit in my opinion.

A: The line between a genuine question and a "develop it for me" question is very thin.
The reason is that paradox: How the person that declares with a question that is not known, to give some signs that in fact is know something.
From my point of view, if we see it like a road, where we have at the start the question, at the end the answer, the person that really know the answer have been walk that road, and understand how far the person that start walk the road have been go.
So if the persons that know the answer, or know how to reach an answer, recognize that the person is make the question is not walk enough then they vote for close.
Of course this general speaking because if some one wish/love/have mood can fully answer anything.

A: This is a difficult problem. My general philosophy on such questions is to only vote to close them if they meet one of the following:

*

*The question is very unclear, it is very difficult to tell what is being asked, if anything.

*The user is clear what they want, but are asking for something very complex, with absolutely nothing shown as to what they want.

Even the last one can be waived, but the right answer is only to point them to the right direction, not to write hundreds of lines of code for them.
Bottom line is, I feel that if a question is asked well, even if it is a basic question, it should be fine. It can be very difficult sometimes to tell what a basic question is, and I have no doubt that I've recently asked a question or two that was quite basic.

A: My stance on this issue is simple. To understand it, let's look at the question you linked and break it down:

*

*Is it possible to implement a multidimensional array of checkboxes?
This is how the question starts off. A simple yes or no question. A simple Is it possible question. To me this says two things: first, that the author doesn't really understand what he's asking about (which isn't a sin). But more importantly it shows that the author put very little effort into researching the question as possible.
To demonstrate this, let's try putting the exact title into google. For me, here are the first 4 results:

*

*Sitepoint

*DevShed

*StackOverflow

*StackOverflow
So the LITERAL title of the offending post, when put into google, answers the first question. This, to me, shows a complete lack of effort on the question asker's part. Even if you don't know how to interpret the results (because you're a beginner), you should realize that it's possible.
So we're off to a great start!

*The Code Block:
<input type='checkbox' name='question[0][]' value='0'>
<input type='checkbox' name='question[0][]' value='1'>
<input type='checkbox' name='question[0][]' value='2'>

While this does give some context, it doesn't really provide much. But at this point, this isn't bad. At least there's an example of what the asker is asking about...

*If this is possible how would you pick up whether the checkboxes are checked or not in javascript?
Again, this shows little to no effort on the asker's part. All it askes is "how would you pick up". It doesn't say why or what they are trying to do with it. All it asks is how to pick up that there are checked boxes.
Now, let's try the google trick again. This time, let's search for the literal title, but adding javascript after: google search. This time, here's the very first result:
StackOverflow: fetching checkbox multidimensional array in javascript
Again, no research. No effort. Just blindly asking very poorly worded questions.
At best, this question should be closed as a duplicate. But it's also very low quality. Even more so, I see this type of question as damaging to the community. The reason is that it's blatantly abusing the system... If the author put in a little bit of effort, and actually said "I found this SO answer which is very similar, but x, y and z don't make sense to me", then that would be productive, because it would fill a gap. But as the question stands now, it's just asking people to do the searching for them (or just constantly re-answer questions over and over again).
Closing is the right action IMHO...


text:
Q: Find Replace Hotkeys In Eclipse Anyone know of a set of hotkeys that can perform a find/replace in eclipse?
Currently the flow looks like:

*

*Select line or lines

*Ctrl+F

*Type phrase

*TAB

*Type replacement

And then I have to do the unthinkable and grab my mouse, choose selected lines and then click on replace. It doesn't sound like much, but it seriously disrupts my flow when i'm doing a bunch of word replacement. I wish their was a way to choose "selected lines only" and "replace all" using keystrokes only besides having to hit TAB 12 times. Or maybe i'm using the wrong tool within eclipse for this sort of thing...
Using Ubuntu and Eclipse Luna 4.4.2

A: Using Find/Replace for refactoring seems like a smell. You should instead use the refactoring operations

*

*Rename : Alt + Shift + R

*Extract constant : Alt + Shift + K

*Extract method : Alt + Shift + M

*Extract variable: Alt + Shift + L

*Inline : Alt + Shift + I

*Change method signature : Alt + Shift +C

*Introduce indirection

*Introduce parameter object

and so on, which all do a kind of replacement by themself, but always work on the syntax tree and not on the text. However, the refactoring support depends much on the language used in the project, and while Java has really good support in Eclipse, this might not be the case for other languages.

A: I had been trying for this for a long time and ended up in multiple pages without help. I figured it out myself after playing around
For the first time, you need to do the below

*

*Ctrl + F - to open the search box on the top right corner of the IDE (as in image)

*You might have to drill down (using the small icon on the left of the search box) to see the replace text

This setup stays from now onwards.
Now you can simply use

*

*Ctrl + F, Tab, Alt+Shift+Enter combinations to do the search and replace

I use eclipse 2020-03 on windows. I am pretty sure many of the previous releases had the same functionality on linux as well.
Screenshot of the feature:

A: I found thath ctrl+K works in my ide (Neon.3 Release (4.6.3) on windows)
First use Ctrl+f to set a term for search, then use ctrl+K to move to next.
If you need to replace something, keep in the clipboard the text and use ctrl+K, ctrl+v.


text:
Q: NTP Server with Authentication on Windows System Can we configure an NTP Server with authentication on Windows OS, i.e Windows Server 2008 R2 Standard or Windows 7 operating system?
I need to sync time securely for my Cisco switch and a router so that is the reason I need to configure secure the NTP server on Windows System.

A: Windows uses W32Time service. W32Time uses Simple Network Time Protocol (SNTP), a subset of NTP, for time synchronization.
Within an AD DS forest, the Windows Time service relies on standard domain security features to enforce the authentication of time data. The security of NTP packets that are sent between a domain member computer and a local domain controller that is acting as a time server is based on shared key authentication. The Windows Time service uses the computer's Kerberos session key to create authenticated signatures on NTP packets that are sent across the network. NTP packets are not transmitted inside the Net Logon secure channel.
Instead, when a computer requests the time from a domain controller in the domain hierarchy, the Windows Time service requires that the time be authenticated. The domain controller then returns the required information in the form of a 64-bit value that has been authenticated with the session key from the Net Logon service. If the returned NTP packet is not signed with the computer's session key or is signed incorrectly, the time is rejected. All such authentication failures are logged in the Event Log. In this way, the Windows Time service provides security for NTP data in an AD DS forest.
So in order to use authentication with Windows Time, you need Active Directory domain membership.
For more detail, please see below link.
https://technet.microsoft.com/en-us/library/cc773013%28WS.10%29.aspx

A: We've been kicking around the idea of having our domain controllers use NIST as an external time source, but authenticated.  I'm not sure if we can do this though.  Anyone else ever tried?


text:
Q: php 7 + mssql + iis 7.5 не удается подключится Добрый день, уже весь иннет перегуглил, ничего не помогает, осталась вся надежда на вас:
PHP 7, IIS 7.5 Windows Server 2008r2
при попытке подключения к MSSQL возникает ошибка:
PHP Fatal error:  Uncaught Error: Call to undefined function sqlsrv_connect() in C:\inetpub\путь\connect.php:4
Stack trace:
#0 {main}
  thrown in C:\путь\connect.php on line 4

в php.ini директива extension=php_mssql.dll отсутствует, самого php.ini в этом релизе нет, его заменили на php.ini-development и php.ini-production
Сам скрипт:
$serverName = "mssql02\";
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
     echo "Соединение удалось.<br />";
}else{
     echo "Соединение не удалось, ошибка:";
     die( print_r( sqlsrv_errors(), true));
}

то что нет имени сервера, пользователя, пароля и тд это не ошибка, просто убрал специально
PDO загрузил, закинул в папку ext:

в php конфиге добавил строчку:

но оно не хочешь работать
в выводе пхпинфо вообще нет PDO драйверов

ODBC драйвер установил , вот этот
https://www.microsoft.com/ru-ru/download/details.aspx?id=36434

A: Все решилось проще, переименовал php dev. в php.ini все заработало


text:
Q: Unable to see the data coming into MySQL from R I am currently running a script that stores the data into MySQL using R.
mydb = dbConnect(MySQL(), user='root', password='xxxxxxx', dbname='test', host='localhost')

dbListTables(mydb)

dbWriteTable(mydb, name='Tables', value=parseTweets(filterStream(file.name= "", track=c("nature"), timeout=0, oauth=my_oauth)))

While the script is running. I would like to also analyze the data as it is coming in. When I open mySQL workbench, I do not see any data stored in the workbench.


text:
Q: UPDATE mysql fields using a value from a SELECT statement with a condition from another table I have two tables that are related to each other.
One is user_registration and the other is user_group.
Inside the user_registration table, I have the fields:

*

*id

*id_user

*date_begin

*date_end

And user_group:

*

*id

*id_user

*id_group

I have just tried to learn simple join statements to select some records based on their group id like:
SELECT a.id_user, a.date_begin, a.date_end, b.id_group
FROM user_registration as a
INNER JOIN user_group as b
ON a.id_user=b.id_user
WHERE b.id_group = '14'

But right now, what I am trying to do is to set the date_end to be the same as the date_begin where in the id_group of the records will be the same.

I already got it. This did the trick although I am not sure this is the most efficient way as I am still learning MySQL.
UPDATE user_registration AS a
INNER JOIN user_group AS b ON a.id_user = b.id_user
SET a.date_end = a.date_begin
WHERE b.id_group = '14'

A: As mentioned on the edit above, this accomplished what I was trying to do.
UPDATE user_registration AS a
INNER JOIN user_group AS b ON a.id_user = b.id_user
SET a.date_end = a.date_begin
WHERE b.id_group = '14'

Assuming that 14 is a group id.
I am not that certain about its efficiency though. I still have to do more readings and learn more about it.


text:
Q: sending data to a particular thread My application has a singleton class (communicating with a serial COM port) that handles data requisitions from multiple threads. While its request is being processed, the threads should wait(). How can I notify a thread that the data is ready (and send it back) without waking all the waiting threads?

A: Create one blocking queue for every threads and inject them into your Singleton. When any answer arrives, just pick the appropriate thread's queue and put the message with the offer(E o) method into it.
In your thread with the take() method you can wait to the answer for infinite time or use poll(long timeout, TimeUnit unit) for the timeboxed  waiting.
You can use an additional concurrent queue to feed the singleton without blocking it.

A: While @Lexandro has a good answer, a simpler alternative that meets your requirements (as I understand them, thread waiting/blocking is o.k.) is to just synchronize the method in the static class.