问:
Using Rails view helpers with Haml::Engine
I have a Rails app in which I am rendering a block of Haml stuff stored in a model attribute. It would be nice to use Rails view helpers in that block of Haml. Currently I am using the Haml::Engine#render in a view helper to render the content of this model attribute. It works well enough but I can't use things like =link_to. To illustrate the problem:

```<code>irb(main):003:0> haml_text=<<"EOH"
irb(main):004:0" %p
irb(main):005:0"   =image_tag 'someimage'
irb(main):006:0" EOH
=> "%p\n  =image_tag 'someimage'\n"
irb(main):007:0> engine = Haml::Engine.new(haml_text)
=> #<Haml::Engine:0x7fa9ff7f1150 ... >
irb(main):008:0> engine.render
NoMethodError: undefined method `image_tag' for #<Object:0x7fa9ff7e9a40>
        from (haml):2:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `instance_eval'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from (irb):8
</code>```

Any thoughts on how to do that?

Better ideas?

答:
```<code>class RailsRenderingContext
  def self.create(controller)
    view_context = ApplicationController.helpers
    class << view_context; include Rails.application.routes.url_helpers; end

    view_context.request = controller.request
    view_context.view_paths = controller.view_paths
    view_context.controller = controller

    view_context
  end
end

class MyController < ApplicationController
  def show
    # ...
    engine = Haml::Engine.new haml
    ctx = RailsRenderingContext.create(self)
    engine.render ctx
  end
end
</code>```

It works for me. Based on this issue.

Body:
I have a Rails app in which I am rendering a block of Haml stuff stored in a model attribute. It would be nice to use Rails view helpers in that block of Haml. Currently I am using the Haml::Engine#render in a view helper to render the content of this model attribute. It works well enough but I can't use things like =link_to. To illustrate the problem:

irb(main):003:0> haml_text=<<"EOH"
irb(main):004:0" %p
irb(main):005:0"   =image_tag 'someimage'
irb(main):006:0" EOH
=> "%p\n  =image_tag 'someimage'\n"
irb(main):007:0> engine = Haml::Engine.new(haml_text)
=> #<Haml::Engine:0x7fa9ff7f1150 ... >
irb(main):008:0> engine.render
NoMethodError: undefined method `image_tag' for #<Object:0x7fa9ff7e9a40>
        from (haml):2:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `instance_eval'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from (irb):8

Any thoughts on how to do that?

Better ideas?

Body:
class RailsRenderingContext
  def self.create(controller)
    view_context = ApplicationController.helpers
    class << view_context; include Rails.application.routes.url_helpers; end

    view_context.request = controller.request
    view_context.view_paths = controller.view_paths
    view_context.controller = controller

    view_context
  end
end

class MyController < ApplicationController
  def show
    # ...
    engine = Haml::Engine.new haml
    ctx = RailsRenderingContext.create(self)
    engine.render ctx
  end
end

It works for me. Based on this issue.


来源: stackexchange

问:
ps2pdf: preserve page size
I have myfile.ps with a vector image included.
But when I run

```<code>ps2pdf myfile.ps
</code>```

it seems that the output page size is A4: the vector image is too large and become cut away, so about one inch is lost.

The following pseudo-header is printed in the output PDF file, in addition to the original vector image:

```<code>PLOT SIZE:8.02x8.62Inches
Magnification:7354.21X
</code>```

Is there any option or any way to convert the PS file to a PDF preserving the original paper size?

答:
Based on @Kurt Pfeifle's answer I wrote this Perl script to do the task:</p>

