text:
Q: Email and log exceptions from an Azure Function I have an Azure function and I wrapped the logic in a try catch block.
I can log the exception to Azure, but I want save and then send the details of the exception to an email address. I see I can use Elmah.io but I have to pay a monthly subscription.
Doesn't Azure have a simple way to log the data and then send me an email?
Something like this
catch (Exception ex)
{
    log.Info($"Points Event Error: " + ex.Message);
    // send me email with details
}

A: The most Azure Function-ish way to do this would be to use Azure Functions SendGrid ouput binding.
You can follow the examples from that article, but instead of out parameter use ICollector / IAsyncCollector because you only need to send e-mails conditionally.
I believe Send Grid has a free tier available for low usage scenarios.

A: Rather than looking to leverage SendGrid to send you emails on Exceptions directly from your Function you could consider leveraging Functions' Application Insights integration. This will give you additional benefits (performance tracking, history of events, trace logging) in addition to being able to set Alerts based on Exceptions in Application Insights itself. It also means your monitoring / alerting isn't baked into your business logic in your Function.
Application Insights has a free tier that should suffice for most use cases.


text:
Q: Is there a way not to call SaveChanges so often in the case of a junction table for a many-to-many relationship? I need to have an extra field in the junction table of a many-to-many relationship, like so:
public class PersonCompany
{
    public int PersonId { get; set; }
    public int CompanyId { get; set; }
    public Person Person { get; set; }
    public Company Company { get; set; }
    public DateTime HireDate { get; set; }
}

with these 2 classes at the ends of the relationship:
public class Company
{
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<PersonCompany> PersonCompanies { get; set; }
}

public class Person
{
    public Person()
    {
        PersonCompanies = new List<PersonCompany>();
    }
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<PersonCompany> PersonCompanies { get; set; }
}

Yet when using it, I have to call SaveChanges on the context too many times for the primary and foreign keys to get their values, like in this example:
private static void AddPersonWithCompanies()
    {
        using (var context = new Context())
        {
            var person = new Person
            {
                LastName = "Dent",
                FirstName = "Juan",
                IsActive = false
            };
            context.People.Add(person);

            context.SaveChanges();

            var comp1 = new Company() { Name = "Universal" };
            var comp2 = new Company() { Name = "Lehmann" };

            context.Companies.Add(comp1);
            context.Companies.Add(comp2);

            context.SaveChanges();

            var pc1 = new PersonCompany() { Company = comp1, Person  = person, HireDate = DateTime.Today };
            var pc2 = new PersonCompany() { Company = comp2, Person=person, HireDate = DateTime.Today };

            person.PersonCompanies.Add(pc1);
            person.PersonCompanies.Add(pc2);

            context.SaveChanges();
        }
    }

I would like to have only one SaveChanges() at the end but can't seem to get it...
I get the following exception if these intermediate SaveChanges() are removed:

System.Data.Entity.Infrastructure.DbUpdateException
  HResult=0x80131501
  Message=Unable to determine the principal end of the 'Chapter3.CSharp.Company_PersonCompanies' relationship. Multiple added entities may have the same primary key.
  Source=EntityFramework
  StackTrace:
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at Chapter3.CSharp.Program.AddPersonWithCompanies() in C:\Users\Juan Dent\OneDrive\CSharp\Code First-Code Bundle\B03947_03_Code\Chapter3.CSharp\Program.cs:line 47
   at Chapter3.CSharp.Program.Main(String[] args) in C:\Users\Juan Dent\OneDrive\CSharp\Code First-Code Bundle\B03947_03_Code\Chapter3.CSharp\Program.cs:line 14

Any ideas?
Regards,
Juan

redpajama_set_name: RedPajamaStackExchange


text:
Q: SSL Certificate on Tomcat - Alias name(tomcat) does not identify a key I am working with an SSL certificate in Apache tomcat. I have created CSR and got a JKS file. Then when I have given the CSR to certificate authority, then they have given me the certificate. When I have tested the JKS certificate using the following command,
keytool -list -keystore ava_bankasia-bd_com.jks

I have got the following output:
Keystore type: PKCS12
Keystore provider: SUN

Your keystore contains 1 entry

tomcat, Jun 22, 2021, trustedCertEntry,
Certificate fingerprint (SHA-256): 7F:F3:C5:60:D1:E6:E5:04:2A:E8:2E:D1:D7:1A:92:DE:39:47:75:BD:06:25:0D:D0:CB:C0:55:BA:D6:2B:28:E9

Then I have configured the tomcat with the following code:
<Connector port="443"
           protocol="org.apache.coyote.http11.Http11Protocol"
           SSLEnabled="true"
           maxThreads="150"
           scheme="https"
           secure="true"
           clientAuth="false"
           sslProtocol="TLS"
           keystoreFile="/u01/csr_certificate/ava_bankasia-bd_com.jks"
           keystorePass="-------"
           keyAlias="tomcat" />

I have imported them all into the Keystore ok (but obviously not!) but the error I'm getting from Tomcat is: 'java.io.IOException Alias name does not identify a key entry. The full error is as follows:
org.apache.catalina.LifecycleException: Protocol handler initialization failed
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:1076)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
        at org.apache.catalina.core.StandardService.initInternal(StandardService.java:552)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
        at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:846)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:639)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:662)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:302)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:472)
    Caused by: java.lang.IllegalArgumentException: Alias name [tomcat] does not identify a key entry
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:100)
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:72)
        at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:247)
        at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:1143)
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.init(AbstractJsseEndpoint.java:222)
        at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:599)
        at org.apache.coyote.http11.AbstractHttp11Protocol.init(AbstractHttp11Protocol.java:80)
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:1074)
        ... 13 more
    Caused by: java.io.IOException: Alias name [tomcat] does not identify a key entry
        at org.apache.tomcat.util.net.SSLUtilBase.getKeyManagers(SSLUtilBase.java:336)
        at org.apache.tomcat.util.net.SSLUtilBase.createSSLContext(SSLUtilBase.java:245)
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:98)
        ... 20 more

Any ideas? This is the first time I've done this so maybe I've messed up something blindingly obvious?
The site works fine on port 80.
Would LOVE to hear some suggestions :)


text:
Q: Conversion Of Map Location To String Below is the code i am running with all other.. Its running perfectly adn its showing all the desired locations on map.
But what i want now is to store all the marked locations in such a way that i can show them as   a list on a new page.
I am not able to retrieve the resulted location from map in the form of some string or may be something else which can be displayed as a list ...
       private void Button_Click_3(object sender, RoutedEventArgs e)
       {

        MapsTask mapsTask = new MapsTask();
        string search = "Coffee";
        mapsTask.SearchTerm = search;
        mapsTask.ZoomLevel = 2;
        mapsTask.Show(); }

A: The MapsTask does not return any information.
If you're looking to get Points of Interest for a given location, you may have to use an external service such as the HERE Places API.


text:
Q: Can connect to some routers but not others 14.04 New Acer Aspire laptop, Ubuntu 14.04. Works great on wifi or wired connection, with one exception: I can't connect to my TP-Link TL-WR702N router, neither wired nor wirelessly.  Ubuntu sees the wireless AP and will let me enter the password, but will just churn a while and then not connect. If I plug the laptop into the Ethernet port, it does basically the same thing, just churns a while (meaning that the little wifi icon throbs and then goes to outline).  The router works fine for other computers, my tablet, phone, etc. The laptop works fine with other routers.  What could be the difference?

A: I had a similar issues with some routers on my end the only way I was able to connect was by changing the mac address even though there was not any filter by mac set up on the router. I used macchanger, to install simply open a terminal and type:
sudo apt-get install macchanger

And to assign a new one simply run:
sudo macchanger -a [interface you want to change (in my case wlan0)]

Make sure the interface is down at the moment you assign the new mac address you can do so by simple unchecking the options enable networking/wifi from the network manager menu.


text:
Q: Efficacy of peer monitoring in Akka I am trying to wrap my brain around Akka and after reading the 2.3.11 dev guide am still a bit confused about Actor monitoring. I essentially have two main concerns:

*

*The messaging that occurs when a watched actors dies or is restarted; and

*The necessity or usefulness of "peer monitoring" in the first place

When I context.watch(someActorRef), I am confused about the messaging I receive when someActorRef dies or is restarted. Do I get a Terminated message or a DeathPactException?
To me, monitoring is really a form of supervision, and so it only makes sense for a supervisor/parent actor to watch a child actor, however I believe the API takes care of this supervision automagically under the hood via supervisor strategy. So it seems like watch/unwatch are there for non-supervisor actors to...well...supervise other actors that aren't their children. So I'm concerned about why I would want to use these API facilities in the first place, to monitor what is essentially another "peer actor".


text:
Q: Cloning HTML and replacing the content id according to the tab selected I have three Tabs "B1", "B2", and  "B3". I want to clone this HTML and load it as the content of three tabs with ids id = "bv-B1-p1", id = "bv-B2-p1", and id = "bv-B3-p1" (i.e. replacing -brand- with B1 , B2 or B3 in accordance with the tab selected).

Static Tab

+

        Add New Image

A: You can use the following code to create divs using jQuery:
CODE:

var brand = 3;
$(document).ready(function() {
    for (var i = 1; i <= brand; i++) {
        $('#test').append('
TESTING
');
    }
});

function checkid(c) {
    var id = c.id;
    alert(id);
}

For example look into the following fiddle:
http://jsfiddle.net/QshmC/1/
Once you click on the divs it will display the id of clicked div.


text:
Q: Как добавить новый document.title = "Новое сообщение!" когда приходит новое сообщение? У меня в чате сделано оповещение конкретному юзеру на JS. Звук реагирует на изменение id в базе и цифры выводятся в самом верху. Хочу, чтобы со звуком менялся title, например когда юзер свернул вкладку, или находится в другом окне. пробовал добавить
var content = document.getElementById('content').value;
document.title = content;

Но не хочет работать с этим кодом:

<audio id="audio-new-message" src="notify.ogg"  ></audio>


text:
Q: Does a constant transition intensity mean that every transition between states increases as time increases? I'm struggling to understand what one of the key assumptions of a Markov survival model. There are three key assumptions stated:
Take for example a simple HSD model (Where state 1 denotes healthy, state 2 denotes Sick and state 3 denotes dead), $x$ in the subscript denotes the age of the individual being observed.
1) The probability of death in a short period of time $\hat{t} \approx \phi_{x+t}^{12}*\hat{t}$ (For $\phi_{x+t}^{12}$ denoting the transition intensity between states 1 and 2)
2)Markov Property
3) For some t, where $0\leq t\leq1$, constant transition intensity is assumed. This means that $\phi_{x+t}^{12} = \phi_{x}^{12}$, for some integer age $x$.
I read that as a result of this third assumption, as you view increasing ages, the force increases each year. ( $\phi_{x}^{12} < \phi_{x+1}^{12} <...<\phi_{x+n}^{12},  n\in \mathbb{Z}^{+}) $.
My question is, does making this assumption  (3) mean that for other transitions (say $\phi_x^{21}$), the same would occur? And I ask if there is an underlying issue with this because I am curious whether this means if you have a state where clearly the opposite will happen ( $\phi_{x}^{ab} > \phi_{x+1}^{ab} >...>\phi_{x+n}^{ab}$), you are making the assumption that the opposite happens in the case of this Markov Survival model...


