text:
Q: Can't form EJB relationship across EAR projects. Relationship Attribute Exception? I am trying to access entity beans from one EAR project to another EAR project, but I am getting this error.

Exception Description: [class
  com.huwag.ao.server.bvg.tarif.ejb.entity.Tarif] uses a non-entity
  [class com.huwag.server.ejb.entity.Mandant] as target entity in the
  relationship attribute [field mandant].

It looks like my Tarif can't find my Mandant entity. Tarif lives in one ear file whereas Mandant lives in another (the core project so to speak).
My Mandant (in the Core project) looks like this :
    @Entity
@Table(name = "HUW_AO_MANDANT")
public class Mandant implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "MANDANT_ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And in my dependant EAR JAR lives this guy :
@Entity
@Table(name = "HUW_AO_TARIF")
@NamedQueries({
    @NamedQuery(
            name = "getAllTarif",
            query = "SELECT t FROM Tarif t")
        ,
    @NamedQuery(
            name = "getTarifForMandant",
            query = "SELECT t FROM Tarif t where t.mandantId = :mandant")
})
public class Tarif implements Serializable {

    @Id
    @Column(name = "NAME")
    private String name;

    @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
    @JoinColumn(name="MANDANT_ID")
    private Mandant mandant;

    public Mandant getMadant() {
        return mandant;
    }

    public void setMadant(Mandant mandant) {
        this.mandant = mandant;
    }

    public String getName() {
        return name;
    }

    public void setName(String firstName) {
        this.name = firstName;
    }
}

Architectually it looks like this.

I am trying to form a relationship from one Entity on another Entity that lives in another deployment artifact.
I am using Glassfish 4. I don't have anything in my persistence.xml, because as I understand, Glassfish 4 just finds these classes instead of looking through the persistence.xml.

*

*Am I using the relationship annotations correctly?

*Do I need to put these entities in the persistence.xml file?

*Do I need to provide Local/Remote interfaces so that one EAR file can see the other?

*Is it at all possible to form this relationship between EJBs across different packaging artifacts?

A: If you don't have any persistence.xml files in the dependent ear, I doubt glassfish will know what entities it must use there. So I suppose you need to import that dependency using the <jar-file> XML element in your persistence.xml file. Also you mapped them correctly, although I would go for a int ID instead of a String.


text:
Q: Compare dates using comparator in Java I would like to compare date times in such a way that I get the end result values that have been sorted in Date ascending and Time descending order.
How could I achieve this in java using Joda-Time library?
Data:
01/31 5:50
01/31 5:40
01/30 2:20

Result
01/31 5:40
01/31 5:50
01/30 2:20

A: A simple TreeSet (assuming you have distinct dates) using a Comparator comparing the dateTime.getMillis() of each date for instance would do the trick.
And better, why not use directly this "out-of-the-box" Comparator ;)
Up to you to implement the exact logic you want. (ascendant, descendant, whatever)

A: Write a new comparator and pass it to Arrays.sort() do the work, e.g.
    Arrays.sort(Your_JODO_time_array, new Comparator<Date>(){

        @Override
        public int compare(Date o1, Date o2) {
            Calendar c1 = Calendar.getInstance();
            c1.setTime(o1);
            c1.set(Calendar.HOUR, 0);
            c1.set(Calendar.MINUTE, 0);
            c1.set(Calendar.SECOND, 0);
            c1.set(Calendar.MILLISECOND, 0);
            Date t1 = c1.getTime();
            c1.setTime(o2);
            c1.set(Calendar.HOUR, 0);
            c1.set(Calendar.MINUTE, 0);
            c1.set(Calendar.SECOND, 0);
            c1.set(Calendar.MILLISECOND, 0);
            Date t2 = c1.getTime();

            if(t1.compareTo(t2) != 0)
                return t1.compareTo(t2)*-1;
            else{
                c1.setTime(o1);
                c1.set(Calendar.YEAR, 0);
                c1.set(Calendar.MONTH, 0);
                c1.set(Calendar.DATE, 0);
                t1 = c1.getTime();
                c1.setTime(o2);
                c1.set(Calendar.YEAR, 0);
                c1.set(Calendar.MONTH, 0);
                c1.set(Calendar.DATE, 0);
                t2 = c1.getTime();
                return t1.compareTo(t2);
            }
        }

    });

A: Easy in Joda-Time
Sorting is quite easy in Joda-Time. Just a one-liner!
Joda-Time 2.3 already implements the compareTo method used by the standard Java Comparable interface. See Java Tutorial if you are unfamiliar.
So just add your DateTime instances to an ordered Collection such as List, then call the static sort method.
The milliseconds since the epoch of Unix time stored within the DateTime is used for comparison. So you needn't worry about time zones.
// Usually better to specify time zone than rely on default.
DateTime now = new DateTime( DateTimeZone.forID( "Europe/Paris" ) );

List<DateTime> list = new ArrayList<DateTime>( 3 );
list.add( now );
list.add( now.plusWeeks( 1 ) );
list.add( now.minusWeeks( 1 ) );

System.out.println( "list: " + list );

// When sorted, the last item moves to first position.
java.util.Collections.sort( list );
System.out.println( "list sorted: " + list );

When run…
Running 2014-01-31T18:44:34.277-08:00
list: [2014-02-01T03:44:34.390+01:00, 2014-02-08T03:44:34.390+01:00, 2014-01-25T03:44:34.390+01:00]
list sorted: [2014-01-25T03:44:34.390+01:00, 2014-02-01T03:44:34.390+01:00, 2014-02-08T03:44:34.390+01:00]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configuration of Server root email - Change Address and Name on outgoing email As a newbie Postfix user, I've gotten so far and now I am stuck with a SMALL problem.
I would like to configure my local network servers to send alerts and like using the following:

*

*From address: hostname@example.com

*From name: Hostname

I can get #1 to work fine using smtp_generic_maps
The problem is that on my email client, the name is listed as "root" - as in the header shows the following:
Date: Sun, 29 Jul 2012 13:21:01 -0400 (EDT)
From: zeus@example.com (root)
To: undisclosed-recipients:;

I'd like to change it to From: zeus@example.com (Zeus)
I imagine that this can be done in the headers_check, but so far I haven't gotten anything to work and before I waste a ton of time trying to get this to work, I'd like to make sure I am on the right track.
My aliasing and generic_maps are set up correctly (As far as I can see and know - the results are correct!).  I just want to change that last bit in the From field to reflect the hostname.
I would also like to add something in the subject of the outgoing messages for easy filtering - something like Subject: [Zeus.domain] - "Original Subject".

A: This is not a job for the MTA; it should be done by the mail client.
Postfix is merely reporting the From: header as passed along by the client; in this case, porbably cron thorugh sendmail(1), which sets the friendlyname to the original sender (system user "root")
Why not have each servers' processes send mail to a designated local system account, and then process that and forward it to wherever you want ?
This allows you to modify each machine's outgoing email while avoiding the (unnecessary) mangling of a central MTA.

A: *

*Change e-mail address:

*

*vi /etc/postfix/generic
root     myname@domain.tld

*vi /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic

*postmap /etc/postfix/generic

*postfix reload

*Change name - change name in passwd file from root to My Name:

*

*vi /etc/passwd:
root:x:0:0:Own Name:/root:/bin/bash


text:
Q: How to hierarchically cluster a data matrix in R? I am trying to cluster a data matrix produced from scientific data. I know how I want the clustering done, but am not sure how to accomplish this feat in R.
Here is what the data looks like:
            A1     A2     A3     B1     B2     B3     C1     C2     C3
sample1      1      9     10      2      1     29      2      5     44
sample2      8      1     82      2      8      2      8      2     28
sample3      9      9     19      2      8      1      7      2     27

Please consider A1,A2,A3 to be three replicates of a single treatment, and likewise with B and C. Sample1 are different tested variables. So, I want to hierarchically cluster this matrix in order to see the over all differences between the columns, specifically I will be making a dendrogram (tree) to observe the relatedness of the columns.
Does anyone know how to appropriately cluster something like this? I tried doing this with this:
raw.data <- read.delim("test.txt",header=FALSE,stringsAsFactors=FALSE)
dist.mat<-vegdist(raw.data,method="jaccard")
clust.res<-hclust(dist.mat)
plot(clust.res)

...However, this resulted in a tree with branches for each sample variable, instead of each column. Thanks for any suggestions!

A: Just transpose your data set:
raw.data <- t(raw.data)
require(vegan)
dist.mat<-vegdist(raw.data,method="jaccard")
clust.res<-hclust(dist.mat)
plot(clust.res)


text:
Q: Error while installing Windows sample port monitor localmon I am trying to install windows sample port monitor(localmon) provided in WDK. But I keep getting error while installing it:

An error occurred while installing port monitor 'DDK sample port monitor'. Please contact manufacturer for assistance.

I am using following instructions to install it:-

Open 'Devices and printers' folder. Right click on my targeted printer and choose 'printer properties'. Click the 'Ports' tab, and then click the 'Add Port...' button. On the Printer Ports dialog, click the 'New Port Type...' button. Type the path to the INF file in the text input box, and then click OK.

I am using windows 7, 64-bit version. Following is my INF file.
; monitor.inf
;
; Installation inf for printer port monitor
;
; (c) Copyright 2001-2003 DDK Example for print monitor installation
;

[Version]
Signature="$Windows NT$"
Provider=%PMProducer%
ClassGUID={4D36E979-E325-11CE-BFC1-08002BE10318}
Class=Printer

[PortMonitors]
"DDK Sample Port Monitor" = sampleportmon

[sampleportmon]
CopyFiles=@ddklocalmon.dll, @ddklocalui.dll
PortMonitorDll=ddklocalmon.dll

[SourceDisksFiles]
ddklocalmon.dll=1,,
ddklocalui.dll=1,,

[SourceDisksNames]
1="Sample Port Monitor Installation Disk",,,

[Strings]
PMProducer="Sample Port Monitor Company, Inc."

Can somebody help me here ?
Thanks a lot !!

A: I was finally able to fix the issue. It was a permissions issue. Method for getting to the Printer Properties with Administrator privileges in windows 7, is via Control Panel, System and Security, Administrative Tools, then right click on Print Management then Run as administrator. Once I did that I was able to install the port monitor.

A: Problem Journey
In the INF file for the port monitor it needs to be directed to install the port monitor DLLs into the Windows\System32.
Following the WDK sample for the Language Port monitor one would think that the [DestinationDirs] directory id might be 66002. Note that the Port Monitor example .inf omits providing a [DestinationDir] section.
https://learn.microsoft.com/en-us/windows-hardware/drivers/print/installing-a-print-monitor
The documentation for printer-dirids seems to confirm this.
https://learn.microsoft.com/en-us/windows-hardware/drivers/print/printer-dirids
[DestinationDirs]
DefaultDestDir = 66002