```<code>#! /usr/bin/env perl
use strict;
use warnings;

use Scalar::Util qw(looks_like_number);
use List::Util qw(all);

sub ps2pdf;
sub get_ps_headers;
sub get_media_size;
sub main;

# Run the program
main();

# Function: main
#
# Program's entry point.
#
sub main {
   for (@ARGV) {

      # check input file
      if(not -r) {
         print "WARN: Cannot read input file: $_\n";
         next;
      }

      # build PDF file name
      my $pdf = $_;
      $pdf =~ s/(\.e?ps)?$/.pdf/i;

      ps2pdf($_, $pdf);
   }
}

# Function: ps2pdf
#
# Converts a PostScript file to PDF format using GhostScript,
# keeping the medium size.
#
# Params:
#
#     $ps_file  - (string) Input [E]PS file name
#     $pdf_file - (string) Output PDF file name
#
sub ps2pdf {
   my ($ps_file, $pdf_file) = @_;
   my $cmd = "gs -q -sDEVICE=pdfwrite -dPDFFitPage ";

   # try to find the media size
   my ($width, $height) = get_media_size(get_ps_header($ps_file));

   # keep media size
   if(defined $height) {
      $cmd .= "-g${width}x${height} ";
   }

   # set input/output
   $cmd .= "-o $pdf_file $ps_file";

   print "Running: $cmd\n";

   system($cmd);
}

# Function: get_media_size
#
# Computes the size of a PostScript document in pixels,
# from the headers in the PS file.
#
# Params:
#
#     $hdr  - (hash ref) Parsed PS header values
#
# Returns:
#
#     On success: Two-element array holding the document's width and height
#     On failure: undef
#
sub get_media_size {
   my ($hdr) = @_;

   # we need the DocumentMedia header
   return undef if not defined $hdr->{DocumentMedia};

   # look for valid values
   my @values = split(/\s+/, $hdr->{DocumentMedia});
   return undef if scalar @values < 3;
   my ($width, $height) = @values[1, 2];

   return undef if not all { looks_like_number($_) } ($width, $height);

   # Ghostscript uses a default resolution of 720 pixels/inch,
   # there are 72 PostScript points/inch.
   return ($width*10, $height*10);
}

# Function: get_ps_header
#
#  Parses a PostScript file looking for headers.
#
# Params:
#
#     $ps_file - (string) Path of the input file
#
# Returns:
#
#     (hash ref) - As expected, keys are header names,
#     values are corresponding header values. A special key
#     named `version' is included for headers of the type
#     `PS-Adobe-3.0'
#
sub get_ps_header {
   my ($ps_file) = @_;
   my %head;

   open my $fh, "<$ps_file" or die "Failed to open $ps_file\n";
   while(<$fh>) {
      # look for end of header
      last if /^%%EndComments\b/;

      # look for PS version
      if(/^%!(\w+)/) {
         $head{version} = $1;
      }

      # look for any other field
      # Ex: %%BoundingBox: 0 0 1008 612
      elsif(/^%%(\w+)\s*:\s*(.*\S)/) {
         $head{$1} = $2;
      }

      # discard regular comments and blank lines
      elsif(/^\s*(%.*)?$/) {
         next;
      }

      # any other thing will finish the header
      else {
         last;
      }
   }

   return \%head;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: ps2pdf: preserve page size

Body:
I have myfile.ps with a vector image included.
But when I run

ps2pdf myfile.ps

it seems that the output page size is A4: the vector image is too large and become cut away, so about one inch is lost.

The following pseudo-header is printed in the output PDF file, in addition to the original vector image:

PLOT SIZE:8.02x8.62Inches
Magnification:7354.21X

Is there any option or any way to convert the PS file to a PDF preserving the original paper size?

Body:
Based on @Kurt Pfeifle's answer I wrote this Perl script to do the task:

#! /usr/bin/env perl
use strict;
use warnings;

use Scalar::Util qw(looks_like_number);
use List::Util qw(all);

sub ps2pdf;
sub get_ps_headers;
sub get_media_size;
sub main;

# Run the program
main();

# Function: main
#
# Program's entry point.
#
sub main {
   for (@ARGV) {

      # check input file
      if(not -r) {
         print "WARN: Cannot read input file: $_\n";
         next;
      }

      # build PDF file name
      my $pdf = $_;
      $pdf =~ s/(\.e?ps)?$/.pdf/i;

      ps2pdf($_, $pdf);
   }
}

# Function: ps2pdf
#
# Converts a PostScript file to PDF format using GhostScript,
# keeping the medium size.
#
# Params:
#
#     $ps_file  - (string) Input [E]PS file name
#     $pdf_file - (string) Output PDF file name
#
sub ps2pdf {
   my ($ps_file, $pdf_file) = @_;
   my $cmd = "gs -q -sDEVICE=pdfwrite -dPDFFitPage ";

   # try to find the media size
   my ($width, $height) = get_media_size(get_ps_header($ps_file));

   # keep media size
   if(defined $height) {
      $cmd .= "-g${width}x${height} ";
   }

   # set input/output
   $cmd .= "-o $pdf_file $ps_file";

   print "Running: $cmd\n";

   system($cmd);
}

# Function: get_media_size
#
# Computes the size of a PostScript document in pixels,
# from the headers in the PS file.
#
# Params:
#
#     $hdr  - (hash ref) Parsed PS header values
#
# Returns:
#
#     On success: Two-element array holding the document's width and height
#     On failure: undef
#
sub get_media_size {
   my ($hdr) = @_;

   # we need the DocumentMedia header
   return undef if not defined $hdr->{DocumentMedia};

   # look for valid values
   my @values = split(/\s+/, $hdr->{DocumentMedia});
   return undef if scalar @values < 3;
   my ($width, $height) = @values[1, 2];

   return undef if not all { looks_like_number($_) } ($width, $height);

   # Ghostscript uses a default resolution of 720 pixels/inch,
   # there are 72 PostScript points/inch.
   return ($width*10, $height*10);
}

# Function: get_ps_header
#
#  Parses a PostScript file looking for headers.
#
# Params:
#
#     $ps_file - (string) Path of the input file
#
# Returns:
#
#     (hash ref) - As expected, keys are header names,
#     values are corresponding header values. A special key
#     named `version' is included for headers of the type
#     `PS-Adobe-3.0'
#
sub get_ps_header {
   my ($ps_file) = @_;
   my %head;

   open my $fh, "<$ps_file" or die "Failed to open $ps_file\n";
   while(<$fh>) {
      # look for end of header
      last if /^%%EndComments\b/;

      # look for PS version
      if(/^%!(\w+)/) {
         $head{version} = $1;
      }

      # look for any other field
      # Ex: %%BoundingBox: 0 0 1008 612
      elsif(/^%%(\w+)\s*:\s*(.*\S)/) {
         $head{$1} = $2;
      }

      # discard regular comments and blank lines
      elsif(/^\s*(%.*)?$/) {
         next;
      }

      # any other thing will finish the header
      else {
         last;
      }
   }

   return \%head;
}


问:
How to initiate a new Node.js file after already initiating some other Node.js file on Windows 10 machine?
I've a laptop running on Windows 10 Home Single Language 64-bit Operating System

I am learning Node.js on this machine.

For downloading and installing Node.js I went to the URL

https://nodejs.org.

From there I downloaded the Node.js setup file v6.10.3 LTS for Windows (x64)

I started installing Node.js by double-clicking on the setup file and keep on clicking the Next button in the installation wizard.

Then, I clicked on the Windows Start button(the button appearing in bottom-left corner of the screen), two new options were appeared in the list of 'Recently Added' as Node.js and 'Node.js command prompt'

I clicked on the option 'Node.js command prompt', then following screen appeared.

Then, I created one file titled myfirst.js at location

```<code>C:\Users\lenovo\myfirst.js
</code>```

Then, I initiated this file by typing in following text at the command prompt I opened earlier :

```<code>C:\Users\lenovo>node myfirst.js
</code>```

Then, I run the file myfirst.js from the browser by hitting the URL :

http://localhost:8080/

Till now everything worked fine for me.

But real problem started when I wanted to run another program.

For it do I need to close the command prompt by clicking on the close button icon appearing on the top-right corner of the window and should I need to do this before running any new Node.js program to initiate the respective file?

The screen I'm having problem with is appears as below with the name of earlier run Node.js program(i.e. with the last initiated Node.js file) :

Someone please help me in this regard.

Thank you.

答:
So, I'm not on Windows, but in general each node application will run in a single process by default.  If you're running it from a command prompt, that will default to running the process in the foreground (meaning, it consumes the same process as your command window) and you have to open a new command window to run another program.  You can either close that first window, or run the node application in the background. </p>

<p>You'll also want to make sure you're not trying to do two programs listening on the same port (i.e. two node apps both running on port 8088), as that's also not possible.  </p>

Body:
I've a laptop running on Windows 10 Home Single Language 64-bit Operating System

I am learning Node.js on this machine.

For downloading and installing Node.js I went to the URL

https://nodejs.org.

From there I downloaded the Node.js setup file v6.10.3 LTS for Windows (x64)

I started installing Node.js by double-clicking on the setup file and keep on clicking the Next button in the installation wizard.

Then, I clicked on the Windows Start button(the button appearing in bottom-left corner of the screen), two new options were appeared in the list of 'Recently Added' as Node.js and 'Node.js command prompt'

I clicked on the option 'Node.js command prompt', then following screen appeared.

Then, I created one file titled myfirst.js at location

C:\Users\lenovo\myfirst.js

Then, I initiated this file by typing in following text at the command prompt I opened earlier :

C:\Users\lenovo>node myfirst.js

Then, I run the file myfirst.js from the browser by hitting the URL :

http://localhost:8080/

Till now everything worked fine for me.

But real problem started when I wanted to run another program.

For it do I need to close the command prompt by clicking on the close button icon appearing on the top-right corner of the window and should I need to do this before running any new Node.js program to initiate the respective file?

The screen I'm having problem with is appears as below with the name of earlier run Node.js program(i.e. with the last initiated Node.js file) :

Someone please help me in this regard.

Thank you.

Body:
So, I'm not on Windows, but in general each node application will run in a single process by default.  If you're running it from a command prompt, that will default to running the process in the foreground (meaning, it consumes the same process as your command window) and you have to open a new command window to run another program.  You can either close that first window, or run the node application in the background.

You'll also want to make sure you're not trying to do two programs listening on the same port (i.e. two node apps both running on port 8088), as that's also not possible.


问:
How to embed a Java control on a C# winforms control?
Can I put a Java control (SWT, Swing, ...) on a C# control?

I know it's possible with web controls but I don't like this way.

答:
I've rechecked that, looks like IKVM currently hasn't enough support in it's AFT assembly. I think the only way to do what you need is run you java control inside separate process with hidden main window and pass handle of that control to your C# application somehow.

Original answer:

I'm not sure if you can just "add" it, but you can try this direction:

It would be necessary to convert java classes to .Net assemblies via IKVM.

First of all you need to get handle of java control. You can look at this post if you need info on how to do this. I failed at this step because I haven't found Win32DrawingSurface and DrawingSurfaces in IKVM's libraries, maybe it's enough to just create some static getHandle() method on the java side.

Get handle of your parent C# control. It's simple since Control have its Handle property.

After obtaining both handles you can set one of the as parent to another. To do this you need to call SetParent function from the WINAPI.

[DllImport("user32.dll")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

OwnerDisplayName: FerranB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmyers

OwnerDisplayName: Dmitriy Matveev

LastEditorDisplayName: Dmitriy Matveev


问:
finding if two words are anagrams of each other
I am looking for a method to find if two strings are anagrams of one another.

```<code>Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - abcfed
Ans = false
</code>```

the solution i came up with so for is to sort both the strings and compare each character from both strings till the end of either strings.It would be O(logn).I am looking for some other efficient method which doesn't change the 2 strings being compared

答:
```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * --------------------------------------------------------------------------
 * Finding Anagrams in the given dictionary. Anagrams are words that can be
 * formed from other words Ex :The word "words" can be formed using the word
 * "sword"
 * --------------------------------------------------------------------------
 * Input : if choose option 2 first enter no of word want to compare second
 * enter word ex:
 *
 * Enter choice : 1:To use Test Cases 2: To give input 2 Enter the number of
 * words in dictionary
 * 6
 * viq
 * khan
 * zee
 * khan
 * am
 *
 * Dictionary : [ viq khan zee khan am]
 * Anagrams 1:[khan, khan]
 *
 */
public class Anagrams {

    public static void main(String args[]) {
        // User Input or just use the testCases
        int choice;
        @SuppressWarnings("resource")
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter choice : \n1:To use Test Cases 2: To give input");
        choice = scan.nextInt();
        switch (choice) {
        case 1:
            testCaseRunner();
            break;
        case 2:
            userInput();
        default:
            break;
        }
    }

    private static void userInput() {
        @SuppressWarnings("resource")
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number of words in dictionary");
        int number = scan.nextInt();
        String dictionary[] = new String[number];
        //
        for (int i = 0; i < number; i++) {
            dictionary[i] = scan.nextLine();
        }
        printAnagramsIn(dictionary);

    }

    /**
     * provides a some number of dictionary of words
     */
    private static void testCaseRunner() {

        String dictionary[][] = { { "abc", "cde", "asfs", "cba", "edcs", "name" },
                { "name", "mane", "string", "trings", "embe" } };
        for (int i = 0; i < dictionary.length; i++) {
            printAnagramsIn(dictionary[i]);
        }
    }

    /**
     * Prints the set of anagrams found the give dictionary
     *
     * logic is sorting the characters in the given word and hashing them to the
     * word. Data Structure: Hash[sortedChars] = word
     */
    private static void printAnagramsIn(String[] dictionary) {
        System.out.print("Dictionary : [");// + dictionary);
        for (String each : dictionary) {
            System.out.print(each + " ");
        }
        System.out.println("]");
        //

        Map<String, ArrayList<String>> map = new LinkedHashMap<String, ArrayList<String>>();
        // review comment: naming convention: dictionary contains 'word' not
        // 'each'
        for (String each : dictionary) {
            char[] sortedWord = each.toCharArray();
            // sort dic value
            Arrays.sort(sortedWord);
            //input word
            String sortedString = new String(sortedWord);
            //
            ArrayList<String> list = new ArrayList<String>();
            if (map.keySet().contains(sortedString)) {
                list = map.get(sortedString);
            }
            list.add(each);
            map.put(sortedString, list);
        }
        // print anagram
        int i = 1;
        for (String each : map.keySet()) {
            if (map.get(each).size() != 1) {
                System.out.println("Anagrams " + i + ":" + map.get(each));
                i++;
            }
        }
    }
}
</code>```

Body:
I am looking for a method to find if two strings are anagrams of one another.

Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - abcfed
Ans = false

the solution i came up with so for is to sort both the strings and compare each character from both strings till the end of either strings.It would be O(logn).I am looking for some other efficient method which doesn't change the 2 strings being compared


问:
very confused working on json in swift
I get totally very confused working with JSON in swift.
according to Apple dec: https://developer.apple.com/swift/blog/?id=37

```<code>/*
    {
        "someKey": 42.0,
        "anotherKey": {
        "someNestedKey": true
        }
    }
*/
</code>```

What is a well-formed way to format this jsonWithObjectRoot json string?
I tried serval ways but n success.

so subsequently, these methods can access it.

```<code>if let dictionary = jsonWithObjectRoot as? [String: Any] {
    if let number = dictionary["someKey"] as? Double {
        // access individual value in dictionary
    }

    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
    }

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]     {
        // access nested dictionary values by key
    }
}
</code>```

答:
Your json looks good. You need to parse it before casting to a [String:Any].</p>

```<code>let jsonWithObjectRoot = "{ \"someKey\": 42.0, \"anotherKey\": { \"someNestedKey\": true } }"
let data = jsonWithObjectRoot.data(using:.utf8)!
do {
    let json = try JSONSerialization.jsonObject(with:data)
    if let dictionary = json as? [String: Any] {
        if let number = dictionary["someKey"] as? Double {
            // access individual value in dictionary
        }

        for (key, value) in dictionary {
            // access all key / value pairs in dictionary
        }

        if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]
        {
            // access nested dictionary values by key
        }
    }
} catch {
    print("Error parsing Json")
}
</code>```

Title: very confused working on json in swift

Body:
I get totally very confused working with JSON in swift.
according to Apple dec: https://developer.apple.com/swift/blog/?id=37

/*
    {
        "someKey": 42.0,
        "anotherKey": {
        "someNestedKey": true
        }
    }
*/

What is a well-formed way to format this jsonWithObjectRoot json string?
I tried serval ways but n success.

so subsequently, these methods can access it.

if let dictionary = jsonWithObjectRoot as? [String: Any] {
    if let number = dictionary["someKey"] as? Double {
        // access individual value in dictionary
    }

    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
    }

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]     {
        // access nested dictionary values by key
    }
}