text:
Q: linux/unix: script starting some command if some directory tree exists I'm a linux newbie, so pardon me if you don't understand me :)
I have a problem that I need to run a command chmod 777 XXX (XXX is directory) but I cant login to it, but I can push UNIX script which will be executed to do this. But the problem is that I don't know in which path this script is started/placed :).
IN DETAIL: I need script which will check if relative path (directory tree) CCCC/YYY/XXX exists on this machine somewhere and if it exists following command needs to be started on this directory chmod 777 XXX.  (XXX should be resolved to absolute path :))
I did some test with find, but no real result.

A: The locate command will help you here:
path_part=CCCC/YYY/XXX
if output=$( locate "$path_part" 2>/dev/null ); then
    grep "$path_part$" <<< "$output" |
    while IFS= read -r dir; do
        # do something in "$dir"
    done
fi

locate requires you to run updatedb -- your system may run it already periodically.


text:
Q: How to remove or edit title bar when nativescript app runs on android platform i've tried in every way to call the requestWindowFeature method, first inside a page script (but raised a very nice error), second on app js, working inside application.launchEvent closure:

    var application = require("application");
    application.mainModule = "main-page";
    application.cssFile = "./app.css";

    application.on(application.launchEvent, function (args) {
        if (args.android) {
        // How to work with android activity in this closure?
        }
    });

application.start();
I was not able to get an android activity instance in order to hide the default title bar.
Assuming that the "launchEvent" event it is assimilable to "onCreate" event, is there a way to get the android activity in this context? Or is necessary to assume that it isn't the proper way in order to achieve the goal?

A: For the time being you can try this:
application.on(application.launchEvent, function (args) {
    if (application.android) {
        var activity = application.android.startActivity;
        // Do something with activity...
    }
});

Our next release will include Android Activity Events. Here is the pull request.


text:
Q: Godaddy не отправляет письмо Добрый день, godaddy не отправляет письма, пробовал на другом хостинге все путем, подскажите пожалуйста в чем может быть проблема? Код отправки привожу ниже.
ini_set('SMTP', 'relay-hosting.secureserver.net');

$file = "./tmp/file.pdf"; // файл
$mailTo = $email; // кому
$from = '****@*****.com'; // от кого
$subject = "Test file"; // тема письма
$message = "Тестовое письмо с вложением"; // текст письма

$separator = "---"; // разделитель в письме
// Заголовки для письма
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: $from\nReply-To: $from\n"; // задаем от кого письмо
$headers .= "Content-Type: multipart/mixed; boundary=\"$separator\""; // в заголовке указываем разделитель
// если письмо с вложением
if($file){
    $bodyMail = "--$separator\n"; // начало тела письма, выводим разделитель
    $bodyMail .= "Content-type: text/html; charset='utf-8'\n"; // кодировка письма
    $bodyMail .= "Content-Transfer-Encoding: quoted-printable"; // задаем конвертацию письма
    $bodyMail .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode(basename($file))."?=\n\n"; // задаем название файла
    $bodyMail .= $message."\n"; // добавляем текст письма
    $bodyMail .= "--$separator\n";
    $fileRead = fopen($file, 'r');
    $contentFile = fread($fileRead, filesize($file)); // считываем его до конца
    fclose($fileRead); // закрываем файл
    $bodyMail .= "Content-Type: application/octet-stream; name==?utf-8?B?".base64_encode(basename($file))."?=\n";
    $bodyMail .= "Content-Transfer-Encoding: base64\n"; // кодировка файла
    $bodyMail .= "Content-Disposition: attachment; filename==?utf-8?B?".base64_encode(basename($file))."?=\n\n";
    $bodyMail .= chunk_split(base64_encode($contentFile))."\n"; // кодируем и прикрепляем файл
    $bodyMail .= "--".$separator ."--\n";
// письмо без вложения
}
$result = mail($mailTo, $subject, $bodyMail, $headers);


text:
Q: Путь к выбранному файлу из JList Есть список JList отображающий файлы определенного диска на компе. Выбираю определенный файл или папку
File root = new File(list.getSelectedValue().toString());

Получаю его имя. Хочу получить полный путь к выбранному файлу на диске вместе с именем.
Пробую так:
root.getAbsolutePath()

Выдает папку проекта\выбранная папка... Это мне не подходит:(
Подскажите как правильно получить полный путь к выбранному в списке файлу?

A: Если этот код дает вам не тот путь, который вы ожидаете:
File file = new File(list.getSelectedValue().toString());
file.getAbsolutePath();

Еще есть getPath() и getCanonicalPath() помимо getAbsolutePath().
Попробуйте следующий, с помощью Path API:
Path path = Paths.get(list.getSelectedValue().toString());
Path folder = path.getParent();

Ссылка на источник:

*

*Get the filePath from Filename using Java (path.getParent)

*Get the filePath from Filename using Java (file.getAbsolutePath)

*Java File Path, Absolute Path and Canonical Path
Немного из крайнего источника с переводом на русский:

getAbsolutePath() - возвращает абсолютный путь к файлу. Если файл
  создан с абсолютным именем пути, он просто возвращает имя пути. Если
  файл создается с использованием относительного пути, абсолютное имя
  пути замещается зависящим от системы образом.
В системах UNIX относительный путь становится абсолютным, замещая его
  текущим каталогом пользователя.
В системах Microsoft Windows относительный путь становится абсолютным,
  замещая его текущим каталогом диска, названного именем пути, если
  таковой имеется, а если нет, он замещается на текущий каталог
  пользователя.

А также:

*

*What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

*Getting the Current Working Directory in Java

*System Properties
Можно склеить полученный путь и путь к текущей рабочей директории - так получится полный путь, начиная с корневого каталога.


text:
Q: How to make outputstream make a file if it doesn't exist? I have a problem with creating an outputstream file.
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();

It worked fine, until I made another method:
public void actionPerformed (ActionEvent e) //When a button is clicked
{
   if (e.getSource() == encrBtn)
   {
        menu.setVisible(false);
      createProfile();
      menu.setVisible(true);
   }
   else
   {
      if (e.getSource() == decrBtn)
      {
         menu.setVisible(false);
         viewProfile();
        menu.setVisible(true);
      }
      else
      {
         if (e.getSource() == exitBtn)
         {
            JOptionPane.showMessageDialog(null, "Goodbye!");
        System.exit(0);
         }
      }
   }
}

Previously, I put throws Exception at the start of each method that calls upon the
createprofile();

method (in which the output stream is). But now I get
ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2     cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
           ^
overridden method does not throw Exception

Previously, I was wondering if there was another way to throw the exception: cannot implement actionPerformed(ActionEvent) in ActionListener
But now I think that it would be better to somehow force the outputstream to make the file. I have googled multiple phrasings of this, but I do now know how to do this... the things I found did not work either.

A: The ActionListener interface does not declare it's actionPerformed method as throwing any type of Exception, you can not change this signature.
You need to catch and manage the exception from within the method.
public void actionPerformed(ActionEvent e) //When a button is clicked
{
    if (e.getSource() == encrBtn) {
        menu.setVisible(false);
        try {
            createProfile();
        } catch (Exception exp) {
            exp.printStackTrace();
            JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE);
        }
        menu.setVisible(true);
    } else {
        //...
    }
}

FileOutputStream is capable of creating the file if it does not exist, but may have issues if the path doesn't or if you don't have adequate permissions to write to the specified location or any number of other possible issues...

A: You're getting a type mismatch. The ActionListener interface's actionPerformed method does not include a throws Exception clause, therefore you can't include one on the method you override. A simple fix is to catch any Exception thrown, and re-throw it as a RuntimeException. Since RuntimeExceptions are unchecked, you don't need to include it in the throws clause.
public void actionPerformed (ActionEvent e) //When a button is clicked
{
  try { // <-- Added try block
     if (e.getSource() == encrBtn)
     {
          menu.setVisible(false);
        createProfile();
        menu.setVisible(true);
     }
     else
     {
        if (e.getSource() == decrBtn)
        {
           menu.setVisible(false);
           viewProfile();
          menu.setVisible(true);
        }
        else
        {
           if (e.getSource() == exitBtn)
           {
              JOptionPane.showMessageDialog(null, "Goodbye!");
          System.exit(0);
           }
        }
     }
  }
  catch (Exception e) { // <-- Catch exception
    throw new RuntimeException(e); // <-- Re-throw as RuntimeException
  }
}

It's usually better to actually handle the exception if possible, but if you just want to see the exception (e.g. for debugging), then I'd say wrapping it in a RuntimeException and re-throwing it is a little cleaner than just adding throws Exception on the end of all your method signatures. It's also better if you can narrow the type of Exception in the catch block down to the actual exception types you're expecting.


text:
Q: what is do(keyword) c++? I never knew there was a keyword, do, in c++!
what is it?

A: Well its used with while keyword:
do {
   ...
} while(foo)

Unlike a for loop a do-while loop is always executed at-least once.
Also note that do { } while(0) is a commonly used idiom in Linux kernel, see this faq for details.

A: It is a looping tool. Sometimes you need a loop that executes at least once. This is when you use a loop such as
do {
/* Code will always be executed at least once */
/* something needed to be done once or more times */
} while ( /* not done /* )

where as
while( /* not done */) {
 /* this code may never be executed */
}

A: It's a loop:
do {
...
} while(someCondition);

A: It is same a while statement (except for the syntax), however if you use a do..while loop, it gurantees that the loop is executed atleast once even if the condition specified in while doesn't satisfy.

A: do keyword is used in the do...while loops. It is like the while loop, the difference is that in the do...while loop condition is checked after the loop execution.

A: do while is usable to executes a statement repeatedly until the specified termination condition (the expression) evaluates to zero.

do    statement    while ( expression
  ) ;

look at this


text:
Q: creating a client-server TCP connection in node : socket.io or net module I'm newbie to node and I would like to create a TCP  connection between client and server using node.js. I already have an http server built on node and which sends/pulls data to and from the client. Now, I need to add this 'connection' oriented concept.
I've been reading tutorials and forums and I'm little confused.
If I understood well, there are two ways of creating such connection:

*

*upgrading my already existing http server to a socket.IO server
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
function handler(req, res){
   //code
}
app.listen(8080);

*creating a separate TCP server based on net module then establish a connection between this TCP server and the http server like is suggested here Create WebSockets between a TCP server and HTTP server in node.js
var net = require('net');
net.createServer(function (socket) {
   socket.write('Hello World!\r\n');
   socket.end();
 }).listen(1337);