Dirid: 66002; Purpose: Represents the directory path to additional files to be copied to \System32 of the  local system. See the paragraph following this table.;  Directory Contents: Print monitor files

Note that INFGate tool will provide the following warning:
.\monitor.inf(xx): warning 8503: (DW22.23.8503) Use of DirID 66002 prevents full remote/point-and-print installation.
However, this still does not work in practice. Attempting to install the port monitor using 66002 again gives the same error that we started with.
Installing Port Monitor
---------------------------
An error occurred installing port monitor 'DDK sample port monitor'. Please contact the  manufacturer for assistance.
---------------------------
OK
---------------------------

Solution
The driver documentation has another list of directory ids, and has another one:
https://learn.microsoft.com/en-us/windows-hardware/drivers/install/using-dirids

11 System directory. This is equivalent to %SystemRoot%\system32 for Windows 2000 and later versions of Windows..

My experience is that using Dirid value of 11 for the System directory seems to work on Windows XP & 10 for Port Monitors.
[DestinationDirs]
DefaultDestDir = 11

Note that INFGate will still provide a warning about its discouraged use although it works.
.\monitor.inf(56): warning 8505: (DW22.23.8505) DirID DefaultDestDir=11 is discouraged.  Should be in 66000-66004 range in order to support remote install.


text:
Q: Como achar um id específico dentro de uma lista? Vou tentar resumir.
Tenho uma lista na qual tenho elementos com vários ids.
Eu gostaria de selecionar um elemento específico dentro dessa lista. Só que o valor que do ID que será procurado será preenchido dinamicamente.
Como faço pra selecionar esse elemento ?
Segue um código de exemplo:

Estou tentabdo selecionar dessa forma:

pagina_atual = parseInt($.parseJSON(data).paginaatual);
$('#pagina-atual').val(pagina_atual);

$("#ul-paginacao li a:contains('" + pagina_atual + "')").css("background", "red");

Porém está acontecendo isso:

Está selecionando todos os elementos que tenham id que contenham '1'. (Podendo ser 1, 144, 145, 194, etc ...)
CÓDIGO DE CRIAÇÃO DOS BOTÕES
<?php

  if($i == $paginaAtual || $i == ($paginaAtual-1) || $i == ($paginaAtual+1)){
     $botoes .= "
";
     $botoes .= "".$i."";
     $botoes .= "
";
  }

   //PARTE QUE envio o JSON do PHP para o retorno do AJAX
   $retorno = array();
   while($linha = mysqli_fetch_object($operacao_consulta))
   {

      $retorno[] = $linha;

   }

   $objeto = array(
   'botoes' => $botoes,
   'dados' => $retorno,
   'paginaatual' => $pg_atual,
   'quantidadebotoes' => $totalDePaginas,
   'totalderegistros' => $totalDeRegistros
    );

    echo json_encode($objeto);

?>

OBS: Essa variável $i é oriunda de um FOR do php
CÓDIGO JAVASCRIPT

//Trás o retorno do banco com todos os botões (

) que serão mostrados na paginação
paginacao += $.parseJSON(data).botoes;
//paginacao += "
Próximo
";
$('#registros-atividades').html(atividades);

//Insere os botões na UL da paginação
$('#ul-paginacao').html(paginacao);

//Coloca no input hidden a página que está sendo mostrada na paginação
pagina_atual = parseInt($.parseJSON(data).paginaatual);
$('#pagina-atual').val(pagina_atual);

//Conta o número de botões que foi retornado no banco de dados.
contador_de_botoes = parseInt($.parseJSON(data).quantidadebotoes);
//Coloca esse valor no input hidden
$('#quantos-botoes-tem-na-pagina').val(contador_de_botoes);

//Total de registros retornados
total_registros = parseInt($.parseJSON(data).totalderegistros);
$('#total-de-registros').html(total_registros);

//$("#ul-paginacao li a:contains('" + pagina_atual + "')").css("background","Indigo");
parametro_id = pagina_atual.toString();
$("#ul-paginacao li#" + parametro_id).css("background", "red");

Poderiam me ajudar ?

A: Como todo id é único ou seja, você só poderá ter um id = "1" na sua página, você poderia fazer assim(muito mais simples):
function SetBackgroundRed(id){
   $("#"+id).css("background", "red");
}

pagina_atual = parseInt($.parseJSON(data).paginaatual);
$('#pagina-atual').val(pagina_atual);
SetBackgroundRed(pagina_atual) //Pelo que vimos pagina_atual = id

Você seleciona o objeto a partir desse trecho $("#"+id), coloquei numa function para você reutilizar em outros lugares.
Caso não seja esse o problema por favor me avise ;)


text:
Q: choose from implication and logical and in write assertions in first-order logic I am a student and I get confused in translating some sentence to logic assertion.
For example: Joe does not have a lawyer, i.e. is not a customer of any lawyer.
The right way to translate is:
"For all $p$, if $p$ is lawyer then Joe is not a customer of $p$"
or
"For all $p$, if $p$ is lawyer ∧ Joe is not a customer of $p$"
What the difference between these two clause?

A: If you are having problems with this sort of very very elementary point, that suggests you need to do some general homework (a one-off answer to this particular question won't get to the roots of your difficulty). Literally dozens of people have written excellent introductory logic books covering exactly this kind of thing, with detailed chapters on question of translation to and from ordinary language to regimented first-order formal languages. You need to be spending some time carefully reading the relevant chapters of such a book. If you are a student, get yourself to the library. It will be time well-spent.
I'd recommend, for example, the coverage in P-t-r Sm-th's Introduction to Formal Logic. Though having no access to a library is no excuse either, as various texts are available online. For example, Paul Teller's Formal Logic Primer is freely available from his website and is also very good on such questions of translation and the principles behind them.


text:
Q: Android SQLite with ContentProvider and BaaS Can BaaS solutions such as Firebase and Parse be used with an already existing SQLite database locally, and interfaced via a ContentProvider that was already configured?
I could only find information so far on using each solution's proprietary local storage solution. However, if I just treat the BaaS as a REST API, is that a feasible solution?
I'm interested in using a BaaS at this time for my first app for data synchronization/user authentication across devices, and eventually learning how to set up my own server for projects thereafter.
Thanks!

A: I am moving from Parse to Firebase.
In the Parse world, I am able to use the best of both BaaS and Content Providers. Had the BaaS invoked in the Sync Adapter calls, refreshed the local SQLite DB and which in turn updated the CursorAdapter via Content Providers.
In the Firebase world, there is no need for any additional Sync Adapters and hence having a local Content Provider and SQLite is redundant. Yeah, still I could have all of them play together, but not needed as Firebase has the ability to directly update the view.


text:
Q: Dynamically adding HTML radio button with jQuery Being a beginner in jquery, I've got some problems with forms and dynamic elements. I know there's already some topic over here but I've tried a lot of things and nothing is working.
Just a precision : I'm working with Phonegap.
There it is. I've got a form where I have to add radio button from a BDD. i've got the data but can't display it on the page.
Here's my form.
<form action="form.php" method="post" id="catDec">

    <fieldset data-role="controlgroup" id="field">

    </fieldset>

            <fieldset data-role="controlgroup">
                <select name="selectTest" id="selectTest">
                    <option value="1">Value1</option>
                    <option value="2">Value2</option>
                    <option value="3">Value3</option>
                </select>
            </fieldset>

       <input type="checkbox" name="cbTest" id="cbTest" class="custom" />
       Some random text
    </fieldset>

<input type="submit" value="Continue" data-icon="arrow-r" >

And here is my js function.
tableau[0]="value1";
tableau[1]="value2";
tableau[2]="value3";
tableau[3]="value4";

for (var i=1; i<tableau.length-1; i++) {
    //$("#field").append('<input type="radio" name="rb_catDec" id="'+tableau[i]+'" value="'+tableau[i]+'" checked="checked" />' );
    //$("#field").append(''+tableau[i]+'

' );
    //$("#field").html('<input type="radio" name="rb_catDec" id="'+tableau[i]+'" value="'+tableau[i]+'" checked="checked" />' );
    //$("#field").html(''+tableau[i]+'

' );
    $("<input type='radio' value='"+tableau[i]+"' />")
        .attr("id", tableau[i])
        .attr("name", "rb_name")
        .prependTo("field");
}
//$("#field").reload();

Well, I've tried with the .append and with the .html methods. With a div to place those inputs and without.
I suppose it has something to do with the fact I add these after the loading of the page but I don't find a way to pass over it.
Can someone can help me, please ?

A: Try to replace this code:
.prependTo("field");

with this:
.prependTo("#field");

Since, you want to prepend all radio button to the element with the ID #field not just the selector field.
Reference: .prependTo()


text:
Q: Truncated backpropagation for text I know truncated backprop is useful for training RNNs like LSTM. But in some datasets of corpus, there are many long sequences with thousands of tokens. However the average length of tokens is just some hundred numbers. If I only backprop 400 or 500 words for training, how do I deal with those long sequences? Only backprop the previous 400 words from the end token? I dont think it could well capture the semantic meaning of the training examples.

A: Have a look at this thread. It is for Keras but it has some great discussion: https://github.com/fchollet/keras/issues/40
Long story short it is a problem and we have to deal with it for now unless:
a)Online Learning is used
b)You group sequences by their length and feed it in these batches


text:
Q: dataTable passing null values to Java backend I have created a jsf file, the most important part is here:
h:dataTable value="#{gatekeeperStatusBean.list}" var="item"
                     styleClass="table-data"
                     headerClass="table-header"
                     rowClasses="table-odd-row,table-even-row">
            <h:column><f:facet name="header">ID</f:facet>#{item.id}</h:column>
            <h:column><f:facet name="header">Name</f:facet>#{item.name}</h:column>
            <h:column><f:facet name="header">Status</f:facet>

                <c:if test="#{gatekeeperStatusBean.isLogged(item)}">
                    LOGGED
                </c:if>

                <c:if test="#{not gatekeeperStatusBean.isLogged(item)}">
                    LOGGED OUT
                </c:if>

            </h:column>
        </h:dataTable>

In the third column "Status" I wanted to print out whether the gatekeeper is logged in the database or not. All the other columns ID with #{item.id} and Name with #{item.name} are printing valid, non-null values. When I want to fill the status using the method #{gatekeeperStatusBean.isLogged(item)} it is apparently passing a NULL item value to the Java method. Can someone explain why is this happening?

