Q: Ionic2 cloud google login with asp.net web api I am building an ionic2 app and implemented google login flow. Which works fine and i get the token after a success full. How do i use this token to authenticate my project web api Endpoint  ( using Oauth for generating the tokens). I am using default asp.net web api project template


Q: How to establish a boost asio tcp socket over http proxy? I am trying to establish a TCP socket over http proxy. My current understand is,

*

*create tcp socket connecting to http_proxy_ip:http_proxy_port

*Via the socket send: CONNECT http://my.server.com:80 HTTP/1.0\r\n\r\n

My question is : is there need to wrap each tcp packet with some http header or use it like normal TCP sokcet(which is not over http proxy)?
Is there any equivalent for boost::asio TCP connection through http proxy
Thanks.


Q: Android app to create .txt file I'm trying to create an app where a user selects a few checkboxes, then when they hit submit it creates a .txt file with a sentence in it for every checkbox selected.
I have had one successful build of this, and it created the file properly, but I need it saved to an accessible file location so that it can be attached to an email.  I don't really care where it saves to, as long as it is accessible.
The following code causes a crash when run in Android Virtual Device and my Galaxy 2.  The application is a proof of concept for a later app.   Thank you.
        @Override
        public void onClick(View v)
        {
             String nochartOutput = " ";
             if (sitting.isChecked())
                 nochartOutput += "The patient was sitting in a chair. ";
             if (breathing.isChecked())
                 nochartOutput += "The patient was breathing. ";
             if (alert.isChecked())
                 nochartOutput += "The patient was alert. ";

             FileOutputStream fOut = null;
             File sdDir = Environment.getExternalStorageDirectory();
             try {
                 fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
             OutputStreamWriter osw = new OutputStreamWriter(fOut);
             try {
                 osw.write(nochartOutput);

                 osw.flush();
                 osw.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
        }

03-04 18:39:53.604: W/dalvikvm(10453): threadid=1: thread exiting with uncaught exception (group=0x40c211f8)
03-04 18:39:53.624: E/AndroidRuntime(10453): FATAL EXCEPTION: main
03-04 18:39:53.624: E/AndroidRuntime(10453): java.lang.IllegalArgumentException: File /mnt/sdcard/samplefile.txt contains a path separator
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ContextImpl.makeFilename(ContextImpl.java:1703)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ContextImpl.openFileOutput(ContextImpl.java:723)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:165)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.example.com.dresdor.autowriter.MainActivity$1.onClick(MainActivity.java:48)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.view.View.performClick(View.java:3620)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.view.View$PerformClick.run(View.java:14292)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Handler.handleCallback(Handler.java:605)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Looper.loop(Looper.java:137)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ActivityThread.main(ActivityThread.java:4507)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at dalvik.system.NativeStart.main(Native Method)

A: Your existing code is a mashup of writing to internal storage and external storage.  The line
fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);

attempts to create a file in the app's private data directory, and you can only pass file names to this method, not a deeper path.  That's where the crash is coming from, but it's not what you want.
You started to create a path to external storage, but never actually used it.  To write the file to that location on the external SD card, modify your code like so:
FileOutputStream fOut = null;
//Since you are creating a subdirectory, you need to make sure it's there first
File directory = new File(Environment.getExternalStorageDirectory(), "AutoWriter");
if (!directory.exists()) {
    directory.mkdirs();
}

try {
    //Create the stream pointing at the file location
    fOut = new FileOutputStream(new File(directory, "samplefile.txt"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);

//...etc...

Using the SD card allows the file to be accessed by anyone.

A: openFileOutput() writes file in the internal memory and not sd card. So change
fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);

to
fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE);

Also the file name can not contain path separators. See Android Developers Reference
public abstract FileOutputStream openFileOutput (String name, int mode)

Open a private file associated with this Context's application package
  for writing. Creates the file if it doesn't already exist.
Parameters name   The name of the file to open; can not contain path
  separators.

The file can be then be accessed like this.
FileInputStream fis = openFileInput("samplefile.txt");

Note:
For files which are huge in size, it's better to save it in sd card. Here is the code snippet.
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    FileOutputStream fos = null;
    try {
        File rootPath = new File(Environment.getExternalStorageDirectory(), "AutoWriter");
        if (!rootPath.exists())
            rootPath.mkdirs();

        File file = new File(rootPath, "samplefile.txt");
        fos = new FileOutputStream(file);

        // ... more lines of code to write to the output stream

    } catch (FileNotFoundException e) {
        Toast.makeText(this, "Unable to write file on external storage", Toast.LENGTH_LONG).show();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {}
        }
    }
}


Q: How to make a rich tooltip with a HTML form in it I have a paragraph of text with a link in it. I want to make a rich tool tip with a title on the top and a field to collect email addresses appear on hovering the link. What approach should I take?
I have looked into tool tip libraries but none seem to have form support. Please find the code below
The content in which the link is present:

Pellentesque habitant Link to show tooltip morbi senectus
tristique senectus et netus et malesuada pellentesque habitant senectus
fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies
eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

Tool tip content:

Tooltip title

Vestibulum tortor quam, feugiat vitae, ultricies
  eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
  Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

  <form>
    <input type="email" placeholder="john@doe.com" />
    <input type="submit" value="subscribe" />
  </form>
  This is our branding message

Now the effect I want to achieve is when I hover the link in the content the tooltip content should appear in a styled div. How should I do it?

A: Check this snippet
Updated

$("a").bind("mousemove", function(event) {
    $("div.tooltip").css({
        top: event.pageY + 10 + "px",
        left: event.pageX + 10 + "px"
    }).show();
})
$('.close').bind('click', function(){
  $("div.tooltip").fadeOut();
});
body{
    font-family:arial;
    font-size:12px;
}
.tooltip {
    width:350px;
    position:absolute;
    display:none;
    z-index:1000;
    background-color:#CB5757;
    color:white;
    border: 1px solid #AB4141;
    padding:15px 20px;
    box-shadow: 0px 3px 2px #8D8D8D;
    border-radius: 6px;
}
.close{
  right: 15px;
  position: absolute;
  background: #fff;
  color: #555;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 50%;
  font-size: 10px;
  cursor:pointer;
}

Pellentesque habitant Link to show tooltip morbi senectus
    tristique senectus et netus et malesuada pellentesque habitant senectus
    fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies
    eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
    Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    X

Tooltip title

Vestibulum tortor quam, feugiat vitae, ultricies
        eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
        Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    <form>
        <input type="email" placeholder="john@doe.com" />
        <input type="submit" value="subscribe" />
    </form>
    This is our branding message

A: Follow these steps:

*

*Add the link and the tooltip div inside a new div.

*Set tooltip div property to be visibility: hidden;

*and on hover set the property of this tooltip to be visible.

like:
HTML:

 Link to show tooltip

 ......

CSS:
.link {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}

.link .tooltip {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;

position: absolute;
z-index: 1;
}

.link:hover .tooltip {
visibility: invisible;
}

A: You could try to display yout tooltip element with the tilde selector on link hover:
.tooltip {
  display: none;
}

a:hover ~ .tooltip{
  display: block;
}

And then place your tooltip after the link element.

  blabla
  hover me
  tooltip content
  blabla

Here a pen where it works


Q: Facebook offline conversions without customer data I need to send offline conversions to facebook (https://developers.facebook.com/docs/marketing-api/offline-conversions) but often I don't know the email or other user data.
Is it possible to use data such as the Google Analytics client ID as an identifier?
I tried to send in the facebook pixel an additional field extern_id which is set to the analytics client id.
I send this identifier to Facebook with the offline API, unfortunately I don't find these conversions in facebook ads...


Q: Finding minimum sum of graph edge weight? I have been given a undirected weighted graph, witch represents the road with junctions. The task is in every cycle, which begins and ends in a same vertex choose the edge with the lowest weight and calculate the sum of all these edges in graph.
Idea is to use Prim algorithm, but there is a chance that some cycles doesn't include edge from MST.
How to solve this problem, and how to modify Prim's algorithm?


Q: conditionally set both fill and color in geom_point ggplot R what is wrong my code that does not change the filling color?
cars %>%
  ggplot() +
  geom_point(aes(x = speed, y = dist,
                 color= I(ifelse(dist >50, 'red', 'black')),
                 fill= I(ifelse(dist >50, 'pink', 'gray'))

                 )

             )

A: You need to have a point shape that allows both fill and colour.
library(ggplot2)
cars %>%
    ggplot() +
    geom_point(
        aes(x = speed, y = dist,
            color= I(ifelse(dist >50, 'red', 'black')),
            fill= I(ifelse(dist >50, 'pink', 'gray')),
        ),
        shape = 21,
        size = 4 # changing size so it's easy to visualise
    )

To check point shapes that allow both fill and colour use help(points) and refer to the 'pch' values section


Q: .Net AES encrypt mismatch after decrypt on Java I have to send the AES encrypted json as content to web server. But after decryption, the content has extra trash symbols appeared at the beggining of the line.
My test method creates the object that is serialized and being send:
[TestMethod]
public void SendModeChangeWorksAsExpected()
{
    var snpashot2Send = new ModeChangedReport
    {

        ControlWorkMode = ModeEnumeration.Stopped,
        //Controls
        ControlDate = DateTime.Now,
        IsSent = false,
        SentTime = null,
        ReportType = ReportType.ModeChanged,

        Line = new Line
        {
            AgencyId = "a799eb4f-86da-4af1-a221-9ed8b741b5ce"
        }
    };

    //Создаём шифрованное значение
    var encryptedString = _agencyReportEncriptingTranslator.ConvertModeChange2CypheredString(snpashot2Send);
    //Отправляем в Агентство и получаем результат
    var value = _agencyClient.SendModeChangeReport(encryptedString);
}

Here are the serialization and encrypt methods:
public string ConvertModeChange2CypheredString(ModeChangedReport report)
{
    if (report == null) throw new ArgumentNullException(nameof(report));

    //obj to json
    var json = new ModeChangedReportJson
    {
        LineId = report.Line.AgencyId,
        Mode = CreateModeFromIktToUzbekistan(report.ControlWorkMode),
        ActionDate = ConvertDateToAgencyString(report.ControlDate)
    };

    //Serialization
    var retString = _agencyJsonSerializer.SerializeReport2Json(json);

    //Шифруем сериализованный json
    var cypheredValue = _encryptionService.EncryptString(retString);
    return cypheredValue;
}

Encrypt method:
public string EncryptString(string plaintext)
{
    var plainTextBytes = Encoding.UTF8.GetBytes(plaintext);
    var cypheredTextBytes = Encrypt(plainTextBytes);
    var converted2Base64Value = Convert.ToBase64String(cypheredTextBytes);
    return converted2Base64Value;
}

private byte[] Encrypt(byte[] bytes)
{
    #region Args Validation

    if (bytes == null || bytes.Length < 1)
    {
        throw new ArgumentException("Invalid bytes to encrypt");
    }

    if (_key == null || _key.Length < 1)
    {
        throw new InvalidOperationException("Invalid encryption key");
    }

    #endregion

    byte[] encrypted;

    try
    {
        using (AesManaged aes = new AesManaged())
        {
            aes.Key = _key;
            aes.IV = _iv;
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, _iv);
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(aes.IV, 0, aes.IV.Length);
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(bytes, 0, bytes.Length);
                }
                encrypted = ms.ToArray();
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

    return encrypted;
}

Http client send method:
public bool SendModeChangeReport(string cypheredValue)
{
    var token = GetAccessToken();

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AuthorizationToken);
        client.DefaultRequestHeaders.Add("DEVICE_ID", _agencyAppSettings.DeviceId);

        var content2Post = new StringContent(cypheredValue, Encoding.UTF8, "application/json");
        using (var response = client.PostAsync(_agencyAppSettings.SendModeChangedReportUrl, content2Post).Result)
        {
            string tokenResponse = null;
            try
            {
                tokenResponse = response.Content.ReadAsStringAsync().Result;
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                _eventLogManager.LogError("При попытке отправить отчёт о смене режима, произошла ошибка: "
                    + $"Код: {response.StatusCode}. Контент: {tokenResponse}. Ошибка: {ex.Message}.");
                return false;
            }
        }
    }
}