So, when do we need to create 2 separate TCP and HTTP servers and when do we need to have only one server (upgrade an HTTP server to a socket.IO one) ?

A: If your clients are browsers, then your only option is to use WebSockets (socket.io provides such an implementation).
Browsers do not have an API that you can use to open raw TCP sockets, which is what the net module gives you.

A: WebSockets don't have anything to do with TCP connections (other than that they use them).  If you just want to open up a regular TCP connection, the built in net package is what you're looking for.
Socket.IO is an RPC package that uses either WebSockets or emulated WebSockets over other transports such as long-polling JSON.


text:
Q: How can I do a loop in the loop i want to do a exit when I want to do a loop in python and how can i do a exit when?
In Turing what I want is
loop
    put " Voulez vous jouer au 6-49 si oui entrez 'commencer' et n'oubliez pas qu'une "
    put " partie coute 3$ " ..
    color (green)
    get word
    color (black)

    %Je clear l'ecrant
    cls
    put " Chargement en cour."
    delay (500)
    cls
    put " Chargement en cour.."
    delay (500)
    cls
    put " Chargement en cour..."
    delay (500)
    cls

    %Je fais certain que le joueur a ecrit commencer
    %Si il entre quelque choses d'autre que commencer le programme ne commence pas il demander de entre le mot commencer

    exit when word = "commencer"
end loop

Now I need to do in Python but I don't know how to do that can someone help me out plzzz????

A: If I understand the semantics of the Turing code,
while True:
    ...
    if word == "commencer":
        break


text:
Q: Weird slow uplink problems on my home Debian router and new fast connection Yesterday I got a new and shiny VDSL2 connection home! It's specced at 100Mbit/10Mbit, and seems to deliver pretty close to the mark.
Now, I have a Debian squeeze linux box acting as a home NAS and router. It's running shorewall, with NAT and tc enabled. I also have an OSX workstation connected via a switch to said linux router:
OSX Workstation <-> Switch <-> Debian router <-> VDSL2 Modem <-> Internet <-> Server
I ran tests against my fast server on the internet:
On Linux router, TCP:
$ iperf -c server -p 3333
------------------------------------------------------------
Client connecting to server, TCP port 3333
TCP window size: 23.5 KByte (default)
------------------------------------------------------------
[  3] local xxx.yyy.bbb.ccc port 41982 connected with xxx.yyy.bbb.ccc port 3333
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  2.89 MBytes  2.42 Mbits/sec

On the above is where the problem lies. The uplink should be ~10Mbit, not 2.4Mbit. Below, you can see that UDP is working fine.
On Linux router, UDP:
$ iperf -u -c server -p 60008 -b 9M
------------------------------------------------------------
Client connecting to server, UDP port 60008
Sending 1470 byte datagrams
UDP buffer size: 1.00 MByte (default)
------------------------------------------------------------
[  3] local xxx.yyy.bbb.ccc port 56484 connected with xxx.yyy.bbb.ccc port 60008
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  10.7 MBytes  9.00 Mbits/sec
[  3] Sent 7658 datagrams
[  3] Server Report:
[  3]  0.0-10.0 sec  10.7 MBytes  9.00 Mbits/sec  0.251 ms    0/ 7657 (0%)
[  3]  0.0-10.0 sec  1 datagrams received out-of-order

And on the OSX Workstation (behind NAT) TCP:
$ iperf -c server -p 3333
------------------------------------------------------------
Client connecting to server, TCP port 3333
TCP window size: 65.0 KByte (default)
------------------------------------------------------------
[  5] local 192.168.9.141 port 54388 connected with xxx.yyy.bbb.ccc port 3333
[ ID] Interval       Transfer     Bandwidth
[  5]  0.0-10.0 sec  13.2 MBytes  11.1 Mbits/sec

The OSX behind the linux router seems to be unaffected by the problems at the linux router. How can this happen? UDP works fine, too.
And on the OSX Workstation (behind NAT) UDP:
$ iperf -u -c server -p 60008 -b 9M
------------------------------------------------------------
Client connecting to server, UDP port 60008
Sending 1470 byte datagrams
UDP buffer size: 9.00 KByte (default)
------------------------------------------------------------
[  5] local 192.168.9.141 port 64588 connected with xxx.yyy.bbb.ccc port 60008
[ ID] Interval       Transfer     Bandwidth
[  5]  0.0-10.0 sec  10.7 MBytes  9.00 Mbits/sec
[  5] Sent 7658 datagrams
[  5] Server Report:
[ ID] Interval       Transfer     Bandwidth       Jitter   Lost/Total Datagrams
[  5]  0.0-10.0 sec  10.7 MBytes  9.00 Mbits/sec  0.133 ms    0/ 7658 (0%)

As you can see, the linux box is stuck at 2.5Mbit/s outbound TCP. UDP works fine, and the workstation behind the router works fine.
To simplify the situation, I modified my Shorewall TC to a very basic level. I also tried turning TC off alltogether from shorewall without any effect. :
tcdevices:
#INTERFACE  IN-BANDWITH OUT-BANDWIDTH
eth0        -           12000kbit

tcclasses:
#INTERFACE      MARK    RATE            CEIL        PRIORITY    OPTIONS
eth0            1       full            full        1           default

tcrules:
#MARK           SOURCE          DEST            PROTO   PORT(S) CLIENT   USER
1:F             0.0.0.0/0       0.0.0.0/0       icmp    echo-request
1:F             0.0.0.0/0       0.0.0.0/0       icmp    echo-reply

Do you have any idea where the problem might be? The only non-default thing I'm running on Debian is a 3.2.0 kernel from backports. The box is a powerful Xeon machine with lots of RAM and Intel network cards. All the tests were done in a short timeframe with practically no other network traffic. And repeated multiple times. Where could I start debugging?

A: I found the solution to the problem. All I had to do was turn off segmentation offloading on the network card:
ethtool -K eth0 gso off tso off

This fixed the problem for me. Apparently it's fairly common.

A: A couple points:
1.) TCP may take a bit to ramp up to full speed - both in terms of finding the appropriate window size on longer flows as well as the setup time on shorter flows (i.e. 1.5 x RTT doing handshakes w/TCP vs immediate start with UDP).  10 megabytes isn't very much data.  As you push toward the 1G mark you should see the average speed of TCP improve.
2.) Even when fully optimized there's a trade-off between reliability and performance.  TCP can be inordinately sensitive to microbursts even in perfect lab conditions.  Running over a DSL setup (no matter how fast) is going to be potentially be exposing the traffic flow to variable amounts of buffering, serialization delay, etc.  Again, this tends to average out over longer flows.  UDP (especially in performance benchmarks) will transmit as hard as it can, without regard for packet loss, buffer overflow, etc.
So the idea with TCP windowing is that if it's operating perfectly then we reach a situation where there's an optimal amount of traffic in flight with the smallest possible percentage of overhead (i.e. acknowledgements, TCP headers, etc).  Indeed, the amount of traffic in transit should allow for a constant amount of bandwidth - even will acknowledgements are flowing.  TCP's performance will asymptotically approach a wide open transmission of data.
UDP, in contrast, is a wide open transmission of data...
Now - the difference in performance between the various platforms is going to be a function of the particular implementation of TCP as well as how the system itself is prioritizing I/O and protocol processing.  There may be a tweak or two that will bring the two values into better parity..  The size of the sample is still going to be an issue, though.  The more tests and the larger the size, the more accurate the results.


text:
Q: User input 10 times into an arraylist I am fairly new to Java but I cannot find the answer to this question.
Is it possible to add user input a set amount of times of integers and store them into an ArrayList?

A: I'm not sure that what you're looking for, but you can try something like this :
Scanner scanner = new Scanner(System.in);
List<String> arr = new ArrayList<String>();
for (int i =0; i<10; i++){
    System.out.println("Input number " + i);
    arr.add(scanner.nextLine());
}


text:
Q: on form submit form data is null Jsf Primefaces I am facing a problem in the form submit, the first thing is without @this my <p:commandButton> is not calling my Managedbean.And when I added @this it's calling my managed bean with empty form data. I am not able to figure out exactly what I am missing here.the structure is
employee.xhtml:
   <ui:composition template="employee/employeeTemplate.xhtml"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:p="http://primefaces.org/ui">
        <ui:define name="mainContent">
            <ui:include src="employee/employeeEditForm.xhtml"></ui:include>
        </ui:define>
    </ui:composition>

And my employeeTemplate.xhtml is :
   <ui:composition template="../../templates/sidebarLayout.xhtml"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"
        xmlns:ui="http://java.sun.com/jsf/facelets">
        <ui:define name="sidebarContent">
            <p:panel styleClass="panelContainer">
                <p:panel styleClass="panelHeader"
                    header="#{o:translate('Employee List')}"></p:panel>
                <p:panel styleClass="panelSpacing">
                    <h:form id="employeeListForm">
                        <ui:include src="employeeList.xhtml">
                        </ui:include>
                        <ui:include src="addNewEmployee.xhtml">
                        </ui:include>
                    </h:form>
                </p:panel>
            </p:panel>
        </ui:define>
    </ui:composition>

And my Dialogbox is in addNewEmployee.xhtml
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"
        xmlns:fn="http://java.sun.com/jsp/jstl/functions"
        xmlns:ui="http://java.sun.com/jsf/facelets">
                <p:commandButton id="addEmployeeBtn"
                             value="#{o:translate('Add New Employee')}"
                             styleClass="btnAction"
                             style="float: right;"
                             oncomplete="PF('dlgExample').show();">
                </p:commandButton>
        <p:dialog id="dlgExample"
                header="#{o:translate('Dlg Example')}"
                widgetVar="dlgExample" dynamic="true" width="750" height="600" appendTo="@(body)">
                <h:form id="dlgExampleForm">
                            <p:outputLabel for="val1"
                                value="#{o:translate('Employee Type')}:" />
                            <p:selectOneMenu value="#{myManagedBean.selectedEmp.type}" id="val1">
                                        <f:selectItems value="#{myManagedBean.employeeTypes}" />
                                    </p:selectOneMenu>
                            <p:commandButton id="cancelButton"
                                value="#{o:translate('Cancel')}" update=":mainContent,:msgs"
                                oncomplete="PF('dlgExample').hide();" />
                            <p:commandButton style="float: right;"
                                styleClass="pull_right btnAction"
                                actionListener="#{myManagedBean.saveEmployee}"
                                value="#{o:translate('Save')}" process="@this"
                                update=":mainPage,:msgs" >
                                <p:confirm header="Confirmation" message="Are you sure you want to Save?"
                                icon="ui-icon-alert" />
                                </p:commandButton>
                </h:form>
            </p:dialog>
</ui:composition>

Any help will be grately apreciated.