A: Please refer answers https://stackoverflow.com/a/3361723/1346369 and https://stackoverflow.com/a/3362869/1346369 for the question c:when and c:if don't work.
There is an alternate you can use
<h:column rendered="#{gatekeeperStatusBean.isLogged(item)}">
     <f:facet name="header">LOGGED</f:facet>

<h:column rendered="#{not gatekeeperStatusBean.isLogged(item)}">
     <f:facet name="header">LOGGED OUT</f:facet>

or have a method in bean
 public void getStatus(Item item)
 {
    return isLogged(item) ? "LOGGED" : "LOGGED OUT" ;
 }

and use it directly similar to other fields
      <h:column><f:facet name="header">Name</f:facet>
           #{gatekeeperStatusBean.status}
      </h:column>


text:
Q: SQL Server Service Stuck in 'Starting' Status I am not able to connect to the database engine. I have recently installed SQL Server 2012 after formatting my hard drive.
Operating system : Win 7 Enterprise 64-bit
When I try to connect to the database engine :

*

*WN7X64-XXXXXXX, I get the following error message

A network-related or instance-specific error occured. Could not open connection to the SQL Server'.

*I tried accessing using (localhost). It did not work.

*I tried accessing using (localhost)/SQLExpress. It did not work.

*I tried accessing using (localhost)/MSSQLServer. It did not work.

*I tried accessing using MSSQLServer. It did not work.
When I checked the services. SQL Server status is starting, and it does not give me the option to start/stop.  SQL Server Agent status is blank, when I start the service it gives

Error 1068 : dependency service or group failed to start.

Name                                                  Status       Startup Type
SQL Full-text Filter Daemon Launcher (MSSQLSERVER)    Started      Automatic
SQL Server (MSSQLSERVER)                              Starting     Automatic
SQL Server Agent (MSSQLSERVER)                                     Automatic
SQL Server Analysis Services (MSSQLSERVER)            Started      Automatic
SQL Server Browser                                    Started      Automatic
SQL Server Distributed Replay Client                  Started      Automatic
SQL Server Distributed Replay Controller              Started      Automatic
SQL Server Integration Services 11.0                  Started      Automatic
SQL Server Reporting Services (MSSQLSERVER)           Started      Automatic
SQL Server VSS Writer                                 Started      Automatic

A: I sometimes get SQL Server Express stuck in 'starting', in fact, just now, which is why I googled up this page.  The solution is to kill the process and restart it.
Simplest way to do that is through Task Manager, which you can start by right clicking the Windows system tray (banner at the bottom of the screen where minised programs go).  Processes tab, Sort processes by Name, find all beginning 'SQL...' and stop them.
To restart SQL Server right click the Windows Start button, start Control Panel, Administrative Tools, Services, scroll to all services starting 'SQL...', right click to refresh, and stop any that are running, then start the 'SQL Server' service, followed by any others that are set to Auto or Manual start.

A: I had the same issue and MSDN Documentation did not help. https://support.microsoft.com/en-us/kb/307288.
It was to do with that there was an orphan Sql related service i.e SqlWriter was hanging around. Go to task manager and killed it. Then the error went away.

A: To connect to a SQL Server default instance (not Express), you can use:

*

*just a . (dot)

*just a (local)   (be aware: in round brackets)

*just a localhost    (be aware: NO brackets)

See the official MSDN documentation on Logging In to SQL Server for more details and explanations, and for even more options how to connect.

A: Try localhost or (local). Not (localhost).

A: I had the same issue . go to task manager , search for "SQL Server Windows NT" then end the task . after that , go to your services (Run services.msc) and restart your sql server instance .
Solution works for me in MSSQL Server express edition with Windows 10 environment .


text:
Q: Bad interoperability between static and dynamic C# This question is somewhat an illustration to a related post, I believe the example below describes the essence of the problem.
class Program
{
    public static IList<string> GetData(string arg)
    {
        return new string[] {"a", "b", "c"};
    }

    static void Main(string[] args)
    {
        var arg1 = "abc";
        var res1 = GetData(arg1);
        Console.WriteLine(res1.Count());

        dynamic arg2 = "abc";
        var res2 = GetData(arg2);
        try
        {
            Console.WriteLine(res2.Count());
        }
        catch (RuntimeBinderException)
        {
            Console.WriteLine("Exception when accessing Count method");
        }

        IEnumerable<string> res3 = res2;
        Console.WriteLine(res3.Count());
    }
}

Isn't it bad that the second call to GetData raises exception only because GetData received a parameter cast to dynamic? The method itself is fine with such argument: it treats it as a string and returns correct result. But result is then cast to dynamic again, and suddenly result data can not be treated according to its underlying type. Unless it's explicitly cast back to a static type, as we see in the last lines of the example.
I failed to understand why it had to be implemented this way. It breaks interoperability between static and dynamic types. Once dynamic is used, it kind of infects the rest of the call chain potentially causing problems like this one.
UPDATE. Some people pointed out that Count() is an extension method, and it makes sense that it's not recognized. Then I changed a call res2.Count() to res2.Count (from an extension method to a property of Ilist), but the program raised the same exception in the same place! Now that is strange.
UPDATE2. flq pointed to Eric Lippert's blog posts on this topic, and I believe this post gives sufficient reasoning for why it is implemented this way:
http://blogs.msdn.com/b/ericlippert/archive/2012/10/22/a-method-group-of-one.aspx

A: The issue is that Count is an extension method.
How would you locate extension methods at runtime?  The information about which are 'in scope' is based on the 'using' statements in the particular file being compiled.  These are not included in the compiled code at runtime, however.  Should it look at all possible extension methods in all loaded assemblies?  What about assemblies that were referenced by the project, but not yet loaded?  There are a surprising number of boundary cases that crop up if you try to allow dynamic use of extension methods.
The correct solution in this case is to call the static method in its non-extension form:
Enumerable.Count(res2)
Or, since you know it's IList<T> in this case, just use the Count property:
res2.Count <--- EDIT: This doesn't work because it's an explicitly implemented interface property when implemented by the array.

Looking at your question again, I see the real question is not about the extension method resolution per se, but rather why it can't determine that there is a single method resolution possible and therefore know the type statically.  I'll have to ponder that a bit more, but I'm guessing it's a similar question of boundary cases, particularly once you start considering multiple overloads.

Here's one nasty boundary case that could come up in the general case (though not directly applicable to your case, since you derive from Object).
Suppose you have a class Base in assembly A.  There is also a class Derived : Base in assembly B.  In the Derived class, you have your code from above and you think there is only one possible resolution for GetData.  However, now suppose that a new version of assembly A is published that has a protected GetData method with a different signature.  Your derived class inherits this and the DLR dutifully allows for dynamic binding to this new method.  Suddenly the return type may not be what you assumed.  Note that all of this can occur without you recompiling assembly B.  This means the pre-runtime compiler can't assume that the DLR will resolve to the type the pre-runtime compiler believes is the only option, since the dynamic environment at runtime could yield a different type.


text:
Q: ASP.NET MVC Ajax post to Action requiring authentication returns login view when user session has timed out I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then the response view is inserted into the UpdateTargetId.
using (Ajax.BeginForm("Save", null,
        new { userId = Model.UserId },
        new AjaxOptions { UpdateTargetId = "UserForm" },
        new { name = "SaveForm", id = "SaveForm" }))
   {
    [HTML SAVE BUTTON]
   }

Everything works great except when the Users session has timed out and then they are redirected back to the login page.  The login page then gets returned from the Ajax call because of the Authorize attribute and the html gets loaded into the UpdateTargetId and therefore I end up with the login page html within the user profile page (at the Target Id).  My controller action looks like this:
[Authorize]
public ActionResult Save(Int32 UserId)
{
    //code to save user
    return View("UserInfoControl", m);

}

How can I solve this problem?
UPDATE (2011-10-20):
Found this post from Phil Haack about this exact issue -  http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx.  I have not gotten a chance to digest or implement his solution yet.

A: I think that you can handle the authorization issue from inside the action.
First remove [Authorize], the use this code:
public ActionResult Save(Int32 UserId)
{
    if (!User.Identity.IsAuthenticated)
    {
        throw new Exception();
    }
    //code to save user
    return View("UserInfoControl", m);

}

Then you can put a OnFailure condition in your AjaxOptions and redirect your page or something.


text:
Q: How can I play Indiana Jones: The Infernal Machine on Windows 8? Due to it being designed for prehistoric computers I can't run it on my Windows 8 laptop. How can I go about making it run on a current operating system?
EDIT: To avoid any confusion, the game can boot normally, but after 4 or so minutes after opening it, it starts gliching, and bugging to the point where it hangs and then crashes.

A: You can just run an older version of windows on Virtual Box or VMWare Workstation. You can play it on the Virtual Machine

A: For the sake of posterity, there is an unofficial installer for Windows 7+ and this file which I found on a forum. I just confirmed that running it from the installed folder makes the Jones3d.exe compatible with Windows 10.
Also, if that doesn't help and you don't have a legit license for an older version of Windows there are reports you can use Linux with Wine to play. And Linux can run in a virtual machine itself if you'd rather not use it as your general-purpose OS.

A: Have you tried buying it from GoG? (https://www.gog.com/game/indiana_jones_and_the_infernal_machine)
Their game page details that it works on Win7, 8 and 10.

GoG optimize old games to run on newer systems, and games bought through them are covered by their Money Back guarantee which covers instances where they don't work. This is probably your best bet.


text:
Q: Get current Windows user name within Silverlight Is it possible to get the currently logged in user's username with Silverlight? You can assume that user has Windows OS and the Silverlight application is hosted in Internet Explorer. Getting the identity from server side with ASP.NET is not an option, this Silverlight application will be hosted on a static HTML file.

A: The highly voted answers to this question did not help me.
Using an ASP.NET web service, this worked however:
string userName =
   System.ServiceModel.ServiceSecurityContext.Current.WindowsIdentity.Name;

And this blog entry is the one that set me on the correct path:
http://rouslan.com/2009/03/12/20-steps-to-get-together-windows-authentication-silverlight-and-wcf-service/
ServiceReferences.ClientConfig needs this:
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding ...>
          <security mode="TransportCredentialOnly" />
        </binding>
      </basicHttpBinding>
    </bindings>
 </system.serviceModel>

And web.config needs this:
  <system.web>
    <authentication mode="Windows" />
    <identity impersonate="false" />
  </system.web>

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding ...>
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>

Those are the only noteworthy changes I needed to make to an otherwise working Silverlight application that previously used anonymous access for web services in IIS.

A: I figured I'd share this code which seems to work (YMMV). It is inspired by CraigTP's answer and his links he provided. I know this doesn't directly answer the part about running in a static web page, but it seems the OP accepted the APSX compromise.
In my ASPX page that hosts Silverlight:
<head>
    <!-- ...snip... -->
    <script runat="server" language="c#">
    void Page_Load()
    {
        this.UsernameField.Value = User.Identity.Name;
    }
    </script>
</head>
<body>
   <input type="hidden" ID="UsernameField" runat="server" />
   <!-- ...snip... -->
</body>

In my silverlight C# code:
 private string GetCurrentUserName()
 {
     HtmlDocument doc = HtmlPage.Document;

     if (doc == null)
     {
         return string.Empty;
     }

     HtmlElement elm = doc.GetElementById("UsernameField");

     if (elm == null)
     {
         return string.Empty;
     }

     return elm.GetAttribute("value");
 }

A: You can manage to get by this way.
1) Create asp.net web service application.
2) Implement web service and method to call from silverlight applicaton.
[WebMethod]
public string GetClientUserName()
{
    return System.Web.HttpContext.Current.User.Identity.Name.ToString();
}