Body:
Your json looks good. You need to parse it before casting to a [String:Any].

let jsonWithObjectRoot = "{ \"someKey\": 42.0, \"anotherKey\": { \"someNestedKey\": true } }"
let data = jsonWithObjectRoot.data(using:.utf8)!
do {
    let json = try JSONSerialization.jsonObject(with:data)
    if let dictionary = json as? [String: Any] {
        if let number = dictionary["someKey"] as? Double {
            // access individual value in dictionary
        }

        for (key, value) in dictionary {
            // access all key / value pairs in dictionary
        }

        if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]
        {
            // access nested dictionary values by key
        }
    }
} catch {
    print("Error parsing Json")
}


问:
How to make a div hide when having same set of classes?
I have two set of div containers with input tags with same classes to both.
only difference is when input box of each clicked the resepctive parent div will add "frame-focus" class. what i want is if input is clicked and frame-focus class is exist, hide the div which has class "panel-set" of which the focus class exist. </p>

<p>Please check my div containers below. please advice how to proceed this
Ex: </p>

```<code><!--- here is 1st div container which input box is selected-->
    <div class="block">
    <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set"></div>
    </div>
    </div>

<!-- here is 2nd div -->
    <div class="block">
    <div class="frame">
    <input name="set1">
    <div class="panel-set"></div>
    </div>
    </div>
</code>```

答:
html

```<code>    <div class="block">
    <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set">1</div>
    </div>
    </div>

<!-- here is 2nd div -->
    <div class="block">
    <div class="frame">
    <input name="set1">
    <div class="panel-set">2</div>
    </div>
    </div>
</code>```

jquery

```<code>$(document).ready(function(){

$("input").click(function() {
  $(this).siblings('.panel-set').hide();
});

});
</code>```

Example jsfiddle

Body:
I have two set of div containers with input tags with same classes to both.
only difference is when input box of each clicked the resepctive parent div will add "frame-focus" class. what i want is if input is clicked and frame-focus class is exist, hide the div which has class "panel-set" of which the focus class exist.

Please check my div containers below. please advice how to proceed this
Ex:

    <input name="set1">

    <input name="set1">

Body:
html

    <div class="block">
    <div class="frame frame-focus">
    <input name="set1">
    <div class="panel-set">1</div>
    </div>
    </div>

<!-- here is 2nd div -->
    <div class="block">
    <div class="frame">
    <input name="set1">
    <div class="panel-set">2</div>
    </div>
    </div>

jquery

$(document).ready(function(){

$("input").click(function() {
  $(this).siblings('.panel-set').hide();
});

});

Example jsfiddle


问:
Why doesn't the JVM emit prefetch instructions on Windows x86
As the title states, why doesn't the OpenJDK JVM emit prefetch instruction on Windows x86? See OpenJDK Mercurial @ http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp

```<code>inline void Prefetch::read (void *loc, intx interval) {}
inline void Prefetch::write(void *loc, intx interval) {}
</code>```

There are no comments and I've found no other resources besides the source code. I am asking because it does so for Linux x86, see http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/linux_x86/vm/prefetch_linux_x86.inline.hpp

```<code>inline void Prefetch::read (void *loc, intx interval) {
#ifdef AMD64
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
#endif // AMD64
}

inline void Prefetch::write(void *loc, intx interval) {
#ifdef AMD64

  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
  //  __asm__ ("prefetchw (%0,%1,1)" : : "r" (loc), "r" (interval));
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));

#endif // AMD64
}
</code>```

答:
As JDK-4453409 indicates, prefetching was implemented in HotSpot JVM in JDK 1.4 to speed-up GC. That was more than 15 years ago, no one will remember now why it was not implemented on Windows. My guess is that Visual Studio (which has always been used to build HotSpot on Windows) basically didn’t understand prefetch instruction at these times. Looks like a place for improvement.

Anyway, the code you’ve asked about is used internally by JVM Garbage Collector. This is not what JIT generates. C2 JIT code generator rules are in the architecture definition file x86_64.ad, and there are rules to translate PrefetchRead, PrefetchWrite and PrefetchAllocation nodes to the corresponding x64 instructions.

An insteresting fact is that PrefetchRead and PrefetchWrite nodes are not created anywhere in the code. They exist only to support Unsafe.prefetchX intrinsics, however, they are removed in JDK 9.

The only case when JIT generates prefetch instruction is PrefetchAllocation node. You can verify with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly that PREFETCHNTA is indeed generated after object allocation, both on Linux and Windows.

```<code>class Test {
    public static void main(String[] args) {
        byte[] b = new byte[0];
        for (;;) {
            b = Arrays.copyOf(b, b.length + 1);
        }
    }
}
</code>```

java.exe -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly Test

```<code># {method} {0x00000000176124e0} 'main' '([Ljava/lang/String;)V' in 'Test'
  ...
  0x000000000340e512: cmp    $0x100000,%r11d
  0x000000000340e519: ja     0x000000000340e60f
  0x000000000340e51f: movslq 0x24(%rsp),%r10
  0x000000000340e524: add    $0x1,%r10
  0x000000000340e528: add    $0x17,%r10
  0x000000000340e52c: mov    %r10,%r8
  0x000000000340e52f: and    $0xfffffffffffffff8,%r8
  0x000000000340e533: cmp    $0x100000,%r11d
  0x000000000340e53a: ja     0x000000000340e496
  0x000000000340e540: mov    0x60(%r15),%rbp
  0x000000000340e544: mov    %rbp,%r9
  0x000000000340e547: add    %r8,%r9
  0x000000000340e54a: cmp    0x70(%r15),%r9
  0x000000000340e54e: jae    0x000000000340e496
  0x000000000340e554: mov    %r9,0x60(%r15)
  0x000000000340e558: prefetchnta 0xc0(%r9)
  0x000000000340e560: movq   $0x1,0x0(%rbp)
  0x000000000340e568: prefetchnta 0x100(%r9)
  0x000000000340e570: movl   $0x200000f5,0x8(%rbp)  ;   {metadata({type array byte})}
  0x000000000340e577: mov    %r11d,0xc(%rbp)
  0x000000000340e57b: prefetchnta 0x140(%r9)
  0x000000000340e583: prefetchnta 0x180(%r9)    ;*newarray
                                                ; - java.util.Arrays::copyOf@1 (line 3236)
                                                ; - Test::main@9 (line 9)
</code>```

Body:
As the title states, why doesn't the OpenJDK JVM emit prefetch instruction on Windows x86? See OpenJDK Mercurial @ http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp

inline void Prefetch::read (void *loc, intx interval) {}
inline void Prefetch::write(void *loc, intx interval) {}

There are no comments and I've found no other resources besides the source code. I am asking because it does so for Linux x86, see http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/linux_x86/vm/prefetch_linux_x86.inline.hpp

inline void Prefetch::read (void *loc, intx interval) {
#ifdef AMD64
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
#endif // AMD64
}

inline void Prefetch::write(void *loc, intx interval) {
#ifdef AMD64

  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
  //  __asm__ ("prefetchw (%0,%1,1)" : : "r" (loc), "r" (interval));
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));

#endif // AMD64
}

Body:
As JDK-4453409 indicates, prefetching was implemented in HotSpot JVM in JDK 1.4 to speed-up GC. That was more than 15 years ago, no one will remember now why it was not implemented on Windows. My guess is that Visual Studio (which has always been used to build HotSpot on Windows) basically didn’t understand prefetch instruction at these times. Looks like a place for improvement.

Anyway, the code you’ve asked about is used internally by JVM Garbage Collector. This is not what JIT generates. C2 JIT code generator rules are in the architecture definition file x86_64.ad, and there are rules to translate PrefetchRead, PrefetchWrite and PrefetchAllocation nodes to the corresponding x64 instructions.

An insteresting fact is that PrefetchRead and PrefetchWrite nodes are not created anywhere in the code. They exist only to support Unsafe.prefetchX intrinsics, however, they are removed in JDK 9.

The only case when JIT generates prefetch instruction is PrefetchAllocation node. You can verify with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly that PREFETCHNTA is indeed generated after object allocation, both on Linux and Windows.

class Test {
    public static void main(String[] args) {
        byte[] b = new byte[0];
        for (;;) {
            b = Arrays.copyOf(b, b.length + 1);
        }
    }
}

java.exe -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly Test