After decryption on receiving server, the string grows with extra trash characters at the beginning, like G���h R��EQ�Z {"lineid":"a799eb4f-86da-4af1-a221-9ed8b741b5ce"...
The decrypt method of the server (Java):

I think that the problem is the padding difference: PKCS7 on my side, and PKCS5 on server.
How can I solve this problem with the extra chars appear on server side?

A: Those aren't trash characters, they're the Unicode Replacement Character returned when bytes are decoded into text using the wrong character set.
The very fact you got readable text means decrypting succeeded. It's decoding the bytes into text that failed.
The bug is in the Java code. It's using the String(byte[]) which, according to the docs:

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

That's obviously not UTF8. The String(byte[] bytes,Charset charset) or String(byte[] bytes,String charsetName) constructors should be used instead, passing the correct character set, eg :
byte[] decryptedBytes = cipher.doFinal(....);
return new String(decryptedBytes, StandardCharsets.UTF_8);

The hacky alternative is to change the remote server's default character set to UTF8.


Q: Break the loop into half, if the loop count is even I want to break the loop into half of the total loop count. If the total loop count is odd, I would like to remove the last array item in order to make the total loop count even and add the deleted item to the second half.
Here is the code structure to demonstrate the loop-
<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

I don't know how to control the loop based on my mentioned conditions. That's why I couldn't able to try loop controlling.

A: In a single loop. Hopefully, it'll work. Couldn't test so let me if you face any situation.
<?php
$faqs = new WP_Query([
    'post_type' => 'faq',
    'post_status' => 'publish',
]);
$half = intval($faqs->post_count / 2);
$counter = 0;
?>

    <?php while ($faqs->have_posts()) : $faqs->the_post(); ?>
        <?php if ( $counter === $half ) : ?>

        <?php endif; ?>

        <?php the_content(); ?>
    <?php ++$counter; endwhile; ?>

A: try it like this
<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>

      <?php
      $i=0;
      while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++
          the_content();
      endwhile();
      ?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query


Q: MySQL and PHP application fails - Error 2002 I've written a php-based site on my local machine and I'm trying to run it using the Apache Web Server in XAMPP and a mySQL database, which is on my local machine, external to XAMPP. When I go to the page where it should be, however, I get the following error:
Sorry, a problem occurred. Please try later.SQLSTATE[HY000] [2002] No such file or directory
I've seen a lot of people saying this points to php.ini not being able to access mysql.sock, but all of the changes haven't worked for me. I don't have any mysql.sock files, but I do have mysqld.sock files, and I've put the paths to them in php.ini at all the points where it asks for them. I haven't seen anyone talking about mysqld.sock files and whether or not it's an issue, so any help would be valuable.
Here's my config.php, if that's valuable:
ini_set( "display_errors", true );
date_default_timezone_set( "Europe/London" );  // http://www.php.net/manual/en/timezones.php
define( "DB_DSN", "mysql:host=localhost;dbname=dog_site" );
define( "DB_USERNAME", "root" );
define( "DB_PASSWORD", "***" );
define( "CLASS_PATH", "classes" );
define( "TEMPLATE_PATH", "templates" );
define( "HOMEPAGE_NUM_POSTS", 5 );
define( "ADMIN_USERNAME", "admin" );
define( "ADMIN_PASSWORD", "***" );
require( CLASS_PATH . "/User.php" );
require( CLASS_PATH . "/Litter.php" );
require( CLASS_PATH . "/Post.php" );
require( CLASS_PATH . "/PostLikes.php" );
require( CLASS_PATH . "/LitterLikes.php" );
require( CLASS_PATH . "/PostComments.php" );
require( CLASS_PATH . "/LitterPhotos.php" );
require( CLASS_PATH . "/PostPhotos.php" );

function handleException( $exception ) {
  echo "Sorry, a problem occurred. Please try later.";
  echo $exception->getMessage();
  error_log( $exception->getMessage() );
}

set_exception_handler( 'handleException' );
?>```


Q: How to configure Maven to build two versions of an artifact, each one for a different target JRE I have a maven module that I need to use in the J2ME client and in the EJB server. In the client I need to compile it for target 1.1 and in the server for target 1.6 .
I also need to deploy the 1.6 version to a Nexus repository, so the members working on the server project can include this dependency without needing to download the source code.
I've read at http://java.dzone.com/articles/maven-profile-best-practices that using profiles is not the best way of doing this, but the author didn't say what's the best way.
Here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>proj-parent</artifactId>
        <groupId>br.com.comp.proj</groupId>
        <version>0.0.4-SNAPSHOT</version>
    </parent>

    <artifactId>proj-cryptolib</artifactId>
    <name>proj - Cryto Lib</name>

    <dependencies>
        <dependency>
            <groupId>br.com.comp</groupId>
            <artifactId>comp-proj-mobile-messages</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>

        <plugins>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.3</source>
                    <target>1.1</target>
                    <fork>true</fork>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

A: As Haylem suggests thought you'll need to do it in two steps, one for the compile and one for the jars.
For the compiler
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5</version>
    <executions>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.5</target>
          <fork>true</fork>
          <outputDirectory>${project.build.outputDirectory}_jdk5</outputDirectory>
        </configuration>
      </execution>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.6</target>
          <fork>true</fork>
          <outputDirectory>${project.build.outputDirectory}_jdk6</outputDirectory>
        </configuration>
      </execution>
    </executions>
 </plugin>

And then for the jar plugin
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.1</version>
        <executions>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
            <configuration>
              <classesDirectory>${project.build.outputDirectory}_jdk5</classesDirectory>
              <classifier>jdk5</classifier>
            </configuration>
          </execution>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
            <configuration>
              <classesDirectory>${project.build.outputDirectory}_jdk6</classesDirectory>
              <classifier>jdk6</classifier>
            </configuration>
          </execution>
        </executions>
      </plugin>

you can then refer to the required jar by adding a <classifier> element to your dependency. e.g.
<dependency>
    <groupId>br.com.comp.proj</groupId>
    <artifactId>proj-cryptolib</artifactId>
    <version>0.0.4-SNAPSHOT</version>
    <classifier>jdk5</classifier>
</dependency>

A: You can configure this via the Maven compiler plugin.
Take a look at the Maven compiler plugin documentation.
You could enable this via different profiles for instance.
If you only want to have different target versions you could simply use a variable target.  Something like this:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.3</source>
        <target>${TARGET_VERSION}</target>
        <fork>true</fork>
    </configuration>
 </plugin>

A: To complement my comment to wjans' answer, as you requested more details.
The following would have the compiler plugin executed twice to produce two different sets of classfiles, identified by what is called a classifier (basically, a marker for Maven to know what you refer to when a single project can produce multiple artifacts).
Roughly, something like:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5</version>
    <executions>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.5</target>
          <fork>true</fork>
          <classifier>jdk5</classifier>
        </configuration>
      </execution>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.6</target>
          <fork>true</fork>
          <classifier>jdk6</classifier>
        </configuration>
      </execution>
    </executions>
 </plugin>

Note that people sometimes frown on using classifiers, as they on using profiles, as they can possibly mean that your project should be scinded in multiple projects or that you are harming your build's portability.


Q: A better way to do this htaccess rewrite rule I have this rewrite rule that checks for a country code in the url and fetches content accordingly.
Problem is there are 60+ countries. Can this be done in a different way rather than entering codes of all the countries in the rule?
RewriteRule ^/?(us|uk|ca)/p([0-9]+)/?$

Note the (us|uk|ca) part? A whole lot more need to go in there. Any better way to do this?

A: RewriteRule ^/?([a-z][a-z])/p([0-9]+)/?$

But it doesn't check if the language is a valid one (and I don't know if you expect language codes with more than 2 characters if such a thing exists)
EDIT : this regexp is shorter :
RewriteRule ^([a-z]{2})/p\d+/?$

The first slash is useless and \d+ means one or more digits, see @TerryE's comment


Q: mysql query that has join and counts I need help getting the top 5 results and their counts from columns from two different tables in a mysql database joined together.
table1 cols
-------
id, country, timestamp

table2 cols
--------
id, table1_id, reason

The results id like to get are the top 5 countries and their number of times found between two timestamps, and the top 5 reasons and their counts for all the rows used to generate the first count. There is a one to many relationship between table1 and table2. This is stumping me and I appreciate any insight you could give me.

A: It's not entirely clear what resultset you want to return.
This may be of some help to you:
SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
     , COUNT(r.id)          AS count_table2_rows
     , COUNT(*)             AS count_total_rows
  FROM table1 t
  LEFT
  JOIN table2 r
    ON r.table1_id = t.id
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP BY t.country
 ORDER BY COUNT(DISTINCT t.id) DESC
 LIMIT 5

That will return a maximum of 5 rows, one row per country, with counts of rows in table1, counts of rows found in table2, and a count of the total rows returned.
The LEFT keyword specifies an "outer" join operation, such that rows from table1 are returned even if there are no matching rows found in table2.
To get the count for each "reason", associated with each country, you could do something like this:
SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
  FROM table1 t
  LEFT
  JOIN ( SELECT s.country
              , r.reason
              , COUNT(*) AS cnt_r
           FROM table1 s
           JOIN table2 r
             ON s.table1_id = t.id
          WHERE s.timestamp >= NOW() - INTERVAL 7 DAY
            AND s.timestamp  < NOW()
          GROUP
             BY s.country
              , r.reason
       ) u
    ON u.country = t.country
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP
    BY t.country
     , u.reason
 ORDER
    BY COUNT(DISTINCT t.id) DESC
     , t.country DESC
     , u.cnt_r DESC
     , u.reason DESC

This query doesn't "limit" the rows being returned. It would be possible to modify the query to have only a subset of the rows returned, but that can get complex. And before we muck the complexity of adding "top 5 within top 5" type limits, we want to ensure that the rows returned by a query are a superset of the rows we actually want.

A: Is this what you want?
select t2.reason, count(*)
from (select t1.country, count(*)
      from table1 t1
      where timestamp between @STARTTIME and @ENDTIME
      group by country
      order by count(*) desc
      limit 5
     ) c5 join
     table1 t1
     on c5.country = t1.country and
        t1.timestamp between @STARTTIME and @ENDTIME join
     table2 t2
     on t2.table1_id = t1.id
group by t2.reason;

The c5 subquery gets the five countries.  The other two bring back the data for the final aggregation.


Q: R: Print list to a text file I have in R a list like this:
> print(head(mylist,2))
[[1]]
[1] 234984  10354  41175 932711 426928

[[2]]
[1] 1693237   13462

Each element of the list has different number of its elements.
I would like to print this list to a text file like this:
mylist.txt
234984  10354  41175 932711 426928
1693237   13462

I know that I can use sink(), but it prints names of elements [[x]], [y] and I want to avoid it. Also because of different number of elements in each element of the list it is not possible to use write() or write.table().

A: Not tested, but it should work (edited after comments)
lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)

A: Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.
dput(mylist, "mylist.txt")

A: I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.
So:
@ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.
sink("mylist.txt")
print(mylist)
sink()

Make sure to have the sink() at the end your code so that you cancel the sink.

A: depending on your tastes, an alternative to nico's answer:
d<-lapply(mylist, write, file=" ... ", append=T);

A: Another way
writeLines(unlist(lapply(mylist, paste, collapse=" ")))

A: Here's another way using sink:
sink(sink_dir_and_file_name); print(yourList); sink()

A: Here is another
cat(sapply(mylist, toString), file, sep="\n")

A: I solve this problem by mixing the solutions above.
sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()

I think it works well


Q: Clearing a text file in PHP I have a text file that ends up with over 500 lines of text each day. I'm setting up a cron job to manually clear the file at the end of the day but I cannot get it to clear. I've looked online and tried the methods below, but nothing seems to clear the text file... (I ran the file on my server and checked the .txt file using Transmit FTP Client to check the text file and the 500+ lines of text were still there.)
$handle = fopen ("emails.txt", "w+");
fclose($handle);

file_put_contents('emails.txt', '');

$handle = fopen("emails.txt", "w+");
fwrite($handle , '');
fclose($handle);

How can I empty this text file using PHP?

A: This works for me:
$f = fopen('emails.txt','r');
$content = file('emails.txt');
array_splice($content, 0, 500);
file_put_contents('emails.txt', $content);
fclose($f);

A: It looks like you want to truncate your file.
Try with w, instead of w+ http://www.tizag.com/phpT/filetruncate.php
You may also want to check your error logs. If the file isn't writeable by the web / apache user then nothing significant will occur.

A: If you have this on a cron task, you may want to use sed instead.  Sed can remove as many lines as you wish from a file.
Unix Sed Command to Delete lines in file
sed '1d' file removes the first line in a file, while sed '2,4d' file would remove lines 2 through 4.
If you do this via cron, be sure to include the full path to your file, from / (root) forward.

A: Assuming that your script have permissions to write to the text file and that the two files are located in the same directory. I guess that you're not running the script from the same directory, so you could try this :
$handle = fopen (__DIR__."/emails.txt", "w");
fclose($handle);


Q: Fastest way to get residuals from linear, poisson, and negative binomial regressions across many responses I have a numeric, a count, and an over-dispersed count large matrices:
set.seed(1)
numeric.mat <- matrix(rnorm(10000*6000),10000,6000)
count.mat <- matrix(rpois(10000*6000,10),10000,6000)
dispersed.count.mat <- matrix(rnegbin(10000*6000,10,2),10000,6000)

And one corresponding factors data.frame (can be a matrix too):
factors.df <- data.frame(f1 = sample(LETTERS[1:3], 10000, replace = T),
                         f2 = sample(LETTERS[4:5], 10000, replace = T))

The number of factors is pretty small (in this case only 2 but won't be more than 5 for real data), and the number of levels in each (they're all categorical) is also small (also up to 5).
I'd like to obtain the residuals for fitting a linear, poisson, and negative binomial regression models to each of the columns in each of the matrices, respectively.
So for a single column:
data.df <- factors.df %>%
    dplyr::mutate(numeric.y = numeric.mat[,1],
                  count.y = count.mat[,1],
                  dispersed.count.y = dispersed.count.mat[,1])

I'd use:
lm(numeric.y ~ f1+f2, data = data.df)$residuals
residuals(object = glm(count.y ~ f1+f2, data = data.df, family = "poisson"), type = 'pearson')
residuals(object = glm.nb(formula = model.formula, data = regression.df), type = 'pearson')

For the three regression models.
Is there a faster way of obtaining these residuals other than, for example, using do.call, for each. E.g.:
do.call(cbind,
        lapply(1:ncol(numeric.mat),
               function(i)
                   lm(numeric.y ~ f1+f2,
                      data = dplyr::mutate(factors.df,
                                           numeric.y = numeric.mat[,i])
                   )$residuals
))

A: I'd slightly readjust how the workflow runs and allow it to be easily run in parallel.
# Use variables to adjust models, makes it easier to change sizes
iter <- 60
iter_samps <- 1000

factors_df <- data.frame(f1 = sample(LETTERS[1:3], iter_samps, replace = T),
                         f2 = sample(LETTERS[4:5], iter_samps, replace = T))

# using a data.frame in a longer format to hold the data, allows easier splitting
data_df <- rep(list(factors_df), iter) %>%
  bind_rows(.id = "id") %>%
  mutate(numeric_y = rnorm(iter_samps * iter),
         count_y = rpois(iter_samps * iter, 10),
         dispersed_count_y = MASS::rnegbin(iter_samps * iter, 10, 2))

# creating function that determines residuals
model_residuals <- function(data) {
  data$lm_resid <- lm(numeric_y ~ f1+f2, data = data)$residuals
  data$glm_resid <- residuals(object = glm(count_y ~ f1+f2, data = data, family = "poisson"), type = 'pearson')
  return(data)
}
# How to run the models not in parallel
data_df %>%
  split(.$id) %>%
  map(model_residuals) %>%
  bind_rows()

To run the models in parallel you can use multidplyr to do all the annoying work
library("multidplyr")
test = data_df %>%
  partition(id) %>%
  cluster_library("tidyverse") %>%
  cluster_library("MASS") %>%
  cluster_assign_value("model_residuals", model_residuals) %>%
  do(results = model_residuals(.)) %>%
  collect() %>%
  .$results %>%
  bind_rows()


Q: Excel Pain: Saved With Filters, Opened And file Was Half the Size So something happened twice that has caused me hours of retroactive work. Extremely, extremely annoying, and the bain of my existence.
I have an .xls file with about 171K rows. I saved it with filters on, reducing the number of shown rows to about 13K. When I reopened the file the next day the filters were not showing, but rows were 'hidden', because in order to show all the rows I had to 'unhide'. The problem is that when I unhide, the total rows is ~65K aka the last numbered row that was showing when I had filters on.
Has this happened to anyone before or know how to recover the full 171K rows? I know for a fact I didn't 'clear' or 'delete' anything before or after saving.

A: One piece of advise I have is for you to start reading screen prompts.  When saving a large file with over 65536 rows this kind of warning is displayed.  Only you can prevent your own errors.

A: You can avoid this by making a copy of the original and filtering on that, then you always have the source if you make an error.


Q: Higher direct image of coherent sheaf Hi.
Can any one me say if there is a simple proof of this claim which i can prove it by localization and no easy technique of nuclear spaces...
Let $f:X\rightarrow S$ be an open, surjective morphism of complex reduced spaces with constant fiber dimension $n$ (or universally open morphism with $n$-fibers between locally noetherian excellent without embedded componnet schemes on field of charact.0).
Let $G$ be a coherent sheaf on $X$.
Claim: ${\rm R}^{n}f_{*}G=0$ if and only if the support of $G$ satisfies:
${\rm Supp}(G)\cap X_{s}$  is nowhere dense in the fiber $X_{s}$.
Remark:
1) We can assume $X$ $n$-complete space(i.e there exist a smooth strongly $n$-convex exhaustion function on $X$)   and then all cohomology group $H^{k}(X, F)$ vanish for all coherent sheaf $F$ and all $k>n$.
2) For a projection $f:S\times U\rightarrow S$ where $U$ is an open polydisque of $C^{n}$, the result is true for ${\rm R}^{n}f_{!}$. By right exactness of the $n$-higher direct image functor, we can localize and deduce from the projection case the general case.... But, it is no simple proof...
Thank you very much.

A: Are you sure this is what you mean? Take $S$ to be a point, $X=$ affine $n$-space ($n>0$), $G=\mathcal{O}_X$. The support is $X$ and the cohomology vanishes.

A: Dear Laurent,
Yes, I'm sure that the claim is what i want and trivially, for $X$ Stein or Stein morphism we have nothing to prove: all the cohomology object vanish.
You can assume $X$ $n$-complete complex space and then $H^{n}(X, G)$ is generally not finite dimensional.
In the general proof, the absolute case is essential and is proved by mean of Serre duality.
The relative case is not so trivial and make fundamental use of free nuclear resolution and quasi-coherency in analytic geometry.
Thank you.

A: Yes,
Excuse me, we must add in the hypothesis that the morphism is not Stein morphism or the cohomology group $H^{n}(X, F}$ dont vanish for all coherent sheaf $F$ on $X$... In fact, we avoid the situation for which the cohomology or the higher direct image are trivial...


Q: Examples table throwing error in Eclipse when parameterising scenario I am in the process of working through a guide on how to parameterise my test runs with an Examples table however when I write the scenario in Eclipse as the guide states, I get an error against the Examples Table.
I tried refreshing my project or attempting to see if I needed to import anything however there Eclipse does not provide any information beyond the error message. "Examples" is set to bold and formatted in the manner of "Scenario Outline:" which suggests Eclipse recognises it for what it is but in spite of this I get an error.
    Scenario: Home page default login
        Given User is on landing page
        When User login to application with username <username> and password <password>
        Then Home page is displayed
        And The user is registered

        Examples:
        |username | password |
        |Leonard  | zxcv     |
        |Lyra     | qwerty   |

The error shown against the Examples line is simply;
missing EOF at 'Examples:'

A: The answer is simple, and not "I'm an idiot" although there's an argument for that.
The issue I am experiencing is that I use Scenario: as opposed to Scenario Outline:
Making that simple change removes the error and allows me to run my test


Q: fixed height Slider for any device I am trying to achieve a full screen option for any device. There is a slider along with 04 boxes which & I am trying to show all of them in full screen on any device. I have almost achieved it by using .carousel-inner {min-height:83vh;} .carousel-inner img{max-height:83vh;} but its stretching the image. I need a better solution.

.container-fluid {
  margin:0;
  Padding:0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        ...

        ...

    Previous

    Next

A: in css only Write This
.carousel-inner > .item > img {
  height:500px;
}

If I use the provided class so its also effecting width but when I used min-height with your class so its working fine but only on laptop and small screen sizes but also stretching. its not working with large screens

A: Plz use it

css >>
.carousel-inner { }
.carousel-inner img { width:100% }

on 4 box container add id >>


Q: How secure is field validation in Google Forms? Some people are using this data validation pattern to protect forms:

*

*A youtube video from Google for Education uses this pattern.

*A similar scenario to mine with a similarly proposed solution.

Since Google for Education showcases this pattern, I want to believe it is reasonably secure. But I also understand the above solution is client-side validation, based on this answer.
Logically, doesn't this imply the validation values and logic can be exposed by scraping/viewing the source? How safe is it to store passwords and unique IDs as a regex in these validation fields?
For context, I'm hoping to use Google Forms + GAS for verified, unique form submissions from a set of non-google account emails while reducing quota usage from spam/misuse.

A: It's not secure. All client side validations are insecure by design. Pattern validation passwords are visible in the source code. Having said that, a single password for multiple users is also insecure. All it takes is one user compromise to invalidate the whole thing.
If you need a fully secure solution, create your own form with HtmlService with oauth authorization and Google identity.


Q: How to flatten a multi column dataframe into 2 columns Given the following table:
group_a = {'ba':[2.0,9.4,10.8],
          'bb':[4.2,7.1,3],
          'bc':[8.1,9.5,6.1]}

A = pd.DataFrame(group_a, index=['aa','ab','ac'])

That looks like this:
    ba   bb   bc
aa  2.0  4.2  8.1
ab  9.4  7.1  9.5
ac  10.8 3.0  6.1

How can I flatten this table so that it looks like this:
       Values
aa_ba  2.0
aa_bb  4.2
aa_bc  8.1
ab_ba  9.4
ab_bb  7.1
ab_bc  9.5
ac_ba  10.8
ac_bb  3.0
ac_bc  6.1

A: You can use stack and rework the index:
B = A.stack()
B.index = B.index.map('_'.join)
out = B.to_frame('Values')

output:
       Values
aa_ba     2.0
aa_bb     4.2
aa_bc     8.1
ab_ba     9.4
ab_bb     7.1
ab_bc     9.5
ac_ba    10.8
ac_bb     3.0
ac_bc     6.1

A: Since you have your indexes set, you can do this most easily with a .stack operation. This results in a pd.Series with a MultiIndex, we can use a "_".join to join each level of the MultiIndex by an underscore and create a flat Index. Lastly, since you wanted a single column DataFrame you can use .to_frame() to convert the Series into a DataFrame
out = A.stack()
out.index = out.index.map("_".join)
out = out.to_frame("values")

print(out)
       values
aa_ba     2.0
aa_bb     4.2
aa_bc     8.1
ab_ba     9.4
ab_bb     7.1
ab_bc     9.5
ac_ba    10.8
ac_bb     3.0
ac_bc     6.1

You can also use a method chained approach- just need to use .pipe to access the stacked index:
out = (
    A.stack()
    .pipe(lambda s: s.set_axis(s.index.map("_".join)))
    .to_frame("values")
)

print(out)
       values
aa_ba     2.0
aa_bb     4.2
aa_bc     8.1
ab_ba     9.4
ab_bb     7.1
ab_bc     9.5
ac_ba    10.8
ac_bb     3.0
ac_bc     6.1

A: Stack, use list comprehension and fstrings to compute new index .
 s = A.stack().to_frame('values')

 s.index=([f'{a}_{b}' for a,b in s.index])

        values
aa_ba     2.0
aa_bb     4.2
aa_bc     8.1
ab_ba     9.4
ab_bb     7.1
ab_bc     9.5
ac_ba    10.8
ac_bb     3.0
ac_bc     6.1


Q: Listing indices using sqlalchemy Is it possible to list all indices in a db using sqlalchemy?

A: yes.
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
for name in insp.get_table_names():
    for index in insp.get_indexes(name):
        print index


Q: Weird 240 ohm resistor on zq line to DDR I've been looking at schematics that interface ddr ram and noticed a weird notation for their zq pull down resistor. What is with the dot at the top as well as the 1%? Haven't seen this before.

A: Because these DDR's have merged drivers and on-chip termination they have an active termination calibration circuitry and procedure.  The calibration resistor should be accurate , thus the 1% selection.
Note that this resistor can be shared amongst die if the controller sequences properly. Look at this app note from Micron (opens a PDF) concerning the calibration "DDR3 ZQ Calibration".
The dot ... see this EE.SE post

From that data sheet.

A: 1% is the resistor tolerance (its 'accuracy' value). The actual resistor used in the circuit must have a value that is within 1% of the specified 240R.
The dot may be an orientation indicator of some sort. Could this resistor be one part of a network or package of multiple resistors?


Q: Comparing two tables and returning rows that do not exist based on multiple field comparisons Say I have a Table called #ListTable:
Item:
Apple
Bannana
Pea
Milk
Green

And Another Table Food similar to:
Date       Fruit       Vegetable      Dairy       Color
2/16/17    Apple       NULL           NULL        Green
2/16/17    NULL        Pea            NULL        Green
2/16/17    NULL        NULL           Milk        White

If the value in the list exists in the Food Table I want to return the record.
So I have something like:
DECLARE @Date = '2/16/17',
@InclusionFlag = 1

SELECT *
FROM Food F
INNER JOIN #ListTable LT1
ON F.Fruit = LT1.Item
WHERE Date = @Date

UNION ALL

SELECT *
FROM Food F
INNER JOIN #ListTable LT2
ON F.Color = LT1.Item
WHERE Date = @Date

...

Essentially returning a record if the item in the List corresponds to one of the fields I specify. I know there could be "duplicate" records like Apple being "Apple" and "Green" and I want that.
However, I also want to be able to toggle the Inclusion Flag to 0 and return items in ListTable that do not have a match with any fields in Food.
How would I return that list of securities that do not match? I know there are similar questions but I am having trouble figuring it out for the multiple field comparison case.
Thanks

A: You can use cross apply() to unpivot your data first, then use a case expression with when exists() in your where clause to return 0 or 1 when it exists and compare that to @InclusionFlag.
;with FoodItem as (
  select x.Item
  from food as f
  cross apply (values (Fruit),(Vegetable),(Dairy),(Color)) as x (Item)
  where x.Item is not null
    and f.Date = @Date
)

select
    lt.Item
from ListTable as lt
where case when exists (
    select 1
    from FoodItem fi
    where lt.Item = fi.Item
  ) then 1 else 0 end = @InclusionFlag

A: If I got it right, Food rows (may be repeating) matching #ListTable
SELECT F.*
FROM Food F
INNER JOIN #ListTable LT1
ON LT1.Item IN (F.Fruit, F.Vegetable, F.Dairy, F.Color)
WHERE Date = @Date


Q: How to get a currency's display name before Android API 19? Currency.getDisplayName(java.util.Locale) is exactly what I want... except it's only available since Android API 19. That's no good as my minSdkVersion < 19.
Does anyone know how to get the locale-specific display name for a currency before API 19? Preferably without having to use a third-party library.
This question can alternatively be expressed as:
How can you get the equivalent of Currency.getDisplayName(java.util.Locale) before Java 7?


Q: Applying finder tags to applications - What are the consequences? I'm trying to put Maveric's new feature - Finder Tags - to a good use, so I have a bunch of installed applications, some I have read/write permissions but for some others I don't (All apps installed by the OS and some others, such as Parallels Desktop, to give one example).
So if I want to get a list with all apps bundled in OSX I could by typing this to Spotlight:
tag:OsApp

Apps installed (not bundled in OSX):
tag:MyApp

The beauty in it is I could, also, find all the web browsers installed (by OSX or by me) by doing this:
tag:WebBrowser

Or get only the browsers installed by me:
tag:MyApp tag:WebBrowser

So far so good, but here is my potential issue:
To be able to tag some apps I should enable write permissions on them, tag the apps, then restore the permissions as it were before I tagged those apps. What happens when there is an update for an app I've tagged by changing its permissions?
Will I get an error? Will the app be updated successfully? Will the tag(s) remain?

A: Since I've asked this a long time ago, now I have some thoughts about my very own question, maybe anyone else is wondering the same so here it goes.
Will I get an error? Will the app be updated successfully? Will the tag(s) remain?
Basically its a NO to both questions.
Why?
When you update an app it overwrites itself. So no tags, at least not as far as I know and/or tested. And tags will not break any update, again, as far as I know and/or tested.
IF someone posts a better answer I will choose the other answer over this.


Q: Issues with wired connection on 20.04 Wired network stopped working after I switched from Gnome to KDE Plasma and back. I got it working on Gnome earlier, switched to KDE and didn't use wired for some time, today I switched back to Gnome and it doesn't work.
$ sudo ethtool wlp2s0
Settings for wlp2s0:
    Link detected: yes

$ sudo lshw -c net
  *-network UNCLAIMED
       description: Ethernet controller
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:01:00.0
       version: 10
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd cap_list
       configuration: latency=0
       resources: ioport:5000(size=256) memory:a4104000-a4104fff memory:a4100000-a4103fff
  *-network
       description: Wireless interface
       product: RTL8821AE 802.11ac PCIe Wireless Network Adapter
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlp2s0
       version: 00
       serial: c8:3d:d4:3b:e9:71
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=rtl8821ae driverversion=5.15.0-57-generic firmware=N/A ip=192.168.1.129 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:128 ioport:4000(size=256) memory:a4000000-a4003fff

# apt list --installed | grep -E '^linux'

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

linux-base/focal-updates,focal-updates,now 4.5ubuntu3.7 all [installed,automatic]
linux-firmware/focal-updates,focal-updates,now 1.187.35 all [installed,automatic]
linux-generic-hwe-20.04/focal-updates,focal-security,now 5.15.0.58.64~20.04.24 amd64 [installed]
linux-headers-5.15.0-57-generic/focal-updates,focal-security,now 5.15.0-57.63~20.04.1 amd64 [installed]
linux-headers-5.15.0-58-generic/focal-updates,focal-security,now 5.15.0-58.64~20.04.1 amd64 [installed,automatic]
linux-headers-5.4.0-137-generic/focal-updates,focal-security,now 5.4.0-137.154 amd64 [installed,automatic]
linux-headers-5.4.0-137/focal-updates,focal-updates,focal-security,focal-security,now 5.4.0-137.154 all [installed,automatic]
linux-headers-generic-hwe-20.04/focal-updates,focal-security,now 5.15.0.58.64~20.04.24 amd64 [installed,automatic]
linux-headers-generic/focal-updates,focal-security,now 5.4.0.137.135 amd64 [installed]
linux-hwe-5.15-headers-5.15.0-57/focal-updates,focal-updates,focal-security,focal-security,now 5.15.0-57.63~20.04.1 all [installed,automatic]
linux-hwe-5.15-headers-5.15.0-58/focal-updates,focal-updates,focal-security,focal-security,now 5.15.0-58.64~20.04.1 all [installed,automatic]
linux-image-5.15.0-57-generic/focal-updates,focal-security,now 5.15.0-57.63~20.04.1 amd64 [installed]
linux-image-5.15.0-58-generic/focal-updates,focal-security,now 5.15.0-58.64~20.04.1 amd64 [installed,automatic]
linux-image-generic-hwe-20.04/focal-updates,focal-security,now 5.15.0.58.64~20.04.24 amd64 [installed,automatic]
linux-libc-dev/focal-updates,focal-security,now 5.4.0-137.154 amd64 [installed,automatic]
linux-modules-5.15.0-57-generic/focal-updates,focal-security,now 5.15.0-57.63~20.04.1 amd64 [installed]
linux-modules-5.15.0-58-generic/focal-updates,focal-security,now 5.15.0-58.64~20.04.1 amd64 [installed,automatic]
linux-modules-extra-5.15.0-57-generic/focal-updates,focal-security,now 5.15.0-57.63~20.04.1 amd64 [installed]
linux-modules-extra-5.15.0-58-generic/focal-updates,focal-security,now 5.15.0-58.64~20.04.1 amd64 [installed,automatic]
linux-sound-base/focal,focal,now 1.0.25+dfsg-0ubuntu5 all [installed,automatic]

# dkms status
nvidia, 525.78.01, 5.15.0-57-generic, x86_64: installed
nvidia, 525.78.01, 5.15.0-58-generic, x86_64: installed
nvidia, 525.78.01, 5.4.0-137-generic, x86_64: installed
rtl8821ce, 5.5.2.1, 5.15.0-57-generic, x86_64: installed
rtl8821ce, 5.5.2.1, 5.15.0-58-generic, x86_64: installed
rtl8821ce, 5.5.2.1, 5.4.0-137-generic, x86_64: installed

# grep r8169 /etc/modprobe.d/*
/etc/modprobe.d/r8168-dkms.conf:# map the specific PCI IDs instead of blacklisting the whole r8169 module
/etc/modprobe.d/r8168-dkms.conf:# to blacklist the whole r8169 module
/etc/modprobe.d/r8168-dkms.conf:#blacklist r8169

# dmesg | grep r8169
<no output>

# lspci -knn | grep Eth -A3
01:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 10)
    Subsystem: Lenovo RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [17aa:384c]
    Kernel modules: r8168
02:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8821AE 802.11ac PCIe Wireless Network Adapter [10ec:8821]
    Subsystem: Lenovo RTL8821AE 802.11ac PCIe Wireless Network Adapter [17aa:a814]

A: You have r8169 module blacklisted.
Run
sudo apt purge r8168-dkms
sudo rm /etc/modprobe.d/r8168-dkms.conf
sudo modprobe r8169

There may be errors when you run first commands depending on what is really installed, but if the 3rd is OK, network should start working.


Q: How can I set static asset cache-control headers while using PHP on Heroku? Is this worth trying to accomplish or should I move the assets to CloudFront (or some other CDN)?
Based on past experience, I'm hesitant to go down the CDN route with this project. I tried using a rake task to minify and concatenate my assets, then upload them to the CloudFront. However, when I deployed the project (now containing the rake task) Heroku decided that my app was now ROR and not PHP and the app was toast.


Q: subtract two values in the field I am using python.
There are two columns. columns A and B. I want to reduce the value in column A and B when the save button in the press
this my code
But what happens when I press the save button. value to 0
def _tot_get_deposit(self, cr, uid, ids, name, arg, context=None):
    res = {}
    for deposit in self.browse(cr, uid, ids, context=context):
        sum = 0.0
        sum = A - B
        return sum
    return res

A: i think you need to read more about how functions work.
once you return anything, the function will end.
you can not itterate over anything and return multiple values within a function.
try saving them locally in the function, and then at the end returning a list/dict/tuple with all the results.
for instance... i think your code could be written:
def _tot_get_deposit(self, cr, uid, ids, name, arg, context=None):
    res = {}
    results = []
    for deposit in self.browse(cr, uid, ids, context=context):
        sum = 0.0
        sum = A - B
        results.append( sum )
    return (res,results)

this will create a list of "sum" which is then added to your dict "res" and then returned. together as a tuple.


Q: How can multiple web devs use git to work on one page simultaneously? We're looking into using git for a new system we're designing.
We currently have a production machine and a dev machine.
We use svn to keep production updated with our dev commits.
The dev machine has a complete copy of our codebase for each developer (just 2 of us currently).
Here's the file structure:
html/
  dev_timmy/
    stuff/
      thing1.php
      thing2.php
  dev_johnny/
    stuff/
      thing1.php
      thing2.php

If we were both working on thing1.php, I would make changes to the file in my directory, and he'd make changes to it in his. To test our changes, we simply include our dev directory in the url.
http://ourwebsite.com/dev_timmy/stuff/thing1.php
http://ourwebsite.com/dev_johnny/stuff/thing1.php

I'm sure having copies of code isn't the best solution.
But how can we view our own changes on the internet?
How can we make dev_timmy-based urls resolve to the version of the page that Timmy is working on?

A: There's nothing special about git to help with this kind of thing: Files have to be on disk somewhere so they can be dished out by a web server.
This question basically boils down to workflow. If you want to be able to look at the code you're working on independent of the code your coworker is working on the general solution is to have multiple sites (either separate web servers or just different virtual hosts behind a server) setup with different URLs. For example at our company we each have our own dev vm, and our own username.company.com URL that we can use to refer to code hosted on our VM.
Generally people have their git repository as the document root (or virtual host root) for their web server. They edit and test on this, committing locally as they go.
When we're done with our development we merge to a central repository, and there's a web server in test that we can go to which shows what's currently merged for testing. Once that's been accepted it's merged to master and pushed to production.

A:
But how can we view our own changes on the internet?

First of all you have to upload it to the internet of course.
You will need some place to store your code (bitbucket, gthub etc).
Those cloud services has a web interface to view your changes and all your history as well.

How can we make dev_timmy-based urls resolve to the version of the page that Timmy is working on?

Using git you can use branches. Each one of you will have its own branch which will allow you 2 to work on the same code at the same time and update your local code whenever you want.
This is what branches are.

Another solution might be to use the same project as submodule or using workdir which will allow you to have the same code under different folders


Q: How to sort different data types in java and print them in a table ? (using method overloading) The objective is to input "any data type" using a java method overloading. After the value has been taken, another method will sort the data according to it's data type in different arrays. After the all the data has been entered and stored in arrays, it has to be printed onto a table.
Eg:
data(23)  - this will store integer value to an array
data(34.453) - this will store the double value to an array
data("hello world") - this will store string value to array
Considering that array size in java are predefined, the table should not print the null or 0 values. All the null/0 values should be excluded while printing.

A: To solve this problem:

*

*We can use the method overloading to capture all data

*Each method will use a different data type but will have the same name - data()

*The number of null values of each array should be found out.

*the variable n will determine which is the largest size among all the 3 integers.

*n will be the test expression limit when printing the table

public class overLoadEg {
//array that will store integers
    static int[] intArray = new int[10];
//array that will store doubles
    static double[] doubleArray = new double[10];
//array that will store strings
    static String[] stringArray = new String[10];
    static int i = 0, j = 0, k = 0, m, n;

    public static void main(String[] args) {
//input values
        data(23);
        data(23.4554);
        data("Hello");
        data("world");
        data("help");
        data(2355);
        data(52.56);
        data("val");
        data("kkj");
        data(34);
        data(3);
        data(2);
        data(4);
        data(5);
        data(6);
        data(7);
        data(8);
        display();
    }

    public static void data(int val){
        //add int value to int array
        intArray[i] = val;
        System.out.println("Int " + intArray[i] + " added to IntArray");
        i++;
    }
    public static void data(Double val){
        //add double value to double array
        doubleArray[j] = val;
        System.out.println("Double " + doubleArray[j] + " added to doubleArray");
        j++;
    }
    public static void data(String val){
        //add string value to stringarray
        stringArray[k] = val;
        System.out.println("String " + stringArray[k] + " added to stringArray");
        k++;
    }

    public static void max(){
        //To get the maximum number of values in each array
        int x, y, z;
        x = y = z = 0;

        //counting all the null values in each array and storing in x, y and z
        for(m=0;m<10;m++){
            if(intArray[m] == 0){
                ++x;
            }
            if(doubleArray[m] == 0){
                ++y;
            }
            if(stringArray[m] == null){
                ++z;
            }
        }

        //subtracting the null/0 count from the array size
        //this gives the active number of values in each array
        x = 10 - x;
        y = 10 - y;
        z = 10 - z;

        //comparing all 3 arrays and check which has the max number of values
        //the max numbe is stored in n
        if(x > y){
            if(x > z){
                n = x;
            }
            else{
                n = z;
            }
        }
        else{
            if(y > z){
                n = y;
            }
            else{
                n = z;
            }
        }

    }

    public static void display(){
        //printing the arrays in table
        //All the null/0 values are excluded

        System.out.println("\n\nInt\tDouble\t\tString");
        max();
        for(m = 0; m < n; m++){
            System.out.println(intArray[m] + "\t" + doubleArray[m] + "\t\t" + stringArray[m]);
        }
        System.out.println("Count : " + m);
    }

}


Q: d3 cloud layout - show all tags [background]
currently I'm working on a little web project for data visualization and I want to use create a tagcloud or wordcloud with cloud layout of the javascript d3 framework (d3 cloud layout).
I've built some examples that almost satisfy my requirements. The only thing that doesn't work is, that some words/tags aren't displayed in my tag cloud.
As far as I understand the placing algorithm for the tags, this comes because the algorithm finds no suitable place to position all tags without overlaying other tags.
My question: How can I display all available tags and is there a setting in the framework to do this?
I'm rather new to javascript so I had quite a hard time to understand the whole cloud layout and the positioning algorithm to find a way to achieve my goal.


Q: iOS8 GameKit TurnBasedMatch playerID deprecated I am working with GameCenter / GameKit in iOS8 to build a TurnBasedMatch. I am confused as to how to identify whether the current player (ie the one with the app running currently on the iPhone) is the one whose turn it is.  The reason I am having this issue is that Apple docs say that GKTurnBasedParticipant.playerID is deprecated in iOS8.
I used to do the following:
- when GameCenter authenticates:
(1) store the current playerID locally
(2) load the current Match
(3) check if Match.currentParticipant's playerID matches the locally stored playerID and if it is then allow the player to take his turn
Now in iOS8 - currentParticipant (which is a GKTurnBasedParticipant) has playerID deprecated. So how do I know whether the currentParticipant is actually the local player?

A: You don't need to store the playerID to check identities. Local playerID can be accessed always with:
[GKLocalPlayer localPlayer].playerID

As to how to use playerID now that it's deprecated, that property was only moved from GKTurnBasedParticipant to GKPlayer. That doesn't affect the code that I pasted before, but it does affect the way you access to match.participants. So, for any given player, the way to access it in iOS8 would be:
GKTurnBasedParticipant *p1 = (GKTurnBasedParticipant *)self.match.participants[index];
p1.player.playerID

As you can see, you only have to add a .player to your current code.


Q: SMPT SSL exception origin I am sending mail using SMTP SSL in my c# code. While sending mail , iam getting the following exception-

Server does not support secure connections.

When does this error comes? Does this implies problem on sender's side or the receiver's side.
SMTP configuration
    <add key="EmailUserName" value="mail@gmail.com" />
    <add key="NameToDisplay" value="Admin" />
    <!--Use proper password-->
    <add key="EmailPassword" value="password" />
    <add key="SmtpHostUrl" value="smtp.gmail.com" />
    <add key="SmtpPort" value="25" />

SendMail method
SmtpClient objSmtpClient = new SmtpClient();
                objSmtpClient.Host = ConfigurationManager.AppSettings["SmtpHostUrl"];
                objSmtpClient.Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
                objSmtpClient.UseDefaultCredentials = false;
                objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                objSmtpClient.EnableSsl = true;
                objSmtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUserName"],
                    ConfigurationManager.AppSettings["EmailPassword"]);

                objSmtpClient.Send(objMailMessage);

Thanks


Q: Which RJ45 pins should I use for power supply? I'm somewhere in a process of creating mini automation system for hobby use.
I've already put CAT 5e cables with RJ-45 connectors in walls. They are somewhere between 5 - 30 meters long.

On one side of the cable there is a host device, on the other a few client devices connected in parallel.
I want to use differential communication (probably RS-485 or CAN) over one pair (A, B) and deliver power through the same cable.
I picked 24V DC as optimal voltage (reduced on devices to 5V by step-down converter). To reduce the resistance I want to use two wires for +24V and two wires for GND.
Now I'm facing a problem of choosing which RJ-45 pins should I use for those signals.
In my first prototype I assigned them:
1 - +24V
2 - +24V
3 - GND
4 - A
5 - B
6 - GND
7 - NC
8 - NC

During hot-plugging, there was a possibility that RS-485 / CAN could make contact before GND pins, but after +24V pins, causing the transceiver to blow.
I also want to make it more "not expirienced user" proof and protect both sides when device or host gets connected to Ethernet (possibly with PoE).
My second idea is to do this:
1 - A
2 - B
3 - NC
4 - GND
5 - GND
6 - NC
7 - +24V
8 - +24V

However on many solutions I have seen using 4 and 5 pin for data transmission is recommended.
I have also seen numerous documents where 4 and 5 pin was left unused.
Which approach should I choose and why? Maybe ther?

A:
Have you considered the POE standard PHY approach?
More options

A: If you’re interested in using CAN, there’s a standard RJ45 wiring:


Q: MPI remote memory access (RMA) inside C++ threads I'm trying to use an MPI remote memory access (RMA) inside C++ threads. This seems to work fine if the number of writes is small, but fails if I attempt to communicate often. The sources below exhibit the following behavior:
(i) if compiled with #define USE_THREADS false the program runs fine, irrespective of the value referred to via MY_BOUND;
(ii) if compiled with #define USE_THREADS true the program runs fine if executed with only two processes (mpiexec -n 2 ...), i.e., using only one thread for communication, irrespective of the value referred to via MY_BOUND;
(ii) if compiled with #define USE_THREADS true the program runs fine if the value referred to via MY_BOUND is low, e.g., 10 or 100, but the program crashes if the value referred to via MY_BOUND is large, e.g., 100000.
The error I obtain in the third case for large values of MY_BOUND is:
[...] *** Process received signal ***
[...] Signal: Segmentation fault: 11 (11)
[...] Signal code: Address not mapped (1)
[...] Failing at address: 0x0
[...] *** End of error message ***
--------------------------------------------------------------------------
mpiexec noticed that process rank 0 with PID 0 on node ... exited on signal 11 (Segmentation fault: 11).
--------------------------------------------------------------------------

Attaching a debugger to the processes reveals the following:
thread #4: tid = 0x5fa1e, 0x000000010e500de7 mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer + 87, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
* frame #0: 0x000000010e500de7 mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer + 87
frame #1: 0x000000010e4fd2a2 mca_osc_pt2pt.so`osc_pt2pt_incoming_post + 50
frame #2: 0x000000010e4fabf1 mca_osc_pt2pt.so`ompi_osc_pt2pt_process_receive + 961
frame #3: 0x000000010e4f4957 mca_osc_pt2pt.so`component_progress + 279
frame #4: 0x00000001059f3de4 libopen-pal.20.dylib`opal_progress + 68
frame #5: 0x000000010e4fc9dd mca_osc_pt2pt.so`ompi_osc_pt2pt_complete + 765
frame #6: 0x0000000105649a00 libmpi.20.dylib`MPI_Win_complete + 160

And when compiling OpenMPI with --enable-debug I get:
* thread #4: tid = 0x93d0d, 0x0000000111521b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
   frame #0: 0x0000000111521b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61
   58       int mid = nranks / 2;
   59
   60       /* base cases */
-> 61       if (0 == nranks || (1 == nranks && peers[0]->rank != rank)) {
   62           if (peer) {
   63               *peer = NULL;
   64           }

Probably something simple is wrong in my implementation, but I have a hard time finding it, likely due to my lack in understanding MPI, C++ and threading. Any thoughts, comments or feedback? Thanks and happy new year.
My setup is GCC 4.9 with OpenMPI 2.0.1 (compiled with --enable-mpi-thread-multiple).
#include <iostream>
#include <vector>
#include <thread>
#include "mpi.h"

#define MY_BOUND 100000
#define USE_THREADS true

void FinalizeMPI();
void InitMPI(int, char**);
void NoThreads(int, int);

void ThreadFunction(int ThreadID, int Bound) {
  std::cout << "test " << ThreadID << std::endl;
  MPI_Group GroupAll, myGroup, destGroup;
  MPI_Comm myComm;
  MPI_Win myWin;
  MPI_Comm_group(MPI_COMM_WORLD, &GroupAll);
  int ranks[2]{0, ThreadID+1};
  MPI_Group_incl(GroupAll, 2, ranks, &myGroup);
  MPI_Comm_create_group(MPI_COMM_WORLD, myGroup, 0, &myComm);
  MPI_Win_create(NULL, 0, 1, MPI_INFO_NULL, myComm, &myWin);
  int destrank = 1;
  MPI_Group_incl(myGroup, 1, &destrank, &destGroup);

  std::cout << "Objects created" << std::endl;

  std::vector<int> data(5, 1);
  for(int m=0;m<Bound;++m) {
    MPI_Win_start(destGroup, 0, myWin);
    MPI_Put(&data[0], 5, MPI_INT, 1, 0, 5, MPI_INT, myWin);
    MPI_Win_complete(myWin);
  }

  MPI_Group_free(&destGroup);
  MPI_Win_free(&myWin);
  MPI_Comm_free(&myComm);
  MPI_Group_free(&myGroup);
  MPI_Group_free(&GroupAll);
}

void WithThreads(int comm_size, int Bound) {
  std::vector<std::thread*> Threads(comm_size-1, NULL);
  for(int k=0;k<comm_size-1;++k) {
    Threads[k] = new std::thread(ThreadFunction, k, Bound);
  }
  for(int k=0;k<comm_size-1;++k) {
    Threads[k]->join();
  }
  std::cout << "done" << std::endl;
}

int main(int argc, char** argv) {
    InitMPI(argc, argv);

    int rank,comm_size;
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    MPI_Comm_size(MPI_COMM_WORLD,&comm_size);

    if(comm_size<2) {
        FinalizeMPI();
        return 0;
    }

    int Bound = MY_BOUND;

    if(rank==0) {
      if(USE_THREADS) {
        WithThreads(comm_size, Bound);
      } else {
        NoThreads(comm_size, Bound);
      }
    } else {
        MPI_Group GroupAll;
        MPI_Comm_group(MPI_COMM_WORLD, &GroupAll);
        std::vector<int> tmp(5,0);
        MPI_Group myGroup, destinationGroup;
        MPI_Comm myComm;
        MPI_Win myWin;
        int ranks[2]{0,rank};
        MPI_Group_incl(GroupAll, 2, ranks, &myGroup);
        MPI_Comm_create_group(MPI_COMM_WORLD, myGroup, 0, &myComm);
        MPI_Win_create(&tmp[0], 5*sizeof(int), sizeof(int), MPI_INFO_NULL, myComm, &myWin);

        int destrank = 0;
        MPI_Group_incl(myGroup, 1, &destrank, &destinationGroup);

        for(int m=0;m<Bound;++m) {
          MPI_Win_post(destinationGroup, 0, myWin);
          MPI_Win_wait(myWin);
        }

        std::cout << " Rank " << rank << ":";
        for(auto& e : tmp) {
          std::cout << " " << e;
        }
        std::cout << std::endl;

        MPI_Win_free(&myWin);
        MPI_Comm_free(&myComm);
        MPI_Group_free(&myGroup);
        MPI_Group_free(&GroupAll);
    }

    FinalizeMPI();
    return 0;
}

void FinalizeMPI() {
   int flag;
   MPI_Finalized(&flag);
   if(!flag)
      MPI_Finalize();
}

void InitMPI(int argc, char** argv) {
   int flag;
   MPI_Initialized(&flag);
   if(!flag) {
      int provided_Support;
      MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided_Support);
      if(provided_Support!=MPI_THREAD_MULTIPLE) {
          exit(0);
      }
   }
}

void NoThreads(int comm_size, int Bound) {
  MPI_Group GroupAll;
  MPI_Comm_group(MPI_COMM_WORLD, &GroupAll);
  std::vector<MPI_Group> myGroups(comm_size-1);
  std::vector<MPI_Comm> myComms(comm_size-1);
  std::vector<MPI_Win> myWins(comm_size-1);
  std::vector<MPI_Group> destGroups(comm_size-1);
  for(int k=1;k<comm_size;++k) {
     int ranks[2]{0, k};
     MPI_Group_incl(GroupAll, 2, ranks, &myGroups[k-1]);
     MPI_Comm_create_group(MPI_COMM_WORLD, myGroups[k-1], 0, &myComms[k-1]);
     MPI_Win_create(NULL, 0, 1, MPI_INFO_NULL, myComms[k-1], &myWins[k-1]);
     int destrank = 1;
     MPI_Group_incl(myGroups[k-1], 1, &destrank, &destGroups[k-1]);
  }

  std::vector<int> data(5, 1);

  for(int k=0;k<comm_size-1;++k) {
    for(int m=0;m<Bound;++m) {
      MPI_Win_start(destGroups[k], 0, myWins[k]);
      MPI_Put(&data[0], 5, MPI_INT, 1, 0, 5, MPI_INT, myWins[k]);
      MPI_Win_complete(myWins[k]);
    }
  }

  for(int k=0;k<comm_size-1;++k) {
    MPI_Win_free(&myWins[k]);
    MPI_Comm_free(&myComms[k]);
    MPI_Group_free(&myGroups[k]);
  }
  MPI_Group_free(&GroupAll);
}

UPDATE: During debugging I observed that the peers pointer doesn't seem to be NULL in the calling stack frame. Maybe another thread is updating the variable once the debugged thread crashed? Could that indicate an issue related to locking?
* thread #4: tid = 0xa7935, 0x000000010fa67b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x000000010fa67b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61
   58       int mid = nranks / 2;
   59
   60       /* base cases */
-> 61       if (0 == nranks || (1 == nranks && peers[0]->rank != rank)) {
   62           if (peer) {
   63               *peer = NULL;
   64           }
(lldb) frame select 1
frame #1: 0x000000010fa67c4c mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer(module=0x00007fc0ff006a00, target=1, peer=0x0000000000000000) + 105 at osc_pt2pt_sync.c:92
   89           return false;
   90       }
   91
-> 92       return ompi_osc_pt2pt_sync_array_peer (target, pt2pt_sync->peer_list.peers, pt2pt_sync->num_peers, peer);
   93   }