3) Deploy this web service application on web server. Don't allow anonymous user to access this.
4) Add this service to Silverlight application. (Add service reference)
5) Now, you can call this method and get user name from entire silverlight application.

A: Unfortunately, I don't think it's possible.
Although you say that we can assume Windows OS/IE, Silverlight itself certainly doesn't assume this, so most of the normal .NET mechanisms that would ordinarily be available to us to get the current logged on user's name do not exist within the subset of the framework available to Silverlight apps:
ie.
System.Net.CredentialCache.DefaultCredentials
System.Security.Principal.WindowsIdentity.GetCurrent().Name
Environment.UserName

are all unavailable within a Silverlight application, whereas in (say) a Windows Forms Application, each of these mechanisms is available to use.
I suppose it makes sense, really, since there's no guarantee that the Silverlight application is going to be running on top of a Windows/IE platform.
Incidentally, this question was also asked over here:
Current Windows Username and Domain
and that thread seems to confirm that there's no native way to achieve this.  The thread then goes on to suggest "injecting" the current ASP.NET user name from the ASP.NET page "hosting" the Silverlight app. into the Silverlight application itself prior to it running in the context of the client's machine.  Of course, even if this works, it'll only give you the ASP.NET user name from either ASP.NET's forms or windows based authentication and not the Windows username of currently logged on user of the client machine.

A: Environment
    .GetFolderPath(Environment.SpecialFolder.Personal)
    .Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)[2];

A: according to this post its not possible in javascript, so i think your out of luck:
http://bytes.com/topic/javascript/answers/616501-how-get-windows-username-using-javascripts
sounds like there is no real way to do it.

A: // a small improvement of Code Maverick answer using System.IO.Path.DirectorySeparatorChar rather // then //
Environment
    .GetFolderPath(Environment.SpecialFolder.Personal)
    .Split(new[] { System.IO.Path.DirectorySeparatorChar  }, StringSplitOptions.RemoveEmptyEntries)[2];

A: well , here is how you can get it wihtout wcf
http://www.codeproject.com/Articles/47520/Silverlight-Windows-User-Identity-Name


text:
Q: C++ - Play back a tone generated from a sinusoidal wave Hey everyone, I'm currently trying to figure out how to play back a tone I have generated using a sinusoidal wave.
Here's my code:
#include <iostream>
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <Math.h>

using namespace std;

int main (int argc, char * const argv[]) {

    int number = 0;
    int i, size;
    double const Pi=4*atan(1);
    cout << "Enter number of seconds:" << endl;
    scanf("%d", &number);
    size = 44100*number;
    unsigned char buffer [size]; //buffer array

    for(i = 0; i < size; i++){
        buffer[i] = (char)sin((2*Pi*440)/(44100*i))*127;
    }

    return 0;
}

Obviously it doesn't do anything at the moment, since I have no idea how to play the buffer.
I don't want to generate a wav file, nor do I want to load one in. I just want to play back the buffer I have generated.
I am currently working on Mac OS X, and have tried using OpenAL methods - however I have found that alut and alu are not part of it anymore and if I try to use it then it turns out that it's all depredated anyway.
I have also tried to include QAudioOutput, but for some reason it does not appear to be anywhere on my Mac.
I just want a simple playback of the tone I've created. Does anyone have anything they can point me to?
Thanks heaps!!!

A: I've written an example exactly for this. Runs fine with OpenAL under MacOSX and plays smooth sines. Take a look here:
http://ioctl.eu/blog/2011/03/16/openal-sine-synth/
Code is quite short, i guess i can add it here as well for sake of completeness:
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <OpenAL/al.h>
#include <OpenAL/alc.h>

#define CASE_RETURN(err) case (err): return "##err"
const char* al_err_str(ALenum err) {
    switch(err) {
        CASE_RETURN(AL_NO_ERROR);
        CASE_RETURN(AL_INVALID_NAME);
        CASE_RETURN(AL_INVALID_ENUM);
        CASE_RETURN(AL_INVALID_VALUE);
        CASE_RETURN(AL_INVALID_OPERATION);
        CASE_RETURN(AL_OUT_OF_MEMORY);
    }
    return "unknown";
}
#undef CASE_RETURN

#define __al_check_error(file,line) \
    do { \
        ALenum err = alGetError(); \
        for(; err!=AL_NO_ERROR; err=alGetError()) { \
            std::cerr << "AL Error " << al_err_str(err) << " at " << file << ":" << line << std::endl; \
        } \
    }while(0)

#define al_check_error() \
    __al_check_error(__FILE__, __LINE__)

void init_al() {
    ALCdevice *dev = NULL;
    ALCcontext *ctx = NULL;

    const char *defname = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
    std::cout << "Default device: " << defname << std::endl;

    dev = alcOpenDevice(defname);
    ctx = alcCreateContext(dev, NULL);
    alcMakeContextCurrent(ctx);
}

void exit_al() {
    ALCdevice *dev = NULL;
    ALCcontext *ctx = NULL;
    ctx = alcGetCurrentContext();
    dev = alcGetContextsDevice(ctx);

    alcMakeContextCurrent(NULL);
    alcDestroyContext(ctx);
    alcCloseDevice(dev);
}

int main(int argc, char* argv[]) {
    /* initialize OpenAL */
    init_al();

    /* Create buffer to store samples */
    ALuint buf;
    alGenBuffers(1, &buf);
    al_check_error();

    /* Fill buffer with Sine-Wave */
    float freq = 440.f;
    int seconds = 4;
    unsigned sample_rate = 22050;
    size_t buf_size = seconds * sample_rate;

    short *samples;
    samples = new short[buf_size];
    for(int i=0; i<buf_size; ++i) {
        samples[i] = 32760 * sin( (2.f*float(M_PI)*freq)/sample_rate * i );
    }

    /* Download buffer to OpenAL */
    alBufferData(buf, AL_FORMAT_MONO16, samples, buf_size, sample_rate);
    al_check_error();

    /* Set-up sound source and play buffer */
    ALuint src = 0;
    alGenSources(1, &src);
    alSourcei(src, AL_BUFFER, buf);
    alSourcePlay(src);

    /* While sound is playing, sleep */
    al_check_error();
    sleep(seconds);

    /* Dealloc OpenAL */
    exit_al();
    al_check_error();
    return 0;
}

Update: I've found OpenAL a bit too limiting for my needs, like I have some problems with low-latency playback as this appears to be not the primary domain of OpenAL. Instead, I've found the very convincing PortAudio: http://www.portaudio.com/
It supports all major platforms (Mac,Win,Unix/ALSA) and looks very good. There is an example for sine playback which is far more sophisticated, yet quite simple. Just download the latest release and find the sine-playback sample at test/patest_sine.c