# {method} {0x00000000176124e0} 'main' '([Ljava/lang/String;)V' in 'Test'
  ...
  0x000000000340e512: cmp    $0x100000,%r11d
  0x000000000340e519: ja     0x000000000340e60f
  0x000000000340e51f: movslq 0x24(%rsp),%r10
  0x000000000340e524: add    $0x1,%r10
  0x000000000340e528: add    $0x17,%r10
  0x000000000340e52c: mov    %r10,%r8
  0x000000000340e52f: and    $0xfffffffffffffff8,%r8
  0x000000000340e533: cmp    $0x100000,%r11d
  0x000000000340e53a: ja     0x000000000340e496
  0x000000000340e540: mov    0x60(%r15),%rbp
  0x000000000340e544: mov    %rbp,%r9
  0x000000000340e547: add    %r8,%r9
  0x000000000340e54a: cmp    0x70(%r15),%r9
  0x000000000340e54e: jae    0x000000000340e496
  0x000000000340e554: mov    %r9,0x60(%r15)
  0x000000000340e558: prefetchnta 0xc0(%r9)
  0x000000000340e560: movq   $0x1,0x0(%rbp)
  0x000000000340e568: prefetchnta 0x100(%r9)
  0x000000000340e570: movl   $0x200000f5,0x8(%rbp)  ;   {metadata({type array byte})}
  0x000000000340e577: mov    %r11d,0xc(%rbp)
  0x000000000340e57b: prefetchnta 0x140(%r9)
  0x000000000340e583: prefetchnta 0x180(%r9)    ;*newarray
                                                ; - java.util.Arrays::copyOf@1 (line 3236)
                                                ; - Test::main@9 (line 9)


问:
web.xml: how to map domain/xx/* to a servlet?
I have these URLs

```<code>abc.com/aa/url1
abc.com/ab/url2
abc.com/ac/url3
etc.
</code>```

How to setup web.xml to map this pattern to a servlet?

```<code><servlet>
<servlet-name>NAME</servlet-name>
<servlet-class>MyClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NAME</servlet-name>
<url-pattern>/xx/*</url-pattern>
</servlet-mapping>
</code>```

Where xx is a two-letter string. What do I put in the place of xx so that all links above will go to MyClass?

答:
You can have more than one url-pattern entries:

```<code><servlet>
    <servlet-name>NAME</servlet-name>
    <servlet-class>MyClass</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>NAME</servlet-name>
    <url-pattern>/aa/*</url-pattern>
    <url-pattern>/ab/*</url-pattern>
    <url-pattern>/ac/*</url-pattern>
</servlet-mapping>
</code>```

Unfortunately, the servlet mapping cannot take a regular expression so you can't do a variation of /a*/* for the mapping.

Body:
I have these URLs

abc.com/aa/url1
abc.com/ab/url2
abc.com/ac/url3
etc.

How to setup web.xml to map this pattern to a servlet?

<servlet>
<servlet-name>NAME</servlet-name>
<servlet-class>MyClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NAME</servlet-name>
<url-pattern>/xx/*</url-pattern>
</servlet-mapping>

Where xx is a two-letter string. What do I put in the place of xx so that all links above will go to MyClass?

Body:
You can have more than one url-pattern entries:

<servlet>
    <servlet-name>NAME</servlet-name>
    <servlet-class>MyClass</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>NAME</servlet-name>
    <url-pattern>/aa/*</url-pattern>
    <url-pattern>/ab/*</url-pattern>
    <url-pattern>/ac/*</url-pattern>
</servlet-mapping>

Unfortunately, the servlet mapping cannot take a regular expression so you can't do a variation of /a*/* for the mapping.


问:
Setting up a table layout in React Native
I'm transitioning a React project into React Native and need help setting up a grid layout in React Native. I want to set up a 5-col by x-row (number of rows may vary) view. I've played around with the react-native-tableview-simple package, but I can't specify the span of a cell. I've also tried the react-native-flexbox-grid package, which I'm able to set up columns, but I'm still not able to set the span-width of a specific cell. I wonder if there's anything I can use.

For reference, I would like my table to look something along the lines like this:

```<code>     |Col 1|Col 2|Col 3|Col 4|Col 5|
     |------------------------------
Row 1|     Text        | Yes |  No |
     |------------------------------
Row 2|     Text        | Yes |  No |
     |------------------------------
Row 3|     Text        |  Dropdown |
</code>```

答:
You can do this without any packages. If each row is exactly the same doing the following should solve your problem;

export default class Table extends Component {
    renderRow() {
      return (
            <View style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}>
                <View style={{ flex: 1, alignSelf: 'stretch' }} /> { /* Edit these as they are your cells. You may even take parameters to display different data / react elements etc. */}
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                <View style={{ flex: 1, alignSelf: 'stretch' }} />
                </View>
        );
    }

    render() {
        const data = [1, 2, 3, 4, 5];
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            {
                data.map((datum) => { // This will render a row for each data element.
                        return this.renderRow();
                    })
            }
            </View>
        );
    }
}
```

Body:
I'm transitioning a React project into React Native and need help setting up a grid layout in React Native. I want to set up a 5-col by x-row (number of rows may vary) view. I've played around with the react-native-tableview-simple package, but I can't specify the span of a cell. I've also tried the react-native-flexbox-grid package, which I'm able to set up columns, but I'm still not able to set the span-width of a specific cell. I wonder if there's anything I can use.

For reference, I would like my table to look something along the lines like this:

     |Col 1|Col 2|Col 3|Col 4|Col 5|
     |------------------------------
Row 1|     Text        | Yes |  No |
     |------------------------------
Row 2|     Text        | Yes |  No |
     |------------------------------
Row 3|     Text        |  Dropdown |

ContentLicense: CC BY-SA 4.0


问:
game programmer portfolio
i want to work as a programmer in a game modification team. Most teams require a portfolio to show.

I haven't any previous experience with game programming and I would like to know what I should program and include in the portfolio

Thank you

答:
All of the suggestions made so far are wise, I'll also add this.

Games in the idea stage are pretty dangerous.  You'll keep thinking of things you want to add, technologies you want to use, and so on.  Get out of that as quickly as possible for every project.

Start by thinking of a core idea for a game, ideally this should be a short, one or two sentence description.  Even better would be a two word description: "Asteroids RPG!".  Then come up with a bullet point list of the features it should have.

Once you've got that list, absolutely never change it and never stray from it while you are coding.  If you have new ideas and you just have to explore them, start a new list for another game.

Hopefully you'll have something you can actually play by the time you've completed one to three of those bullet points; you can make the character move on the screen, or enemies do their thing, something you can interact with.  At this stage, although the game isn't very deep, it should already be fun.  Just moving your guy around in an interesting way should feel a bit stimulating and make you actually want to play the rest of the game.

If it doesn't, figure out why not and fix it.  If you can't figure out why it's not fun by this stage, or you can't figure out what would have to change for it to be fun, drop it immediately.  If the core gameplay mechanic, the first thing you needed to make the game a game, isn't fun now, it won't ever be fun.

You need it to be fun if you want to use it in your portfolio.  If it's not fun the interviewer won't play it much.  You don't want it to be too much fun, of course, you really want the interviewer to be interested in it and then move on to the source code or the next game.  You want to show them a variety of ideas you can explore, and a variety of techniques you can use.

Title: game programmer portfolio


问:
How to send an e-mail from *any* email address in ASP.NET?
I have a basic SmtpClient and I use it to send e-mails.

```<code>using (var client = new SmtpClient())
using (var mail = new MailMessage())
{
    mail.From = new MailAddress(fromEmailAddress);
    mail.Body = "body text";
    mail.To.Add(new MailAddress(myEmailAddress));
    client.Send(mail);
}
</code>```

This code works well if I set the fromEmailAddress to a real e-mail address. If I set it to a fake e-mail address, let's say test@test.com, the code sends the message, but I don't receive the e-mail.

I'm using it on a contact form where there is a field for their e-mail and a field for their message.

Is there a way to send the e-mail regardless of whether the e-mail is valid or not? (In PHP's mail method, it was possible)

Optionally, is it possible to check if the e-mail had been received by me? (to display an error to the user)

答:
You make a mistake in thinking your end matters.

What matters is how stupid or not - and in these days you can count on not - the receiving email server is in regarding to spam.

Your email is simply thrown away for being spam, and it is likely obvious - like the domain you send "from" (fake address) either not existing or having an SPF or other record listing the allowed senders - which you aren't one of.

Simple like that. The internet is a bad place and every sysadmin not a total idiot deploys anti spam mechanisms.

Now, if you put up some form like that or something, it needs to be fixed. Seen that many times. You can not do that - because domains are protected. Which means you can not just pretend you are allowed to send on another domain's behalf. I have seen this type sometimes with contact forms - it's a mistake of programmers not understanding that my domains have SPF records.

Body:
I have a basic SmtpClient and I use it to send e-mails.

using (var client = new SmtpClient())
using (var mail = new MailMessage())
{
    mail.From = new MailAddress(fromEmailAddress);
    mail.Body = "body text";
    mail.To.Add(new MailAddress(myEmailAddress));
    client.Send(mail);
}

This code works well if I set the fromEmailAddress to a real e-mail address. If I set it to a fake e-mail address, let's say test@test.com, the code sends the message, but I don't receive the e-mail.

I'm using it on a contact form where there is a field for their e-mail and a field for their message.

Is there a way to send the e-mail regardless of whether the e-mail is valid or not? (In PHP's mail method, it was possible)

Optionally, is it possible to check if the e-mail had been received by me? (to display an error to the user)


问:
Transform each user_id group to a feature vector
I am having a table user_aisles which is a data frame containing user_id grouped by user_aisles and n which is the number of items bought by a user in an aisle.

```<code>kable( head( summarize(user_aisles, n=n()) , 9) )
</code>```

gives

```<code>| user_id| aisle_id|  n|
|-------:|--------:|--:|
|       1|        2|  8|
|       1|        3| 12|
|       1|        4|  5|
|       2|        1|  1|
|       2|        3|  6|
|       2|       14|  1|
|       2|       17|  2|
|       2|       20|  1|
|       2|       21|  5|
</code>```

I would like to transform this into feature vectors for each user id. Such a feature vector should be nrow(aisles) dimensional.

So each user_id gets a corresponding feature vector. Feature vector for user 1 could (based on the data) look like

```<code>1: [0, 8, 12, 5, 0, .., 0]
</code>```

How can I do this?

答:
```<code>groups <- split(df, df$user_id)
lapply(groups, function(x) rep(x$aisle_id, x$n))
</code>```

You can use split to group your users and then the rep function to expand the aisle ids.

Body:
I am having a table user_aisles which is a data frame containing user_id grouped by user_aisles and n which is the number of items bought by a user in an aisle.

kable( head( summarize(user_aisles, n=n()) , 9) )

gives

| user_id| aisle_id|  n|
|-------:|--------:|--:|
|       1|        2|  8|
|       1|        3| 12|
|       1|        4|  5|
|       2|        1|  1|
|       2|        3|  6|
|       2|       14|  1|
|       2|       17|  2|
|       2|       20|  1|
|       2|       21|  5|

I would like to transform this into feature vectors for each user id. Such a feature vector should be nrow(aisles) dimensional.

So each user_id gets a corresponding feature vector. Feature vector for user 1 could (based on the data) look like

1: [0, 8, 12, 5, 0, .., 0]

How can I do this?

Body:
groups <- split(df, df$user_id)
lapply(groups, function(x) rep(x$aisle_id, x$n))

You can use split to group your users and then the rep function to expand the aisle ids.


问:
Angula2 input not binding
I am trying to  bind some data but is not working on

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="25"></child>`
 })