(lldb) p (pt2pt_sync->peer_list)
(<anonymous union>) $1 = {
  peers = 0x00007fc0fb534cb0
  peer = 0x00007fc0fb534cb0
}
(lldb) p pt2pt_sync->peer_list.peers
(ompi_osc_pt2pt_peer_t **) $2 = 0x00007fc0fb534cb0


Q: Differentiate between IE compatibility view If a user is on IE 7 and I read
<% = Request.Browser.Version %>

I get 7.0
if they have IE 9 and are on compatibility view, I get the same thing.
Is there anything in Request.Browser that can differentiate between a real IE7 user and a user that is using IE8 or IE9 but in compatibility mode?

A: It would be better to do this on the client side using JavaScript.  You can use something like this:
http://code.google.com/p/ie6-upgrade-warning/
You can tweak it to whatever you want.
If your goal is simply to make sure the user is not in compatibility mode, then you can use either the meta tag or http header version of X-UA-COMPATIBLE:

       <meta http-equiv="X-UA-Compatible" content="IE=Edge" >

Content goes here.


Q: Is there any software or hardware which lets you stop, slow down, speed up or even reverse time? Obviously I'm talking about time in terms of the PC clock rather than real time.
We were testing an application we've developed at work by setting the clock forward and back to simulate different scenarios and I started thinking how useful it would be if you could adjust the rate(?) of the system clock with finer control. So you could make a minute pass in a second or a day pass in 30 seconds and watch how the program you're developing copes with changes in date and time.
Is there any such software available?
I'd be interested to hear if anyone knows of any software or hardware which can let you do some or all of the above.