text:
Q: What is going on in this proof of the Cayley-Hamilton theorem? I am reading a proof of the Cayley-Hamilton theorem here. For a rough outline of the proof, let $A$ be a matrix representing the endomorphism $\phi$ over  finitely-generated module $M$ with generators $m_1,...,m_n$. Now, we can regard $M$ as an $R[x]$-module by letting $x$ act as $\phi$.
This next part is where I am confused. They let $\mathfrak{m}$ the column vector whose entries are the $m_j$. Then, we get $(xI-A)\mathfrak{m}=0$, which I guess works by letting matrix multiplication be letting the elements in the matrix with coefficients in $R[x]$ act on the elements of $\mathfrak{m}$.
The next step multiplies both sides by the adjugate matrix to get $[\det(xI-A)]I\cdot\mathfrak{m}=0$, which then completes the proof, as we $p(\phi)=0$, where $p(x):=\det(xI-A)$.
I guess my real question is: what is actually going on? I've never seen matrices used this way; is this just a formal manipulation? But then it feels like multiplying by the adjugate matrix is "wrong". How do I know that the manipulation in $R[x]$ preserves the module action structure? I'm sorry for phrasing this poorly but I just have a feeling that something is off and I may not have it articulated it that well.

A: My previous answer made a false claim -- that we wanted to view $M$ as an $M_{n\times n}(R[x])$-module. In fact, this will not work in general: while given an endomorphism $\phi\in\operatorname{End}_R(M)$ and a generating set $\{m_1,\dots, m_n\}$ of $M$ we may produce a matrix $A_\phi\in M_{n\times n}(R)$ such that
$$\require{AMScd}
\begin{CD}
R^n @>A_\phi>> R^n \\
@V\pi VV @VV\pi V\\
M @>>\phi > M
\end{CD}
$$
commutes, it is not the case that in general a matrix $B\in M_{n\times n}(R)$ induces a well-defined endomorphism of $M.$ However, this doesn't mean we can't use the main idea that $(xI - A)^{\textrm{adj}}(xI -A) = \det(xI - A)I\in M_{n\times n}(R[x]),$ we just need to be careful.
First, let's choose our generating set $\{m_1,\dots, m_n\}$ of $M$ and our  matrix representation $A_\phi$ of $\phi$ with respect to this generating set. Explicitly, we have some collection of constants $r_{ij}\in R$ such that
$$
\phi(m_i) = \sum_{j=1}^n r_{ij} m_j.
$$
If we let $\delta_{ij} = \begin{cases} 1,\quad i = j\\ 0,\quad i\neq j\end{cases}$ and we consider $M$ as an $R[x]$-module where $x$ acts on $M$ by $xm = \phi(m),$ then the previous equation is equivalent to
$$
\sum_{j}(x\delta_{ij} - a_{ij})m_j = 0.
$$
Observe that if we assemble the coefficients of the $m_j$ as we range over all $j$ and all $i$ into a matrix, we obtain
$$(x\delta_{ij} - a_{ij})_{ij} = xI - A_\phi.$$
Now we apply the adjugate trick. Write $(xI - A_\phi)^{\textrm{adj}} = (b_{ij})_{ij}.$ Then the fact that $(xI - A_\phi)^{\textrm{adj}}(xI - A_\phi)  = \det(xI - A_\phi) I$ means that
$$
\sum_{k=1}^n b_{ik}(x\delta_{kj} - a_{kj}) = \det(xI - A_\phi)\delta_{ij}.
$$
Taking  our equation $0 = \sum_{j}(x\delta_{kj} - a_{kj})m_j$ and multiplying by $b_{ik},$ we have
$$
0 = \sum_j b_{ik}(x\delta_{kj} - a_{kj})m_j.
$$
Next we sum these equations over $k$:
\begin{align*}
0 &= \sum_{k=1}^n\sum_{j=1}^n b_{ik}(x\delta_{kj} - a_{kj})m_j\\
&=\sum_{j=1}^n\sum_{k=1}^n b_{ik}(x\delta_{kj} - a_{kj})m_j\\
&= \sum_{j=1}^n\det(xI - A_\phi)\delta_{ij} m_j\\
&= \det(xI - A_\phi)m_i.
\end{align*}
This holds for any $i,$ so that $\det(xI - A_\phi) = p(x)$ acts on $M$ identically as zero; i.e., $p(\phi) : M\to M$ is zero.


text:
Q: Update android app from apk file. Hybrid app I'm currently developing a hybrid app in html, css, angular and ionic, that in the future needs some update functionality.
The iOS app is installed from ipa file, and when in want to update it, i just open/link to a manifest.plist, and the app is downloaded and updated.
But i can't make this to work with Android.
The app is installed from an apk-file. I would like to somehow download and install the updated apk-file so i dont need to remove the old app first.
Is there some way this can be done?

A: You need to upload your new app as the same app as previous version except you need to increment the version number in manifest xml.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      android:versionCode="1"

. . .

</manifest>

You will need following:
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

      android:versionCode="2"

. . .

</manifest>


text:
Q: It is possible to get my current location via the Facebook Graph API? I am trying to build a portion into my personal website that shows the locations I have tagged in my posts on facebook. My understanding is that I need to do an oAuth Request on the server to get the AccessToken:
UPDATE
I built a php file that gets a file with the token in it and refreshes it. I can call this file with a cron job every hour and have an unlimited token. It looks like this:
    $appID = "APPID";
    $appSecret = "APPSECRET";
    $currentToken = file_get_contents(__DIR__."/token.txt");
    $url = "https://graph.facebook.com/oauth/access_token?client_id=".$appID."&client_secret=".$appSecret."&grant_type=fb_exchange_token&fb_exchange_token=".$currentToken;
    $ci = curl_init();
    curl_setopt($ci, CURLOPT_URL, $url);
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ci, CURLOPT_TIMEOUT, 10);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, TRUE);

    $newtoken = curl_exec($ci);
    curl_close ($ci);

    $newtoken = str_replace("access_token=","",$newtoken);
    $newtoken = substr($newtoken, 0,strpos($newtoken, "&expires=",0));

    if($newtoken == "")
    {
        echo "error";
    }
    else
    {
        $file = __DIR__."/token.txt";
        file_put_contents($file, $newtoken);
        echo $newtoken;
    }

A: If the Access Token has the form {app_id}|{app_secret}, you're not using a User Access Token, but an App Access Token.
Seems like you don't implement the proper Login process to gather the User Access Token. Stick to the provided sample code of the FB PHP SDK.
See

*

*https://developers.facebook.com/docs/php/gettingstarted/4.0.0

*https://developers.facebook.com/docs/facebook-login/access-tokens#usertokens


text:
Q: Integer programming: Finding an integral solution in polynomial time I'm currently studying integer programming and I would like to confirm that the following understanding regarding how to find an integral solution in an integral polyhedron is correct.
Assume that an integer program is given where the corresponding polyhedron is integral (i. e. every face contains an integral solution). Most publications state that in order to find an integral, optimal solution to the IP we can simply solve the linear relaxation using a polynomial-time algorithm without specifying the algorithm any further.
However, this does not seem to be sufficient in general, since a general LP algorithm might also return a fractional optimal solution, if there is more than one optimal solution (i. e. the optimal solution is not an extreme point of the polyhedron).
The above procedure would work if we applied (e. g.) Karmakars algorithm, which returns a optimal basic solution (which is integral).
I'm not sure about applying the ellipsoid method to the combination of the primal and the dual LP: I assume that this might return a fractional optimal solution.
Is my reasoning correct?
Thanks in advance!

A: Your interpretation of "integer polyhedron" (that every face contains an integer point) differs from what I believe is standard usage. My understanding (which matches the Wikipedia entry) is that for a polytope to be "integer", all vertices must be integer-valued. Under that definition, solving a linear program over the polytope is guaranteed to find an integer-feasible solution as long as the solution method (whether polynomial time or not) finds a basic feasible solution (vertex).


text:
Q: Regarding slew rates, what would be the minimum for amplifying audio using an op-amp? Many, many choices. And this is just Microchip's offerings.
I'm going to be amplifying by a maximum of 5x using an op-amp. So I choose an op-amp with a GBWP of 50 kHz * 5 = 250 kHz. That still leaves many op-amps. What slew rate should I be looking for? (with low distortion on the output.) And are there any other parameters to look out for, like input noise and offset?
EDIT: It seems I need to clarify. I'm only looking for a single channel op-amp for amplifying a mono signal with reasonable levels of distortion. I'm not looking for high quality prosumer gear audio.

A: As Mark said, if you want to look at the distortion of a 20kHz sine wave with 1Vpp you get about 0.125V/us every Vpp. It depends how much your output peak-peak is. Because your amplification is only 5 times, I don't think you're going for 30Vpp but more something like 10Vpp?
Because you're amplifying audio, you could use an AC coupling so you don't have to worry about the offset very much.   The noise can be significant, but not with these amplifications. You can calculate the RMS noise RTI according to your bandwidth:
e_noise = sqrt(Bandwidth) * NoiseFigure (nV/sqrt(Hz))
So your Bandwidth = 20kHz (ideal situation, a simple low pass will add penalties), your noise figure is for example 50nV/rt Hz (not counting 1/f noise), which means your RTI (input) noise RMS value is 7.071uV. If you amplify the signal by 5 times, you RTO (Output) noise, taking away external noise sources (resistors, etc.) you get 35.4uV rms noise added. At this gain and bandwidth, that isn't very much, but please note that your input noise (from the source) may already be 120uV, which means you would get 0.6mV RMS noise at the output.
Noise becomes a significant factor at high gain and/or higher bandwidths.

A: Sine_Max_slew = 2*pi*f* Vpeak
so "V peak" which should not to be confused with V peak-to-peak (Vpp).
However, the equation can be reduced further though when using Vpp because Vp = Vpp/2 which means:
Sine_slew = 2*pi*f*Vpp / 2

and the 2's cancel, which leaves:
Sine_Max_slew = pi*f*Vpp

There's also a linear slew (triangle waveform) and sine waveform max slew amplitude relationship occurring under equal frequency.  To understand this relationship, a reduced amplitude sine waveform will fit inside a triangle waveform of higher amplitude but same frequency when the sine waveforms max slew equals the linear slew rate.  At that point, the sine waves amplitude is:
Sine(Vpp) = 2/pi * Triangle(Vpp)

There's also a relationship for equal slew rates between linear and sine when amplitudes are the same but frequency is different:
Sine(Hz) = 2/pi * Triangle(Hz)

Just a little noteworthy background on the whole slew subject...

A: the slew rate needs to be \$\geq 2\pi f V_{\text{peak}}\$ to not impart distortion on a sinusoidal signal.
\$f\$ = frequency of the sinusoid and \$V_{\text{peak}}\$ = peak voltage.
So in your case you'd probably use 20kHz for the frequency and whatever your \$V_{\text{peak}}\$ is to find your minimum slew rate.

A: Two AmpOps in the same package could be a good choise if you're planning to design stereo sound amplifier.
With the two of them in the same package the distortion from temperature variation would be the same.