export class AppComponent {}
</code>```

and the child component

```<code>import { Component, Input } from '@angular/core';
@Component({
  selector: 'child',
  template: '<h1>{{in}}</h1>',
})

export class ChildComponent {

   @Input()  in: string;
 }
</code>```

答:
You should actually assign a variable and then refer it. public Hello = "25";
Then  [in]="this.hello"
 OR
Remove the brackets and assign directly
in ="25";</p>

Title: Angula2 input not binding

Body:
I am trying to  bind some data but is not working on

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="25"></child>`
 })
export class AppComponent {}

and the child component

import { Component, Input } from '@angular/core';
@Component({
  selector: 'child',
  template: '
{{in}}
',
})

export class ChildComponent {

   @Input()  in: string;
 }


答:
C# aside, thats not a good idea if you can avoid it. Setting the 'From' field doesnt actually send from that address - this would mean that anyone could impersonate your bank, for instance.

Most mail providers will regard it quite poorly in terms of spam score - meaning you are likely to have delivery issues if you are sending from a domain that you are not authorised to send from - and that is at least one possible reason why you are experiencing issues with fake addresses.

Here's some more info on why this is bad (see point #4), and some other useful tips - https://www.campaignmonitor.com/blog/email-marketing/2015/09/9-things-that-are-killing-your-email-deliverability/

Title: How to send an e-mail from *any* email address in ASP.NET?


问:
result of group_by mysql more than 1 same data
I use function group_by in mysql, but in big data 116000 record when I run this sintax there is more than 1 same data. What should I do ??

```<code>SELECT fiedl1, field2, field3
 FROM table
GROUP BY field2
ORDER BY 'field2' ASC

field1|field2|field3
1     |you   |a
2     |you   |b
3     |you   |c
4     |you    |d
5 ...etc
</code>```

result

```<code>field1|field2|field3
1     |you   |a
2     |you   |b
</code>```

答:
Best practice is to use group by on all fields, or agregate functions, for example

SELECT fiedl1, field2, field3
  FROM table
  GROUP BY fiedl1, field2, field3
  ORDER BY field2 ASC

OR

SELECT sum(fiedl1), field2, avg(field3)
  FROM table
  GROUP BY field2
  ORDER BY field2 ASC

Body:
I use function group_by in mysql, but in big data 116000 record when I run this sintax there is more than 1 same data. What should I do ??

SELECT fiedl1, field2, field3
 FROM table
GROUP BY field2
ORDER BY 'field2' ASC

field1|field2|field3
1     |you   |a
2     |you   |b
3     |you   |c
4     |you    |d
5 ...etc

result

field1|field2|field3
1     |you   |a
2     |you   |b


问:
Android status bar hide/change color in splash screen
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

```<code><style
    name="AppTheme"
    parent="@android:style/Theme.Material.Light.NoActionBar">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColor">@color/textColor</item>
    <item name="iconColor">@color/iconColor</item>
    <item name="android:statusBarColor">@color/colorPrimaryDark</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style
    name="SplashTheme"
    parent="AppTheme">

    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>
</code>```

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

```<code>View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
</code>```

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23

答:
I've had the similar problem few months ago. I've managed to solve this by using following codes.

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

Use the above code in your java file after setContentView.

Then use this in the manifest file for the activity that you are trying to hide the title bar.

android:theme="@style/Theme.AppCompat.NoActionBar"

To change the color of the title bar, you can use the following line of code,

```<code>getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));
</code>```

Replace the hex code of the color that you want to add to the title bar in value part of the code.

Body:
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23

Body:
I've had the similar problem few months ago. I've managed to solve this by using following codes.

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

Use the above code in your java file after setContentView.

Then use this in the manifest file for the activity that you are trying to hide the title bar.

android:theme="@style/Theme.AppCompat.NoActionBar"

To change the color of the title bar, you can use the following line of code,

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));

Replace the hex code of the color that you want to add to the title bar in value part of the code.


问:
Can I share iOS Realm Databases with App Groups?
Can I share iOS Realm Databases with App Groups? If yes, how? If not, how can I share my Realm Database to my other apps?</p>

答:
To share Realms between apps in the same iOS app group, you'll need to specify a common location for the Realm:</p>

```<code>let fileURL = FileManager.default
    .containerURL(forSecurityApplicationGroupIdentifier: "group.io.realm.app_group")!
    .appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: fileURL)
let realm = try Realm(configuration: config)
</code>```

Body:
To share Realms between apps in the same iOS app group, you'll need to specify a common location for the Realm:

let fileURL = FileManager.default
    .containerURL(forSecurityApplicationGroupIdentifier: "group.io.realm.app_group")!
    .appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: fileURL)
let realm = try Realm(configuration: config)


问:
How to run and install files in directory inside /opt in ubuntu?
Hi I have installed ubuntu in virtual box and I downloaded petalinux2017.1 into downloads directory and moved the run file into a directory called PetaLinux in opt in my root directory.

But i couldnot run the file when my commands are in the following way and it is showing an error "command not found".

```<code>my@my-Ubuntu: /opt/PetaLinux$petalinux-v2017.1-finalinstaller.run
</code>```

i tried the same with sudo and the error is same and i want to install it into the directory PetaLinux and I am a beginner in these.

答:
Try these commands :</p>

```<code>cd /opt/PetaLinux
sudo chmod 777 PetaLinux$petalinux-v2017.1-finalinstaller.run
./Petalinux-v2017.1-finalinstaller.run
</code>```

Body:
Hi I have installed ubuntu in virtual box and I downloaded petalinux2017.1 into downloads directory and moved the run file into a directory called PetaLinux in opt in my root directory.

But i couldnot run the file when my commands are in the following way and it is showing an error "command not found".

my@my-Ubuntu: /opt/PetaLinux$petalinux-v2017.1-finalinstaller.run

i tried the same with sudo and the error is same and i want to install it into the directory PetaLinux and I am a beginner in these.

Body:
Try these commands :

cd /opt/PetaLinux
sudo chmod 777 PetaLinux$petalinux-v2017.1-finalinstaller.run
./Petalinux-v2017.1-finalinstaller.run


问:
F# - Turn simple for loop into more functional construct
I have this simple "Investment" type with a "lifetime" property:

```<code>type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}
</code>```

I would like to iterate over the years of investment and perform some calculations for each year:

```<code>for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething
</code>```

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

答:
The go-to method of performing calculations on every item in a list is called map. Specifically, for your case, you can create a list of numbers from 1 to Lifetime and then use List.map to perform a calculation on each:

```<code>let calculation year = year * 2 // substitute your calculation here

let calcResults = [1..int CoffeMachine.Lifetime] |> List.map calculation
</code>```

That said, I think you're confusing "functional" with "hard to understand" (or, perhaps, "show off"). The point of "functional programming" is not to be all mathematics and inaccessible to the uninitiate. The point of "functional programming" is "programming with functions". There are some practical implications of that, such as "immutable data" and "no side effects", and as long as your program satisfies those, you can consider it "functional", however simple it may look. In fact, I would argue that the simpler it looks, the better. Software maintainability is a very worthy goal.

In particular, if you just wanted to print out the years, then your code is fine: printing out itself is a "side effect", so as long as that's a requirement, there is no way to make it more "functional". But if your goal is to perform some calculation (as in my example above), then that could be expressed cleaner with a list comprehension:

```<code>let calcResults = [for year in 1..int CoffeMachine.Lifetime -> calculation year]
</code>```

Body:
I have this simple "Investment" type with a "lifetime" property:

type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}

I would like to iterate over the years of investment and perform some calculations for each year:

for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

Body:
The go-to method of performing calculations on every item in a list is called map. Specifically, for your case, you can create a list of numbers from 1 to Lifetime and then use List.map to perform a calculation on each:

let calculation year = year * 2 // substitute your calculation here

let calcResults = [1..int CoffeMachine.Lifetime] |> List.map calculation

That said, I think you're confusing "functional" with "hard to understand" (or, perhaps, "show off"). The point of "functional programming" is not to be all mathematics and inaccessible to the uninitiate. The point of "functional programming" is "programming with functions". There are some practical implications of that, such as "immutable data" and "no side effects", and as long as your program satisfies those, you can consider it "functional", however simple it may look. In fact, I would argue that the simpler it looks, the better. Software maintainability is a very worthy goal.

In particular, if you just wanted to print out the years, then your code is fine: printing out itself is a "side effect", so as long as that's a requirement, there is no way to make it more "functional". But if your goal is to perform some calculation (as in my example above), then that could be expressed cleaner with a list comprehension:

let calcResults = [for year in 1..int CoffeMachine.Lifetime -> calculation year]


问:
Modify Request in Sparkweb framework using RequestWrappers
In my app I want to add a filter using spark.Spark.before for validation, if the request is granted, then I want to add some information to the request itself, so in my spark.Route implementation can access to this information.

But I don't know how to do this

For example:

```<code>// RequestFilter
before((request, response) -> {
    if (isGrantedRequest()) {
        // modify request adding params, etc
        // maybe using some kind of RequestWrapper
    }
})

.....

post("/", this::handle);

.....

// Request handler
Object handle(Request request, Response response) throws Exception {
    // access to information added in request
}
</code>```

答:
You can use session for this purpose. It's a place on the request used to set data like you wanted.

In the before code you'll create a session and set some attributes in it, according to the result of isGrantedRequest() method:

```<code>Spark.before("/somePath", (req, res) -> {
    Session ses = req.session(true);
    if (isGrantedRequest()) {
        ses.attribute("attr1", "valA");
        ses.attribute("attr2", "valB");
    } else {
        ses.attribute("attr1", "valX");
        ses.attribute("attr2", "valY");
    }
});
</code>```

In the get/post code you'll retrieve the session attributes:

```<code>Spark.get("/somePath", (req, res) -> {
    Session ses = req.session();
    if (ses != null) {
        String val1 = ses.attribute("attr1");
        String val2 = ses.attribute("attr2");
        System.out.println(val1 + " " + val2);
    }
    return "";
});
</code>```

Look at Spark's sessions API to see more options.

Body:
In my app I want to add a filter using spark.Spark.before for validation, if the request is granted, then I want to add some information to the request itself, so in my spark.Route implementation can access to this information.

But I don't know how to do this

For example:

// RequestFilter
before((request, response) -> {
    if (isGrantedRequest()) {
        // modify request adding params, etc
        // maybe using some kind of RequestWrapper
    }
})

.....

post("/", this::handle);

.....

// Request handler
Object handle(Request request, Response response) throws Exception {
    // access to information added in request
}

Body:
You can use session for this purpose. It's a place on the request used to set data like you wanted.

In the before code you'll create a session and set some attributes in it, according to the result of isGrantedRequest() method:

Spark.before("/somePath", (req, res) -> {
    Session ses = req.session(true);
    if (isGrantedRequest()) {
        ses.attribute("attr1", "valA");
        ses.attribute("attr2", "valB");
    } else {
        ses.attribute("attr1", "valX");
        ses.attribute("attr2", "valY");
    }
});

In the get/post code you'll retrieve the session attributes:

Spark.get("/somePath", (req, res) -> {
    Session ses = req.session();
    if (ses != null) {
        String val1 = ses.attribute("attr1");
        String val2 = ses.attribute("attr2");
        System.out.println(val1 + " " + val2);
    }
    return "";
});

Look at Spark's sessions API to see more options.


问:
How to return starting and end point of a path in a hierarchical structure
I have a table that looks like that

```<code>---------------------------
| id1 | id2 | col1 | col2 |
+-----+-----+------+------+
|  1  |  1  |  a   |  b   |
|-----+-----+------+------|
|  1  |  2  |  b   |  c   |
|-----+-----+------+------|
|  5  |  1  |  d   |  f   |
---------------------------
</code>```

The idea is that the table stores paths: a->b->c and d->f. What I want is a query that will return a->c and d->f.

答:
I think you might mean

```<code>select a, b, c from whateveryourtablenameis;
</code>```

and include whatever columns you want in addition to a, b, and c.

This would return just columns a, b, and c. I know of no way to ask SQL for a range of columns other than *.

Body:
I have a table that looks like that

---------------------------
| id1 | id2 | col1 | col2 |
+-----+-----+------+------+
|  1  |  1  |  a   |  b   |
|-----+-----+------+------|
|  1  |  2  |  b   |  c   |
|-----+-----+------+------|
|  5  |  1  |  d   |  f   |
---------------------------

The idea is that the table stores paths: a->b->c and d->f. What I want is a query that will return a->c and d->f.

Body:
I think you might mean

select a, b, c from whateveryourtablenameis;

and include whatever columns you want in addition to a, b, and c.

This would return just columns a, b, and c. I know of no way to ask SQL for a range of columns other than *.


问:
How do I set AFrame position using variables and javascript?
When I use:

```<code>myObject.setAttribute('position','3 0 35' );
</code>```

everything works fine.

I want to set attributes from variables,
instead of having to manually type in the numbers,
like this:

```<code>myObject.setAttribute('position','myX myY myZ' );
</code>```

What am I doing wrong?

答:
I tried to preposition them too quickly, the loop created them, but I was trying to move them before they were fully loaded into the scene.
The room is so dense with objects that it took longer than expected.

Aframe being a higher level language, it takes longer to load.
Three.js loaded more quickly, but the AFrame animations seem smoother.
I will just need a "loading" message to keep people from thinking it is broken.

Body:
When I use:

myObject.setAttribute('position','3 0 35' );

everything works fine.

I want to set attributes from variables,
instead of having to manually type in the numbers,
like this:

myObject.setAttribute('position','myX myY myZ' );

What am I doing wrong?


问:
how to save or move image file to a folder contain in my php file folder
I'm building a media and I want my users to
 upload as many images as they like,But my problem
 is how to save or move this image to a folder
 called photo contain in folder called my_media,
 my_media folder contain my php files such as
 index.php and more,I can move this file to
 my_media folder once upload,But i don't want
 the file they for security purpose,please
 someone should fix my code thanks.

this my code

```<code>require_once ('connect.php');

if (isset($_POST['Submit'])) {

 $tmp_dir = "my_media/photo";
 //it will move to my_media if assign my_media only to the variable $tmp_dir
 //but don't work with  $tmp_dir = "my_media/photo"

 $tmp_name = $_FILES["image"]["tmp_name"];
 $name = $_FILES["image"]["name"];

move_uploaded_file($tmp_name,$tmp_dir . basename($name));

    //rename("my_media/photo","my_media/photo". basename($name));
$location=$name;
$fname=$_POST['first_name'];
$lname=$_POST['last_name'];

$sql = "INSERT INTO tbl_image (first_name, last_name, image_location)
VALUES ('$fname', '$lname', '$location')";
 $res = mysqli_query($con,$sql);
//with this my the image name is inserted into my database but not into the foldermy_media/photo
header("Location:imgview.php");
}
</code>```

答:
```<code>require_once ('connect.php');
if (isset($_POST['submit'])) {

 $tmp_dir = "/my_media/photo/";
 $name = time().$_FILES["image"]["name"];

 move_uploaded_file($_FILES["image"]["tmp_name"], $name);
 $location=$name;
 $fname=$_POST['first_name'];
 $lname=$_POST['last_name'];

 $sql = "INSERT INTO tbl_image (first_name, last_name, image_location)
 VALUES ('$fname', '$lname', '$location')";
 $res = mysqli_query($con,$sql);
 header("Location:imgview.php");
}
</code>```

Body:
I'm building a media and I want my users to
 upload as many images as they like,But my problem
 is how to save or move this image to a folder
 called photo contain in folder called my_media,
 my_media folder contain my php files such as
 index.php and more,I can move this file to
 my_media folder once upload,But i don't want
 the file they for security purpose,please
 someone should fix my code thanks.

this my code

require_once ('connect.php');

if (isset($_POST['Submit'])) {

 $tmp_dir = "my_media/photo";
 //it will move to my_media if assign my_media only to the variable $tmp_dir
 //but don't work with  $tmp_dir = "my_media/photo"

 $tmp_name = $_FILES["image"]["tmp_name"];
 $name = $_FILES["image"]["name"];

move_uploaded_file($tmp_name,$tmp_dir . basename($name));

    //rename("my_media/photo","my_media/photo". basename($name));
$location=$name;
$fname=$_POST['first_name'];
$lname=$_POST['last_name'];

$sql = "INSERT INTO tbl_image (first_name, last_name, image_location)
VALUES ('$fname', '$lname', '$location')";
 $res = mysqli_query($con,$sql);
//with this my the image name is inserted into my database but not into the foldermy_media/photo
header("Location:imgview.php");
}


问:
attr new onclick function not working
I am replacing an onclick attr as so....

```<code>$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}
</code>```

My current html is

```<code><div id="divName" onclick="oldFunction()">
</code>```

and after i insert the new attr , inspecting element shows this

```<code><div id="divName" onclick="newFunction()">
</code>```

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

答:
I don't know what the purpose of that codes.
but i try to give you another solution.
Hope will solve your problem.

html:

```<code> <div id="divName" onclick="oldFunction()">
</code>```

on script:

```<code> $('#divName').addClass('newClass');

 $('.newClass').click(
   function(){
    alert('New Function Success');
   }
 );
</code>```

if you need to change another function you can change your attribute.

Title: attr new onclick function not working

Body:
I am replacing an onclick attr as so....

$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}

My current html is

and after i insert the new attr , inspecting element shows this

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

Body:
I don't know what the purpose of that codes.
but i try to give you another solution.
Hope will solve your problem.

html:

 <div id="divName" onclick="oldFunction()">

on script:

 $('#divName').addClass('newClass');

 $('.newClass').click(
   function(){
    alert('New Function Success');
   }
 );

if you need to change another function you can change your attribute.


问:
PHP curl cannot save ASP.net MVC generated cookie
I need to write a bot to login into a website and do some query, problem is this website is written in ASP.NET MVC and needs two cookies to identify user! I can save one cookie using my PHP curl but the other one .AspNet.ApplicationCookie (which is as large as ~400KB) cannot be stored!

Here is my code:

```<code>$ch = curl_init('MY URL...');
$cookie = __DIR__ . '/cookie.txt';
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserName=123&Password=123");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
$result = curl_exec($ch);
var_dump($result);
</code>```

答: I found the solution, ASP.net uses a mechanism to avoid CSRF attacks which is using a token field (hidden text input as "__RequestVerificationToken") and a cookie on the same page also as "__RequestVerificationToken" these tokens comes with different values but are related with each other, what you need to do for a remote login using PHP cURL is to fetch these values at the same time and posting them together if you get the __RequestVerificationToken field and get the cookie another time or vice versa, ASP.net considers this as an attack and changes values both on cookie and the field which will result to a failed login.</p>

Body:
I need to write a bot to login into a website and do some query, problem is this website is written in ASP.NET MVC and needs two cookies to identify user! I can save one cookie using my PHP curl but the other one .AspNet.ApplicationCookie (which is as large as ~400KB) cannot be stored!

Here is my code:

$ch = curl_init('MY URL...');
$cookie = __DIR__ . '/cookie.txt';
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserName=123&Password=123");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
$result = curl_exec($ch);
var_dump($result);


问:
Nested tables with thymeleaf
I'm trying to get a thymeleaf page to show something like following on page:

```<code>Question 1:
answer 1
answer 2
answer 3
etc...
</code>```

The amount of answers or questions in page is not known. But it can be calculated from a database if needed.

I'm passing two separate list objects with model.addAttribute. One is called answer and one is called survey. I know both of them work, I can print list of questions or list of answers, but not both at the same time, in this format.

I currently have this code in my HTML page

```<code><table class="table table-hover">

    <tr th:each="survey : ${survey}">
        <td th:text="${survey.name}">

            <table class="second table">
                <tr th:each="answer : ${answer}">
                    <td th:text="${answer.name}"></td>
                </tr>
            </table>
        </td>
    </tr>

</table>
</code>```

How do I go about nesting the loop so I can present them in the page as shown in beginning?

To be more clear: question = survey.name and answer = answer.name

答:
If someone wonders here, you can use nested lists like this:</p>

```<code>               <table>
                <span th:each="survey : ${survey}">
                    <h1 th:text="${survey.name}"></h1>
                    <td>
                        <tr th:each="answer: ${answer}">
                            <p th:text="${answer.name}"></p>
                        </tr>
                    </td>
                </span>
              </table>
</code>```

Title: Nested tables with thymeleaf

Body:
I'm trying to get a thymeleaf page to show something like following on page:

Question 1:
answer 1
answer 2
answer 3
etc...

The amount of answers or questions in page is not known. But it can be calculated from a database if needed.

I'm passing two separate list objects with model.addAttribute. One is called answer and one is called survey. I know both of them work, I can print list of questions or list of answers, but not both at the same time, in this format.

I currently have this code in my HTML page

How do I go about nesting the loop so I can present them in the page as shown in beginning?

To be more clear: question = survey.name and answer = answer.name

Body:
If someone wonders here, you can use nested lists like this:

               <table>
                <span th:each="survey : ${survey}">
                    <h1 th:text="${survey.name}"></h1>
                    <td>
                        <tr th:each="answer: ${answer}">
                            <p th:text="${answer.name}"></p>
                        </tr>
                    </td>
                </span>
              </table>


问:
Incremental SMT solver with ability to drop specific constraint
Is there an incremental SMT solver or an API for some incremental SMT solver where I can add constraints incrementally, where I can uniquely identify each constraint by some label/name?

The reason I want to identify the constraints uniquely is so that I can drop them later by specifying that label/name.
The need for dropping constraints is due to the fact that my earlier constraints become irrelevant with time.
I see that with Z3 I cannot use the push/pop based incremental approach because it follows a stack based idea whereas my requirement is to drop specific earlier/old constraints.
With the other incremental approach of Z3 based on assumptions, I would have to perform check-sat of the format "(check-sat p1 p2 p3)" i.e. if I had three assertions to check then I would require three boolean constants p1,p2,p3, but in my implementation I would have thousands of assertions to check at a time, indirectly requiring thousands of boolean constants.
I also checked JavaSMT, a Java API for SMT solvers, to see if the API provides some better way of handling this requirement, but I see only way to add constraints by "addConstraint" or "push" and was unable to find any way of dropping or removing specific constraints since the pop is the only option available.

I would like to know if there is any incremental solver where I can add or drop constraints uniquely identified by names, or an API where there is an alternative way to handle it. I would appreciate any suggestion or comments.

答:
The "stack" based approach is pretty much ingrained into SMTLib, so I think it'll be tough to find a solver that does exactly what you want. Although I do agree it would be a nice feature.

Having said that, I can think of two solutions. But neither will serve your particular use-case well, though they will both work. It comes down to the fact that you want to be able to cherry-pick your constraints at each call to check-sat. Unfortunately this is going to be expensive. Each time the solver does a check-sat it learns a lot of lemmas based on all the present assertions, and a lot of internal data-structures are correspondingly modified. The stack-based approach essentially allows the solver to "backtrack" to one of those learned states. But of course, that does not allow cherry-picking as you observed.

So, I think you're left with one of the following:

Using check-sat-assuming

This is essentially what you described already. But to recap, instead of asserting booleans, you simply give them names. So, this:

```<code>  (assert complicated_expression)
</code>```

becomes

```<code>  ; for each constraint ci, do this:
  (declare-const ci Bool)
  (assert (= ci complicated_expression))
  ; then, check with whatever subset you want
  (check-sat-assuming (ci cj ck..))
</code>```

This does increase the number of boolean constants you have to manage, but in a sense these are the "names" you want anyhow. I understand you do not like this as it introduces a lot of variables; and that is indeed the case. And there's a good reason for that. See this discussion here: https://github.com/Z3Prover/z3/issues/1048

Using reset-assertions and :global-declarations

This is the variant that allows you to arbitrarily cherry-pick the assertions at each call to check-sat. But it will not be cheap. In particular, the solver will forget everything it learned each time you follow this recipe. But it will do precisely what you wanted. First issue:

```<code>(set-option :global-declarations true)
</code>```

And somehow keep track of all these yourself in your wrapper. Now, if you want to arbitrarily "add" a constraint, you don't need to do anything. Just add it. If you want to remove something, then you say:

```<code> (reset-assertions)
 (assert your-tracked-assertion-1)
 (assert your-tracked-assertion-2)
;(assert your-tracked-assertion-3)  <-- Note the comment, we're skipping
 (assert your-tracked-assertion-4)
 ..etc
</code>```

etc. That is, you "remove" the ones you don't want. Note that the :global-declarations call is important since it'll make sure all your data-declarations and other bindings stay intact when you call reset-assertions, which tells the solver to start from a clean-slate of what it assumed and learned.

Effectively, you're managing your own constraints, as you wanted in the first place.

Summary

Neither of these solutions is precisely what you wanted, but they will work. There's simply no SMTLib compliant way to do what you want without resorting to one of these two solutions. Individual solvers, however, might have other tricks up their sleeve. You might want to check with their developers to see if they might have something custom for this use case. While I doubt that is the case, it would be nice to find out!

Also see this previous answer from Nikolaj which is quite related: How incremental solving works in Z3?

Body:
The "stack" based approach is pretty much ingrained into SMTLib, so I think it'll be tough to find a solver that does exactly what you want. Although I do agree it would be a nice feature.

Having said that, I can think of two solutions. But neither will serve your particular use-case well, though they will both work. It comes down to the fact that you want to be able to cherry-pick your constraints at each call to check-sat. Unfortunately this is going to be expensive. Each time the solver does a check-sat it learns a lot of lemmas based on all the present assertions, and a lot of internal data-structures are correspondingly modified. The stack-based approach essentially allows the solver to "backtrack" to one of those learned states. But of course, that does not allow cherry-picking as you observed.

So, I think you're left with one of the following:

Using check-sat-assuming

This is essentially what you described already. But to recap, instead of asserting booleans, you simply give them names. So, this:

  (assert complicated_expression)

becomes

  ; for each constraint ci, do this:
  (declare-const ci Bool)
  (assert (= ci complicated_expression))
  ; then, check with whatever subset you want
  (check-sat-assuming (ci cj ck..))

This does increase the number of boolean constants you have to manage, but in a sense these are the "names" you want anyhow. I understand you do not like this as it introduces a lot of variables; and that is indeed the case. And there's a good reason for that. See this discussion here: https://github.com/Z3Prover/z3/issues/1048

Using reset-assertions and :global-declarations

This is the variant that allows you to arbitrarily cherry-pick the assertions at each call to check-sat. But it will not be cheap. In particular, the solver will forget everything it learned each time you follow this recipe. But it will do precisely what you wanted. First issue:

(set-option :global-declarations true)

And somehow keep track of all these yourself in your wrapper. Now, if you want to arbitrarily "add" a constraint, you don't need to do anything. Just add it. If you want to remove something, then you say:

 (reset-assertions)
 (assert your-tracked-assertion-1)
 (assert your-tracked-assertion-2)
;(assert your-tracked-assertion-3)  <-- Note the comment, we're skipping
 (assert your-tracked-assertion-4)
 ..etc

etc. That is, you "remove" the ones you don't want. Note that the :global-declarations call is important since it'll make sure all your data-declarations and other bindings stay intact when you call reset-assertions, which tells the solver to start from a clean-slate of what it assumed and learned.

Effectively, you're managing your own constraints, as you wanted in the first place.

Summary

Neither of these solutions is precisely what you wanted, but they will work. There's simply no SMTLib compliant way to do what you want without resorting to one of these two solutions. Individual solvers, however, might have other tricks up their sleeve. You might want to check with their developers to see if they might have something custom for this use case. While I doubt that is the case, it would be nice to find out!

Also see this previous answer from Nikolaj which is quite related: How incremental solving works in Z3?