A: It's not necessarily going to speed up time, but it can be useful for debugging.
Nirsoft's RunAsDate
From the site:

RunAsDate is a small utility that allows you to run a program in the date and time that you specify. This utility doesn't change the current system date and time of your computer, but it only injects the date/time that you specify into the desired application.
  You can run multiple applications simultaneously, each application works with different date and time, while the real date/time of your system continues to run normally.

A: On unix systems, libfaketime is the de facto standard solution for this problem in software. It performs a sort of man-in-the-middle operation between your application and the system's time library. The requests are passed through to the system, but the replies are modified as needed. It also modifies the results of stat() calls, so file modification times & c. are also modified.
The settings are made with environment variables, so you might have to learn about those if you're not already familiar with their workings.
libfaketime supports relative and absolute offsets, stopped and running time and speeding up or slowing down. I don't know about running backwards, though.
Note that the current version pretends seconds are the highest resolution of time there is, and passes sub-second parts of responses through to the application unmodified. Thus, if you slow down the clock to half speed, a sub-seconds aware program making very rapid time calls will experience the whole second twice after each other rather than once just taking twice as long. If the clock is stopped, this means the application sees a random time within the selected second.
Unfortunately, Github is down today, so the docs are unavailable right now, but that will probably be fixed soon.
Edit:
With Github back up I tried it, and found the code for speed change to be general enough that it works well with negative values or anything else accepted by atof().
However, a different issue became apparent: For speed change, a time origin is necessary in addition to the real current time and the desired time offset. This origin is set independently for subprocesses, so that (when running backwards at nominal speed) when the parent process has retracted one minute, a newly spawned subprocess will see the current time as two minutes later than the parent process does.

