text:
Q: update element using underscore I have used templates using underscore using this tutorial. http://backbonetutorials.com/what-is-a-view/
I have a situation where I just want to add some text in a p tag to a div structure.
This is not a template just some text that needs to have some values injected into it.
Is there a way to use underscore to just updated the variables in this text. Or would I need to create the text as a template and then add the template using html(_template)

I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%>

UPDATE:
I tried doing it based off the template docs using this code.

Then in my core js file I have this code below inside a click event that launches my popup
var variables = {variable1:'[xxxx]', variable2:'[MM/YY]'};
var template = _.template( $("#card-success_tmp").html(), variables );
$('#popup #template_holder').html(template);

But the above is still not working.
I have even tried
var template = _.template( $("#card-success_tmp").html() );
$('#popup #template_holder').html(template({variable1:'[xxxx]', variable2:'[MM/YY]'}));

It renders the text but the passed in variables do not get rendered.
If I added the template as a string and not from the script tag then it will work.
The question is why is it not working from the script tag. It renders the text but not the variables passed into it.
var template = _.template( "
I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%>
" );
$('#popup #template_holder').html(template({variable1:'[xxxx]', variable2:'[MM/YY]'}));

A:
This is not a template just some text that needs to have some values injected into it.

Which makes it a template, doesn't it?
As the Underscore docs mention, you can either precompile it:
var tmpl = _.template("
I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%>
");

// often:
$("#popup").append(tmpl({variable1: "some text", variable2:"another variable text"}));

or directly call it:
$("#popup").append(_.template(
    "
I want to add some text in here <%=variable1%>, Then add another variable text in here <%=variable2%>
",
    {variable1: "some text", variable2:"another variable text"}
));

On your provided snippets: The template_holder div has an id, not a class attribute. Fixing that, both of your codes work.

A: The reason my code was not working just incase anyone else runs into this same problem.
My template is inside a .gsp file which is a grails application file. So when it renders to html it removes the underscore tags because grails uses the ERB syntax for comments. The key here is to change the ERB syntax to mustache.js style tags. In order for underscore to know this change has happened you must also add some default settings for underscore.
So in your js file just add this at the top.
_.templateSettings.interpolate = /\{\{=(.+?)\}\}/g;
_.templateSettings.evaluate = /\{\{(.+?)\}\}/g;

Then your template code can look like this.

Here is another good post on this. Boolean checks in underscore templates


text:
Q: Android - ellipse to the left textView I have three elements like that:
ELEMENT1 - ELEMENT3
The second element is "-"
By default with ellipse Android will truncate the ELEMENT3, but I want to truncate ELEMENT1. Is there a way to accomplish that?
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="left">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:singleLine="true"
                android:text="CIAO CIAO CIAO CIAO CIAO CIAO CIAO CIAO"
                android:textColor="@color/text_content" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text=" - "
                android:textColor="@color/text_content" />
            </LinearLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="CIAO CIAO CIAO CIAO CIAO CIAO"
            android:ellipsize="none"
            android:textColor="@color/important_content"/>
    </LinearLayout>

EDIT: The second element and the third elements must be aligned to the left!

A: You can use the layout weight attribute to control the "importance" of each element in a LinearLayout.  See here for more information: Linear Layout Weight
I've taken your xml layout below and edited it a bit to produce the result which I think you are looking for.  Note that TextView1 has layout weight 1, whilst TextView2 and TextView3 have layout weight 0.  What this does is force the LinearLayout to assign space to TextView2 and TextView3 first and then assign whatever space is left over to TextView1.  Therefore TextView1 is the element that will be ellipsized first.
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:layout_weight="1"
        android:text="element1element1element1" />

    <TextView
        android:id="@+id/TextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:layout_weight="0"
        android:text=" - " />

    <TextView
        android:id="@+id/TextView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="none"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:layout_weight="0"
        android:text="element3element3element3" />
</LinearLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert Observable> to a sequence of Observable in RxJava Given a list of cars (List<Car> cars), I can do:
Observable.just(cars); //returns an Observable that emits one List<Car>
Observable.from(cars); //returns an Observable that emits a squence of Car

Is there a way I can go from an Observable of a List<Car> to a sequence of Observable<Car>?
Something like a from without parameters
Obserable.just(cars).from()

A: you can use this
flatMap { t -> Observable.fromIterable(t) }

A: You can map an Observable<List<Car>> to Observable<Car> like so:
yourListObservable.flatMapIterable(x -> x)

Note that flatMapping might not preserve the order of the source observable. If the order matters to you, use concatMapIterable. Read here for more details.


text:
Q: Missing Authentication Token Error with CloudFront & API Gateway I have setup a CloudFront Distribution with an API Gateway as one of the origins and this API Gateway is configured with an AWS IAM authorizer.
When CloudFront url is invoked with Authorization headers, it returns a 403 error.
{
    "message": "Missing Authentication Token"
}

However, when the API Gateway url is invoked instead of CloudFront url with the same Authorization headers, it worked.
I've also tried invoking the endpoint without any authorizer via CloudFront url and it worked. Any idea on how to solve this issue.

A: When provisioning a CloudFront distribution, remember that CloudFront removes most headers from the request by default.
This is done to optimize the cache hit ratio while preventing your origin server from making decisions based on those headers that would not be appropriate for different requests based on other variations (or absence) of those headers, which CloudFront would then serve from cache, inappropriately.
You'll need to whitelist the Authorization header for forwarding to the origin.
Note also that when provisioning API Gateway behind a CloudFront distribution that you control, you'll probably want to deploy your API endpoint as regional and not edge-optimized.

A: Please see below, in case if anyone is facing this issue when using API Gateway as a secondary origin - behavior instead of default behavior for the Cloudfront Distribution i.e.

*

*forwarding all paths like /api/* requests to API Gateway

*serving the remaining paths with an s3 or other default resource like an Application load balancer
I was using AWS CDK to define and deploy AWS API Gateway as a secondary behavior and faced the same issue and I did everything including

*

*forwarding headers and query params

*enabling all http request methods

*Setting the API gateway as regional
My configuration for the deployment is as follows:
            originConfigs: [{
            customOriginSource: {
                domainName: clientAppBucket.bucketWebsiteDomainName,
                originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY
            },
            behaviors: [{
                isDefaultBehavior: true,
                compress: true
            }]
        },
        {
            customOriginSource: { domainName: `${api.restApiId}.execute-api.${this.region}.amazonaws.com/prod` },
            behaviors: [
                {
                    pathPattern: "/api/*",
                    allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL,
                    defaultTtl: cdk.Duration.seconds(0),
                    forwardedValues: {
                        queryString: true,
                        headers: ["Authorization"],
                    },
                },
            ],
        }]

The problem was that Cloudfront prepends the path that we are using as a custom behavior with each request i.e. when we call domain.com/api/something, It will not call ${api.restApiId}.execute-api.${this.region}.amazonaws.com/prod/something. Instead it will call ${api.restApiId}.execute-api.${this.region}.amazonaws.com/prod/api/something.
Therefore, either the stage name of the default API Gateway URL which is usually prod should be equal to the behavior path which we specify i.e /path/* or /api/* or /backend/* etc -> /prod/* or we should have a /path/ as a resource at the top level of RestApi and nest all the resources under it


text:
Q: Python speech_recognition can't not read wav file I want to use recognize_google to analyze the number in the wav file
 try:
   temp = r.recognize_google(".//splitAudio//split.wav",language="zh-TW")
   print("You have said \n" + temp )
   print("Audio Recorded Successfully \n ")
 except Exception as e:
   print("Error :  " + str(e))

but I got the following error: Error :  audio_data must be audio data
I have found this answer for a while, but I don't figure out.
Who can help me,i really appreciate it,thanks.

A: I do not have time to install stuff and find a WAV file but here's what The Ultimate Guide To Speech Recognition With Python says re "Using record() to Capture Data From a File"
import speech_recognition as sr
r = sr.Recognizer()
harvard = sr.AudioFile('harvard.wav')
with harvard as source:
    audio = r.record(source)

r.recognize_google(audio)


text:
Q: Convert all columns in a Pandas DF to separate lists and assign it a name same as column name I am trying to create separate lists for each column in a pandas DF and this code doesn't seem to work and not sure why:
columns = df.columns
for column in columns:
    column = list(df[column])

So, if I have a column df['LAT'], I need a series name LAT with df['LAT'] as values. I am not able to find a way to loop over all the columns to do this but when I select individuals columns it works, like:
LAT = list(df['LAT'])

A: It's a lot easier (and probably better) to create a dictionary where each key is the name of the column and each value is a Series:
columns = df.columns
columns_dict = {} # empty dictionary

for column_name in columns:
    # assign column to dictionary key
    columns_dict[column_name] = df[column_name].tolist()

Then the list for LAT would be accessible as columns_dict["LAT"].


text:
Q: Display database record as matrix style Is it possible to use select statement to select data from a database as matrix style?
Below is my table
ProductID Size Quantity
p001       37    2
p001       38    2
p001       39    3
p003       40    1
p004       41    1

I want to display those record like below
Product ID  37  38  39 40  41
p001        2   2   3  0   0
p003        0   0   0  1   0

The column size is dynamic. Is it possible to select data like my example at above? Please help. Thanks in advance.

A: Check below link for reference
http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables
Create Below procedure
CREATE PROCEDURE [dbo].[crosstab]
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)
AS

DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

print ('SELECT ' + @pivot + ' AS [pivot] INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('SELECT ' + @pivot + ' AS [pivot] INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')

SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'

SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' FROM ##pivot

DROP TABLE ##pivot

SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)
SET ANSI_WARNINGS ON
GO

and then use the procedure as below
EXECUTE crosstab @select = 'Select productid from Products',
                 @sumfunc = 'AVG(Quantity)',
                 @pivot = 'Size',
                 @table = 'Product'

Stackoverflow reference - SQL Rows to Columns

A: You'll need to use PIVOT()
http://msdn.microsoft.com/en-us/library/ms177410.aspx
It's not the simplest function but it will do what you are asking for.

A: you need to use PIVOT.
hope this will help you,
DECLARE @columns VARCHAR(8000)

SELECT @columns = COALESCE(@columns + ',[' + cast(Size as varchar) + ']',
'[' + cast(Size as varchar)+ ']')
FROM MyTable

DECLARE @query VARCHAR(8000)

SET @query = '
SELECT *
FROM MyTable
PIVOT
(
MAX(Quantity)
FOR [Size]
IN (' + @columns + ')
)
AS p'

EXECUTE(@query)

For more about PIVOT, take a look at here


text:
Q: iBooks management of PDF files I've always used "Open in iBooks" to view PDF files I come across on the internet. I don't do anything explicit to save these files, but it seems something does because when I open iBooks, those PDFs are all there. I have hundreds of these PDFs, but iBooks doesn't seem to support folders to organize the files. The first problem is that I can't seem to get an app like PDF Pro to see the PDFs that I viewed in iBooks.
Does iOS save these PDF files, and where are they save?
Using Collections is inadequate for my needs. Does iBooks support nested folders? How would one create the folder structure, and populate it with the PDFs?

A: Usually the .pdf files can be only viewed in Safari without opening in iBooks, and this is as such since I remember, and this is default in any browser.
To save them, you have the option to "open in iBooks" and they will copied there, and the different Collection items is the only possibility to categorise them in iBooks.
But in Safari there are another possibility: from sharing symbol, choose "Save to Files" - and there you may create any number of folders, nested or not, as you wish/need.
The good news is you can move those .pdf files from iBooks: go Library -> Collections -> Edit and select the files you intend to move to Files and again, from sharing symbol choose "Save to Files" - then delete them from iBooks.


text:
Q: Able to connect through CMD but not to Oracle SQL developer to Oracle DB So I got connected to Oracle 11g in cmd as follows

However, when I type the same username and password in Oracle SQL Developer, it does not work. And I have uname and pwd, what goes in the connection name?

This what I got, when i entered a connection name and My uname and PWD
Oracle SQL Developer

A: Just give any string in your connection name, that is used for identify different connection in sql developer.
Like,
Connection name : Connection_1
username : system
password : yourpass

If you want to create another connection to another database or another schema then you have to give another name and by login you can directly access that particular schema.
Hope it will help.

A: I think the issue might be that SQL Developer uses a different tnsnames.ora file. The file can be set under:
Tools>Preferences>Database>Advanced

Choose the correct tnsnames directory there.
Depending on your developer version, you might also want to set the Oracle Client folder.
After that in your connection dialog choose TNS instead of BASIC. And pick the tnsalias name from the list from the file.

Let me know if that works.

A: I also faced the same issue and after trying series of steps came to this conclusion.
1)Make sure to follow the blog to install the DB and check the validation steps too :
  https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/12c/r1/Windows_DB_Install_OBE/Installing_Oracle_Db12c_Windows.html
This blog makes sure that you are able to connect to SQL via CMD.
2) If you still face issue while connecting to SQL developer for the same configuration,check :  Advanced system settings-->Environment variables-->system variables--> PATH
Make sure you have entry for the DB here.
 Environment variable for DB
3) If above step is a success,check the tnsnames.ora and listener.ora files present in the location : dbhome_1\network\admin
These files should have a valid entry for the localhost and SID/service name.
Thanks,
Sandeep


text:
Q: Find avg difference in dates stored as strings I have a Mongo database and I have stored dates as strings. Per document I have a field called "creationdate" and a field called "completiondate". The dates format is "YYYY-MM-dd" (ex "2011-12-18"). Even I can execute simple aggregation like greaterThan, greaterThanEqual, I cannot find the difference in dates, which I have to find to calculate the average days difference between completion and creation date.
The above query I have to write it on spring-boot with MongoTemplate if it is possible.
I am trying something like this but it doesn't work.
Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("creationdate").gte(date1).lte(date2).andOperator(Criteria.where("completiondate").ne(""))),
                Aggregation.project("servicerequesttype").and(DateOperators.DateFromString.fromStringOf("completiondate").withFormat("%Y-%m-%d")).minus(DateOperators.DateFromString.fromStringOf("creationdate").withFormat("%Y-%m-%d")).as("diff"),
                Aggregation.group("servicerequesttype").avg("diff").as("average")
        );

date1, date2 are given strings like "2011-01-01"

A: Is this what you are looking for?
db.collection.aggregate([
  {
    $project: {
      creationdate: {
        $dateFromString: {
          dateString: "$creationdate",
          format: "%Y-%m-%d"
        }
      },
      completiondate: {
        $dateFromString: {
          dateString: "$completiondate",
          format: "%Y-%m-%d"
        }
      }
    }
  },
  {
    $project: {
      difference: {
        $subtract: [
          "$completiondate",
          "$creationdate"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      average: {
        $avg: "$difference"
      }
    }
  },
  {
    $project: {
      _id: 0,
      dayAverage: {
        $divide: [
          "$average",
          86400000
        ]
      }
    }
  }
])

I have created interactive demo here: https://mongoplayground.net/p/wGRw12m3UbB
Hope it helps :)

A: Spring-Boot
Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("creationdate").gte(date1).lte(date2).andOperator(Criteria.where("completiondate").ne(""))),
                Aggregation.project("servicerequesttype").and(DateOperators.DateFromString.fromStringOf("creationdate").withFormat("%Y-%m-%d")).as("creationdate").and(DateOperators.DateFromString.fromStringOf("completiondate").withFormat("%Y-%m-%d")).as("completiondate"),
                Aggregation.project("servicerequesttype").and("completiondate").minus("creationdate").as("difference"),
                Aggregation.group("servicerequesttype").first("servicerequesttype").as("servicerequesttype").avg("difference").as("temp"),
                Aggregation.project("servicerequesttype").and("temp").divide(86400000).as("average")
        );


text:
Q: MySQL match a value with wildcard in multiple columns I have a teachers table that looks like this:

teacherid
teacherfname
teacherlname
salary

1
Alexander
Bennett
55.30

I would like to return any record that contains a given string in the teacherfname, teacherlname and salary columns.
What I have right now (this returns exact match only):
SELECT * FROM `teachers` WHERE 'Alexander' IN (teacherfname, teacherlname, salary)

What I would like to do is something like this (this would not return anything):
SELECT * FROM `teachers` WHERE '%Alex%' IN (teacherfname, teacherlname, salary)

What do I need to make the query work? Thank you.

A: I would assume that the value %Alex% won't ever match the salary column. If you want to search for any rows where the first name or last name include "Alex" I would use simple pattern matching, and force all comparisons to use the same letter case.
For example:
SELECT *
FROM `teachers`
WHERE lower(teacherfname) like '%alex%'
   or lower(teacherlname) like '%alex%'


text:
Q: How to associate a certificate with a soap request in C#? I am new to Web Services in general, and we are using .Net Framework 4.5.2, anyway I am trying to consume a web service that requires a certificate and a password.
I added the certificate gained from the providers in the project properties --> Resources --> file --> add, I also tried to use the SetCertificate() function but It seems to be a little complicated for me so I stick with loading the certificate from the properties as mentioned, however I already set all the binding setting as wanted, but somehow I am missing something, Here is my code:
            string clientUrl = "some wsdl URL goes here";
            BasicHttpsBinding binding = new BasicHttpsBinding

            {
                MaxReceivedMessageSize = Int32.MaxValue,
                MaxBufferSize = Int32.MaxValue,
                SendTimeout = new TimeSpan(0, 15, 0),
                MessageEncoding = WSMessageEncoding.Text,
                Security = {
                        Mode =  BasicHttpsSecurityMode.Transport,
                    Transport = {
                        ClientCredentialType = HttpClientCredentialType.Certificate
                    }
                }
            };

 ClientsClient testClient = new ClientsClient(binding, new EndpointAddress(new Uri(clientUrl)));
 testClient.ClientCredentials.ClientCertificate.Certificate = LoadCertification();

        private X509Certificate2 LoadCertification()
        {
            byte[] bytes = Properties.Resources.publicCert;
            return new X509Certificate2(bytes, "password");
        }

Note 1: The certificate extenstion is '.p12', It may be a list of certifications, if that is the case!, is it possible to pass them all?.
In the code I presented I am always getting The exception:
System.ServiceModel.ProtocolException: The 'Security' header from the namespace 'Some Http url goes here' not was understood by the recipient of the message. The message was not processed. The error usually indicates that the sender of the message has enabled a communication protocol that cannot be processed by the recipient. Verify that the client binding configuration is consistent with the service binding.

I tried to test the web service with "SOAP UI" and it worked, which made me sure that I am doing something wrong with the code, So I appreaciate any possible help that explains how to associate the certifcate in the code in the right way!.
EDIT:
in the .p12 file there are 3 certifications, which I tried to add also like this:
            X509Certificate2Collection coll = LoadCertification();
            int count = 0;
            foreach (X509Certificate2 cert in coll)
            {
                testClient.ClientCredentials.ClientCertificate.Certificate = cert;
                count++;// this variable is just to check the number of certificates
            }

And I modified the loadCertification() method to look like this:
        private X509Certificate2Collection LoadCertification()
        { string certPath = "C:/Users/ISA/Desktop/Progetti/Certificato e password/name.p12";

            X509Certificate2Collection coll = new X509Certificate2Collection();
            coll.Import(certPath , "password", X509KeyStorageFlags.DefaultKeySet);
            return coll;

        }


text:
Q: Запись в бд с динамической формы имеется форма (вопрос, ответ (4шт), правильный ответ), при нажатии на кнопку добавить вопрос - добавляются такие же поля. Проблема заключается в следующем, как правильно организовать запись введённых данных с динамической формы? name имею сл вид ans1_1 (ans_1_2 - при создании 2 формы) и так далее.

до

Добавление вопросов

Вoпрос #1 <input type="text" name="test_name" id="que_desc" class="form-control">

Ответ #1 <input type="text" name="ans1_1" class="form-control">

Ответ #2 <input type="text" name="ans2_1" class="form-control">

Ответ #3 <input type="text" name="ans3_1" class="form-control">

Ответ #4 Binput type="text" name="ans4_1" class="form-control"[

Верный ответ (1-4)  <input type="text" name="true_ans_l" class="form-control">

<button type="button" class="btn btn-primary addQuestion">Добавить вопрос</button>
Watch Sass Строка 109, столбец

AddTest.php JS app.js appjs > Gon(click') callback let resultNum = 1;
foot.php
до
$('.addQuestion').on('click', function() {
questionNum++; let questionBlock = $('.question-items');
questionBlock. appena

Boпрос #S{questionNum} <input type="text" name="que_desc_${questionNum}" id="answer_text_1_1" class="form-control">

Ответ #${questionNum} <input type="text" name="ansl_${questionNum}" id="answer_text_1_1" class="form-control">

Ответ #${questionNum} <input type="text" name="ans2_${questionNum}" id="answer_text_1_1" class="form-control">

Ответ #${questionNum} <input type="text" name="ans3_${questionNum}" id="answer_text_1_1" class="form-control">

Ответ #S{questionNum} <input type="text" name="ans4_${questionNum}" id="answer_text_1_1" class="form-control">

Верный ответ (1-4)  <input type="text" name="true_ans_s{questionNum}" id="answer_text_1_1" class="form-control">


text:
Q: Can users install applications in RDC sessions to Windows Server that are limited to Windows 10? This might be a really basic question, but I couldn't find an answer here or on Google. The situation

*

*Windows Server installed in the cloud (we can choose 12,16,19)

*Remote Desktop installed (authenticating with AD)

*Remote Users connecting to the server over RDC

The question:
Can users who connect via RDC install applications that only work in Win10? That is, does Window Server present itself as Win10 to RDC clients or does it present itself as Windows Server? We believe there may be some desktop apps that will work (and are licensed) for Win10 but are not allowed on Windows Server.
We aren't going to install apps on Windows Server for all these users, but if a user wants to install an app on their local desktop on this RDC instance, will the application think it's installing onto Win10 or to Windows Server?
If there is a better approach to this problem, acceptable answers could include better approaches.

A: Windows allows developpers to check whether it's a Server Edition, or a Client Edition.
The OS Version and the fact that it's a Server or Client release are two different things:

*

*Windows provides a way to check whether you are running (for example) Windows 10 or higher:

IsWindows10OrGreater

The version helper functions do not differentiate between client and
  server releases[...]

*The developper can check if it's a Server release with IsWindowsServer

Indicates if the current OS is a Windows Server release. Applications
  that need to distinguish between server and client versions of Windows
  should call this function.

So, it depends on the application and license agreement (don't forget that because the application can start doesn't mean that you are allowed to use it on a Server OS if the license agreement says the opposite)
You can try using App-V. Sometimes, applications that are incompatible with multi-user or server environments end up working.


text:
Q: Need the highest dir of the URL new URL("http://example.com/public/files/random.php")
I want to fetch the highest directory of the URL when the URL ends with a file extension. For ex: that URL ends with .php so I want to fetch http://example.com/public/files/ from that. Is there a specific way to do this?

A: Yes, there is a way:
URL url = new URL("http://example.com/public/files/random.php");
String urlString = url.toString();
String fetched = urlString.substring(0, urlString.lastIndexOf('/'));

this finds the last slash and cuts the String there. If the URL doesn't end with an file extension, like "http://example.com/public/", then the last occurence of '/' is exactly the last character in the String, so nothing changes.

A: Assuming you're looking for the address String minus the PHP page, you could use URI#resolve instead
URI uri = URI.create("http://example.com/public/files/random.php");
String noPage = uri.resolve("").toString();


text:
Q: monkey patch node module I'm trying to monkey patch this node module in electron application. I want to change the capture method input arguments.
My code so far looks like this:
if (process.platform == "darwin") {
      let refSCapt = screenshot.capture;
      console.log("Outside");
      screenshot.capture = function(output: string, callback: any) {
        console.log("Inside");
        // Override output path of a temp .png file
        let tempOutput = output.split("/")[-1];
        refSCapt(this.screenshotsPath + tempOutput, callback);
      };
    }

The problem is that the patch is not reflecting and the original method is called as if nothing would've change. The Outside get's logged but the Inside is never called.
So how can I monkey patch this module method?

A:
So how can I monkey patch this module method?

What you have would work fine ... but only if your code runs before it is used elsewhere. For reliable patching I recommend https://github.com/ds300/patch-package which patches modules on install.


text:
Q: How to implement Binding for ImageButtons so that the image is only displayed once the image is loaded? I have two ImageButtons which should switch their images when clicked.
<ImageButton
      Grid.Column="15"
      Grid.Row="20"
      Clicked="Clicked"
      Source="{Binding Game[0], Converter={StaticResource StringToSourceConverter}}"
       >
</ImageButton>

<ImageButton
      Grid.Column="15"
      Grid.Row="20"
      Clicked="Clicked"
      Source="{Binding Game[1], Converter={StaticResource StringToSourceConverter}}"
       >
</ImageButton>

The Clicked method swaps the Sources in my Game array and activates INotifyPropertyChanged. It all works out fine. I would just like to know how to implement, that the image should only bind if the image is loaded. Because as you see in the following Images there is a short period where no image is displayed. It's short but it is annoying. The ImageSource is an EmbeddedResource.

A: I'm wondering if you are using Embedded images or just Local images ? Local images is recommended .
What's more , there is another way to implement this function(swap the image by clicking the button).

*

*Add a bool property in viewmodel.
public class ViewModel : BaseViewModel
 {
     private bool _isOne;
     public bool isOne {
         get
         {
             return _isOne;
         }
         set
         {
             _isOne = value;
             NotifyPropertyChanged();
         }
     }
 }

*Add two Converter for the two ImageButton .
public class FirstConverter : IValueConverter
 {

     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {

         bool isOne = (bool)value;

         return isOne ? "a.jpg" : "b.jpg";

     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
         return true;
     }
 }
 public class SecondConverter : IValueConverter
 {

     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {

         bool isOne = (bool)value;

         return isOne ? "b.jpg" : "a.jpg";

     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
         return true;
     }
 }

*Create binding on the ImageButton .
<ContentPage.Resources>
     <ResourceDictionary>
         <local:FirstConverter x:Key="first" />
         <local:SecondConverter x:Key="second" />
     </ResourceDictionary>
 </ContentPage.Resources>

 <StackLayout>
     <ImageButton Clicked="ImageButton_Clicked"  Source="{Binding isOne, Converter={StaticResource first}}"/>
     <ImageButton Clicked="ImageButton_Clicked"  Source="{Binding isOne, Converter={StaticResource second}}"/>
 </StackLayout>

*Change the property in Button Click event.
private void ImageButton_Clicked(object sender, EventArgs e)
     {
         model.isOne = !model.isOne;
     }


text:
Q: SIP/Asterisk: No domain name in FROM uri's header I am using FreePBX. While trying to login I am getting
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c:
<--- SIP read from UDP:83.245.241.98:34479 --->
SUBSCRIBE sip:5666@0.0.0.0;transport=UDP SIP/2.0
Via: SIP/2.0/UDP 83.245.241.98:34479;branch=z9hG4bK-524287-1---e49547006939fc6c
Max-Forwards: 70
Contact: <sip:5666@83.245.241.98:34479>
To: <sip:5666@0.0.0.0>
From: <sip:5666@>;tag=b9144d7a
Call-ID: wDigYoT9KjWu52sD4lFLTQ..
CSeq: 1 SUBSCRIBE
Expires: 3600
Allow: INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE
Supported: replaces, norefersub, extended-refer, timer, outbound, path, X-cisco-serviceuri
User-Agent: Z 3.9.32144 r32121
Event: message-summary
Allow-Events: presence, kpml
Content-Length: 0

<------------->
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c: --- (15 headers 0 lines) ---
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c: Sending to 83.245.241.98:34479 (NAT)
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c: Creating new subscription
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c: Sending to 83.245.241.98:34479 (NAT)
[2017-09-12 12:09:03] VERBOSE[5545] sip/route.c: sip_route_dump: route/path hop: <sip:5666@83.245.241.98:34479>
[2017-09-12 12:09:03] ERROR[5545] chan_sip.c: Empty domain name in FROM header
[2017-09-12 12:09:03] NOTICE[5545] chan_sip.c: Failed to authenticate device <sip:5666@>;tag=b9144d7a for SUBSCRIBE
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c:
<--- Transmitting (NAT) to 83.245.241.98:34479 --->
SIP/2.0 403 Forbidden
Via: SIP/2.0/UDP 83.245.241.98:34479;branch=z9hG4bK-524287-1---e49547006939fc6c;received=83.245.241.98;rport=34479
From: <sip:5666@>;tag=b9144d7a
To: <sip:5666@0.0.0.0>;tag=as03163a1a
Call-ID: wDigYoT9KjWu52sD4lFLTQ..
CSeq: 1 SUBSCRIBE
Server: FPBX-13.0.192.16(14.6.0)
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
Content-Length: 0

<------------>
[2017-09-12 12:09:03] VERBOSE[5545] chan_sip.c: Really destroying SIP dialog 'wDigYoT9KjWu52sD4lFLTQ..' Method: SUBSCRIBE

On registering device it shows
09-12 19:27:20.483 I/System.out: 19:27:20.484   pjsua_core.c  .TX 645 bytes Request msg REGISTER/cseq=54664 (tdta0x78c4c36c) to UDP 35.162.177.84:5060:
09-12 19:27:20.483 I/System.out: REGISTER sip:mydomain.com SIP/2.0
09-12 19:27:20.483 I/System.out: Via: SIP/2.0/UDP 192.168.43.224:6000;rport;branch=z9hG4bKPj8a5802d4-1b9a-49f0-b3c1-b38a23e51299
09-12 19:27:20.483 I/System.out: Max-Forwards: 70
09-12 19:27:20.483 I/System.out: From: <sip:5666@mydomain.com>;tag=6390922e-056e-4421-a55f-13e76117593e
09-12 19:27:20.483 I/System.out: To: <sip:5666@mydomain.com>
09-12 19:27:20.483 I/System.out: Call-ID: 63b10417-58a5-44b5-83a3-1fc1febab86b
09-12 19:27:20.483 I/System.out: CSeq: 54664 REGISTER
09-12 19:27:20.483 I/System.out: User-Agent: Pjsua2 Android 2.6-svn
09-12 19:27:20.483 I/System.out: Contact: <sip:5666@192.168.43.224:6000;ob>
09-12 19:27:20.483 I/System.out: Expires: 300
09-12 19:27:20.483 I/System.out: Allow: PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS
09-12 19:27:20.483 I/System.out: Content-Length:  0
09-12 19:27:20.483 I/System.out: --end msg--
09-12 19:27:20.973 I/System.out: 19:27:20.981    pjsua_acc.c  ...SIP registration failed, status=408 (Request Timeout)
09-12 19:27:20.973 I/System.out: 19:27:20.982    pjsua_acc.c  ...Scheduling re-registration retry for acc 0 in 297 seconds..

From device logs I see the domain name, but in error message it's empty. Why can it be so?
Registering device is Android, but when I try desktop Zoiper, the error is the same.
I can show any settings from FreePBX, but I don't know which ones to show. If you feel that you need some of them to help me, feel free to request, and I'll post them as update
UPD
Here are new log portion
<--- SIP read from UDP:83.245.241.98:34479 --->
REGISTER sip:0.0.0.0;transport=UDP SIP/2.0
Via: SIP/2.0/UDP 83.245.241.98:34479;branch=z9hG4bK-524287-1---42d9af389a67cbe0
Max-Forwards: 70
Contact: <sip:5666@83.245.241.98:34479;transport=UDP;rinstance=5ffbd839a509bdb2>;expires=0
To: <sip:5666@0.0.0.0>
From: <sip:5666@>;tag=99170228
Call-ID: mH4uHh2CI96Kfv9h6c1uHA..
CSeq: 3 REGISTER
Allow: INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE
Supported: replaces, norefersub, extended-refer, timer, outbound, path, X-cisco-serviceuri
User-Agent: Z 3.9.32144 r32121
Allow-Events: presence, kpml
Content-Length: 0

<------------->
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: --- (13 headers 0 lines) ---
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: Sending to 83.245.241.98:34479 (NAT)
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c:
<--- Transmitting (NAT) to 83.245.241.98:34479 --->
SIP/2.0 200 OK
Via: SIP/2.0/UDP 83.245.241.98:34479;branch=z9hG4bK-524287-1---42d9af389a67cbe0;received=83.245.241.98;rport=34479
From: <sip:5666@>;tag=99170228
To: <sip:5666@0.0.0.0>;tag=as718e8353
Call-ID: mH4uHh2CI96Kfv9h6c1uHA..
CSeq: 3 REGISTER
Server: FPBX-13.0.192.16(14.6.0)
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
Expires: 0
Date: Tue, 12 Sep 2017 17:30:02 GMT
Content-Length: 0

<------------>
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: Scheduling destruction of SIP dialog 'mH4uHh2CI96Kfv9h6c1uHA..' in 32000 ms (Method: REGISTER)
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c:
<--- SIP read from UDP:83.245.241.98:34479 --->
SUBSCRIBE sip:5666@0.0.0.0;transport=UDP SIP/2.0
Via: SIP/2.0/UDP 83.245.241.98:34479;branch=z9hG4bK-524287-1---5d5c7b4cc8b27f1c
Max-Forwards: 70
Contact: <sip:5666@83.245.241.98:34479;transport=UDP>
To: <sip:5666@0.0.0.0>
From: <sip:5666@>;tag=134c433d
Call-ID: 9Fo9pY2cNfL9I3ZcT_rE1w..
CSeq: 1 SUBSCRIBE
Expires: 3600
Accept: application/simple-message-summary
Allow: INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE
Supported: replaces, norefersub, extended-refer, timer, outbound, path, X-cisco-serviceuri
User-Agent: Z 3.9.32144 r32121
Event: message-summary
Allow-Events: presence, kpml
Content-Length: 0

<------------->
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: --- (16 headers 0 lines) ---
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: Sending to 83.245.241.98:34479 (NAT)
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: Creating new subscription
[2017-09-12 13:30:02] VERBOSE[5545] chan_sip.c: Sending to 83.245.241.98:34479 (NAT)
[2017-09-12 13:30:02] VERBOSE[5545] sip/route.c: sip_route_dump: route/path hop: <sip:5666@83.245.241.98:34479;transport=UDP>
[2017-09-12 13:30:02] ERROR[5545] chan_sip.c: Empty domain name in FROM header
[2017-09-12 13:30:02] NOTICE[5545] chan_sip.c: Failed to authenticate device <sip:5666@>;tag=134c433d for SUBSCRIBE

UPD2
I changed client's wifi to another and it worked. Then I changed it back and it did not work again. The local subnet of wifi in which it worked has the same subnet address and mask (although it's another subnet), can it be the reason?

A: Your REGISTER message looks valid - and contains correct domain name set in proper places. But it has no Authenticatioon header.
According to the logs registration failed due to timeout - but I see no response 408 - so probably timeout is on the client. Nobody responded to the REGISTER.
So you need to find a reason for failure to handle REGISTER on the server, or to transfer request to the Server, or to deliver response to the client.
Even if you post SUBSCRIBE message first - I suppose the SUBSCRIBE should follow the REGISTER. But since registration was not finished properly - some variables in the client were not initialized. And client created invalid SUBSCRIBE request. Domain in request URI and in the to is 0.0.0.0 in the From is missing.
So this message probaby will never be delivered properly. And even if it is delivered - will fail the parsing. So it is rejected. This message should never be sent - it is bug of the client. It should check the registration state before trying to subscribe to the message-summary event.

A: Have you set your network on sip.conf?
Example:
[general]
externip = 83.245.241.98
localnet=192.168.43.0/255.255.255.0


text:
Q: Phone gap Web-view camera not working? I installed Phonegap..from this and created android app...
So in that.. at index.html I have added a camera from web-view with this...
here I replaced index.html content with Full Example's... index.html.... from the above link..
and I have added permission for camera in manifest and config.xml..
But its not working... I have done this in android studio...
cant any one suggest me...
Update:
after Installing Phonegap
I have done this..
C:user.... : phonegap create my-app
C:user.... : cd my-app
C:user.... : phonegap run android

I opened that android project under my-app\platforms.. directly to Android Studio I got this...

so I skipped this step in camere...

I dont know where Should I run this.. command... And I have given all permissions according to this tutorial except... above command...
can any one suggest me what should and where should I run this command I am using windows 10..


text:
Q: Dragging an view in limited boundaries not beyond that After googling a lot and still not finding any solution, I am asking a question.
My question is:- I want to drag my view in a particular area, beyond that, I do not want my view to drag but it should be draggable in the specified view.
I am able to achieve to stop dragging if is drags beyond but again when I touches it to drag in the permitted area it does not drag.
My code:-
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

        UITouch *touch=[touches anyObject];
        CGPoint pt = [[touches anyObject] locationInView:touch.view];
        startLocation = pt;
    }

    - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
        // Move relative to the original touch point
        UITouch *touch=[touches anyObject];
        CGPoint pt = [[touches anyObject] locationInView:touch.view];
        CGPoint pt2 = [[touches anyObject] locationInView:self.view];

        if ([touch.view isKindOfClass:[MyView class]]) {

            CGRect frame = [touch.view frame];
            CGRect prevFrame=[touch.view frame];
            frame.origin.x += pt.x - startLocation.x;
            frame.origin.y += pt.y - startLocation.y;
            CGRect boundsA = [touch.view convertRect:touch.view.bounds toView:nil];
            CGRect boundsB = [self.canvasVw convertRect:self.canvasVw.bounds toView:nil];

                Boolean viewsOverlap = CGRectContainsRect(boundsB,boundsA );
                if (viewsOverlap==YES) {
                    NSLog(@"intersects");
                    [touch.view setFrame:frame];

                }
                else{
                    NSLog(@"not intersects");

    }
        }
      }

The problem in the code is suppose I drag the view , and it goes outside the area then it does not drag again.
See the image:-

I need to drag the red view in only white area not the black area.
Please suggest me how to do this.
Thanks.

A: Well, boundaries, basically. As much as boring as it seems, make sure:

*

*the self.frame.position.x of the red is not < 0 (zero is the position of its parent)

*the self.frame.position.x + self.frame.size.width is not > than self.superview.size.width

The same logic for the Y.

Edit 1:
double possibleNewX = pt.x - startLocation.x;

if (((self.frame.position.x + possibleNewX) > 0) && ((self.frame.size.width + self.frame.position.x + possibleNewX) < self.superview.frame.size.width))
{
   frame.origin.x += possibleNewX;
}

double possibleNewY = pt.y - startLocation.y;

if (((self.frame.position.y + possibleNewY) > 0) && ((self.frame.size.height + self.frame.position.y + possibleNewY) < self.superview.frame.size.width))
{
   frame.origin.y += possibleNewY;
}


text:
Q: How to use itoa in C Can anybody tell me how to use itoa function in C?
The prototype is:
char*itoa(int_Val,char*_DstBuf,int_Radix)

I think that int_Val is the value that I want to convert
char*_DstBuf, is the string where I want to store the result
But what is int_Radix?

A: It is the base to convert to
10 - Decimal
16 - Hexidecimal
8 - Octal
A per the manual page http://www.cplusplus.com/reference/cstdlib/itoa/


text:
Q: Android studio 3.1.2 cursor disappering I recently updated my android studio from 2.3 to 3.1.2 after updating while syncing gradle cursor disappears and tick black horizontal line comes when i click on editor.
I searched on SO. As SO answers i checked my date and time of PC. and re-installed my OS and installed Android studio again but still i'm facing this issue.
Do any one know why this issue is coming?


text:
Q: How to get all XP service packs, updates, etc. together to avoid future downloads? I am going through an agonizing re-install, on day three now of Windows Updates, VS Service Packs, etc.  It's been tough having to download all this again on a 384kbps ADSL line.
Besides the installs that I explicitly download, how can I back up installs such as all the Windows Updates; SQL Server 2008 Express that installs through Web Platform Installer, and any other goodies that MS deem to be better left uncontrolled by me?
ADDENDUM:  Many people are giving answers that involved downloading.  My whole point is to avoid downloading again what Windows already has downloaded.

A: Perhaps
nlite would be useful?

nLite is a tool for pre-installation
  Windows configuration and component
  removal at your choice. Optional
  bootable image ready for burning on
  media or testing in virtual machines.
  With nLite you will be able to have
  Windows installation which on install
  does not include, or even contain on
  media, the unwanted components.

Features
* Service Pack Integration
* Component Removal
* Unattended Setup
* Driver Integration
* Hotfixes Integration
* Tweaks
* Services Configuration
* Patches
* Bootable ISO creation

A: If you are talking about a single machine/hardware config, you could make an image of the system using any of the many system imaging programs, then just re-deploy the image whenever you want to do a full re-install.
If you're mainly talking about Windows, you could slipstream the various updates into an updated installer disc.

A: This is the best officially supported solution
Step 1 - Download and install SP3:
Take a look at the Service Pack Center to find the download link for the latest Service pack.
From everything I've read, Service Pack 3 will be the last service pack to be released for XP.
Step 2 - Fetch the latest security updates (released after SP3)
Take a look at the Microsoft Security Bulletin Search tool to determine which updates you'll need to download.
Here are the settings I recommend to get all of the relevant updates after post-SP3

Then it's just a matter of downloading the relevant install executables for offline use.
Note: While I would personally choose to use the WSUSOffline tool that @Journeyman suggested, there are risks of using an unofficial tool to support Microsoft products. Downloads that come from third parties may contain malicious code so Microsoft may push to get a third party tool shutdown overnight if it deems the tool unsafe for its users. WSUSOffline gets around that by downloading the actual updates directly from Microsoft but as with all unofficial tools, convenience comes with risk.

A: Make all the downloads, install and updates that you want. Get a backup and burn it. This will be the easiest method.
You can also use nLite.

Have you ever wanted to remove Windows components like Media Player,
  Internet Explorer, Outlook Express, MSN Explorer, Messenger... How
  about not even to install them with Windows ?
nLite is a tool for pre-installation Windows configuration and
  component removal at your choice. Optional bootable image ready for
  burning on media or testing in virtual machines. With nLite you will
  be able to have Windows installation which on install does not
  include, or even contain on media, the unwanted components.

A: http://www.wsusoffline.net/ This is what i use as part of my toolkit - it downloads everything and has a front end that automatically patches up a box. The neat thing about it is you can pick as many of as few products as you need, and it'll apply only the ones you need.

Windows XP is currently under legacy products, and since WSUS offline updates directly downloads the updates off MS, this may stop working when MS stops hosting patches, some time in the future.
EDIT: As of 2014, support for XP has been dropped on new updates of WSUS offline updates - You can find the last version that supports this, 9.2.1 in their archives.

A: I think you have to get the packages manually and save them somewhere.  I think the best you can do is install the latest xp service pack and visual studio service packs and then use windows updates to grab the updates released since then.  I think you'll need xp service pack 2 and xp service pack 3.  You could grab each hotfix/update separately as well if you wanted, but that is probably a lot of work.  I'd have thought setting windows update to autiomatic and just letting it go through and update woulod be the easiest
some instructions here

A: You need to download the offline install packages.

A: As suggested above use nLite in order to prepare an updated XP iso or dvd.
Apart from slipstreaming sp3 you can also integrate some hotfixes or even microsoft programs,
such as IE or WMP.
However a lot of hotfixes won't be integrated, so you will have to run a batch to finish the job.
A good basis for building your "perfect" xp installer is pre-SP4 project:
http://dimadr.ru/critical-pre-sp4-eng
and for .NET
http://forum.oszone.net/thread-46682.html

A: IMHO,  it is possible to reuse updates already downloaded, but, although their files are expanded on c:\windows\softwaredistribution\download, one must find a way to recover installation scripts and install order to know what to do with them.

A: Have you already wiped the drive you are installing to? If so, then no, there is no way to avoid having to re-download the updates. If you have not wiped it (check the drive to see if there the previous Windows directory has been renamed as a backup), then you can probably avoid re-downloading a lot of it.
Open C:\Windows\SoftwareDistribution\Download (replacing C:\Windows with the path to your old Windows directory).
You will find a bunch of files with a long alphanumeric name and no extension. These are the updates (and miscellaneous files). What you need to do is to figure out which ones are executable and run them. You could try using a hex-editor or something to open and view them, but it is much easier to just rename them.
First make sure that extensions are shown (Tools->Folder Options->View->de-select Hide extensions for known file types). Now for each file in the Download directory, rename it, adding .EXE to the end and then run it. (Consider creating a temporary folder to move them into after running them to make it easier to keep track of your progress.)
You will likely find that some of them crash and give an error message. Don't worry about this since not all of the files in there are actually executable files, some are text files containing licences agreements, etc.
Once you have run all of the updates, reboot the system and run Windows Update again. You should find that fewer (if any?) updates are listed (it depends on how many were still in the Download directory).


text:
Q: Working with MergeAdapter and BaseAdapter I already have used MergeAdapter and works really well with ArrayAdapter, but when I used with LazyAdapter extends BaseAdapter, it doesn't show any error on Logcat and the emulator don't show nothing of the LazyAdapter content.
Question:
So is possible to work with BaseAdapter and MergeAdapter?
If not, its my code, what I should do?
ListFragment:
public class HomeFragment extends ListFragment{

    private static final String TAG = "URL";
    private MergeAdapter adapter = null;
    private ImageView [] imageView;
    private ViewFlipper flippy;
    private ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
    private NoticiaAdapter nAdapter = null;
    // XML node keys
        static final String KEY_SONG = "news"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_TEXT = "text";
        static final String KEY_HOUR = "hour";
        static final String KEY_THUMB_URL = "thumb_url";

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);

        setRetainInstance(true);

        String[] Url = create();
        new MyAsyncTask(Url).execute();
        nAdapter = new NoticiaAdapter(getActivity(), newsList);
        adapter = new MergeAdapter();
        adapter.addView(buildlabel1());
        adapter.addAdapter(nAdapter);

        setListAdapter(adapter);
        //mergeadapter
    }

LazyAdapter:
public class NoticiaAdapter extends BaseAdapter {

    private FragmentActivity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader;
    ViewHolder holder = null;

    public final class ViewHolder {
        public TextView title;
        public TextView text;
        public TextView hour;
        public ImageView thumb_image;
        // public Button save_btn;

    }

     public NoticiaAdapter(FragmentActivity fragmentActivity, ArrayList<HashMap<String, String>> d) {
            super();
            this.activity = fragmentActivity;
            this.data = d;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader=new ImageLoader(activity.getApplicationContext());
        }

     public int getCount() {
       return data.size();
     }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return data.get(position);
        }

     public long getItemId(int position) {
      return position;
     }

     @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }

     public View getView(int position, View convertView, ViewGroup parent) {
         View vi=convertView;
            if(convertView==null)

                vi = inflater.inflate(R.layout.news_list_row, null);
            holder = new ViewHolder();
            holder.title = (TextView)vi.findViewById(R.id.txtTitle); // title
            holder.text = (TextView)vi.findViewById(R.id.txtDescription); // artist name
            holder.hour = (TextView)vi.findViewById(R.id.txtHour); // duration
            holder.thumb_image=(ImageView)vi.findViewById(R.id.img_news); // thumb image

            HashMap<String, String> news = new HashMap<String, String>();
            news = data.get(position);

            holder.title.setText(news.get(HomeFragment.KEY_TITLE));
            holder.text.setText(news.get(HomeFragment.KEY_TEXT));
            holder.hour.setText(news.get(HomeFragment.KEY_HOUR));
            imageLoader.DisplayImage(news.get(HomeFragment.KEY_THUMB_URL), holder.thumb_image);

      return vi;
     }

     public void add(HashMap<String, String> map) {
            // TODO Auto-generated method stub
            data.add(map);
            notifyDataSetChanged();

        }

    }

A: Just to put an answer in this question, I have made a mistake, the xml file in my server was misspelled, So Yes MergeAdapter works with BaseAdapter.
So this could be a sample code for who wants to use.
Thanks Commonsware for your help.


text:
Q: Get current taxonomy post count Is there a way to get the current taxonomy (category or tag) post count? The code i'm having is only for category
<?php
    $cat = get_query_var( 'cat' );
    $categories = get_categories( 'include='.$cat );
    if ( $categories ) {
        foreach( $categories as $category ) {
            echo '' . $category->count;
        }
    }
?>

A: I guess you can do something like this:
// Set the name of your Taxonomy or get it as you're currently doing
// It can be category, tag or custom taxonomy name
$taxonomy = "your_taxonomy";

$total_count = 0;

// Get all the terms in your Taxonomy and add the count for each term
foreach ( get_terms( $taxonomy ) as $term ) {
    $total_count += (int) $term->count;
}

echo $total_count;

This will give you the count of all the posts that have assigned ANY term in the Taxonomy your_taxonomy, which I understand is what you want...


text:
Q: Enable TLS 1.2 for SQL Server 2016 database mail I have been puzzled by this issue for almost 1 week. Hopefully someone in our community has experienced the same issue and already found a solution.
So here is my problem:
As per our company policy, we want database mail to be able to send emails over port 25 with TLS 1.2 enabled and with TLS 1.0 & TLS 1.1 disabled.
Our mail server is Exchange Server 2010, our SQL Server 2016 (Developer and Enterprise editions) boxes have OS of Windows Server 2016 Standard editions.
Our SQL Server version is:
select @@version
----------------------------------------
Microsoft SQL Server 2016 (SP1-CU7-GDR) (KB4057119) - 13.0.4466.4 (X64)
    Dec 22 2017 11:25:00
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows Server 2016 Datacenter 10.0 <X64> (Build 14393: ) (Hypervisor)

We have the DB mail configuration as shown here.

The issue is whenever we turn on SSL
use msdb
exec dbo.sysmail_update_account_sp @account_id=2, @enable_ssl = 1;

We CANNOT send db mail (no matter whether our SMTP authentication is Windows Authentication, Basic authentication or Anonymous Authentication). The error message in db mail log is as follows:

Message
The mail could not be sent to the recipients because of the
  mail server failure. (Sending Mail using Account 2
  (2018-07-30T10:52:41). Exception Message: Cannot send mails to mail
  server. (Failure sending mail.). )

But if we turn off this SSL, there is no problem for db mail sent out.
So how can we enable SSL and uses TLS 1.2 for db mail?
I have enabled TLS 1.2 by adding registry as shown below

The details is from this link (see the FAQ section)

A: Since it seems nobody can answer this question, I opened a support case with Microsoft, and still it took almost 1 week for MS support to come back with an answer as he went through various internal resources to get the definite answer.
The summary is:

SQL Server Database mail uses System.Net.Mail to do the work, the
  System.Net.Mail is able to send mail using TLS 1.2 but only when the
  build runtime version is 4.6 or above. SQL Server 2016 db mail is built for
  .Net 3.5, hence SQL Server 2016 db mail does not support TLS 1.2 as of
  now.

A: It's odd because the linked article clearly states:

Support for TLS v1.2 included in the .NET Framework version 3.5 SP1 on Windows 8.1 and Windows Server 2012 R2

which contradicts the response you get from MS support. Edit: I found in this StackOverflow question that although .NET 3.5 didn't include support for TLS 1.2 at first it was added later by MS:
Support for TLS System Default Versions included in the .NET Framework 3.5.1 on Windows 7 SP1 and Server 2008 R2 SP1
Reading the FAQ section I think that the problem is that you missed one registry key when enabling TLS 1.2. The FAQ section says:

The correct registry settings are as follows:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
  "DisabledByDefault"=dword:00000000
  "Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
  "DisabledByDefault"=dword:00000000
  "Enabled"=dword:00000001

These settings are required for both server and client computers.

But in the screen shot that you provided I only see "Enabled"=dword:00000001, the "DisabledByDefault"=dword:00000000 key is missing.
Also it says:

Is TLS 1.1 supported on SQL Server 2016?
Yes. SQL Server 2016 and SQL Server 2017 on Windows versions ship with
  TLS 1.0 to TLS 1.2 support. You have to disable TLS 1.0 and 1.1 if you
  want to use only TLS 1.2 for client-server communication.

which can be interpreted as that you need to disable TLS 1.0 and 1.1 in order to use 1.2, but I'm not sure about this one.

A: TLS1.2 is the only version of TLS considered secure now (March 2019).  It took considerable time and effort to discover that there are 2 essential, additional settings which are required to get this working which are not well known nor well documented, by Microsoft or on the web generally.  The following could save you a great deal of time and effort.
These are the 2 new Registry settings that fixed the problem for us:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

This is a reference to the thread where we eventually found this information, buried halfway down the thread: TLS 1.2 in .NET Framework 4.0

Below is the content for a simple executable registry file that I put together that will make the 2 new settings and the settings already shown on the thread above (i.e. this makes all of the necessary Registry settings*):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

Note 1: SQL needs to be restarted for these settings to take affect but it is better to restart Windows since the new settings will affect .NET 4.x generally.
Note 2: In SQL, the SSL-checkbox must be ticked in the mail profile to use TLS1.2.
*Note 3: FYI We ran the free tool, Crypto V2, with the "Best Practices" option enabled before starting on getting this working.  We verified our changes afterwards using the new Crypto version 3.
Hopefully this will save considerable time, effort and frustration for others ;)

A: *

*We have a similar issue few weeks ago with SQLServer database mail. We use office365 SMTP server in Azure.

Configuration was "Windows 2012R2 + SQLServer 2012" and "Windows 2012R2 + SQLServer 2014".
Error on database mail was "The message could not be sent to the recipients due to an email server error".
Error was not systematic. We suppose that when we reach an azure end point allowing TLS1.0 the email is well sent but when we reach an end point using TLS1.2 our email is rejected.

*

*If we analyze email header sent by database mail we can see that SMTP server use TLS1.2 but database mail sent email with TLS1.0 protocol.

Microsoft SMTP Server (version=TLS1_2,...)
Received: from ... with Microsoft SMTP Server (version=TLS1_0, ...

*

*We fix the issue with adding following registry key on each server (Powershell Script)

#TLS1.2 configure strong encryption
#The strong cryptography uses more secure network protocols (TLS 1.2, TLS 1.1, and TLS 1.0) and blocks protocols that are not secure.
#64 bits applications
New-ItemProperty -Path "HKLM:\Software\Microsoft\.NETFramework\v2.0.50727" -Name "SchUseStrongCrypto" -Value "1"  -PropertyType "dword";
New-ItemProperty -Path "HKLM:\Software\Microsoft\.NETFramework\v4.0.30319" -Name "SchUseStrongCrypto" -Value "1"  -PropertyType "dword";

#32 bits applications
New-ItemProperty -Path "HKLM:\Software\WOW6432Node\Microsoft\.NETFramework\v2.0.50727" -Name "SchUseStrongCrypto" -Value "1"  -PropertyType "dword";
New-ItemProperty -Path "HKLM:\Software\WOW6432Node\Microsoft\.NETFramework\v4.0.30319" -Name "SchUseStrongCrypto" -Value "1"  -PropertyType "dword";

#SystemDefaultTlsVersions
#A value of 1 causes your app to allow the operating system to choose the protocol
New-ItemProperty -Path "HKLM:\Software\Microsoft\.NETFramework\v2.0.50727" -Name "SystemDefaultTlsVersions" -Value "1"  -PropertyType "dword";
New-ItemProperty -Path "HKLM:\Software\Microsoft\.NETFramework\v4.0.30319" -Name "SystemDefaultTlsVersions" -Value "1"  -PropertyType "dword";

#32 bits applications
New-ItemProperty -Path "HKLM:\Software\WOW6432Node\Microsoft\.NETFramework\v2.0.50727" -Name "SystemDefaultTlsVersions" -Value "1"  -PropertyType "dword";
New-ItemProperty -Path "HKLM:\Software\WOW6432Node\Microsoft\.NETFramework\v4.0.30319" -Name "SystemDefaultTlsVersions" -Value "1"  -PropertyType "dword";


text:
Q: Call GWT Method from Handwritten JavaScript I'd like to execute some js method from browser console to call gwt code. For ex.

showMyWindow();

js:
function showMyWindow() {
// call gwt code from here MyWindow::showMe()
}

gwt:
class MyWindow extends Window {
  public static showMe {
    MyWindow wnd = new MyWindow();
    wnd.show();
  }
}

How to do that? Thanks.

A: As outlined in the JSNI documentation on calling GWT Java from handwritten Javascript, you need to expose the showMyWindow function so your other javascript can be called. Sometime before you want to actually call showMyWindow in JS, run a function like this.
public static native void exportShowMe() /*-{
  $wnd.showMyWindow = $entry(@my.package.client.MyWindow::showMe());
}-*/;

After you have called that, you'll be able to call showMyWindow() in regular JS and have your static method called.
As an aside, your showMe method probably needs a return type, in this case, most likely void.


text:
Q: c# How do I use this function on a file Sorry if the title may be misleading, but I have created a decoder in c#, but how do I use the function on (save.dat (the game save)) it needs to be loaded in a byte array.
Code for the decoder: https://del.dog/sorononami
Sorry I'm a starter in c#.
I have tried but I got this error:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'ConsoleApp8.Program' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at ConsoleApp8.Program.PwDecLol(Byte[] lel) in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 180
   at ConsoleApp8.Program..cctor() in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 183
   --- End of inner exception stack trace ---
   at ConsoleApp8.Program.Main() in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 15

Looks like I am not doing it correctly

A: I don't think it's anything wrong with your decoder. The error message suggests you have a parameter in the constructor to your program, which the runtime doesn't know how to resolve.
Try removing any parameters from the main entry point into your programs (except string[] args).
Alternatively, post the code from your program's entry point.


text:
Q: Repeated Measures of ANCOVA in R I conducted a study. Here is the structure of the data: https://ibb.co/CzLK9jP
repeated measures (mood_1 and mood_2) dependent variables, group is a between subject factor, and
ruminati is a covariate.
I prepared the data like this in R: https://ibb.co/KWz9GPC However, I do not get the same result from R as I got from SPSS.
It is significant in SPSS, but not significant in R. What is exactly missing here to conduct the same think in the first picture?
model <- lm(depression ~ group * ruminati)
anova(model)

A: Try this
ancova_model <- aov(depression ~ group + ruminati, data = data)


text:
Q: Openpyxl & Python - Combining data from cells in two columns into a single column I have a spreadsheet with data on people, in which first names are in cells in column L and last names are in the cells in column M. I need to combine these into variables that contain both the first and last name for each person.
import openpyxl
wb = openpyxl.load_workbook('/Users/userName/Desktop/sheetName.xlsx')
main = wb['Sheet1']

The following code will do this for a single row, but I need to make it iterate through every row containing data.
cell1 = main['L1'].value
cell2 = main['M1'].value
cell3 = cell1+cell2
print(cell3)

Here is what I'm trying, but I keep getting the error message name 'rows' is not defined
combined = []
for i in main.rows:
    combined.append(i.value for i in row)
print(combined)

Thanks in advance for help with this puzzle!

A: This is what I got working:
import openpyxl
wb = openpyxl.load_workbook('/Users/userName/Desktop/testSheet.xlsx')
main = wb['Sheet1']

for row in range(2, main.max_row +1):
    firstName = main["L" + str(row)].value
    lastName = main["M" + str(row)].value
    fullName = firstName + ' ' + lastName
    print(fullName)


text:
Q: Cannot delete torrent file from desktop I have this torrent file on the desktop that has zero file size and is not being used by anything, yet I cant delete the icon or file from the desktop. Every time I try to delete it I get an error saying
"could not find this item this is no longer located in C:\...\Desktop. Verify the item's location and try again."
I have tried writing a program to write a file to desktop under the same filename with a file attached to it. When I do that, I can delete the file, but only temporarily as when I refresh the desktop, it will reappear.
I've also tried using Unlocker, which worked for me in the past when I had a 32-bit OS, but since i have a 64-bit OS now it doesn't work any more.

A: As a replacement of unlocker on 64-bit windows/windows 7, you could use LockHunter.
But If it's a corrupted filename: try Delete Doctor (freeware) or delinvfiles (shareware, but have more features) to delete the file with its short or UNC name

A:
"could not find this item. this is no
  longer located in C:...\Desktop.
  Verify the item's location and try
  again."

This error is usually realted to a file name or path exceeding the maximum length, use rename and shorten the name.

A: Does it exist under C:(Users if you're on Vista\7, Documents and Settings if you're on XP)\Public(My if you're on XP) Desktop\?
Under Vista, this had the annoying side effect of creating an un-deletable icon, XP may have handled it differently.

A: Try this.  Go to Command Prompt and using CD Command get the desktop folder.  Suppose that the file you want to delete is named 2009-0000001-whatever, write DEL 2009*.*.  Be sure that no file is named with the same you put before the *, just the file you want to delete.  Enter, and that's all.  Best Regards.

A: Consider running a rootkit detector like F-Secure Blacklight or Rootkit Revealer.  There might be something nefarious going on there.

A: Before you try anything complicated, have you tried clicking on any icon then pressing  F5?
Sometimes Windows Vista and Windows 7 for some reason do not update the desktop or folders, but pressing refresh works and shows everything.
Also, maybe just try a restart - something may have an open handle to it and if it exists, you can do a delete after a restart.
Again, it may be something more complicated, but this is worth a try first!

A: Try using Process Explorer to see if something is using the file.
Open Process Explorer, select Find Handle or DLL... under the Find menu, type the file name and click Search
It's not as fast as Unlocker but it should tell you which process is using that file.


text:
Q: slfj4 logging - MDC.put function not printing anything I am trying to print the username who has logged in along with their id in the logs using slfj4 MDC class. Here is my code, please tell me where i am wrong.
JAVA FILE -
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public classResponse getuser(@PathVariable("user_id") Integer user_id, @RequestParam(value = "department_id", required = false) Integer department_id) {
    JSONObject response = null;
    String username = getUserName();
    logger.debug("Testing MDC.");
    MDC.put("FirstName", "First");
    MDC.put("LastName", "Last");
    logger.info(":::ServiceContoller.getuser starts for userid" + user_id);
    logger.info(":::ServiceContoller.getCreateEnvironment:Ends for username" + username);
    try {
        response = classServiceImpl.getUser1(username, user_id, department_id);
        logger.info("Sending Environment details - {}", response);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return new ClassResponse(Constants.STR_ERROR, "Error getting USERDetails");
    }
    return new ClassResponse(Constants.STR_SUCCESS, response);
}

XML PROPERTIES FILE - logback.xml -
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <layout>
      <Pattern>%-4r [%thread] %-5level C:%X{FirstName} N:%X{LastName} - %m%n</Pattern>
    </layout>
  </appender>

  <root>
  <level value="info" />
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

Please tell me what more I need to have or where I am wrong. Any help appreciated. Thank you in advance.

A: Can you try this.. https://logback.qos.ch/manual/appenders.html
<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>


text:
Q: PGError: ERROR: relation "table_name" does not exist I am trying to push a simple app up to heroku and run:
heroku rake db:migrate

But I get the following error:
rake aborted!
PGError: ERROR:  relation "posts" does not exist
:             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
             WHERE a.attrelid = '"posts"'::regclass
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum

Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)

My migration looks like this:
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :source
      t.string :tweetid
      t.string :pure
      t.string :media
      t.string :destination
      t.datetime :time
      t.timestamps
    end
  end
end

And, after referring to another SO answer, I have included the following in my Gemfile:
# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.1.4'
  gem 'coffee-rails', '~> 3.1.1'
  gem 'uglifier', '>= 1.0.3'
  gem 'pg'
end

Thank you in advance for any help!
--- UPDATE ---
The main reason I am confused is that this all works locally, just not when I run the migration on heroku.
Here is the error I get now:
rake aborted!
Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)

I have been looking at this question:
Heroku error when launch rails3.1 app missing postgres gem
I am almost-certain my database.yml should not look like this (seeing as I need to be running postgresql!!!):
# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

Serious apologies for the nubishness here. Thank you for your help in advance!
Also tried this link: Uploading to Heroku DB rake:migrate problem

A: I had a similar problem, but it wasn't caused by the migration or the Gemfile. I had 4 models setup in a polymorphic relationship. Removing the statement
belongs_to :assetable, :polymorphic => true, :dependent => :destroy

and removing the subclass' acts_as_* declarations was enough to enable the db:migrate to successfully complete. I then added back the statements in the models and everything worked great. I'm not exactly sure why this is the case, but if you are in a similar situation this may help temporarily until a better solution presents itself.
My situation is polymorphic multi-table inheritance scheme between one parent and 3 objects using http://mediumexposure.com/multiple-table-inheritance-active-record/ as a baseline.

A: If you're using ActiveAdmin, whichever table PG says doesn't exist, comment out the contents of that ActiveAdmin rb file.
For example, for this case PGError: ERROR:  relation "posts" does not exist, comment out the entire contents of app/admin/posts.rb, then uncomment after you've done your migrations.

A: create_table :posts

Didn't you forget the s? The table names should be plural.

A: I just ran: bundle exec rake db:migrate and it worked

A: Robin probably has it right but just in case...
Check the filename/timestamps on your migrations.  These get run in sequence.  I had an issue where a generator that made my migrations was putting the foreign table first...I switched the file names and it worked.
It's a long shot but I thought I'd put that out there.

A: In my case, I was doing rename_table in my migration, after having already modified my model name to reflect the new table name. I had moved User into User::User. The users table needed to be renamed to user_users, so my migration looked like
class RenameUsersTableWithPrefix < ActiveRecord::Migration
  def up
    rename_table :users, :user_users
  end

  def down
    rename_table :user_users, :users
  end
end

Instead of
app/models/user.rb

I now had
app/models/user.rb
app/models/user/user.rb

with the latter containing the User::User model, and the former containing simply
module User
  def self.table_name_prefix
    "user_"
  end
end

It was this class method in the newly added User module that was giving me the PGError when running rake db:migrate like the OP had. Temporarily removing this class method while I ran my migration allowed the migration to run smoothly.

A: I was having the same problem.  I ran heroku run rake db:migrate and that solved the problem.


text:
Q: How to start an activity if the power button is pressed (x) no of times in my android app? Please also explain how it works. This should also work when my app is closed.(it should be running in background)

A: you need to register broadcast rceciever for this
This work when app is closed in background
public class MyReceiver extends BroadcastReceiver
{
private static int countPowerOff = 0;

public MyReceiver ()
{

}

@Override
public void onReceive(Context context, Intent intent)
{
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
    {
        Log.e("In on receive", "In Method:  ACTION_SCREEN_OFF");
        countPowerOff++;
    }
    else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
    {
        Log.e("In on receive", "In Method:  ACTION_SCREEN_ON");
    }
    else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
    {
        Log.e("In on receive", "In Method:  ACTION_USER_PRESENT");
        if (countPowerOff > 2)
        {
            countPowerOff=0;
            Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }
    }
  }
}


text:
Q: How to create multiple log file for multiple user using log4j.properties How to create multiple log file for multiple user. Log files will be generated based on username and username coming from API and store in log4j.property file dynamically.

A: Take a look on MDC:
https://www.baeldung.com/mdc-in-log4j-2-logback
You can put the username into MDC and then group the log messages based on the MDC key using log4j configuration file.


text:
Q: How to calculate quantiles? Could someone please show(!) and explain step-by-step how to calculate the theoretical quantiles for the following normally distributed dataset:
{1,1,2,2,2,3,3,5,8,14,24,40}
Given this table:
http://imgur.com/5oHgSVu
EDIT: I am looking for the numbers at the bottom. The original "question": http://imgur.com/TZ4V1RG

A: These (indeed - see comments) are theoretical quantiles of the normal distribution for different $\alpha_j$. These are the values such that $\alpha_j$ of the probability mass of a standard normally distributed random variable is to the left of that value.
The reported quantiles are following:
> round(pnorm(c(-1.73,-1.15,-.81,-.55,-.32,-.1,.1,.32,.55,.81,1.15,1.73)),3)
 [1] 0.042 0.125 0.209 0.291 0.374 0.460 0.540 0.626 0.709 0.791 0.875 0.958

So, this for example means that $-1.73$ is the 4.2%-quantile of the standard normal distribution, the value such that smaller realizations from a standard normal distribution will occur with probability 4.2%.
They are "equally spaced" (evenredig verdeeld) in the sense that there is a roughly constant amount of probability mass between each pair of neighboring quantiles:
> round(diff(x),3)
 [1] 0.083 0.084 0.082 0.083 0.086 0.080 0.086 0.083 0.082 0.084 0.083

As the cdf of the standard normal is not available in closed form, calculating these values by hand is not possible and numerical approximations are used.


text:
Q: Node.js: TypeError: object is not a function I have a weird error:
var http = require("http");
var request = require("request");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});

    request('http://www.google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // Print the google web page.
        }
    });
    response.end();
}).listen(8888);