A: You will need to go through the OS to play back sounds. It's not as straightforward as you would think. In OSX, you will need to go through CoreAudio.
A better approach would be to use a wrapper library like PortAudio (http://www.portaudio.com/) which will make your code more portable and save you some of the boilerplate needed to get sound out of your program.

A: Try this (this program uses Z transform concept, a complete example that generates dtmf tones using ALSA and compilable on LINUX are available here):
/*
 *  Cosine Samples Generator
 *
 *  Autor: Volnei Klehm
 *  Data: 04/01/2014
 */

#include <math.h>
#include <stdio.h>

#define S_FREQ 8000 /*Sample frequency, should be greater thar 2*sineFrequency
          If using audio output it has to be the same saple frequency
          Used there*/

const float frequency_in_Hertz = 697; /*set output frequency*/
const float generatorContant1 = cosf(2*M_PI*(frequency_in_Hertz/S_FREQ));
const float generatorContant2 = sinf(2*M_PI*(frequency_in_Hertz/S_FREQ));

float GenerateSignal(){
  static float Register[2]={1,0};
  static float FeedBack;

  FeedBack=2*generatorContant1*Register[0]-Register[1];
  Register[1]=Register[0];
  Register[0]=FeedBack;

  return (generatorContant2*Register[1]);
}

int main(void) {
  /*generate 300 samples*/
  for (int NumberOfSamples = 300; NumberOfSamples > 0; NumberOfSamples--)
    printf("\n%f", GenerateSignal());
  return 0;
}


text:
Q: Upgrade gcc compiler / other fix for backward compatible For a project I need to upgrade application on older hardware, but the used kernel version is very old. and compiling the current application is a pain.
The whole picture, for a project we used x86 board with a 2.6.32 kernel.(Debian)
compiling the application with gcc 4.4.5.
Years later we swapped the cpu's for ARM7 and new kernel 3.0.35 (buildroot)
Using linaro-arm-linux-2013.01.(gcc version 4.7.3 20130102)
The main problem is that the code is now based on GCC 4.7.3 and is more C11 then with gcc 4.4.5.
Local compile is not an option as my machine is x64 and the target is x86. One of the packages used is GTK2, and this is not supported in the x86/x64 build method.
The code for the x86 board is now compiled on an older virtual machine.
How can I overcome this problem without rewriting the program to keep the older gcc 4.4.5. happy?
Upgrading the x86 board is not an option as I do not get time to develop and test this.

A: try to compile hello.c with those linaro arm cross compiler:
see if ./a.out works or not.
gcc-4.x
https://releases.linaro.org/components/toolchain/binaries/latest-4/
gcc-5.x
https://releases.linaro.org/components/toolchain/binaries/latest-5/
gcc-6.x
https://releases.linaro.org/components/toolchain/binaries/latest/arm-linux-gnueabihf/
1.gcc-linaro-xxx-i686_arm-linux-gnueabi.tar.xz
2.gcc-linaro-xxx-x86_64_arm-linux-gnueabi.tar.xz

A: How I solved this problem:
Got the buildroot files from this webpage: https://gist.github.com/icopitg-fh
Got the buildroot version 2013.11
Build the kernel + needed packages. Be aware that some like the libc will break due to the version of make. my version is 4 and the configure script does not not accept version found. This can be solved by changing the make. (change the regexp).


text:
Q: Create a CosmosDB collection with shared throughput instead of using the deprecated SharedOfferThroughput Previously, I used to create collections by calling CreateDocumentCollectionAsync() and passing a RequestOptions parameter in which I set SharedOfferThroughput. It looks like this property is deprecated now, but I cannot find a good example to replace it with. I have a single Cosmos database and I want every collection to share the RU pool of the database.

A: Take a look a the new SDK: Blog post or GitHub.
From the blog post:

We've created a new top level CosmosClient class to replace
  DocumentClient, and split up its methods into modular CosmosDatabase,
  CosmosContainer, and CosmosItems classes. The new programming model
  removes the need for UriFactory and other "noise" from the application
  code.

Within those docs, you can find references to how to manipulate the throughput at a Database or Container level.


text:
Q: How to set string on spinner? String str = countries.get(country);
mSpinnerCountry.setSelection(Integer.parseInt(str));
mSpinnerCountry have items but I want to set a particular item on spinner for update.

A: Do like this by getting item index from spinner list.
spinner.setSelection(countries.indexOf(str));

Complete Exampple:
public class SpinnerModel {

        private  String CompanyName="";
        private  String Image="";
        private  String Url="";

        /*********** Set Methods ******************/
        public void setCompanyName(String CompanyName)
        {
            this.CompanyName = CompanyName;
        }

        public void setImage(String Image)
        {
            this.Image = Image;
        }

        public void setUrl(String Url)
        {
            this.Url = Url;
        }

        /*********** Get Methods ****************/
        public String getCompanyName()
        {
            return this.CompanyName;
        }

        public String getImage()
        {
            return this.Image;
        }

        public String getUrl()
        {
            return this.Url;
        }
  }

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

      <TextView
          android:paddingTop="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>

      <Spinner
          android:id="@+id/spinner"
          android:drawSelectorOnTop="true"
          android:prompt="@string/defaultText"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"

          />

      <TextView
          android:paddingTop="20dip"
          android:paddingLeft="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:id="@+id/output"
          />

  </LinearLayout>

Full Code:
public class CustomSpinner extends Activity {

    /**************  Intialize Variables *************/
    public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
    TextView output = null;
    CustomAdapter adapter;
    CustomSpinner activity = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_spinner);

        activity  = this;

        Spinner  SpinnerExample = (Spinner)findViewById(R.id.spinner);
        output                  = (TextView)findViewById(R.id.output);

        // Set data in arraylist
        setListData();

        // Resources passed to adapter to get image
        Resources res = getResources();

        // Create custom adapter object ( see below CustomAdapter.java )
        adapter = new CustomAdapter(activity, R.layout.spinner_rows, CustomListViewValuesArr,res);

        // Set adapter to spinner
        SpinnerExample.setAdapter(adapter);

        // Listener called when spinner item selected
        SpinnerExample.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                // your code here

                // Get selected row data to show on screen
                String Company    = ((TextView) v.findViewById(R.id.company)).getText().toString();
                String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();

                String OutputMsg = "Selected Company : \n\n"+Company+"\n"+CompanyUrl;
                output.setText(OutputMsg);

                Toast.makeText(
                        getApplicationContext(),OutputMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
    }

    /****** Function to set data in ArrayList *************/
    public void setListData()
    {

        // Now i have taken static values by loop.
        // For further inhancement we can take data by webservice / json / xml;

        for (int i = 0; i < 11; i++) {

            final SpinnerModel sched = new SpinnerModel();

              /******* Firstly take data in model object ******/
               sched.setCompanyName("Company "+i);
               sched.setImage("image"+i);
               sched.setUrl("http:\\www."+i+".com");

            /******** Take Model Object in ArrayList **********/
            CustomListViewValuesArr.add(sched);
        }

    }

  }

CustomAdapter:
/***** Adapter class extends with ArrayAdapter ******/
public class CustomAdapter extends ArrayAdapter<String>{

    private Activity activity;
    private ArrayList data;
    public Resources res;
    SpinnerModel tempValues=null;
    LayoutInflater inflater;

    /*************  CustomAdapter Constructor *****************/
    public CustomAdapter(
                          CustomSpinner activitySpinner,
                          int textViewResourceId,
                          ArrayList objects,
                          Resources resLocal
                         )
     {
        super(activitySpinner, textViewResourceId, objects);

        /********** Take passed values **********/
        activity = activitySpinner;
        data     = objects;
        res      = resLocal;

        /***********  Layout inflator to call external xml layout () **********************/
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      }

    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    // This funtion called for each row ( Called data.size() times )
    public View getCustomView(int position, View convertView, ViewGroup parent) {

        /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
        View row = inflater.inflate(R.layout.spinner_rows, parent, false);

        /***** Get each Model object from Arraylist ********/
        tempValues = null;
        tempValues = (SpinnerModel) data.get(position);

        TextView label        = (TextView)row.findViewById(R.id.company);
        TextView sub          = (TextView)row.findViewById(R.id.sub);
        ImageView companyLogo = (ImageView)row.findViewById(R.id.image);

        if(position==0){

            // Default selected Spinner item
            label.setText("Please select company");
            sub.setText("");
        }
        else
        {
            // Set values for spinner each row
            label.setText(tempValues.getCompanyName());
            sub.setText(tempValues.getUrl());
            companyLogo.setImageResource(res.getIdentifier
                                         ("com.androidexample.customspinner:drawable/"
                                          + tempValues.getImage(),null,null));

        }

        return row;
      }
 }

spinner_rows.XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         />
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>

Explanation demo


text:
Q: How to redirect a request to another URL on json-server? I need to request paginated data from json-server. I want to retrieve a page of users containing 10 results for each page. For this, I am making a GET request to /posts/page/1, but I know I need to request it like /posts?_start=0&_end=9 because this is the way json-server works.
The problem is that my real backend works like that, and both requests should be done the same way from frontend, regardless if I am using my real backend server or my test json-server.
I tried to use routes.json but I cant see a way to add logic to convert the page number to the _start and _end parameters on routes.json since it is a json file.
I just need json-server to return response from /posts?_start=0&_end=9 everytime I request /trips/page/1, again, with logic to convert the page number to the _start and _end parameters.
How can I accomplish this?

A: Use _page with _limit instead of _start/_end.
Then add to routes.json like:
{
  "/:type/page/:page": "/:type?_page=:page&_limit=10"
}

Which should handle /posts/page/1 or /trips/page/1.

A: If anyone landed here like me looking for how to redirect to a different url on json-server, this is how:
server.get('/redirect', (req, res) => {
    res.redirect('http://localhost:3000/my_other_url')
})


text:
Q: Refresh JDesktopPane not working I want to create a preview of the file I read with a specified number of lines. My code works fine, the problem is that if I choose another number of lines, the JDesktopPane is not refreshing and it's overwriting the previous lines.
My code looks like this:
previewButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {

                        try {

                            if(Integer.parseInt(nrLines.getText()) < 20) {
                            for(int i=0; i< Integer.parseInt(nrLines.getText());i++){
                            previewLabel[i] = new JLabel(" ");
                            previewLabel[i].setText("Line nr. "+(i+1)+": "+previewList.get(i));
                            previewLabel[i].setBounds(20,575+25*i,700,300);
                            previewLabel[i].setVisible(true);
                            desktopPane.add(previewLabel[i]);
                            }
                            desktopPane.repaint();
                            }
                            else {
                                System.out.println("Maximim number of lines is 20 !");
                            }

                        } catch (Exception e) {
                            System.out.println("Please enter a integer value !");
                        }

                        }
                });

                desktopPane.add(previewButton);

Here is how it looks after I choose another number of lines:

Thanks in advance for help !

A: Looking at your code, it seems that every time actionPerformed() is called, you add new previewLabels to the desktopPane. You could try keeping track of what you've added (or inspecting the children of desktopPane), and removing old labels before adding new ones.
Alternatively, instead of creating new labels, perhaps you could replace the contents of the old ones.
Example (I haven't used your code, but it shows the two approaches I'm thinking of):
import javax.swing.*;
import java.util.*;
import java.awt.event.*;

class Test {

   static JLabel labelToReplace;
   static JLabel labelToUpdate;

   private static JLabel newLabel(String s) {
     JLabel l = new JLabel(s);
     l.setBounds(30, 160, 200, 40);
     labelToReplace = l;
     return l;
   }

   public static void main(String[] args) {
     JFrame frame = new JFrame("Test");
     frame.setSize(300, 300);
     JDesktopPane desktopPane = new JDesktopPane();
     frame.setContentPane(desktopPane);

     // This one we will update.
     labelToUpdate = new JLabel("Test label");
     labelToUpdate.setBounds(30, 120, 200, 40);
     desktopPane.add(labelToUpdate);

     // This one we will replace.
     desktopPane.add(newLabel("Another"));

     JButton btnRefresh = new JButton("Refresh");
     btnRefresh.addActionListener(
         new ActionListener() {
           public void actionPerformed(ActionEvent e) {
             labelToUpdate.setText(new Date().toString());

             desktopPane.remove(desktopPane.getIndexOf(labelToReplace));
             desktopPane.add(newLabel(new Date().toString()));
           }
         }
     );
     btnRefresh.setBounds(30, 50, 100, 70);
     desktopPane.add(btnRefresh);

     frame.show();
   }
}


text:
Q: Laravel, PHP: json_encode gives different result in Laravel and raw PHP In my mysql database table there are utf-8 characters.(my table collation is utf8_unicode_ci)
অà§à¦¯à¦¾à¦¸à¦¿à¦¡à¦¿à¦¤à¦¿ কমিয়ে উরà§à¦¬à¦°à¦¤à¦¾ ফিরিয়ে আনতে কোনটি বà§à¦¯à¦¬à¦¹à¦¾à¦° করা হয়?