A: You could always script it.  (Does CMD still support the DATE/TIME commands?)
Any program you'd end up using would probably work by resetting the time in small increments anyways.  If you didn't need super-fine-grained control, a batch script (or perl:) could control those changes pretty easily.
Gotchas: NTP update services would need to be turned off to use this solution, so that the OS didn't keep resetting the clock back to whatever it's supposed to be.

A: I spotted a reference to an old program called ASpeeder.  I've no idea how it works, if it works, or if it's an ancient scam site.  Try at your own risk.  Hail Eris.
It is payware ($20).  Take a look, and be sure to virus-check the download before you install.
A Speeder 2008.4 Features (from the website):

*

*Change the speed of desktop games or online games

*Control application speed and windows speed

*Easy to use, just drag the track bar or press hotkey

*From 1/32 times speed to 32 times system speed

*From 1/256 times speed to 256 times Windows speed

*The speed setting is locked automatically

*Offer three kinds of methods to change speed

A: Virtual machines can be sped up, so dor example VirtualBox:
VBoxManage setextradata "VM name" "VBoxInternal/TM/WarpDrivePercentage" 200


Q: Deleting nodes from a binary search tree I understand the idea when deleting a node that has two subtrees: I "erase" the node's value and replace it with either its predecessor from the left subtree's value or its successor from the right subtree's value, and then delete that node.
However, does it matter if I choose the successor from the right subtree or the predecessor from the left subtree? Or is either way valid as long as I still have a binary search tree after performing the deletion?