The idea is for it to listen as a webserver, and then do a request.
But this is what I get as error:
    request('http://www.google.com', function (error, response, body) {
    ^
TypeError: object is not a function
    at Server.<anonymous> (/Users/oplgkim/Desktop/iformtest/j.js:8:2)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2056:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
    at Socket.socket.ondata (http.js:1946:22)
    at TCP.onread (net.js:525:27)

What am I doing wrong?
I installed request, so that's not it :)

A: Access to the request global variable is lost as you have a local variable with the same name.  Renaming either one of the variables will solve this issue:
var http = require("http"); var request = require("request");

http.createServer(function(req, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
    request('http://www.google.com', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Print the google web page.
      }
    })
  response.end();
}).listen(8888);

A: You are no longer able to access the global variable 'request'. You need to rename your local variable 'request' with some other name and the problem will be resolved.


text:
Q: string or nsstring with string Lets assume myProp is @property (retain) NSString * myProp and synthesized for us....
self.myProp = @"some value";//string literal?

self.myProp = [NSString stringWithString:@"some value"];

Is there a difference here?
Is the first one a string literal that doesnt get autoreleased or is it just in memory for it's current scope and I dont have to worry about it?

A: You might want to spend some time with the String Programming Guide. From the linked section (about creating @"string constants"):