Now when i get the table column using Laravel Model and the json_encode the data, i get
"\u00e0\u00a6\u2026\u00e0\u00a7\u008d\u00e0\u00a6\u00af\u00e0\u00a6\u00be\u00e0\u00a6\u00b8\u00e0\u00a6\u00bf\u00e0\u00a6\u00a1\u00e0\u00a6\u00bf\u00e0\u00a6\u00a4\u00e0\u00a6\u00bf \u00e0\u00a6\u2022\u00e0\u00a6\u00ae\u00e0\u00a6\u00bf\u00e0\u00a7\u0178\u00e0\u00a7\u2021 \u00e0\u00a6\u2030\u00e0\u00a6\u00b0\u00e0\u00a7\u008d\u00e0\u00a6\u00ac\u00e0\u00a6\u00b0\u00e0\u00a6\u00a4\u00e0\u00a6\u00be \u00e0\u00a6\u00ab\u00e0\u00a6\u00bf\u00e0\u00a6\u00b0\u00e0\u00a6\u00bf\u00e0\u00a7\u0178\u00e0\u00a7\u2021 \u00e0\u00a6\u2020\u00e0\u00a6\u00a8\u00e0\u00a6\u00a4\u00e0\u00a7\u2021 \u00e0\u00a6\u2022\u00e0\u00a7\u2039\u00e0\u00a6\u00a8\u00e0\u00a6\u0178\u00e0\u00a6\u00bf \u00e0\u00a6\u00ac\u00e0\u00a7\u008d\u00e0\u00a6\u00af\u00e0\u00a6\u00ac\u00e0\u00a6\u00b9\u00e0\u00a6\u00be\u00e0\u00a6\u00b0 \u00e0\u00a6\u2022\u00e0\u00a6\u00b0\u00e0\u00a6\u00be \u00e0\u00a6\u00b9\u00e0\u00a7\u0178? "

But if i fetch the column using mysqli prepared statement in plain PHP and the use json_encode, i get
"\u0985\u09cd\u09af\u09be\u09b8\u09bf\u09a1\u09bf\u09a4\u09bf \u0995\u09ae\u09bf\u09df\u09c7 \u0989\u09b0\u09cd\u09ac\u09b0\u09a4\u09be \u09ab\u09bf\u09b0\u09bf\u09df\u09c7 \u0986\u09a8\u09a4\u09c7 \u0995\u09cb\u09a8\u099f\u09bf \u09ac\u09cd\u09af\u09ac\u09b9\u09be\u09b0 \u0995\u09b0\u09be \u09b9\u09df? "

I want this json, but laravel generating another one.
Laravel code:
app/config/database.php
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',

//Model
class Problem extends \Eloquent {
    protected $fillable = [];
    public $timestamps = false;
    protected $table = 'problems';

}
// Controller function
public function test()
{
    $tmp = Problem::find(33551);
    return json_encode($tmp['body']);
}

Plain PHP code:
$sql = "SELECT body FROM problems WHERE id = ?";
$id = 33551;
$statement = $mysqli->prepare($sql);
$statement->bind_param("i", $id);
$statement->execute();
$ret = "";
$statement->bind_result($ret);
$statement->fetch();
echo json_encode($ret);

Why is json_encode working so strangely in laravel. How can i solve this problem ?
I'm using Laravel 4.2
Please help...

A: There is no difference with json_encode,you should check the result you got from the both way,
and Problem::find(33551) will not get column "body",it will get whole row(an object) with id 33551..
you should try var_dump($tmp) and see what you have got.
get column body using $tmp->body


text:
Q: CSS presedence of selector over class .formWrap input[type="text"] {
    font-size: 12px;
}

.bigger {
    font-size: 14px
}

<div class="formWrap">
    <input type="text" class="bigger" />
</div>

Why does the above not make the text of the input field 14px?
When I am using the input[type="text"] selector how can I target a particular class that is a child of formWrap?
Is there a better method to give all my inputs a particular style then be able to make adjustments to certain inputs (hopefully based on a class)?

A: The answer is Specificity.
Your first selector has higher specificity than your second selector, so its properties are prioritised.
.formWrap input[type="text"] contains a class, an element and attribute selector. As per the CSS selectors specification (linked above), this selector has a specificity of 21. .bigger on the other hand only has a class selector, and therefore only has a specificity of 10. 21 is greater than 10.
From MDN:

Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts.

In your case, an easy way to get your second selector to be prioritised over the first is by increasing this selector to have equal or higher specificity:
input.bigger {}    /* 11 */

You can even repeat the same selector multiple times (as also noted in the specification):
input.bigger.bigger {}               /* 21 */

Note that if the specificity of both selectors are equal, the selector included later in your stylesheet will be the one prioritised.

A: The first selector has higher specificity than the .bigger class.
To increase the specificity of the .bigger class, you could do this:
.formWrap input[type="text"]{
       font-size: 12px;
}

.formWrap input[type="text"].bigger{
       font-size: 14px
}

OR (Not really recommended):
.bigger{
font-size: 14px !important;
}

A: There is a good article on specificity and how to calculate here. Something that takes a while to click when first starting to write CSS.
Calculating CSS Specificity Value
http://css-tricks.com/specifics-on-css-specificity/


text:
Q: How to find out the edited column name in cell end edit event of grid angularjs? In my application, ngGrid having nearly 10 number of columns, in that half of them are editable one. Once cell editing is completed, then its calling ngGridEventEndCellEdit event. its working fine.
But I want to know name which cell is edited.
Is there possible to get edited cell name in the event ngGridEventEndCellEdit ?
Or Is there any other event available for returning row with cell edited column name once editing is completed like ngGridEventEndCellEdit?

A:     var columnName = data.targetScope.col.field

This will return column name for edited cell.
    data.targetScope.col

This will return all information of edited column


text:
Q: Ovirt Hosted Engine live migration I have trouble with live migration HE in ovirt.
I have 2 nodes.
My nodes
if i migrate HE to other node, i getting an error
My error
Ovirt version 4.1
If i run host-deploy on node, i getting an error

Failed to execute stage 'Environment customization': Setup of additional hosts using this software is not allowed anymore. Please use the engine web interface to deploy any additional hosts.

A: sometimes the live migration of the ovirt-hosted-engine failed for me too. Log in via SSH on a server in your cluster and check via hosted-engine --vm-status what the score of the server is. Sometimes the activation of the server failed and the state of the node is still in maintenance.
Best workaround for me was to reboot the server or try in the UI the maintenance mode and actiation again.
Do you have your Power Management set up?


text:
Q: How to pronounce LINQ? How to pronounce LINQ? Or should I just say L-I-N-Q? (LINQ is a .NET extension for queries.)

A: As someone posted on Stack Overflow and taken from the mouth of the founder of LINQ himself, take a look at the video under this link (hmmm):
https://stackoverflow.com/a/15557254/1654098
And here:
http://www.infoq.com/interviews/erik-meijer-linq

A: It seems the consensus is on "link".

A: In all the tutorials and according to Wikipedia it's simply pronounced /lɪŋk/ exactly like link.
It's a Microsoft .NET Framework Component.

A: I normally pronounce it as lee-n-kyu

A: It is supposed to be pronounced as LINK.


text:
Q: Hiding later achievement levels I have a series of achievements, (1k meters, 10k meters, 50k meters, etc) and I would like to hide the achievements later in the series until the level before it is unlocked. So at first only the 1k would be displayed, then once that was unlock 10k would be displayed, and so on.
I tried setting the achievements to 'hidden' but that makes them be displayed as 'Secret'. How can I completely hide the later achievements?

A: Based from this documentation, you can use hidden wherein the details about the achievement are hidden from the player. The Google Play games services provides a generic placeholder description and icon for the achievement while it's in a hidden state. We recommend making an achievement hidden if it contains a spoiler you don't want to reveal about your game too early (for example, "Discover that you were a ghost all along!"). For your case, you need to use the incremental achievements since you want to display it per level. You can follow this guide on how to add achievements to your game.

To unlock an achievement, call the unlock() method and and pass in the achievement ID.
Games.Achievements.unlock(mGoogleApiClient, "my_achievement_id");

If the achievement is of the incremental type (that is, several steps are required to unlock it), call increment() instead.
Games.Achievements.increment(mGoogleApiClient, "my_incremental_achievment_id", 1);

Hope this helps!


text:
Q: RX Objservable - .of() method does not exist from angular 2 beta So I'm quite new to Angular 2 and I have a question that I can't seem to find anywhere else online.
I'm trying to have some protected routes in my app.
I'm following some examples online. But I guess these example are based on Angular 2 beta.
There is a return function that has Observable.of(somevalue). This .of() method doesn't exist in RC i believe.
How can I make this work?
I will appreciate any help or thoughts.

A: You need to import:
import 'rxjs/observable/of';

or to import all at once
import 'rxjs/Rx';


text:
Q: Most efficient way to control a C++ instance through Lua? I'm currently coding a game in C++ with cocos2d-x, which comes bundled with tolua++, so I wanted to take advantage of that and have some functionalities be in Lua scripts. Eventually I'd like to expand how many functionalities will be controlled by script, but for now I'm just trying to have Lua scripts for enemy behavior, which seems like a good place to start.
Each enemy has a C++ Entity instance associated with it. As the game stands now, each enemy performs its behavior calculations on update(), but I'd like to change that so each enemy has a script or script function that represents its behavior, and that gets called on update(). I've come to the conclusion that there's essentially two ways of accomplishing this:

*

*Have one global function for each behavior, as pass the enemy instance as a parameter

*Have all enemy instances be tracked on Lua's side with a reference (or an instance ID) on the C++ side
I've already worked out how to implement solution #1. Here's my test:
C++:
lua_getglobal(L, "printNodePosition");
tolua_pushusertype(L, pNode, "CCNode");
lua_call(L, 1, 0);

Lua:
function printNodePosition(n)
    n:setPosition(66, 99)
    print ("Node position: " .. n:getPositionX() .. ", " .. n:getPositionY())
end

This works fine, the node position value gets altered as expected. However I can't help by feel that this seems a little bit hacky, and that maybe this could cause a serious overhead (there can be up to 50 enemies on screen at any time, each one of them calling the script on every tick.)
Solution #2 seems a bit more appropriate, but I can't figure out how to implement it. What do you guys think?
Thanks!

A: How you decide to handle this will largely depend on a sort of division of labor if you will. You will need to set clear and precise boundaries on who's taking care of what, otherwise you'll end up duplicating information on both sides, or worse. Some logic handled with C++, yet some other logic handled with Lua, but it isn't clear what divides the two.
Why track them on Lua's side, when they could be in Lua? If you're interested in expanding how much control Lua has over your engine, then all the better. Now's a good time to start moving over your data and logic.
I feel that this problem comes up because there are things that both C++ and Lua can handle, obviously, but it's not immediately clear which should handle what. I propose the following division, and I'd like you to tell me what you think.
C++

*

*Graphics

*Audio

*Networking

*Functions which need to be more efficient but can't be made any better in Lua.

Lua

*

*Everything else

To summarize this, keep a strict limit on having C++ handle things Lua couldn't do intrinsically, like platform-dependent features such as graphics, and let Lua take care of the rest. The one exception being that you find a critical point in your engine which absolutely must be made faster, and offload it to C++.
Imagine as if Lua is the main language where C/C++ libraries fill in the gaps, essentially.
That said, this may not be the best solution for all programs requiring scripting, but I think it's a decent one for your case of a game engine.