A: Both ways to perform a delete operation are valid if the node has two children.
Remember that when you get either the in-order predecessor node or the in-order successor node, you must call the delete operation on that node.

A: It doesn't matter which one you choose to replace. In fact you may need both.
Look at the following BST.
    7
   / \
  4   10
 / \   /
1   5  8
 \
  3

To delete 1, you need to replace 1 with right node 3.
And to delete 10, you need to replace 10 with left node 8.


Q: Why is Google App Engine Making --set-default a default parameter? So, in the past, when I've used Google App Engine, I've utilized their wonderful version system to create an integration, staging, and production environment. When we're ready to go live, we set the production environment to be the default, and it starts receiving traffic at the standard AppSpot URL (myapp.appspot.com), if it's not the default you have to manually go to the version itself (dev.myapp.appspot.com) for your testing. This is an awesome system for a pre-prod deployment with a full test.
However, I just went to do an App Engine deployment today and got this warning:
WARNING: Soon, deployments will set the deployed version to receive all traffic by
default.

To keep the current behavior (where new deployments do not receive any traffic),
use the `--no-promote` flag or run the following command:

  $ gcloud config set app/promote_by_default false

To adopt the new behavior early, use the `--promote` flag or run the following
command:

  $ gcloud config set app/promote_by_default true