Such an object is created at compile
  time and exists throughout your
  program's execution. The compiler
  makes such object constants unique on
  a per-module basis, and they're never
  deallocated, though you can retain and
  release them as you do any other
  object.

A: A string literal is a hard-coded NSString that exists indefinitely while your application is running. You can even send it messages that NSString responds to, such as [@"test" length].
To answer your question, the first line is setting the property to the string literal, while the second is going through an extra step of creating a new string based off the string literal.

A: To add to the posts by Joshua and Preston, in fact [NSString stringWithString:xxx] returns xxx itself when xxx is a literal.
This is an implementation detail, so you shouldn't write any program relying on this fact, but it's fun to know.
You can check this fact thus:
 NSString*a=@"foo";
 NSString*b=[NSString stringWithString:a];
 NSLog(@"a at %p, class %@",a,[a class]);
 NSLog(@"b at %p, class %@",b,[b class]);

At least on my 10.6.3 box, both give the same address, with class NSCFString.
Remember: retain & release concern your responsibility on the ownership, and they don't always decrease/increase the retain count. The implementation can do whatever optimization it wants, as long as the said optimization doesn't break the ownership policy.
Or in other words: write retain & release so that the objects are kept/destroyed in the case the implementation always does the naive increase/decrease of the retain count. That's the contract between Cocoa and you. But Cocoa can do and indeed does a lot of optimization.