That aside, I'd like to share a rant written by the developer of LuaJIT on the topic of Design mistakes in mixed C/C++ and Lua projects in response to the scenario of 1. Not truly choosing a language to implement the project in (eg., too much mixing between the 2 languages).


text:
Q: how to make menu always open and close when scrolling in tailwind css I'm developing a website using Tailwind. I want to make Level 2 of navigation menu to always open and close when scrolling down. I tried to use display: block, but what I've got, it's overridden the flex rule. I did use a ternary code inside "ul" tag but it's not working.
Please see the screenshot of my expectation:

Currently, I placed the open class inside ul tag, trying to make the Level 2 to always open. I really appreciate your inputs

@tailwind base;
@tailwind components;
@tailwind utilities;

.work-sans {
    font-family: 'Work Sans', sans-serif;
}

#menu-toggle:checked + #menu {
    display: block;
}

.hover\:grow {
    transition: all 0.3s;
    transform: scale(1);
}

.hover\:grow:hover {
    transform: scale(1.02);
}

.carousel-open:checked + .carousel-item {
    position: static;
    opacity: 100;
}

.carousel-item {
    -webkit-transition: opacity 0.6s ease-out;
    transition: opacity 0.6s ease-out;
}

#carousel-1:checked ~ .control-1,
#carousel-2:checked ~ .control-2,
#carousel-3:checked ~ .control-3 {
    display: block;
}

.carousel-indicators {
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    bottom: 2%;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 10;
}

#carousel-1:checked ~ .control-1 ~ .carousel-indicators li:nth-child(1) .carousel-bullet,
#carousel-2:checked ~ .control-2 ~ .carousel-indicators li:nth-child(2) .carousel-bullet,
#carousel-3:checked ~ .control-3 ~ .carousel-indicators li:nth-child(3) .carousel-bullet {
    color: #000;
    /*Set to match the Tailwind colour you want the active one to be */
}

.mega-menu {
    display: none;
    left: 0px;
    position: absolute;
    text-align: left;
    width: 100%;
}

.mega-menu > .open {
    height: auto!important;
    visibility: visible!important;
}

.hoverable {
    position: static;
}

.hoverable > a:after {
   content: "\25BC";
   font-size: 10px;
   padding-left: 12px;
   position: relative;
   top: -1px;
}

.hoverable:hover .mega-menu {
   display: flex;
}

                            Shop

                                    Prams & Strollers

Baby Carriers

Nursey

Feeding

Bundles

Capsules

Accessories

Need help deciding?

                            Demonstrations

                                    Demos on Demand

In-Person

Events & Expos

Live Q&A

                            About Us

                                    For Purpose

Our Origins

Why Redsbaby?

                    Redsbaby

                Need help?

                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg>

                    <svg class="fill-current hover:text-black" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                        <circle fill="none" cx="12" cy="7" r="3" />
                        <path d="M12 2C9.243 2 7 4.243 7 7s2.243 5 5 5 5-2.243 5-5S14.757 2 12 2zM12 10c-1.654 0-3-1.346-3-3s1.346-3 3-3 3 1.346 3 3S13.654 10 12 10zM21 21v-1c0-3.859-3.141-7-7-7h-4c-3.86 0-7 3.141-7 7v1h2v-1c0-2.757 2.243-5 5-5h4c2.757 0 5 2.243 5 5v1H21z" />
                    </svg>

                    <svg class="fill-current hover:text-black" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                        <path d="M21,7H7.462L5.91,3.586C5.748,3.229,5.392,3,5,3H2v2h2.356L9.09,15.414C9.252,15.771,9.608,16,10,16h8 c0.4,0,0.762-0.238,0.919-0.606l3-7c0.133-0.309,0.101-0.663-0.084-0.944C21.649,7.169,21.336,7,21,7z M17.341,14h-6.697L8.371,9 h11.112L17.341,14z" />
                        <circle cx="10.5" cy="18.5" r="1.5" />
                        <circle cx="17.5" cy="18.5" r="1.5" />
                    </svg>

A: I managed to add the functionalities by using Alpine JS. I added as per below:

      Shop
       <button @click="open = !open" class="flex items-center justify-between pb-3 text-gray-500 hover:text-gray-700 focus:outline-none">

               <svg class="w-4 h-4" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path x-show="! open" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" style="display: none;" />
                   <path x-show="open" d="M19 9L12 16L5 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                   </path>
                </svg>

         </button>

           Prams & Strollers
           Nursey
           Feeding
           Bundles
           Capsules
           Accessories
           Need help deciding?

Read Alpinejs doc here : https://alpinejs.dev/directives/data


text:
Q: how to find this with regex
Possible Duplicate:
What is the best regular expression for validating email addresses?

Hi
How can I find emails with regex ?

"sdafsad@asdfsa.com"
"sdaf-sad@asdfsa.com"
"sdaf-sad@asdfsa.com"
"sdaf-sad@asdf-sa.com"
"sdaf_sad@asdf-sa.com"

Also how can I find this items :

track0; (any track number);
track50 (any track number);
Track 0 (any track number);
Track 10 (any track number);
Track10 (any track number);

A: \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
found on http://www.regular-expressions.info/email.html

A: 1) Straight from Microsoft: How to match a pattern by using regular expressions and Visual C#
using System.Text.RegularExpressions;
Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>.+)");
Match m = emailregex.Match(s);

2) Do you want to validate all entries with that format or do you just want to get that "(any track number)" value?

A: First one, try searching or use Regular Expression Library
Second, try this:
Regex regex = new Regex(@"[^\d]+\d");


text:
Q: Built in function that returns the type of its input I'm beginning to learn pascal, and for the life of me can't find a simple function that returns the type of its input.
If any of you know Python, then the function I'm looking for is the equivalent of type(object).
Thank you for your help, I'm really surprised at how this wasn't easily findable.

A: You can't get there from here.  Pascal doesn't have introspection.
Either the function accepts a type or it doesn't it can't guess the type of its argument.  In pascal types are fixed at compile time, so there's no need for a function that can recognise objects.

A: As said in a previous answer, Object Pascal is statically typed so you don't need this. However for objects (classes) you have the equivalent of isinstance() with the is operator.
program isop;

type
  TFoo = class(TObject)
  end;
  TBar = class(TObject)
  end;
  TBaz = class(TBar)
  end;

var
  Obj1, Obj2, Obj3: TObject;
  Baz: TBaz;
begin
  Obj1 := TFoo.Create;
  Obj2 := TBar.Create;
  Obj3 := TBaz.Create;

  writeln(Obj1 is TFoo);
  writeln(Obj1 is TBar);
  writeln(Obj1 is TBaz);
  writeln(Obj2 is TFoo);
  writeln(Obj2 is TBar);
  writeln(Obj2 is TBaz);
  writeln(Obj3 is TFoo);
  writeln(Obj3 is TBar);
  writeln(Obj3 is TBaz);

  if Obj1 is TBaz then // false
    Baz := TBaz(Obj1);
  // or
  if Obj3 is TBaz then // true
    Baz := Obj3 as TBaz;
end.

In some case (like here) you only know that instances are TObject (common ancestor for all classes). So you can dynamically cast later to the right class type after a verification with is.