问:
How to move some files from one git repo to another (not a clone), preserving history
Our Git repositories started out as parts of a single monster SVN repository where the individual projects each had their own tree like so:

```<code>project1/branches
        /tags
        /trunk
project2/branches
        /tags
        /trunk
</code>```

Obviously, it was pretty easy to move files from one to another with svn mv. But in Git, each project is in its own repository, and today I was asked to move a subdirectory from project2 to project1. I did something like this:

```<code>$ git clone project2
$ cd project2
$ git filter-branch --subdirectory-filter deeply/buried/java/source/directory/A -- --all
$ git remote rm origin  # so I don't accidentally overwrite the repo ;-)
$ mkdir -p deeply/buried/different/java/source/directory/B
$ for f in *.java; do
>  git mv $f deeply/buried/different/java/source/directory/B
>  done
$ git commit -m "moved files to new subdirectory"
$ cd ..
$
$ git clone project1
$ cd project1
$ git remote add p2 ../project2
$ git fetch p2
$ git branch p2 remotes/p2/master
$ git merge p2 # --allow-unrelated-histories for git 2.9+
$ git remote rm p2
$ git push
</code>```

But that seems pretty convoluted. Is there a better way to do this sort of thing in general? Or have I adopted the right approach?

Note that this involves merging the history into an existing repository, rather than simply creating a new standalone repository from part of another one (as in an earlier question).

答:
The one I always use is here http://blog.neutrino.es/2012/git-copy-a-file-or-directory-from-another-repository-preserving-history/ . Simple and fast.

For compliance with stackoverflow standards, here is the procedure:

```<code>mkdir /tmp/mergepatchs
cd ~/repo/org
export reposrc=myfile.c #or mydir
git format-patch -o /tmp/mergepatchs $(git log $reposrc|grep ^commit|tail -1|awk '{print $2}')^..HEAD $reposrc
cd ~/repo/dest
git am /tmp/mergepatchs/*.patch
</code>```

Body:
Our Git repositories started out as parts of a single monster SVN repository where the individual projects each had their own tree like so:

project1/branches
        /tags
        /trunk
project2/branches
        /tags
        /trunk

Obviously, it was pretty easy to move files from one to another with svn mv. But in Git, each project is in its own repository, and today I was asked to move a subdirectory from project2 to project1. I did something like this:

$ git clone project2
$ cd project2
$ git filter-branch --subdirectory-filter deeply/buried/java/source/directory/A -- --all
$ git remote rm origin  # so I don't accidentally overwrite the repo ;-)
$ mkdir -p deeply/buried/different/java/source/directory/B
$ for f in *.java; do
>  git mv $f deeply/buried/different/java/source/directory/B
>  done
$ git commit -m "moved files to new subdirectory"
$ cd ..
$
$ git clone project1
$ cd project1
$ git remote add p2 ../project2
$ git fetch p2
$ git branch p2 remotes/p2/master
$ git merge p2 # --allow-unrelated-histories for git 2.9+
$ git remote rm p2
$ git push

But that seems pretty convoluted. Is there a better way to do this sort of thing in general? Or have I adopted the right approach?

Note that this involves merging the history into an existing repository, rather than simply creating a new standalone repository from part of another one (as in an earlier question).

Body:
The one I always use is here http://blog.neutrino.es/2012/git-copy-a-file-or-directory-from-another-repository-preserving-history/ . Simple and fast.

For compliance with stackoverflow standards, here is the procedure:

mkdir /tmp/mergepatchs
cd ~/repo/org
export reposrc=myfile.c #or mydir
git format-patch -o /tmp/mergepatchs $(git log $reposrc|grep ^commit|tail -1|awk '{print $2}')^..HEAD $reposrc
cd ~/repo/dest
git am /tmp/mergepatchs/*.patch


问:
Add event on inner class by mouseovering on outer class in html using javascript
I have class post and another class postinr defined in post class. I want to attach event to class postinr while mouseovering on class post. But I am unable to do that. What is the solution. Here is simple structure of html and javascript...`

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{
post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "70px");
}
function animate2() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "123px");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3></h3>
  </div>
</div></code>```

答:
If i understood you well, you need something like this.

What here is done when .post element gets hovered at that instance .postinr gets changed or updated as you want.

h3 { margin:0; }
.post {
  background: yellow;
  padding: 15px;
}
.postinr {
  background: #cecece;
  padding: 10px;
  margin-top:123px;
  transition: margin-top 0.2s ease;
}

.post:hover .postinr {
  margin-top:70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3>Hello World!</h3>
  </div>
</div></code>```

The solution here is just using HTML & CSS, i guess you do not need JS for this.

Hope this helps you :-), Thank You!

Body:
If i understood you well, you need something like this.

What here is done when .post element gets hovered at that instance .postinr gets changed or updated as you want.

h3 { margin:0; }
.post {
  background: yellow;
  padding: 15px;
}
.postinr {
  background: #cecece;
  padding: 10px;
  margin-top:123px;
  transition: margin-top 0.2s ease;
}

.post:hover .postinr {
  margin-top:70px;
}

<div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3>Hello World!</h3>
  </div>
</div>

The solution here is just using HTML & CSS, i guess you do not need JS for this.

Hope this helps you :-), Thank You!


问:
How do I sort a List of TreeSets with java8 streams
My list contains sets like [1,3,5][2,6,4] etc, all of the same size.
I tried doing this but it doesn't seem to work.

```<code>List<TreeSet<T>> block;
    for(TreeSet<T> t : block){
        block.stream().sorted((n,m)->n.compareTo(m)).collect(Collectors.toSet());

    }
</code>```

The end result I want is [1,2,3][4,5,6].

I could try to add all the elements in an ArrayList and sort that out then make a new List of TreeSet's. But is there is some kind of one liner?

UPDATE:

```<code>List<T> list=new ArrayList<T>();
    for(TreeSet<T> t : block){

        for(T t1 : t)
        {
            list.add(t1);

        }
    }

    list=list.stream().sorted((n,m)->n.compareTo(m)).collect(Collectors.toList());
</code>```

This works but could this be simplified?

答:
Adding another answer since this would be bigger than a comment. It's really what the accepted answer has done, but with a "smarter" combiner that does not have to stream all the time again.</p>

```<code> private static <T> Collector<T, ?, List<Set<T>>> partitioning(int size) {
    class Acc {
        int count = 0;

        List<List<T>> list = new ArrayList<>();

        void add(T elem) {
            int index = count++ / size;
            if (index == list.size()) {
                list.add(new ArrayList<>());
            }
            list.get(index).add(elem);
        }

        Acc merge(Acc right) {

            List<T> lastLeftList = list.get(list.size() - 1);
            List<T> firstRightList = right.list.get(0);
            int lastLeftSize = lastLeftList.size();
            int firstRightSize = firstRightList.size();

            // they have both the same size, simply addAll will work
            if (lastLeftSize + firstRightSize == 2 * size) {
                System.out.println("Perfect!");
                list.addAll(right.list);
                return this;
            }

            // last and first from each chunk are merged "perfectly"
            if (lastLeftSize + firstRightSize == size) {
                System.out.println("Almost perfect");
                int x = 0;
                while (x < firstRightSize) {
                    lastLeftList.add(firstRightList.remove(x));
                    --firstRightSize;
                }
                right.list.remove(0);
                list.addAll(right.list);
                return this;
            }

            right.list.stream().flatMap(List::stream).forEach(this::add);
            return this;
        }

        public List<Set<T>> finisher() {
            return list.stream().map(LinkedHashSet::new).collect(Collectors.toList());
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}
</code>```

Body:
My list contains sets like [1,3,5][2,6,4] etc, all of the same size.
I tried doing this but it doesn't seem to work.

List<TreeSet<T>> block;
    for(TreeSet<T> t : block){
        block.stream().sorted((n,m)->n.compareTo(m)).collect(Collectors.toSet());

    }

The end result I want is [1,2,3][4,5,6].

I could try to add all the elements in an ArrayList and sort that out then make a new List of TreeSet's. But is there is some kind of one liner?

UPDATE:

List<T> list=new ArrayList<T>();
    for(TreeSet<T> t : block){

        for(T t1 : t)
        {
            list.add(t1);

        }
    }

    list=list.stream().sorted((n,m)->n.compareTo(m)).collect(Collectors.toList());

This works but could this be simplified?

Body:
Adding another answer since this would be bigger than a comment. It's really what the accepted answer has done, but with a "smarter" combiner that does not have to stream all the time again.

 private static <T> Collector<T, ?, List<Set<T>>> partitioning(int size) {
    class Acc {
        int count = 0;

        List<List<T>> list = new ArrayList<>();

        void add(T elem) {
            int index = count++ / size;
            if (index == list.size()) {
                list.add(new ArrayList<>());
            }
            list.get(index).add(elem);
        }

        Acc merge(Acc right) {

            List<T> lastLeftList = list.get(list.size() - 1);
            List<T> firstRightList = right.list.get(0);
            int lastLeftSize = lastLeftList.size();
            int firstRightSize = firstRightList.size();

            // they have both the same size, simply addAll will work
            if (lastLeftSize + firstRightSize == 2 * size) {
                System.out.println("Perfect!");
                list.addAll(right.list);
                return this;
            }

            // last and first from each chunk are merged "perfectly"
            if (lastLeftSize + firstRightSize == size) {
                System.out.println("Almost perfect");
                int x = 0;
                while (x < firstRightSize) {
                    lastLeftList.add(firstRightList.remove(x));
                    --firstRightSize;
                }
                right.list.remove(0);
                list.addAll(right.list);
                return this;
            }

            right.list.stream().flatMap(List::stream).forEach(this::add);
            return this;
        }

        public List<Set<T>> finisher() {
            return list.stream().map(LinkedHashSet::new).collect(Collectors.toList());
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}