Either passing one of the new flags or setting one of these properties will
silence this message.

So, apparently, very soon Google will make it so that for every deploy of any version, they will just automatically promote that to be the default and be accessible at the standard AppSpot URL.
My question is, what's the benefit in this? I can't use this for A/B testing (since there's no B in the equation here). I can't use this as a pre-prod test, because it takes over my environment right away. Why would I want any version I push up to be the default? Am I missing something? Was I using versions wrong?
I'm just genuinely curious.


Q: About spherical coordinates I will post an image which believe it is essential to understand the question:
See the image:
Figure book

Spherical coordinates $r, \theta, \phi$ are perfectly intuitive
because the angles $\theta$ and $\phi$ correspond, respectively, to
longitude and latitude on the surface of the Earth, and $r$ is the
distance to the center of the Earth.

I believe the notation is wrong, since theta is the angle wrt north and south axis, shouldn't be the reverse?

A: Which textbook is this taken from? If it is a mathematics textbook, the convention is that $\phi$ corresponds to latitude and $\theta$ to longitude, but if it is a physics textbook, then $\theta$ will usually correspond to latitude and $\phi$ to longitude. This sort of confusion is why I usually stay away from spherical coordinates.

A: The $(r,\theta,\phi)$ convention for three dimensional spherical polar coordinates is used in mathematics, as it follows naturally from the $(r,\theta)$ convention used for the two dimensional case. However, physicists for some bizarre reason prefer $(r,\phi,\theta)$. What makes it even more confusing is that the very order the coordinates are written is also sometimes switched. Some authors order it as radial, azimuthal, polar which seems reasonable whereas some authors use radial, polar, azimuthal instead. So even if the author says "I'll use the $(r,\phi,\theta)$ convention" it might not even mean what you think it does!
So, if you're using spherical coordinates, it's best to explicitly state the coordinate transformation you're using. Here's a passage from some recent work of mine:

I will also use the $\displaystyle ( r,\theta ,\phi )$ convention for spherical coordinates, as used by Wolfram Mathworld. Explicitly, the coordinate transformation is
\begin{equation*}
\begin{bmatrix}
x\\
y\\
z
\end{bmatrix} =\begin{bmatrix}
r\cos \theta \sin \phi \\
r\sin \theta \sin \phi \\
r\cos \phi
\end{bmatrix}
\end{equation*}

Suggested reading: https://mathworld.wolfram.com/SphericalCoordinates.html


Q: Nginx not responding worker_processes  1;

error_log  logs/error.log;
pid        logs/nginx.pid;

events {
    worker_connections  10000;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    access_log  off;

    sendfile        on;
    tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  30;
    keepalive_requests  100000;

    ssl_session_timeout 10m;
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1 SSLv3;
    ssl_ciphers ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH;
    ssl_prefer_server_ciphers on;

    gzip  on;
    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
    gzip_disable "MSIE [1-6]\.";

    # http server
    server {
        listen   80;
        listen   [::]:80;

        server_name www.mywebsite.net;

        return 301 https://$server_name$request_uri;
    } # end http server

    # https server
    server {
        listen 443 default ssl;
        server_name www.mywebsite.net;
        ssl_certificate      mywebsite.net.crt;
        ssl_certificate_key  www.mywebsite.net.key;

        ## Parameterization using hostname of access and log filenames.
        access_log logs/localhost_access.log;
        error_log logs/localhost_error.log;

        ## Root and index files.
        root html;
        index  index.php index.html index.htm;

        ## If no favicon exists return a 204 (no content error).
        location = /favicon.ico {
            try_files $uri =204;
            log_not_found off;
            access_log off;
        }

        ## Don't log robots.txt requests.
        location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
        }
        ## Try the requested URI as files before handling it to PHP.
        location / {

            ## Regular PHP processing.
            location ~ \.php$ {
                root           html;
                try_files  $uri =404;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                include        fastcgi_params;
            }

            ## Static files are served directly.
            location ~* \.(?:css|gif|htc|ico|js|jpe?g|png|swf)$ {
                expires max;
                log_not_found off;
                ## No need to bleed constant updates. Send the all shebang in one
                ## fell swoop.
                tcp_nodelay off;
                ## Set the OS file cache.
                open_file_cache max=1000 inactive=120s;
                open_file_cache_valid 45s;
                open_file_cache_min_uses 2;
                open_file_cache_errors off;
            }

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   html;
            }

            # deny access to .htaccess files, if Apache's document root
            # concurs with nginx's one

            location ~ /\.ht {
                deny  all;
            }

            ## Keep a tab on the 'big' static files.
            location ~* ^.+\.(?:ogg|pdf|pptx?)$ {
                expires 30d;
                ## No need to bleed constant updates. Send the all shebang in one
                ## fell swoop.
                tcp_nodelay off;
            }
        } # / location
    } # end https server
}