text:
Q: How to implement ElasticSearch with asp.net web application? I have read the documentation of ElasticSearch and I am familiar with its endpoints and how to maintain Clusters,Nodes,Indices,etc.
Now I am planning to use it in an Asp.net web api and I am a little bit confused about what is the best way to implement it.
I found that ElasticSearch provides two options to work with .Net application:
1)Nest
2)ElasticSearch.net
So, my first question which way is preferred to integrate my web application with ElasticSearch so I can get advantage of the power of Elasticsearch in searching/analyzing/managing big amount of data and what are the advantages and disadvantages of each one ?
My second question I have read that Nest is a high level client and Elasticsearch.net is a low level one.What does that mean?
My third question do the above libraries expose all ElasticSearch endpoints or are there limitations?
My fourth question is there another way to integrate ElasticSearch in my web application other than the above two libraries?
I would appreciate any references,tutorials so I can get started with(because the documentation of ElasticSearch website is not clear).

A: Check out the documentation for the .NET clients as I think it answers all your questions.
Both NEST and Elasticsearch.Net expose all of the APIs within Elasticsearch, with the former mapping each request and response to a type so you don't need to do this yourself.
You can of course write your own implementation to interact with Elasticsearch over HTTP. Use whichever you're most comfortable with, but personally I'd recommend starting with NEST as it handles a lot of things for you such as mapping inference, connection behaviour with round-robin, etc. (disclaimer: I work on the Elasticsearch .NET clients).
For an example tutorial of integrating with a .NET (Nancy) web application, check out NuSearch.