text:
Q: Proving discontinuity of a piecewise function using $\delta-\epsilon$ definition $\text { Let } f: \mathbb{R} \rightarrow \mathbb{R} \text { be defined by } f(x)=\left\{\begin{array}{ll}
0 & \text { if } x \leq 0 \\
1 & \text { if } x>0
\end{array}\right.$
I am trying to prove that this function is discontinuous at $0$. Is the following correct?
Set $\epsilon:= a \in [0,1]$. Consider an arbitrary $\delta>0$. Set $x:=\delta - w >0, w>0$. Then $|x|<\delta$ and $|f(x)|=1 \geq a$.

A: To begin with, let us stress the definition of continuity on the real line.
We say the function $f:X\to Y$, where $X\subseteq\mathbb{R}$ and $Y\subseteq\mathbb{R}$, is continuous at $a\in X$ iff
\begin{align*}
(\forall\varepsilon >0)(\exists\delta_{\varepsilon}>0)(\forall x\in X)(|x - a| < \delta_{\varepsilon} \Rightarrow |f(x) - f(a)| < \varepsilon)
\end{align*}
We are now able to deny it to obtain the definition of discontinuity.
We say that a function $f:X\to Y$ (in the same conditions as above) is discontinuous at $a\in X$ iff
\begin{align*}
(\exists\varepsilon > 0)(\forall\delta > 0)(\exists x\in X)((|x - a| < \delta)\wedge(|f(x) - f(a)| \geq \varepsilon))
\end{align*}
In the present case, $a = 0$. Thus it suffices to take $\varepsilon = 1/2$ to make things work.
Indeed, for such value of $\varepsilon$, no matter which value for $\delta > 0$ one chooses, it is enough to consider an $x\in(-\delta,0)$ to obtain $|x - 0| < \delta$ and $|f(x) - f(0)| = |0 - 1| = 1 \geq \varepsilon$.
Hopefully this helps!


text:
Q: Principal bundles on 3-manifolds If G is a simply connected Lie Group then why is every G-bundle over an orientable 3-manifold trivial? (Why is orientability important?)

A: Are you sure that orientability is necessary? The result is proved in lemma 4.1.1.  here and I do not see where orientability is used.


text:
Q: Unit & magnitude of NTP / ntpdate I have a cluster of 10 virtualized ubuntu servers. For all of them, I installed the ntp-Daemon. Since I currently running some time sensitive experiments, I am interested in the offsets between my nodes.
I found that the command ntpdate can be used to obtain offsets between the machine clocks. However,running from the first node nodeA0, the command gives:
ubuntu@nodeA0:~$ sudo ntpdate -q nodeA0 nodeA1 nodeA2 nodeA3 nodeA4 nodeA5 nodeA6 nodeA7 nodeA8 nodeA9
server 192.168.1.75, stratum 3, offset -0.000016, delay 0.02570
server 192.168.1.93, stratum 3, offset -0.000190, delay 0.02725
server 192.168.1.245, stratum 3, offset -0.000390, delay 0.02623
server 192.168.1.63, stratum 2, offset -0.000917, delay 0.02646
server 192.168.1.61, stratum 3, offset 0.000015, delay 0.02692
server 192.168.1.107, stratum 2, offset -0.002031, delay 0.02669
server 192.168.1.132, stratum 3, offset -0.000462, delay 0.02655
server 192.168.1.175, stratum 3, offset -0.000317, delay 0.02719
server 192.168.1.92, stratum 3, offset -0.000237, delay 0.02638
server 192.168.1.98, stratum 3, offset -0.000586, delay 0.02786
 1 Feb 10:33:21 ntpdate[3214384]: adjust time server 192.168.1.63 offset -0.000917 sec

My questions:

*

*As the offset gives the clock differences between the machines, I wonder, what unit that is? milliseconds or seconds? In the manpages, I couldn`t find any information regarding that.

*Asssuming the unit is milliseconds: Then I would have an offset of 0.016 ms for nodeA1 (the first). This seems too short - I read somewhere that NTP accuracy is in the magnitude of tens of milliseconds.

*Did I do anything wrong? Or what would be the optimal way to measure clock differences between two servers?

Edit: The command ntp -qd gives:
ubuntu@nodeA0:~$ ntpq -qn
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 0.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 1.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 2.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 3.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 ntp.ubuntu.com  .POOL.          16 p    -   64    0    0.000    0.000   0.000
*217.91.44.17    192.168.100.15   2 u   36  256  377   11.388    0.222   0.153
-162.159.200.1   10.100.8.32      3 u   81  128  377    7.829   -0.107   1.089
+80.153.195.191  192.168.100.15   2 u   92  128  377   14.382   -0.056   0.379
+144.76.43.40    213.239.239.164  3 u  109  128  377    7.119    0.331   0.440
-194.35.12.189   131.188.3.220    2 u  108  128  377    5.618   -0.213   0.192


text:
Q: Can somebody explain these entries in my sudoers file? What is going on in my sudoers file? I have no idea who the
FULLTIMERS = millert, mikef, dowdy

are or what these IP addresses
Host_Alias CUNETS = 128.138.0.0/255.255.0.0
Host_Alias CSNETS = 128.138.243.0, 128.138.204.0/24, 128.138.242.0

are? Has somebody tampered with the file?
PS: Full file below
#
# Sample /etc/sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.

##
# Override built-in defaults
##
Defaults    env_reset
Defaults    env_keep += "BLOCKSIZE"
Defaults    env_keep += "COLORFGBG COLORTERM"
Defaults    env_keep += "__CF_USER_TEXT_ENCODING"
Defaults    env_keep += "CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE"
Defaults    env_keep += "LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME"
Defaults    env_keep += "LINES COLUMNS"
Defaults    env_keep += "LSCOLORS"
Defaults    env_keep += "SSH_AUTH_SOCK"
Defaults    env_keep += "TZ"
Defaults    env_keep += "DISPLAY XAUTHORIZATION XAUTHORITY"
Defaults    env_keep += "EDITOR VISUAL"
Defaults    env_keep += "HOME MAIL"

Defaults    lecture_file = "/etc/sudo_lecture"

##
# User alias specification
##
# User_Alias    FULLTIMERS = millert, mikef, dowdy

##
# Runas alias specification
##
# Runas_Alias   OP = root, operator

##
# Host alias specification
##
# Host_Alias    CUNETS = 128.138.0.0/255.255.0.0
# Host_Alias    CSNETS = 128.138.243.0, 128.138.204.0/24, 128.138.242.0
# Host_Alias    SERVERS = master, mail, www, ns
# Host_Alias    CDROM = orion, perseus, hercules

##
# Cmnd alias specification
##
# Cmnd_Alias    PAGERS = /usr/bin/more, /usr/bin/pg, /usr/bin/less

##
# User specification
##

# root and users in group wheel can run anything on any machine as any user
root        ALL = (ALL) ALL
%admin      ALL = (ALL) ALL

## Read drop-in files from /private/etc/sudoers.d
## (the '#' here does not indicate a comment)
#includedir /private/etc/sudoers.d

A: This is the off-the-mill standard sudoers file which gets installed by default and contains some examples about potential configurations. Any line starting with # is a comment and doesn't enable anything. So at least from looking at the file you've included in the question it doesn't seem as if somebody has tampered with it.

A: It says right at the top…
# Sample /etc/sudoers file.
The lines you expressed concern over are commented out with the # character and are only presented as examples so you can see the correct syntax to create your own entries.


text:
Q: How do I set idle timeout on SQL Report server (SSRS) I am trying to stop the service going into shutdown, so that next time its used, it doesnt take 2 mins to load.
Unfortunately I cannot find where to alter such settings, as the report server to my suprise is NOT hosted on IIS. It has some sort of native host.
How can I edit the timeout. Below is what an IIS timeout setting looks like.

A: I would create a simple "Warmup report", then schedule it to run every 30 minutes or so.


text:
Q: haskell fromInteger with multiple data constructors I am looking for a solution that is quite generic I think. My goal is to find a clean way to do operations on Points (coordinates), either in 2D or 3D. my data Point is an instance of Num that gives functions to do basics maths operations.
data Point = Point2D Float Float
       | Point3D Float Float Float deriving Show

add :: Point -> Point -> Point
add (Point2D xa ya) (Point2D xb yb) = Point2D (xa+xb) (ya+yb)
add (Point3D xa ya za) (Point3D xb yb zb) = Point3D (xa+xb) (ya+yb) (za+zb)

divT (Point2D x y) v = Point2D (x / v) (y / v)
divT (Point3D x y z) v = Point3D (x / v) (y / v) (z / v)

fromIntegerP :: Integer -> Point
fromIntegerP v = Point2D (fromIntegral v) 0
--fromIntegerP v = Point3D (fromIntegral v) 0 0

instance Num Point where
    (+) = add
    fromInteger = fromIntegerP

p2D1 = Point2D 1.0 2.0
p2D2 = Point2D 4.0 5.0
p3D1 = Point3D 1.0 2.0 3.0
p3D2 = Point3D 6.0 6.0 6.0

main = do
    putStrLn . show $ sum [p2D1,p2D2]
    putStrLn . show $ sum [p3D1,p3D2]

This code outputs :
Point2D 5.0 7.0
*** Exception: pointStackoverflow.hs:(5,1)-(6,75): Non-exhaustive patterns in function add

... because every Point.fromInteger produces a Point2D, even if we expect a Point3D. I would like to have a way to say in "instance Num Point" that if a Point2D is needed then fromInteger is fromIntegerToPoint2D else fromIntegerToPoint3D. But I don't know how to make a choice based on the return type.
Any hint ? Thank you

A: You want to make Point2D and Point3D be different types, not different constructors for the same type.
Start with this and fill out the definitions:
data Point2D = Point2D Float Float
data Point3D = Point3D Float Float Float

instance Num Point2D where
    fromInteger = ...
    (+) = ...

instance Num Point3D where
    fromInteger = ...
    (+) = ...

A: Here is one solution :
class Point a where
    add :: a -> a -> a
    fromIntegerP :: Integer -> a

data Point2D = Point2D Float Float deriving Show
data Point3D = Point3D Float Float Float deriving Show

instance Point Point2D where
    add (Point2D xa ya) (Point2D xb yb) = Point2D (xa+xb) (ya+yb)
    fromIntegerP v = Point2D (fromIntegral v) 0

instance Point Point3D where
    add (Point3D xa ya za) (Point3D xb yb zb) = Point3D (xa+xb) (ya+yb) (za+zb)
    fromIntegerP v = Point3D (fromIntegral v) 0 0

instance Num Point2D where
    (+) = add
    fromInteger = fromIntegerP

instance Num Point3D where
    (+) = add
    fromInteger = fromIntegerP

p2D1 = Point2D 1.0 2.0
p2D2 = Point2D 4.0 5.0

p3D1 = Point3D 1.0 2.0 3.0
p3D2 = Point3D 6.0 6.0 6.0

main = do
    putStrLn . show $ sum [p2D1,p2D2]
    putStrLn . show $ sum [p3D1,p3D2]

I am still looking for improvements (instance Num Point2D where and instance Num Point3D where) but it works !


text:
Q: Create one aar from multi module library in android I have the following modules in my aaplication
Module
-app

-library_1

-library_2

the module library_1 'has dependecy of library_2
build gradle library_1
dependencies {
api project(":library_2")
}

When I build the project I get the aar which I put in my app module
dependencies {
implementation files('libs/library_1-debug.aar')
}

Now when I run my app I get the exception java.lang.NoClassDefFoundError: Failed resolution of: Lcom/dinklo/library_2/LibraryB
The class LibraryB is defined in library_2 and being called from library_1
I am looking for a solution where I can get a single aar file for all the modules I have.

A: I ended up using third party library Fat-aar
In root build gradle
 classpath 'com.github.kezong:fat-aar:1.3.8'

In your library module
apply plugin: 'com.kezong.fat-aar'

dependencies{
embed project(path: ':lib-2', configuration: 'default')}

I have added a sample project on github will be useful for others
Fat-arr Sample - Github


text:
Q: iPhone project "No launchable executable present at path" I downloaded one of the sample apps for iOS and it gives me the above error.
No launchable executable present at path /Users/..../MyProject/build/Debug-iphonesimulator/MyProject.app
What i do have is the MyProject/build/MyProject.build/Debug-iphonesimulator/GeneratedResources.build/ some files.
No build errors.
When I see in the finder the directory is indeed not even present. What could be the problem ?
Update: Yes, i did try cleaning & deleting Build directory, doesn't help

A: Try opening the Info.plist and removing "executable name" value if it's filled with custom string instead of string variable (the one that should look like ${FOO_BAR}, but doesn't).

A: I had this problem.  it turned out I had the active target set incorrectly, in my case to a cocos library instead of to my own app.

A: I also had this same error code for my project. I was using a number in the Target -> Product Name.  Once I changed the Product Name of the target to letters only everything worked fine.

A: After trying the things mentioned here, also make sure you click on "Clean All Targets" then quit XCode and restart XCode. This fixed it for me and many others on the web!

A: I had the same problem. In my case, I had an additional target for the same project (which contained test libraries). At some point xCode always tried to launch the test binary, regardless of what binary it compiled.
Removing the pbxuser and perspective files (inside project.xcodeproj) solved it for me.


text:
Q: Get Simplygon UV Index I am currently converting our custom mesh format to simplygon, running a mesh reduction then converting back. The problem at the moment is that the UV number is skyrocketing after converting back to our format. I believe that the UVS are becoming unwelded.
I am using:
spRealArray texcoords = inGeom->GetTexCoords(i);

to get the texture coordinates, I am then using:
spRealData texcoords_xy = g_simplygonSDK->CreateRealData();
texcoords->GetTuple(j, texcoords_xy);

to get each texture coordinate.
But now I need to create a channel of each shared uv index instead of exporting everything as a seperate vertex. How do I find the UV index given a face and a vertex index.

A: Turns out you need to call: spPackedGeometryData PackedGeom = inGeom->NewPackedCopy();
This will pack the data for you. You can then use your code as normal.
spRidArray PackedVertexIds = PackedGeom->GetVertexIds();

will contain the properly packed indices now.