text:
Q: React Eslint destructuring-assignment I am using eslint rule react/destructuring-assignment which throws. How can I destructure this?
getStuff(model = this.state.model) {
   // some stuff
}

A: ESLINT doesn't allow to use this.state.model and it suggests you to utilize destructuring:
const { model: stateModel } = this.state
getStuff(model = stateModel) {

But, I'm afraid as it's inside react class component. Thus, you can't define a const or var before method definition. You should disable the eslint for the line:
getStuff(model = this.state.model) { // eslint-disable-line

Alternatively, you may use like:
 getStuff(model) {
   const { model: stateModel } = this.state
   const passedModel = model ? model : stateModel

   // then work through passedModel
}

Hmm, I can think of this should do the trick:
getStuff({state: {model}} = this) {

But, frankly I have never used such. Just try and let me know.
Update:
You may also use like:
getStuff(model) {
  const { model: stateModel } = this.state || { model: model }
  console.log(stateModel)

Or, simply:
getStuff(model) {
  const { model } = this.state || { model }
  // ----------------- similar to { model: model }
  console.log(model)

A: As I understand your need, you want to have a default var for a model from state and be able to pass it also if needed.
getStuff(passedModel) {
   const { model } = this.state
   const toUseModelInMethod = passedModel || model
   // or
   const toUseModelInMethod = passedModel ? passedModel : model
}

If you just want to get the model from this.state it's simple
getStuff() {
   const { model } - this.state
}

Also you can pass your state to the method
getStuff({ model }) {...}
this.getStuff(this.state) // linter is not happy
// that's is better
getStuff(model){...}
const { model } = this.state
this.getStuff(model)

A: Your example isn't destructuring. A function would look like this:
function getStuff({ property1, property2 }) {
...
}

The above example would pull property1 and property2 from whatever object is passed to the given function.


text:
Q: Concorde installation : need to link an lp solver to use this function I'be been trying to install the TSP solver of Concorde on Cygwin, but I'm facing some difficulties :
I downloaded Qsopt on the official website, the two files in the "Cygwin" part, and put them in /home/qs. Then, I download concorde, gunzip it, tar it, so I have /home/concorde. I go in this folder and type "./configure --with-qsopt=/home/qs". Everything seems to go well, so I type "make", and this is what I've got (several lines like this) :
/home/concorde/LP/lpqsopt.c:645 : undefined reference « QSget_param »
/home/concorde/LP/lpqsopt.c:674 : undefined reference « QSset_param »
/home/concorde/LP/lpqsopt.c:650 : undefined reference « QSset_param »
/home/concorde/LP/lpqsopt.c:655 : undefined reference « QSopt_dual »

Do you have an idea on how to solve this ? I didn't find anything on the web.
(I 've got automake 1.15)
The command that produce this error seems to be :
gcc -fPIC -O2 -g  -o concorde concorde.o tsp.a ../PQ/pq.a ../VERIFY/verify.a ../LOCALCUT/localcut.a   ../TINY/tiny.a ../LINKERN/linkern.a   ../EDGEGEN/edgegen.a ../KDTREE/kdtree.a     ../FMATCH/fmatch.a ../UTIL/util.a ../BIGGUY/bigguy.a     ../CUT/cut.a ../HELDKARP/heldkarp.a ../LP/lp.a ../COMBS/combs.a /home/qs/qsopt.a -liberty -lm ../LP/lp.a(lpqsopt.o)

And then as you see, the errors seems to come from LP
Thanks a lot,
Djazouli

A: So I found the source code and it looks like the problem is in TSP/Makefile.in.
The problem is that the parameters given to the link editor (ld) are positional: object files (and convenience static archives) need to come before the libraries they link to.
In this case there is a second instance of ../LP/lp.a(lpqsopt.o) being passed at the end, and given nothing to link against. I'm not sure where that is coming from though. The build system is quite a mouthful to figure out where the error comes from.


text:
Q: Как перевести char в формат unicode? Допустим у меня есть char в котором хранится число 62:
char c = 62;

Я хочу вывести 62-ой символ в unicode. Если я сделаю System.out.println(c);, то увижу символ >.
Я знаю, что можно было задать c так: char c = '\u0062'. Но как быть если не я создаю переменную c, а она ко мне приходит в метод в качестве аргумента, например ?


text:
Q: $f$ is either regular or $df_x = 0$. In the text, it says:

Consider smooth functions on a manifold $X$: $f: X \to \mathbb{R}$, at a particular $x \in X$, $f$ is either regular or $df_x = 0$.

So I am not certain here: if $df_x \neq 0$, then all we know here is $df_x$ is injective. Hence how can we conclude that $df$ us surjective?

A: The image of $d_xf$ is a subspace of a one dimensional vector space: it is either zero or the whole thing.


text:
Q: Keyboard shortcuts for navigating working files in Visual Studio Code I'm a web developer accustomed to Sublime Text. Often I'll have multiple files open and will navigate between them with cmd + option + left (or +right).
I'd love to have something as close to this functionality as possible in Visual Studio Code. From what I've read, in Visual Studio Code it sounds like instead of having multiple documents open in tabs across the top, you're supposed to use the "Working Files" list in the sidebar on the left. A few questions:

*

*Is there a keyboard shortcut for navigating between these files sequentially? (the equivalent to cmd + option + left (or +right) in Sublime Text?)

*Is there a keyboard shortcut for closing a file and removing it from the working files list? cmd + w just closes its editor window.

*If these shortcuts don't exist by default, can I create them?

I did just discover Ctrl + - and Ctrl + shift + - (ref), which navigate between "edit locations." This is handy, but sometimes it jumps around between different locations in the same file (depending on where you've been editing). Also I would love an option that moved through files sequentially, i.e not based on most recently viewed, but rather top-to-bottom according to how they are listed in the Working Files list.

A: I'm used to having the numbered tabs being tabbable with your keyboard. Similar to Google Chrome.
cmd+1 # First tab
cmd+2 # Second tab
etc.
I did not find the settings for this in Visual Studio Code. I was able to map the keys to the arrows to be able to tab through one at a time.
[{
    "key": "cmd+shift+left",
    "command": "workbench.action.previousEditor"
}, {
    "key": "cmd+shift+right",
    "command": "workbench.action.nextEditor"
}]

It is not ideal, but it will do.

A: Linux default bindings for going to desired tab within current editor group is:
Alt + 1
Alt + 2
...
To change, menu File → Preferences → Keyboard shortcuts → search: openEditorAtIndex

Linux default bindings for switching between editor groups is:
Ctrl + 1
Ctrl + 2
...
To change, menu File → Preferences → Keyboard shortcuts → search: focusFirstEditorGroup, focusSecondEditorGroup ect.

A: I also get annoyed with the default behaviour of cycling through recent files instead of working files, but it turns out you can re-map the keyboard to work a little differently.
To map Ctrl+Tab and Ctrl+Shift+Tab to cycle through working files similar to how other versions of Visual Studio work you can add this to your keybindings file:
[
  { "key": "ctrl+tab", "command": "workbench.files.action.openNextWorkingFile" },
  { "key": "ctrl+shift+tab", "command": "workbench.files.action.openPreviousWorkingFile" }
]

A: Use the out of the box window management hotkeys.
Between Editor Groups

*

*Ctrl + 1 to Left

*Ctrl + 2 to Side

*Ctrl + 3 to Right

*Ctrl + K Ctrl + Left to Left

*Ctrl + K Ctrl + Right to Right

Within an Editor Group

*

*Ctrl + Tab to Next

A: New VSCode ver 1.36.1 on my Mac I have to do as following:
    {
        "key": "shift+cmd+[BracketLeft]",
        "command": "workbench.action.previousEditor"
    },
    {
        "key": "shift+cmd+[BracketRight]",
        "command": "workbench.action.nextEditor"
    }

A: Hold ctrl and navigate between files using tab, after selecting the file, release ctrl to go to that file.

A: For Macs: from the menu, select menu Code → Preferences → Keyboard Shortcuts to open User/keybindings.json. Then inside the square brackets, add:
{ "key": "shift+cmd+[",          "command": "workbench.action.previousEditor"},
{ "key": "shift+cmd+]",          "command": "workbench.action.nextEditor"}

This binds the standard Mac tab switching shortcuts ⌘+shift+[ and ⌘+shift+] to switch to previous and next tab, respectively. It was tested in Visual Studio Code 1.3.1.
If you'd rather use ⌘+⌥+← and ⌘+⌥+→, the key strings for those are "cmd+alt+left" and "cmd+alt+right". Although from my testing it looks like these are already bound to the appropriate commands by default in Visual Studio Code 1.3.1, so maybe this question is obsolete?

A: Ctrl + Page Up
Ctrl + Page Down
would be the best answer for navigating sequential tabs.

A: what @Mesco answered still works, but the default bindings have changed to:
Ctrl + 1
Ctrl + 2
To change them from default, you have to:

*

*Preferences > Keyboard Shortcuts

*search for: openEditorAtIndex

*change keybinding to whatever

A: I like the idea of having commands for closing a working file or closing all working files and I can look into adding those for the next update.
As for navigation between working files: We have a very powerful tool for navigation called Navigate History. By default it is assigned to Ctrl + Tab and you can leave the Ctrl key pressed and click Tab to cycle through the list of files, similar how you can switch between windows on the OS.
Navigate history is not identical to what you are asking for because it also contains files that you opened that are not in working files. Can you give it a try and report back if it solves the navigation problem for you?
We feel that this is a more natural way of navigating, because you don't have to worry about the order of working files. Instead you navigate across the list of most recently used files.
In our team we are so used to Navigate history that we cannot live without it anymore. Very often we would press Ctrl + Tab one or two times without even looking at the list that opens because we know that the file we want was either one or two history entries away.
Update
With the release of Visual Studio Code 0.5.0 there are now keyboard shortcuts to navigate back and forward in the list of working files. The shortcut is CMD + K + ↑ and CMD + K + ↓ (on Windows use the Ctrl key).

A: You can install keybindings like Sublime Text, Atom or any other available on Visual Studio marketplace, look this:
Sublime Text Keymap and Settings Importer
Personally, I like the atom keybindings :)
Atom Keymap
It works like a charm.

A: Ctrl+PageUp: SelectPreviousSuggestion
Ctrl+PageDown: SelectNextSuggestion

A: I still prefer the approach you've described, but it seems the current solution in Visual Studio Code is to use keyboard "chords" as follows:
Previous working file - ⌘+K;↑
Next working file - ⌘+K;↓
Close working file - ⌘+K;W
Note: On Windows/Linux, use Ctrl+K instead of ⌘+K.
Source

A: In windows you can use
Ctrl + Tab

A: For me it was to simply find the certain commands in the keyboard shortcuts and then modify them in a way which I prefer(Mac: CMD+1/2/.../9 respectively).
So navigate to VS Code -> preferences -> Keyboard Shortcuts.
Then search for: workbench.action.openEditorAtIndex1 and remap your desired key to this command.
Do this last step for all nine indices, so you can change between nine open working files.
For me this works best because it reminds me of changing between windows tabs on google chrome and etc.


text:
Q: Apache: restrict access to folder based on certificate Hope someone can point me in the right direction.
I have created a simple Apache srv on 2.4.25
The srv has a cert from letsencrypt and enforces access to https only.
I have a "secret" folder (test). It has been protected by basic auth (user/PW).
This means that if you access https://www.example.org/test, you'll be prompted for authentication; works fine.
Now the question:
I would like to enforce that access to this folder is only allowed from clients (in this case some phones). The phones has a device certificate, and I would like to use this cert for authentication. However the cert is not from a trusted CA like letsencrypt or Digicert. They are signed by the company that manufactors the phone (self-signed)
My thought is to import the CA, and then look up if the request to access the folder is from a phone(allowed) or not. I tried to add :
SSLVerifyClient require
SSLVerifyDepth 1
SSLCACertificatePath /path/to/ssl/
to the folder, but this causes the srv to start as:
"Your SSL library does not have support for per-directory CA"
Seems that this takes bit more to get working, so any hints and advises will be greatly appreciated.


text:
Q: Redis session store on heroku I am attempting to use redis store as my session store on heroku. It works fine in development but I am unable to get a redis connection on heroku. It is attempting to connect to a 127.0.0.1 instead of the correct redis server.
Error:
ActionView::Template::Error (Error connecting to Redis on 127.0.0.1:6379 (ECONNREFUSED)):

I have set the heroku redis config to the correct server (not really using for the session store but it is set)
REDISTOGO_URL: redis://redistogo:################################@carp.redistogo.com:9274/

session_store.rb
GrnAuth::Application.config.session_store :redis_store, :server => APP_CONFIG['redis_server'], key: '_grn_session'

environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)
require 'yaml'
APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

# Initialize the rails application
GrnAuth::Application.initialize!

config.yml
development:
  redis_server: redis://localhost:6379/

test:
  redis_server: redis://localhost:6379/

production:
  redis_server: redis://redistogo:################################@carp.redistogo.com:9274/

When I console in to heroku I can check APP_CONFIG['redis_server'] and it is set to the redis server.
I have also set up a redis connection just to use that works.
redis.rb
uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/" )
$redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)

When I console in to heroku I can do and get the following
irb(main):001:0> $redis
=> #<Redis client v3.0.1 for redis://carp.redistogo.com:9274/0>

Any help would be much appreciated. Thank you.

A: It looks like this:
GrnAuth::Application.config.session_store :redis_store, :server => APP_CONFIG['redis_server'], key: '_grn_session'

Should instead be this:
GrnAuth::Application.config.session_store :redis_store, :servers => APP_CONFIG['redis_server'], key: '_grn_session'


text:
Q: Windows Phone 8 SDK running in Visual Studio 2010 I know that the SDK is not finished, yet a few lucky developers have got their hands on it already, so here's my question: when you installing Windows Phone 8 SDK, did it install the SDK in Visual Studio 2010 also, or just on the 2012 edition (including 2012 Express)?

A: After posting my question, two different developers that had access to the SDK contacted me directly stating that there is no integration of the Windows Phone 8 SDK in Visual Studio 2010, just on the 2012 version.

A: No, You need Visual Studio 2012, Windows 8 Pro or Enterprise x64 + processor supporting SLAT for running Hyper-V.
You can now download the WP8 SDK here:
http://www.microsoft.com/en-us/download/details.aspx?id=35471


text:
Q: Second order linear ODEs and analytic coefficients A second order, linear, homogeneous ODE can be expressed as:
$$a(x)y''(x) + b(x)y'(x) + c(x)y(x) = 0$$
I have only a basic knowledge about differential equations. However, all the texts state that: in order to find a solution at a specific point $x = x_0$, the functions
$\displaystyle \frac{b(x)}{a(x)}$ and $\displaystyle \frac{c(x)}{a(x)}$
must be analytic at $x_0$.
For example, from this document:

A linear, analytic equation is one for which the coefficient functions
  are analytic and therefore possess convergent power-series expansions
  [...]. The simple conclusion will be that the solutions also possess
  convergent power-series expansions.

Why, if the coefficient functions are analytic, there is guarantee that  the solution is analytic, too, and vice-versa?
They are only the coefficients of the unknown function $y(x)$ in that equation, not the function $y(x)$ itself, so how can they affect the function in such a heavy way? If for example $a(x_0) = 0$, how can this determine also the form of $y(x)$ at $x_0$? I can't find the link between these two facts.

A: It's easier to see if we take it down to first order. Let's look at $$ a(x)y'(x) + b(x)y(x) = 0$$
To solve this equation, we can simply separate the variables and integrate, so $$ \int\frac{y'(x)}{y(x)}\text dx = c - \int \frac{b(x)}{a(x)}\text dx \\ \Rightarrow y(x) = C\exp\left( \int f(x)\text dx \right) = C\exp(F(x)) $$
where $f(x) = -\frac{b(x)}{a(x)}$ and $F'(x) = f(x)$. The question here is, when is the solution $y(x)$ an analytic function at some given point $x_0$? Well, an analytic function is one whose derivatives all exist at $x_0$, so let's find the derivatives of $y$. The expression for the $n$-th derivative of $\exp(F(x))$ is
$$\frac{\text d^n \exp(F(x))}{\text dx^n}\biggr|_{x=x_0} = \exp(F(x_0)) \sum_{k=0}^n \frac{1}{k!} \sum_{j=0}^k (-1)^j \binom{k}{j}F(x_0)^j \frac{\text d^n F(x)^{k-j}}{\text dx^n}\biggr|_{x=x_0} $$
The only time this expression doesn't exist for some $n$ is if the $p$-th derivative of $F$ doesn't exist for some $0\leq p\leq n$. In other words, $\exp(F(x))$ is analytic iff $F(x)$ is. Since $F$ is the integral of $f$, $F$ is analytic iff $f$ is analytic, and recall that $f = -\frac{b(x)}{a(x)}$. Thus,
$$ y(x) \text{ is analytic } \Leftrightarrow \frac{b(x)}{a(x)} \text{ is analytic. } $$
The same idea is true for higher order equations; the only issue is that "integrating" higher order equations isn't as simple as actually integrating a function as it was in the first order case. However, making use of the Picard iteration, we can show the exact same thing for higher order equations (albeit with a lot more work).

A: Given a second order ODE
$$
a(x)y''(x)+b(x)y'(x)+c(x)y(x)=0 \tag{1} \label{eq1}
$$
We can introduce a new variable $z(x)=y'(x)$ and reduce the equation to a first order system (the same idea works for higher order equations).
$$
\begin{align}
  y'(x)-z(x)&=0 \\
  a(x)z'(x)+b(x)z(x)+c(x)y(x)&=0 \\
\end{align}\tag{2} \label{eq2}
$$
We can write the system in a matrix-vector form
$$
\mathbf{A}(x)\cdot\vec{Y}'(x)+\mathbf{B}(x)\cdot\vec{Y}=0 \tag{3} \label{eq3}
$$
where
$$
\mathbf{A}(x)=\left(\begin{matrix}
    1 & 0  \\
    0 & a(x)  \\
\end{matrix}\right) \tag{4} \label{eq4}
$$
$$
\mathbf{B}(x)=\left(\begin{matrix}
    0 & -1  \\
    c(x) & b(x)  \\
\end{matrix}\right)\tag{5} \label{eq5}
$$
$$
\vec{Y}(x)=\left(\begin{matrix}
     y(x)  \\
     z(x)  \\
\end{matrix}\right) \tag{6} \label{eq6}
$$
if $a(x)\neq 0$ in the integration domain we can find $\mathbf{A}^{-1}$ given by
$$
\mathbf{A}^{-1}(x)=\left(\begin{matrix}
    1 & 0  \\
    0 & \frac{1}{a(x)}  \\
\end{matrix}\right) \tag{7}\label{eq7}
$$
Using $\eqref{eq7}$ we can rewrite $\eqref{eq3}$ in the following way:
$$
\vec{Y}'(x)=-\mathbf{A}^{-1}(x)\cdot\mathbf{B}(x)\cdot\vec{Y}=-\mathbf{C}(x)\cdot\vec{Y} \tag{8} \label{eq8}
$$
where
$$
\mathbf{C}(x)=\left(\begin{matrix}
    0 & -1 \\
    \frac{c(x)}{a(x)} & \frac{b(x)}{a(x)}  \\
\end{matrix}\right). \tag{9}\label{eq9}
$$
Notice that $\mathbf{C}$ contains the ratio of the coefficients. If $\mathbf{C}(x_1)\cdot\mathbf{C}(x_2)=\mathbf{C}(x_2)\cdot\mathbf{C}(x_1)$, $\forall\{x_1,x_2\}\in D(\mathbf{C})$ the solution to $\eqref{eq8}$ is similar to the first order scalar case:
$$
\vec{Y}=\mathbf{K\cdot\mathrm{e}}^{-\int \mathbf{C}(x)\mathrm{d}x} \tag{10} \label{eq10}
$$
where we use the matrix exponential and $\mathbf{K}$ is a constant matrix. In that case, we required $\frac{c(x)}{a(x)}=k_1,\frac{b(x)}{a(x)}=k_2$, where $k_1,k_2$ are constants. A general solution is given by the Magnus expansion (see ref. 1 and ref. 2).
Perhaps, it is easier to analyze the effect of the coefficients for a first order equation:
$$
y'=-\alpha(x)y
$$
the solution in this case is
$$
y=\kappa\mathrm{e}^{-\int \alpha(x)\mathrm{d}x}
$$
Therefore, the solution is the composition of $\int \alpha(x)\mathrm{d}x$ and the exponential function. Given a $C^{n}$ function at $x_0$, its integral is $C^{n+1}$. For example, consider the following step-like function:
$$
\alpha(x)=\left\{\begin{matrix}
    0 & x<0  \\
     1 & x\geq 0 \\
\end{matrix}\right.
$$
It is discontinuous at $x = 0$; its integral in $(-\infty,x]$ is a $C^0$ function (i.e. a continuous function):
$$
\int_{-\infty}^x\alpha(s)\mathrm{d}s=\left\{\begin{matrix}
    k & x<0  \\
     k+x & x\geq 0 \\
\end{matrix}\right.
$$
where $k$ is a constant. Regarding the questions:

*

*Why, if the coefficient functions are analytic, there is guarantee that the solution is analytic, too, and vice-versa?
Given the integration of the matrix $\mathbf{C}$, you need the ratio of the coefficient to be analytic, i.e., $C^{\infty}$ in order to get a solution which is $C^{\infty}$ as well.

*They are only the coefficients of the unknown function $y(x)$ in that equation, not the function $y(x)$ itself, so how can they affect the function in such a heavy way? Given the solution $\eqref{eq10}$, we see that the coefficients fully determine the solution. Therefore, they strongly affect the resulting solution (they are part of the solution).

*If for example $a(x_0)=0$, how can this determine also the form of $y(x)$ at $x_0$? In that case you find a singularity at $x_0$, the solution won't be analytic in that case (it may be $C^n$ in the best case).


text:
Q: How can I use vue-monaco? I'm trying to implement vue-monaco, but I get these errors:
ERROR  Failed to compile with 2 errors                                                                                4:59:58 PM

 error  in ./node_modules/monaco-editor/esm/vs/basic-languages/_.contribution.js

Module parse failed: Unexpected token (37:13)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     return lazyLanguageLoaders[languageId];
|   }
>   _languageId;
|   _loadingTriggered;
|   _lazyLoadPromise;

 @ ./node_modules/monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js 9:0-56 10:0-16
 @ include-loader!./node_modules/vue-monaco/node_modules/monaco-editor/esm/vs/editor/editor.main.js
 @ ./node_modules/vue-monaco/dist/vue-monaco.es.js
 @ ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/PlaygroundView.vue?vue&type=script&lang=js&
 @ ./src/views/PlaygroundView.vue?vue&type=script&lang=js&
 @ ./src/views/PlaygroundView.vue
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://X.X.X.X:8081&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

 error  in ./node_modules/monaco-editor/esm/vs/language/typescript/monaco.contribution.js

Module parse failed: Unexpected token (76:15)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| })(ModuleResolutionKind || {});
| var LanguageServiceDefaultsImpl = class {
>   _onDidChange = new monaco_editor_core_exports.Emitter();
|   _onDidExtraLibsChange = new monaco_editor_core_exports.Emitter();
|   _extraLibs;

 @ include-loader!./node_modules/vue-monaco/node_modules/monaco-editor/esm/vs/editor/editor.main.js 101:0-92
 @ ./node_modules/vue-monaco/dist/vue-monaco.es.js
 @ ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/PlaygroundView.vue?vue&type=script&lang=js&
 @ ./src/views/PlaygroundView.vue?vue&type=script&lang=js&
 @ ./src/views/PlaygroundView.vue
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://X.X.X.X:8081&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

I think these issues are related to my vue.config.js; this is it:
const MonacoEditorPlugin = require('monaco-editor-webpack-plugin')

module.exports = {
  transpileDependencies: [
    'vuetify'
  ],
  configureWebpack: {
    plugins: [
      new MonacoEditorPlugin({
        languages: ['javascript', 'typescript']
      })
    ],
  },
}

Component implementation is almost identical to the guide. The guide seems pretty straightforward, so what am I doing wrong?
P.S. I even tried monaco-editor-vue, but I got almost the same errors.

A: To make it work I had to downgrade monaco-editor-webpack-plugin to 1.9.1; related link here. Note that typescript language is also needed, even though you want only javascript; related link here.


text:
Q: Correct vector calculus divergence identity I came across this vector calculus identity (in this wikipedia article, but also in other sources):
$$
\vec{\nabla} \cdot (\vec{B}\times \vec{C}) = \vec{C}\cdot(\vec{\nabla}\times \vec{B})-\vec{B}\cdot(\vec{\nabla}\times \vec{C})
$$
where $\vec{\nabla}=(\partial/\partial x,\partial/\partial y,\partial/\partial z)$. However, based on equation (2.5) of the Feynman Lectures on Physics, vol. II, which states that
$$\vec{A} \cdot (\vec{B}\times \vec{C}) = (\vec{A}\times \vec{B})\cdot \vec{C},$$
the above identity should only contain the first term on the right-hand side.
I'm getting confused. Does anyone know which one is correct and what's the difference between the two?

A: The divergence operator looks like a vector but it's still an operator and contains derivatives. Most importantly you have to use the product rule, since the derivative acts on both $\mathbf{A}$ and $\mathbf{B}$. In general for these types of problems working with index notation and Einstein Summation is the best choice. For example
\begin{align*}
\nabla\cdot(\mathbf{A}\times\mathbf{B}) = \partial_i \varepsilon_{ijk} a_j b_k &= \varepsilon_{ijk} \left(\frac{\partial a_j}{\partial x_i} b_k + a_j \frac{\partial b_k}{\partial x_i}\right) \\
&= \varepsilon_{kij} b_k \partial_i a_j - \varepsilon_{jik} a_j \partial_i b_k \\
&= \mathbf{B}\cdot\left(\nabla\times\mathbf{A}\right) - \mathbf{A}\cdot\left(\nabla\times\mathbf{B}\right)
\end{align*}


text:
Q: Creating Graphs in Pythons using matplotlib: ERROR Module 6 I am trying to create a graph on Python (version 3 and above) using matplotlib, however I keep getting the error saying
ImportError: No module named 'six'

Does anyone know how to fix this? I have already tried downloading the module. And I still get this error.

A: Are you sure you've installed six?
If you have both python 2.x and 3.x installed, it may be that when running easy_install or pip, you're installing six for 2.x rather than 3.x. If you have pip, try running pip3 install six in a shell, or for easy_install, run easy_install-3.4 six (replace 3.4 with your 3.x python version).


text:
Q: How to load a database with more than a million rows into pivot table cache? I have a pivot table that shows the sales data of the company since 2019, and I need to update it with June's information. However, the problem is that Excel cannot handle adding 200,000 rows to the 1,046,984 in my current database. How can I do this without using Access? Should I use a CSV file instead?

A: The only way I am aware of that this works within excel is by leveraging PowerPivot (see here).


text:
Q: Modify a csv file line by line I have a big file that I want to modify every line in it.
I want to use PHP to do it quickly :
My file is CSV file ;
20010103,02,00,00,0.9496
20010103,03,00,00,0.9504
20010103,04,00,00,0.9499

I want to make it like this to be able to use it late with Highchart:
[Date.UTC(2001,01,03,02,00,00),0.9496],
[Date.UTC(2001,01,03,03,00,00),0.9504],
[Date.UTC(2001,01,03,04,00,00),0.9499],

How canI loop every line and make this modification ?

A: Try this code:
<?php
    $filename = 'info.csv';
    $contents = file($filename);

    foreach($contents as $line) {
       $data = explode(",",$line);
       $val = "[Date.UTC(".substr($data[0],0,4).",".(substr($data[0],4,2)).",".substr($data[0],6,2).",".$data[1].",".$data[2].",".$data[3]."),".$data[4]."],";
    }
?>

A: See the fgetcsv and fputcsv PHP functions. It will basically be something like:
if (($handle1 = fopen("input.csv", "r")) !== FALSE) {
    if (($handle2 = fopen("output.csv", "w")) !== FALSE) {
        while (($data = fgetcsv($handle1, 1000, ",")) !== FALSE) {
           // Alter your data
           $data[0] = '...';

           // Write back to CSV format
           fputcsv($handle2, $data);
        }
        fclose($handle2);
    }
    fclose($handle1);
}


text:
Q: popup doesn't work correctly on my mobile phone-JQM please any help ?
I'm trying to add popup div to my mobile web app in JQM , but unfortunately the code above doesn't work on my mobile phone , it show the app in tiny at the right corner. but in IE I see it fine.
what i'm doing wrong?

            Close

and my javascript code:
    $("#popupBasic2").popup('open');

screenshot:

any suggestions?
Thanks, MOR

A: I found what cause this happen . it seems that popup doesn't work on  the rtl messed it up..

A: check if you have <meta name="viewport" content="width=device-width, initial-scale=1"> in your head.
Here is an example my popup:
Delete Bonus

Delete?

To Delete Bonus?

This action cannot be undone.

                Cancel
                Delete

A: u can use  "Bootstrap"  http://getbootstrap.com/
1.  Include it at the beginning of all your projects.

<link href="css/bootstrap.css" rel="stylesheet">

2. For Example:
<button class="btn btn-success" data-toggle="modal" data-target="#newModal"></button>

 ->data-target ="#newModal" !! so...find the id named 'newModal'

3. Pop-up

      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

hihihihihi

   Name

     <input type="text" class="form-control" id="myName" name="myName" maxlength="20">

      there is a footer

Like this
Sorry i cant post the image!
u can try this link!!  http://images.plurk.com/2Ovvy6BlcrVkFJTGyPLubS.jpg
thx!!


text:
Q: How to create a search box and SQL statement for searching an attribute field? How can I add a HTML search bar that the user can use to search an attribute field for a polygon layer, and then tie that input into the SQL statement?
So far I am able to hard code the query  of sending a SQL statement and returning a answer using cartodb. My problem is figuring out how to  take the input from the search box and automatically inserting the input into the sql statement.
I am using Cartodb api.
 var sql = new cartodb.SQL({ user: 'jmann111' });
   sql.getBounds("select * from stations where station_nm like ='%" + user_input +"'").done(function(bounds) {
  map.fitBounds(bounds)
  });

A: In SQL you will need a parameter, usually declared somewhere before the select statement. The parameter is the same as a variable. So something like:
Declare @userinput as varchar
Set @userinput = textbox.text
Select * From stations where Station_nm Like '%@userinput%'
Your command has like = and they can't be used together.


text:
Q: extract url between 2 strings in a file I have a file in which each line is like this
"372"^""^"2015-09-03 06:59:44.475"^"NEW"^"N/A"^""^0^"105592"^"https://example-url.com"^"example-domain < MEN'S ULTRA < UltraSeriesViewAll (18)"^"New"^"MERCHANT_PROVIDED"

I want to extract the urls in the file -- https://example-url.com
I tried these regex using sed command -- sed -n '/"^"http/,/"^"/p'
But it didn't solve my problem.

A: If your version of grep supports PCRE mode, you could try
grep -Po '(?<="\^")http.+?(?="\^")'

A: You could use this
sed -n 's!^.*\^"\(http[^^]*\)"^.*!\1!p'

The potential gotcha for a beginner to REs is that ^ is an indicator for start of line, so you have to ensure you escape it \^ if you want a literal up arrow at the start of your RE.
The RE pattern match can be explained as follows

*

*^.*\^" -- Match from start of line until we see the last possible up-arrow double-quote ^" that satisfies the rest of the pattern

*\( -- Start a substitution block that can be substituted as \1

*http[^^]* -- Match http followed by as many characters that are not ^ as possible

*\) -- End the substitution block
"^.* -- Match double-quote and up-arrow "^, then as much as possible (until end of line)

This entire match is replaced by \1, which is the pattern block starting http

A: Try this:
echo "372"^""^"2015-09-03 06:59:44.475"^"NEW"^"N/A"^""^0^"105592"^"https://example-url.com"^"example-domain < MEN'S ULTRA < UltraSeriesViewAll (18)"^"New"^"MERCHANT_PROVIDED" | cut -f9 -d^

A: If your URLs always start with http and end with a quote, you can just search for the string http and everything up to the next quote:

*

*grep
$ grep -o 'https*://[^"]*' file
https://example-url.com

*sed
$ sed -n 's#.*\(https*://[^"]*\).*#\1#;p' file
https://example-url.com

*Perl
$ perl -ne 's#.*(https*://[^"]*).*#\1# && print' file
https://example-url.com

*With a slightly different approach, you can use awk as well. Just use -F to set the field delimiter to " and print any field starting with hhtp:
$ awk -F\" '{for(i=1;i<NF;i++){if($i~/^http/){print $i}}}' file
https://example-url.com


text:
Q: Authorize on-premises user against Azure Active Directory (AD) I have an on-premises Windows server 2022, which is running AD DS, NPS and DHCP. I also have Azure AD subscription, where my users are located. I would like to keep my users database (AD) in the cloud, since currently, I do not have any backup solutions and it is easier for me to manage. I want to have ieee 801.x on premises, as well as VPN service. Is it possible to force the NPS to authenticate against the Azure AD, where all my users are located? If yes, how can this be done?
I know that Azure AD Connect provides hybrid integration, but from what I read, it is only one way, i.e from on-premises AD to cloud synchronization, but not the other way around.

A: Yes, you are correct that the synchronization is only one-way and the workarounds currently are to use use PowerShell export/import or use a third-party tool. In the NPS article you linked, the on-premises users ultimately authenticate against Azure MFA. The NPS extension acts as an adapter between RADIUS and cloud-based Azure AD Multi-Factor Authentication to provide MFA for the federated or synced users. Your cloud users would just use regular Azure MFA without needing that adapter.
The most common workaround for the user writeback scenario is to create a PowerShell script that scans Azure AD regularly, finds the users in Azure, and then creates an on-premises user with the attributes in Azure AD.
The regular user writeback feature is on the roadmap and actively being worked on though. I've asked for an update from the PG and will edit this post once it is available.
For cloud VPN options, see: Azure AD Authentication - Open VPN.


text:
Q: Stream closed before the program finishes I am using jetty server to receive calls from http clients.
I am using BufferedWriter object to write a log file for debugging.
The server is always running in order to receive calls.
How can i tell the program to only close the stream (log_file.close) when the server stops?
I am not supposed to stop the server, but before the program terminates (when i touch the terminate button for example) how can i close the stream file in that point?

A: If your code is running inside a web application (aka war) you can (and it's actually a best practice) to implement ServletContextListener and register it in your web.xml.
In contextInitialized you can make the necessary init operations.
In contextDestroyed you can close the stream.

A: If you are running Jetty embedded, then you have a couple of options.
You haven't indicated which version of Jetty, so I can't give you exact code for it, but your options are:

*

*Register a "LifeCycle" object in the server, and implement a stop method in that lifecycle object that closes your log file. (Using something like addLifeCycle or addBean, depending on your Jetty version)

*Add a shutdown thread in the JVM (Runtime.addShutdownHook)


text:
Q: The specified type member 'Product' is not supported in LINQ to Entities I'm getting the error 'Product' is not supported in LINQ to Entities whilst using cartItems.Product.UnitCost when trying to get the total of the basket.
public decimal GetTotal()
    {
        //Multiply price by count of item to get price for each item in cart and them sum all prices up
        decimal? total = (from cartItems in db.ShoppingBaskets where cartItems.BasketID == ShoppingCartID select (int?)cartItems.BasketQuantity * cartItems.Product.UnitCost).Sum();

        return total ?? decimal.Zero;
    }

I then tried splitting the query up to see if this would fix the problem
int? quantity = (from cartItems in db.ShoppingBaskets where cartItems.BasketID == ShoppingCartID select (int?)cartItems.BasketQuantity).Sum();

decimal? price = (from cartItems in db.ShoppingBaskets where cartItems.BasketID == ShoppingCartID select cartItems.Product.UnitCost).Sum();

I get the same problem with the second separate query with 'Product'.
Product Class
public partial class Product
{
    public Product()
    {
        this.OrderCheckouts = new HashSet<OrderCheckout>();
        this.ProductReviews = new HashSet<ProductReview>();
    }

    public int ProductID { get; set; }
    public int CategoryID { get; set; }
    public int ManufacturerID { get; set; }
    public string ProductName { get; set; }
    public string ProductCode { get; set; }
    public decimal UnitCost { get; set; }
    public int UnitQuantity { get; set; }
    public string ProductDescription { get; set; }
    public string ProductImage { get; set; }

    public virtual Category Category { get; set; }
    public virtual Manufacturer Manufacturer { get; set; }
    public virtual ICollection<OrderCheckout> OrderCheckouts { get; set; }
    public virtual ICollection<ProductReview> ProductReviews { get; set; }
}

ShoppingBasket Class
public partial class ShoppingBasket
{
    public int CartID { get; set; }
    public string BasketID { get; set; }
    public int BasketQuantity { get; set; }
    public int ProductID { get; set; }
    public virtual Product Product { get; set; }
}

Could someone explain the problem more clearly and how I can solve this? Thanks!

A: I think it's because Entity Framework hasn't fully created the relationship between ShoppingBasket and Product. Try adding:
public virtual ICollection<ShoppingBasket> ShoppingBaskets { get; set; }

to the Product class.


text:
Q: WordPress. Сломалась пагинация. Не делит на страницы Доброго времени суток!
Проблема заключается в том, что WP не высчитывает количество страниц. Стоят два плагина WP-PageNavi (активен), WP-Paginate (отключен).
В итоге, на странице 419 записей, и все они на первой странице. Внизу отображается, что это первая страница, и всё. Больше страниц нет. В настройках менял количество записей на странице и по 10, и по 20, не помогает.
Несколько дней мучаюсь с проблемой, уже не знаю где копать.


text:
Q: Using Hillshade option in ArcMap? Here is a pretty pic of the raster I am using - with no effects applied - just the color ramp and histogram adjusted to show out all the relief - albeit in a very 2D way!

I have a raster layer that I want to display with hillshade as a default.  I can do this in code and in effect it is the same as selecting the Hillshade option in ArcMap (see below):

When you do this however - it looks disappointing:

Especially if you zoom into the raster you see all kinds of gridded articfacts - which does not look nice at all!

However if I create a proper Hillshade layer using the raster with Spatial Analyst and overlay it with transparancy of 85% it looks pretty good and very different!:

*

*How can I acheive this effect in ArcMap and override the default functionality of the Hillshade option (I supsect this is impossible, or is it some setting I have missed out that is caused the raster to be displayed poorly).  If it is possible to override or select the correct settings - is it possible to do in ArcObjects.

*If option 1 is not possible, can I create my effect with creating a Hillshade layer (without using Spatial Analyst) and effectively fuse it to the orginal raster - i.e. I don't want people to see two layers in the table of contents in ArcMap. I just want one layer but with a default hillshade rendering of my choosing/configuration.  I need to do this programmatically too i.e ArcObjects.

One thing I have learned is that you must have your DEM in the correct Spatial Reference and measurement units or the resulting hillshade looks too black and over exaggerated - check out this video to find out more - its a very good explanation.
So I think I now know what I need to do in regards to producing some high quality hillshading, but I think it's going to take some low level tweaking ArcObjects code.  I am thinking I need to come up with my own graphics rendering and plug this into ArcMap (I have a dll that renders bitmaps of grids in a cool way).  I think a good place to show this would be to override the Draw() event on something like the IRasterRenderer, and insert my own image rendering.  Of course it might get a bit complicated with reprojections etc.
Has anyone done any kind of this low level graphics rendering in ArcMap - if so can you offer any guidance or things I should be aware of?

A: If you are looking for a good looking hillshade that takes some time to create, but is great for larger projects where it will get a lot of exposure, you might try the Swiss Hillshade Method - it requires 3 layers, but you can then export them to one georeferenced tiff to save space and for portability. This method DOES require Spatial Analyst, I believe, so it is not a direct answer to OP's question, but may be useful to others looking at hillshade methods in ArcGIS. The method works in other GIS systems too, but the linked toolbox is for ArcGIS.
Edit 11/2014: Esri recently released a new tool for creating Hillshades. It look really slick and should fuse with the Asker's workflows. They introduce it here and you can download the code and installation instructions here

A: I have always been instructed to increase the z exageration when doing hillshade.
I just tried 100 on mine and it seems a bit extreme.
Also changing the stretch type makes a big difference in the look of hillshade.
Since you are talking about how it looks you might also look at this help item.
esir help
Which says that hillshading iis applied at the display pixel resolution.
And to change the illumination angle
Esri help
Also changing the direction and contrast

A: When you say in item #2 "can I create my effect with creating a Hillshade layer (without using Spatial Analyst)", do you mean alternate applications for creating a hillshade?
If you want to use an application outside of Spatial Analyst, I just recently learned about (but never have used) the "SEXTANTE for ArcGIS extension" (free), which allows users to consume SEXTANTE tools in ArcMap.  If you watch this video clip, you can see that they demonstrate ways to create a hillshade.

A: Use Bilinear Interpolation resampling during display
You can somewhat improve the display by changing the resampling method used from the default Nearest Neighbor to Bilinear Interpolation.  Layer Properties -> Display Tab -> Resample during display using: Bilinear Interpolation.
This effect works best with DEM and the default black and white color ramp.
You will get a much better result and a lot more control over the display when using 2 raster as you have already done. Make sure you also use the Bilinear Interpolation resampling method during display.
Add DEM:

Toggle "Use Hillshade Effect" on:

Renders as follows on screen:

Change resampling during display to Bilinear Interpolation:

Renders as follows on screen:

A: Arcmap's on the fly hillshade, the method described, is quick and dirty and was never meant to replace the hillshade result from Spatial Analyst and/or 3D Analyst. Although the same term is used to describe both they are not the same at all.
To create a true hillshade without Spatial Analyst you might try GDAL's gdaldem:
gdaldem hillshade dem.tif shade.tif

The TileMill Terrain Data Tutorial has a nice overview of how to use gdaldem to build a composite hillshade with hypsometric tinting.

If the utility is not direct enough for your application the C++ source code for gdaldem is here.


text:
Q: Cannot run app after updating SocialSharing-PhoneGap-Plugin I made an update to the SocialSharing-PhoneGap-Plugin and it now has a new dependency on this plugin es6-promise-plugin.
The issue I am experiencing is that when I try to load the app I receive an error:
Error: Module es6-promise-plugin.Promise does not exist.

in this function of the native file
function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {
    if (!(moduleName in moduleMap)) {
        throw new Error('Module ' + moduleName + ' does not exist.');
    }
    symbolList.push(strategy, moduleName, symbolPath);
    if (opt_deprecationMessage) {
        deprecationMap[symbolPath] = opt_deprecationMessage;
    }
}

This es6 plugin was added automatically and I didnt change anything about it.
Should I note the dependency somewhere else as well?
Thanks!