I am running 1.5.2 on my Windows Server 2012, I've heard that it's bad to have a high worker processes value so I've decreased it to 1, still the same issue as with 10 workers, the website responds great but suddenly stops responding after 6-10 hours.
All the needed ports are open and the server is running great.


Q: ListView shows wrong layout I have a listview and in its adapter according to some situations I inflate layouts. for example consider this:
if (state1){
    resource = R.layout.layout_1

}else if (state2){
    resource = R.layout.layout_2
}
if (convertedView == null) {
    view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(resource, parent,false);
}
return view;

But sometimes ListView gets confused and it shows same layout for different states. I am sure there nothing wrong in code. But in ListView behavior. Any Suggestion?
Thanks

A: if (state1){
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.layout_1, parent,false);

}else if (state2){
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.layout_2, parent,false);
}

return view;

A: Well I found the Solution.
The problem is that I check if ConverView parameter is NOT null then the adapter doesn't inflate new view and it uses the last one. If I delete this condition and make the adapter to always inflate a new layout the problem gets solved.
Like this:
public View getView(int position, View convertedView, ViewGroup parent) {
View view;
int resource = 0;
if (state1){
    resource = R.layout.layout_1;
}else{
    resource = R.layout.layout_2;

}
//if (convertedView == null) { //I should Delete this condition
     view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
            .inflate(R.layout.layout_2, parent,false);
//}
return view;


Q: highlight row when rowdetails is expanded Is there any way to get it highlight the row when rowdetails is expanded in ngx-datatable ?
we can get highlight expanded row. but can't able to the clicked row

A: findParentNode(parentName, childObj) {
let tempNodeObj = childObj.parentNode;
while(tempNodeObj.tagName != parentName) {
  tempNodeObj = tempNodeObj.parentNode;
}
return tempNodeObj;
}

this.findParentNode('DATATABLE-BODY-ROW',$event.target);

this will help to find you the data table row element
this.render.addClass(findParentNode,"row-expanded");


Q: Please help identify the mistake in this clock divider code Clock divider from 50mhz (verilog code). I am trying to burn this on fpga but its not working properly. I am using model sim from mentor graphics. Please help identify my mistake.
module clk_div(
clk,
rst,
count);

parameter count_width=27;
parameter count_max=25000000;

output [count_width-1:0] count;
reg [count_width-1:0] count;
input clk,rst;

initial
count=0;

always@(posedge clk)
  if (rst)
  begin
      count<=0;
  end
  else if (count<count_max-1)
  begin
      count<=count+1;
  end
  else if (count==count_max)
  begin
      count <=~count;
  end
  else if (count>count_max)
  begin
      count<=0;
  end
endmodule

A: Three things. First, you need begin and end for your always block. Second, why are you doing count <= ~count when the count hits the max? Shouldn't you just set it back to 0? Third, you can't give the internal count register the same name as the count output. You will need to call one of them something else. Actually, why do you want to output count? If this is a clock divider, you want to output another clock, right? The following should work.
module clk_div(
    clk,
    rst,
    outclk);

parameter count_width=27;
parameter count_max=25000000;

reg [count_width-1:0] count;
input clk,rst;
output outclk;
reg intern_clk;
assign outclk = intern_clk;

initial begin
    count=0;
    intern_clk=1'b0;
end

always @(posedge clk) begin
    if (rst)
        count <= 0;
    else if (count == count_max) begin
        count <= 0;
        intern_clk <= !intern_clk;
    end else
        count <= count + 1'b1;
end

endmodule

But it seems like you are trying to divide the clock down to 1 Hz. That's quite a lot. I recommend you use a PLL instead of making your own clock divider. Since you mention a 50 MHz clock, I'm guessing you are using an Altera FPGA? If so, open up the MegaWizard plugin manager and create a PLL.


Q: How to loop in powershell where loop value is combination of string and variable $A1= get-content -path  "File path a1"
$B1= get-content -path "File path b1"
$A2= get-content -path "File path a2"
$B2= get-content -path "File path B2"
$A3= get-content -path "File path a3"
$B3= get-content -path "File path B3"

#I want to select A.i and B.i in each loop

while ($i -le 5)
{
foreach ($line1 in "What to put here"))
{
$found = $false
foreach ($line2 in "What to put here"))
{
if ($line1 -eq $line2)
{
   write-host "Do something"
}
}

I want to know what should I use in "what to put here" so that
a) first loop select a1 and b1 files
b) second loop selects a2 and b2 files
and so on

Hello,
The below code is taking too long for large files to print whats different in each file. Can you suggest some optimization?
$i = 1
while ($i -le 7)
{
$t1 = Get-Content -Path $(($oldpath) +($(Get-Variable "F$i").Value) +($Format))
$t2 = Get-Content -Path $(($NEWpath) +($(Get-Variable "F$i").Value) +($Format))
$list1      = new-object 'system.collections.generic.list[string]'
$list2      = new-object 'system.collections.generic.list[string]'
$listshared = new-object 'system.collections.generic.list[string]'
$found = $false

foreach ($line1 in $t1)
{
$found = $false
foreach ($line2 in $t2)
if (-not $found)
{
   $list1.add($line1)
}
}

foreach ($line2 in $t2)
{
$found = $false
foreach ($line1 in $t1)

if (-not $found)
{
   $list2.add($line2)
}
}
Write-Host "Things only in new txt file:" -foreground "magenta"
$list1

Write-Host "Things only in old txt file:" -foreground "magenta"
$list2

Remove-Variable "t1"
Remove-Variable "t2"
$i++
}

A: You can use for example:
Get-Variable -Name "A$i" |select Value

but it seems like a bad practice to use a variable for each file...
But you did not specify if you compare paths or files.
If files, combine with Get-Content.
UPDATE:
$i=1
while ($i -le 5)
{
$file1=Get-Content -Path $($(Get-Variable "A$i").Value)
$file2=Get-Content -Path $($(Get-Variable "B$i").Value)
    foreach ($line1 in $file1)
    {
        $found = $false
        foreach ($line2 in $file2)
        {
            if ($line1 -eq $line2)
            {
                write-host "Do something"
            }
        }

    }
    Remove-Variable "file1"
    Remove-Variable "file2"
    $i++
}

This is the version without Get-Content at every variable