text:
Q: What is different between typedef with invariant and nomal typedef I came Across a line of code in an example that I can not understand how is it being utilized and what benefit on using this type of declaration.
following in the part of code extracted from that example
const uint16_t cycles = 8;
typedef uint8_t invariant(value < cycles) TIndex_t;

struct TData
{
uint16_t readings[cycles];
volatile uint16_t sum;
TIndex_t index;

void addReading(uint16_t arg)
writes(*this; volatile)
pre(invar())
pre(arg <= 1023)
post(invar())
{
   sum = sum - readings[index] + arg;
   readings[index] = arg;
   index = static_cast<TIndex_t>((index + 1u) % cycles);
}
void init()
writes(*this; volatile)
post(invar());

ghost(
    bool invar() const
        returns((forall r in readings :- r <= 1023) && sum == + over readings);
)

This is GNU C++ the struct is a kind of class definition as I can tell

A: This is not pure C++.
It looks like somebody has written either a compiler extension or a series of macros to allow the specification of pre- and post-conditions for a block of code.
You're going to have to ask that person.
(As an aside, this is why just "extracting code" is often insufficient for understanding; you need to observe the full context in order to know what's going on. In this case, the context includes definitions and/or documentation found elsewhere and not included in your question.)


text:
Q: How to read from second line of text file using vba I would like to read from the second line of a text file to write its data into a CSV file.
What is the best way of doing this?
Open InputFile For Input As #1
Open OutputFile For Output As #2
Do Until EOF(1)
     Line Input #1, strData
    'Read data from second line of text file and Write into CSV file
    Print #2, strData
Loop
Close #1
Close #2

A: Just read in the first line and discard it:
Sub Luxation()
    Dim InputFile As String, OutputFile As String, strData As String
    InputFile = "C:\TestFolder\File1.txt"
    OutputFile = "C:\TestFolder\xxxx.txt"
    Open InputFile For Input As #1
    Open OutputFile For Output As #2
    Line Input #1, strData
    Do Until EOF(1)
        Line Input #1, strData
        Print #2, strData
    Loop
    Close #1
    Close #2
End Sub


text:
Q: Выбор кодировки для MySQL Начал свой проект, хочется сразу использовать лучшие наработки.
Понял, что одна из utf8_general_ci или utf8_unicode_ci.
Склоняюсь к utf8_unicode_ci.
Но наткнулся на информацию, что это немного уже устарело и стоит использовать utf8mb4_general_ci и utf8mb4_unicode_ci.
Посоветуйте какую кодировку выбрать для БД.

A: Вольный перевод вопроса What's the difference between utf8_general_ci and utf8_unicode_ci.
Обе эти кодировки (utf8_general_ci и utf8_unicode_ci) работают с символами UTF-8, разница в сортировке строк и их сравнении.

Заметьте: начиная с MySQL версии 5.5.3 предпочтительнее использовать
  utf8mb4, а не utf8. Они обе являются кодировками UTF-8, но более
  старая uft8 имеет специфические для MySQL ограничения символов UTF-8
  выше 0xFFFD.

Сравнение по отдельным параметрам.
Точность

*

*utf8mb4_unicode_ci основана на стандарте Unicode по сортировке и
сравнению строк, который более точно сортирует строки в широком
диапазоне языков/алфавитов.

*utf8mb4_general_ci не реализует все правила сортировки Unicode, что
зачастую влечёт нежелательный результат в некоторых ситуациях для
определённых языков/символов.
Производительность

*

*utf8mb4_general_ci быстрее в сравнении и сортировке, потому что она
содержит большое число оптимизаций.
На современных серверах, это приращение скорости будет всегда, но незначительно. Оптимизации были задуманы во время, когда мощности серверов были значительно меньше сегодняшних.

*utf8mb4_unicode_ci, которое использует правила Unicode для сортировки
и сравнения, по-честному использует более сложные алгоритмы для
точной сортировки для широкого числа языков и при использовании
спецсимволов. Эти правила принимают во внимание специфические
соглашения для языка, не всегда сортировки идёт в соответствии с
"алфавитным" порядком.
В принципе, для группы т.н. "европейских" языков нет особой разницы между строгой сортировкой по Unicode и упрощенной сортировкой utf8mb4_general_ci, но несколько различий:
Например, Unicode сортирует "ß" так же как и "ss", и "Œ" как "OE" так же как это делают люди, в то время как utf8mb4_general_ci сортирует их как отдельные символы (предположительно как "s" и "e" соответственно).
Некоторые символы Unicode определены как незначимые, что означает, что они не должны влиять на порядок сортировки и сравнение должно переходить к следующему символу. И utf8mb4_unicode_ci обрабатывает эти символы корректно.
Для группы неевропейских языков, таких как азиатские языки или языки с другим алфавитом существует гораздо больше различий между сортировкой Unicode и упрощённой сортировкой в utf8mb4_general_ci. То, насколько подходит utf8mb4_general_ci будет зависеть от конкретного языка. Для некоторых языков разница может быть сильно недостаточной.
Что же использовать?
Практически нет смысла предпочитать utf8mb4_general_ci по соображениям производительности, потому что на современных процессорах разница не будет играть роль "бутылочного горлышка".
Какая-то разница в производительности может быть в каких чрезмерно специализированных ситуациях и если это ваш случай вы должны знать об этом.
Раньше некоторые специалисты рекомендовали использовать utf8mb4_general_ci кроме тех случаев, когда необходима точная сортировка и это важнее проседания производительности. Сегодня больше обращают внимание на точную поддержку интернационализации, чем на незначительное проседание производительности.
И ещё я добавлю, что даже если ваше приложение должно поддерживать только английский язык  - в нём может оказаться ситуация, когда в приложении будут вводиться имена людей и часто вводимые имена должны содержать символы, которые встречаются в других языках, поэтому так важно использовать корректные правила сортировки. Использование Unicode во всех местах, где это возможно, поможет вам разработать более качественные приложения.


text:
Q: Continuous current op-amp I'm using an LMC7101 op-amp.  V+ is 5 V and V- is 0 V.
I want to know whether the op-amp can provide continuous current output (100 mA) while the input voltage is coming from a DAC ranging 0 to 2 V with 10 mA current. We are using it as a voltage feedback function along with maximum current output.

A: TLDR: The thing you missed here is the fact that the short circuit ratings are NOT given for continuous operation and therefore they don't tell you anything about maximum continuous output current. Which means, just because the short circuit current is given as 120 mA (min) doesn't mean a continuous output current of 100mA is safe for the op amp.
The max output current and short circuit current can be comparable when the short circuit condition is given as "indefinite" or "continuous" in the datasheet (of course, there are still some limitations such as max supply voltage e.g. for supply voltages higher than a particular level a long-duration short circuit can be destructive).

The output configuration of an op amp is like following (may vary from op amp to op amp but overall config is almost the same):

simulate this circuit – Schematic created using CircuitLab
This is basically a totem pole output but with series emitter resistors. The ref voltages (an unknown voltage generated internally) are for biasing the output transistors. Although they can be combined to a single one for both of the transistors, I preferred to show separately for the sake of simplicity.
Each series emitter resistor, Re, is there to protect the respective output transistor as well as to define the max output current. If the unloaded output voltage is 5V, the max current defined by Re and VBE of the Q1 will flow when the output is shorted to ground. Likewise, if the unloaded output voltage is 5V and if you load the output with say, 600 Ohms, then a non-zero voltage will drop across the collector-emitter of Q1 and the series emitter resistor. This is where the max voltage swing ratings come from (Note: collector-emitter drop of a BJT changes with collector current).

Now let's make a rough calculation for your case: If your follower configuration forces the output voltage to be 2V at 100 mA output current then the total voltage drop across Re and Q1 will be supply voltage minus the output voltage i.e. 5V - 2V = 3V. At 100 mA output current the total dissipation will be 0.3 W (neglecting the dissipation of previous sections). The thermal resistance is given as 325 °C per Watt which means a temperature rise of 325 x 0.3 = 97 °C relative to ambient. You won't be able to touch the op amp during normal operation, and it will be destroyed after a couple of minutes or even maybe seconds. That's why there's a note warning about potential destruction during short circuit.
The short circuit ratings do not always give an idea about maximum continuous output current.