text:
Q: Characteristics of the abstract class I would like to know what makes a class to be called as an abstract class. I believe, abstract keyword definitely make a class, but if one takes out the keyword, then we can create the instance of the class.
In otherwords, what are the characteristics of the abstract class.
Thanks in advance.
-Harsha

A: An abstract class does not form a concrete object in the real world unlike pure implementation classes. Abstract as the name suggestes they hold/define common behaviours of related objects that need to be reused/defined independantly in all related objects.
Take an example of Birds. If you are writing a progrm that will have something to do with the birds, then you'll first have an abstract base class as Bird and each bird deriving from the abstract base class Bird. Do note that abstract class BIRD does not represent a concrete real world object but a type of related objects that is birds!
Lets start with the class-diagram and then some code.
alt text http://ruchitsurati.net/files/birds.png
public abstract class Bird
{
    protected string Name = string.Empty;
    public Bird(string name)
    {
        this.Name = name;
    }

    public virtual void Fly()
    {
        Console.WriteLine(string.Format("{0} is flying.", this.Name));
    }

    public virtual void Run()
    {
        Console.WriteLine(string.Format("{0} cannot run.", this.Name));
    }
}

public class Parrot : Bird
{
    public Parrot() : base("parrot") { }
}

public class Sparrow : Bird
{
    public Sparrow() : base("sparrow") { }
}

public class Penguin : Bird
{
    public Penguin() : base("penguin") { }

    public override void Fly()
    {
        Console.WriteLine(string.Format("{0} cannot fly. Some birds do not fly.", this.Name));
    }

    public override void Run()
    {
        Console.WriteLine(string.Format("{0} is running. Some birds do run.", this.Name));
    }
}

class Program
{
    static void Main(string[] args)
    {

        Parrot p = new Parrot();
        Sparrow s = new Sparrow();
        Penguin pe = new Penguin();

        List<Bird> birds = new List<Bird>();

        birds.Add(p);
        birds.Add(s);
        birds.Add(pe);

        foreach (Bird bird in birds)
        {
            bird.Fly();
            bird.Run();
        }

        Console.ReadLine();
    }
}

A: An abstract class has one singular characteristic: no instances of the class can be created.  Abstract classes are designed to be used as base classes for other abstract and non-abstract classes.

A: For the abstract on the class to have any meaning, it must have abstract members that need implementing, otherwise it's extraneous (unless you intended to prevent instantiation) and you should remove it.
It might have an abstract property an inheritor needs to declare, like this
public abstract int ID { get; }

or a method it must implement:
public abstract void DoSomething();

You would use it if the class itself was never to be instantiated but you needed more than an interface, for example base properties and you wanted to use it later:
((MyAbstractClass)obj).DoSomething(); //All inheritors implemented this

A: An abstract class serves two related purposes:

*

*You can place abstract members into the class

*You cannot create an instance of the abstract class

The main purpose of an abstract class is to serve as a base class for descendant classes, providing perhaps some common functionality, but at least providing a common set of methods that the descendants has to implement.
For instance, you could create an abstract class Fruit, with an abstract method Eat. Since you cannot actually eat a "fruit", you need to eat a specific type of fruit, the class is abstract and you will never see an object that is labelled "Fruit" in the wild.
Instead, you will see objects of type Apple, Banana, Orange, etc. that are descendants of Fruit, and which have an actual implementation of Eat.
Other than the two things at the top, there is nothing special about an abstract class.

A: I don't think anybody has said this yet, but I believe the distinguishing characteristic of an abstract class is:
The coder knows how X%  of the class is implemented, and how (100-X)% of the class should be implemented, but which cannot be.
This is what distinguishes the abstract class.  Interfaces describe how a class should be implemented, but do not give implementors any code or support.  Base classes with virtual methods provide default implementations that inheritors may possibly override.
It is only the abstract class that can provide a partial implementation, but cannot provide a complete implementation.


text:
Q: Displaying Desired output in Powershell Script Hi I'm trying to get a menu listing of all VMs in Hyper-V Host. However I'm getting extra information in my menu list. How can I get rid of it?
'''
  $VMs = @(Get-VM | Select-Object Name)
    $menuIndex = 1
    Write-Host "Select a VM from the list"
    $VMs | foreach {
        Write-Host $menuIndex " - $_";
        $menuIndex += 1;
        }

     $ChosenItem = [int](Read-Host "Please select a Virtual Machine (1 to $($menuIndex-1))")

$VM = $VMs[$ChosenItem-1]

'''
The output of this script gives me extra data I don't want to display. I just need the VM Name.
Instead I get:
1 - @{Name=VirtualMachine1}
2 - @{Name=VirtualMachine2}
I would desire to get the following instead:
1 - VirtualMachine1
2 - VirtulaMachine2
How do I remove the "@{Name=}" portion of the output?
Thank You

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mocking inbound Jax-RS Response with Entity I am trying to unit test a class that uses Jersey 2 Client + Moxy to call a REST service. I want to mock the response, which contains a large JSON object. The code is structured in such a way that I can override/mock the following method:
protected Response doPost(String path, Entity<?> entity) {
    Invocation.Builder invocationBuilder = getRestInvocationBuilder(path);
    Response response = invocationBuilder.post(entity);
    return response;
}

I would like to somehow inject some example JSON data (ideally from a file) into the Response at this point, prior to readEntity() being called, so that I can test that the JSON data is correctly unmarshalled into the target object.
Is there any way to do this? Note that this is for unit testing and therefore I'm not interested in running a local server or other integration testing techniques.
I'm aware similar questions have been asked, but many seem out of date or have incomplete solutions. The closest solution suggested is to mock the readEntity() method of the Response, this will not work for me because it would involve creating an object of the desired type to return, rather than creating one from the example JSON data.


text:
Q: Remove Non-Ansi Chars from a UTF String and Keep Others We have a java lib accpeting a UTF8 string as the input. But if there is any char which is a non-ansi char in the input, the lib may crash. So, we want to remove all non-ansi char from the string. But how to do that in java?
Thanks,

A: Try this, I pulled this from here so haven't tested it
// Create a encoder and decoder for the character encoding
Charset charset = Charset.forName("US-ASCII");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

// This line is the key to removing "unmappable" characters.
encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
String result = inString;

try {
    // Convert a string to bytes in a ByteBuffer
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(inString));

    // Convert bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    CharBuffer cbuf = decoder.decode(bbuf);
    result = cbuf.toString();
} catch (CharacterCodingException cce) {
    String errorMessage = "Exception during character encoding/decoding: " + cce.getMessage();
    cce.printStackTrace()
}

A: Take a look at String.codePointAt(index).  That can give you the Unicode code point for a given character, and from there you could remove those outside your range.
How you handle the fact that a character has been removed is on your end, but keep in mind that the string you'll be sending to the library isn't necessarily the same as that provided by the client.  This may or may not cause problems.
I'm not sure what you mean by ANSI here.  Do you mean the Windows 1252 character encoding that people typically call ANSI?  That's not ASCII and it's also not IS0-8859-1, so make sure you get your code pages correct.


text:
Q: Printing static content from a WebView in a Windows Store App UPDATE 3
There's a bounty on this question now. The sample project and problem brief are at the bottom of the page under TL;DR; so save yourself some reading and skip to the end!
...
I've been trying to get this highly detailed, upvoted answer from JerryNixon working using a statically loaded page via NavigateToString. I don't see why this shouldn't work, but admittedly there are parts of the code that absolutely baffle me.
The original answer is here but I'll replicate the code here for completeness sake. Jerry provides the following sample / solution to those who want to print from a WebView
<Grid Background="Blue">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="995" />
        <ColumnDefinition Width="300" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <WebView Grid.Column="0" x:Name="MyWebView" Source="http://www.stackoverflow.com" HorizontalAlignment="Right" />
    <Rectangle Grid.Column="1" x:Name="MyWebViewRectangle" Fill="Red" />
    <ScrollViewer Grid.Column="2" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <ItemsControl x:Name="MyPrintPages" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Rectangle Height="150" Width="100" Fill="White" Margin="5" />
            <Rectangle Height="150" Width="100" Fill="White" Margin="5" />
            <Rectangle Height="150" Width="100" Fill="White" Margin="5" />
            <Rectangle Height="150" Width="100" Fill="White" Margin="5" />
            <Rectangle Height="150" Width="100" Fill="White" Margin="5" />
        </ItemsControl>
    </ScrollViewer>
</Grid>

public MainPage()
{
    this.InitializeComponent();
    MyWebView.LoadCompleted += MyWebView_LoadCompleted;
}

void MyWebView_LoadCompleted(object sender, NavigationEventArgs e)
{
    MyWebViewRectangle.Fill = GetWebViewBrush(MyWebView);
    MyPrintPages.ItemsSource = GetWebPages(MyWebView, new Windows.Foundation.Size(100d, 150d));
    MyWebView.Visibility = Windows.UI.Xaml.Visibility.Visible;
}

WebViewBrush GetWebViewBrush(WebView webView)
{
    // resize width to content
    var _OriginalWidth = webView.Width;
    var _WidthString = webView.InvokeScript("eval",
        new[] { "document.body.scrollWidth.toString()" });
    int _ContentWidth;
    if (!int.TryParse(_WidthString, out _ContentWidth))
        throw new Exception(string.Format("failure/width:{0}", _WidthString));
    webView.Width = _ContentWidth;

    // resize height to content
    var _OriginalHeight = webView.Height;
    var _HeightString = webView.InvokeScript("eval",
        new[] { "document.body.scrollHeight.toString()" });
    int _ContentHeight;
    if (!int.TryParse(_HeightString, out _ContentHeight))
        throw new Exception(string.Format("failure/height:{0}", _HeightString));
    webView.Height = _ContentHeight;

    // create brush
    var _OriginalVisibilty = webView.Visibility;
    webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
    var _Brush = new WebViewBrush
    {
        SourceName = webView.Name,
        Stretch = Stretch.Uniform
    };
    _Brush.Redraw();

    // reset, return
    webView.Width = _OriginalWidth;
    webView.Height = _OriginalHeight;
    webView.Visibility = _OriginalVisibilty;
    return _Brush;
}

IEnumerable<FrameworkElement> GetWebPages(WebView webView, Windows.Foundation.Size page)
{
    // ask the content its width
    var _WidthString = webView.InvokeScript("eval",
        new[] { "document.body.scrollWidth.toString()" });
    int _ContentWidth;
    if (!int.TryParse(_WidthString, out _ContentWidth))
        throw new Exception(string.Format("failure/width:{0}", _WidthString));
    webView.Width = _ContentWidth;

    // ask the content its height
    var _HeightString = webView.InvokeScript("eval",
        new[] { "document.body.scrollHeight.toString()" });
    int _ContentHeight;
    if (!int.TryParse(_HeightString, out _ContentHeight))
        throw new Exception(string.Format("failure/height:{0}", _HeightString));
    webView.Height = _ContentHeight;

    // how many pages will there be?
    var _Scale = page.Width / _ContentWidth;
    var _ScaledHeight = (_ContentHeight * _Scale);
    var _PageCount = (double)_ScaledHeight / page.Height;
    _PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);

    // create the pages
    var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
    for (int i = 0; i < (int)_PageCount; i++)
    {
        var _TranslateY = -page.Height * i;
        var _Page = new Windows.UI.Xaml.Shapes.Rectangle
        {
            Height = page.Height,
            Width = page.Width,
            Margin = new Thickness(5),
            Tag = new TranslateTransform { Y = _TranslateY },
        };
        _Page.Loaded += (s, e) =>
        {
            var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
            var _Brush = GetWebViewBrush(webView);
            _Brush.Stretch = Stretch.UniformToFill;
            _Brush.AlignmentY = AlignmentY.Top;
            _Brush.Transform = _Rectangle.Tag as TranslateTransform;
            _Rectangle.Fill = _Brush;
        };
        _Pages.Add(_Page);
    }
    return _Pages;
}

My only change is to remove the Source attribute from the webview and add this line to the MainPage() method
var html = await Windows.Storage.PathIO.ReadTextAsync("ms-appx:///Assets/sherlock.html");
MyWebView.NavigateToString(html);

Sherlock.html is a excerpt from the Arthur Conan Doyle story, The Red-Headed League, the full code of this HTML page is here - note that a segment near the end repeats several times. This was done in testing, I'll explain below
This sample initially worked for me, on a small file. (Sherlock.html without the padded chapters)
However when I get above a certain file-size (usually around 4000 words+) the following behaviour occurs with the sample.
The WebView shrinks to a very narrow view
(see update notes on why this is struck out)
and then the screen goes gray. (I feel a little silly posting a screenshot of a gray screen, but I'm trying to be thorough here)

The app does NOT crash. No debugging messages appear, no exceptions occur. It is as if the Grid is simply removed. . It's not the splash screen (which I've set blue) and it's not the app background (darker gray). It's as if something else is loaded over the top of the page.
I've tried adjusting every part of the code, but I can't seem to isolate what causes the issue. Furthermore, parts of this code just confuse the hell out of me. For instance, in the Load_Completed Method
MyWebViewRectangle.Fill = GetWebViewBrush(MyWebView);
MyPrintPages.ItemsSource = GetWebPages(MyWebView, new Windows.Foundation.Size(100d, 150d));
MyWebView.Visibility = Windows.UI.Xaml.Visibility.Visible;

Line1: MyWebViewRectangle is filled with a shot of the WebView. Why? This control is never referenced again. I guess it could be for the user to get a clearer view of the page, but it seems to serve no programmatic purpose
Line3: MyWebView.Visibility is set to Visible This happens again later, in GetWebViewBrush.
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
// and a few lines later...
webView.Visibility = _OriginalVisibilty;

As far as I can tell, the webview is never Collapsed, yet it is set to Visible three times.
If anyone can explain any of this to me (maybe even JerryNixon himself?) I would really appreciate it. I've spent several months working on an app and this is the last piece of the puzzle. I can't launch without the ability to print!
UPDATE
Made some discoveries this morning. I had been setting the width of the WebView in XAML. Without this even the smallest files were failing. Based on this discovery I set the width in the html file itself to 800px, and it worked. Hooray, problem solved, right? Unfortunately, no. I tried with a longer file again (the full version of The Red-headed league, here) and the same issue is happening again. It's now gotten a lot weirder.
I inserted a breakpoint at webView.Height = _ContentHeight; in the GetWebPages method. This shows me that _ContentHeight is exactly "13241".
However, inserting a breakpoint makes the code work. Once I hit the break and continue, it all seems to load. Although oddly again, the WebView is invisible until I mouseover the scrollbar.
If I remove the breakpoint, I get the grey screen again.
If I manually set _ContentHeight to 13230, the page loads. This seems to be the magic number. Anything higher than this and the page fails. However, if I change the width of the html to less than 800px, it also fails. So logically, there's some kind of magic ratio of 800:13230 pixels (or 1:16.5375). If I go over this ratio, I set off the gray screen of death. I can disable the Red rectangle and restrict GetWebPages to 3 pages, and the gray screen is still there. That tells me that the issue is with the WebView itself
An issue that goes away if I set a breakpoint.
Also note the extra whitespace in MyWebViewRectangle and extra blank pages in MyPrintPages when it does work:

Note: I've also added NateDiamond's suggestions of the events LongRunningScriptDetected, UnsafeContentWarningDisplaying, and UnviewableContentIdentified
Here's the complete source of my sample project:
https://onedrive.live.com/redir?resid=EE99EF9560A6740E!110509&authkey=!ACrZgm6uq5k5yck&ithint=file%2czip
UPDATE 2
Some success.
I put some headers into my sample file (found the "bottom" of each computed page by trial and error) and upped the page size so I could see the markers. Although there are 9 pages, only 5 and a small part of 6 are rendered. 9 Page objects are created by GetWebPages, but only 5ish have rendered HTML content. The rest are empty

(Note, I changed the background colors as the red on blue was giving me a migraine)
I've gone through the code and made some modifications, and now I no longer get the gray screen at all. However, about 2 out of every 3 times I run it, only the first page is rendered, and it is cropped. This seems to be totally random. When 9 pages are rendered not all have content, as stated.
Here are my changes:
added new method Resize_WebView()
public void ResizeWebView()
{
    OriginalHeight = MyWebView.Height;

    var _WidthString = MyWebView.InvokeScript("eval", new[] { "document.body.scrollWidth.toString()" });
    int _ContentWidth;
    if (!int.TryParse(_WidthString, out _ContentWidth))
        throw new Exception(string.Format("failure/width:{0}", _WidthString));
    MyWebView.Width = _ContentWidth;

    // ask the content its height
    var _HeightString = MyWebView.InvokeScript("eval", new[] { "document.body.scrollHeight.toString()" });
    int _ContentHeight;
    if (!int.TryParse(_HeightString, out _ContentHeight))
        throw new Exception(string.Format("failure/height:{0}", _HeightString));
    MyWebView.Height = _ContentHeight;
}

in MyWebView_LoadCompleted commented out the rectangle fill, added call to ResizeWebView():
void MyWebView_LoadCompleted(object sender, NavigationEventArgs e)
{
    ResizeWebView();

    //MyWebViewRectangle.Fill = GetWebViewBrush(MyWebView);
    MyPrintPages.ItemsSource = GetWebPages(MyWebView, new Windows.Foundation.Size(300d, 450d));
}

in GetMyWebPages changed where the brush is loaded:
IEnumerable<FrameworkElement> GetWebPages(WebView webView, Windows.Foundation.Size page)
{
    // ask the content its width
    /*var _WidthString = webView.InvokeScript("eval",
        new[] { "document.body.scrollWidth.toString()" });
    int _ContentWidth;
    if (!int.TryParse(_WidthString, out _ContentWidth))
        throw new Exception(string.Format("failure/width:{0}", _WidthString));
    webView.Width = _ContentWidth;

    // ask the content its height
    var _HeightString = webView.InvokeScript("eval",
        new[] { "document.body.scrollHeight.toString()" });
    int _ContentHeight;
    if (!int.TryParse(_HeightString, out _ContentHeight))
        throw new Exception(string.Format("failure/height:{0}", _HeightString));
    webView.Height = _ContentHeight;

    // Manually set _ContentHeight: comment out the above block and uncomment this to test.
    // int _ContentHeight = 13230;
    // webView.Height = _ContentHeight;*/

    // how many pages will there be?
    //var _Scale = page.Width / _ContentWidth;
    var _Scale = page.Width / webView.Width; // now sourced directly from webview
    //var _ScaledHeight = (_ContentHeight * _Scale);
    var _ScaledHeight = (webView.Height * _Scale); // now sourced directly from webview
    var _PageCount = (double)_ScaledHeight / page.Height;
    _PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);

    // create the pages
    var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
    for (int i = 0; i < (int)_PageCount; i++)
    {
        var _TranslateY = -page.Height * i;
        var _Page = new Windows.UI.Xaml.Shapes.Rectangle
        {
            Height = page.Height,
            Width = page.Width,
            Margin = new Thickness(5),
            Tag = new TranslateTransform { Y = _TranslateY },
        };
        var _Brush = GetWebViewBrush(webView);
        _Brush.Stretch = Stretch.UniformToFill;
        _Brush.AlignmentY = AlignmentY.Top;
        _Brush.Transform = _Page.Tag as TranslateTransform;
        _Page.Fill = _Brush;
        /*_Page.Loaded += async (s, e) =>
        {
            var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
            var _Brush = await GetMyWebViewBrush(webView);
            _Brush.Stretch = Stretch.UniformToFill;
            _Brush.AlignmentY = AlignmentY.Top;
            _Brush.Transform = _Rectangle.Tag as TranslateTransform;
            _Rectangle.Fill = _Brush;
        };*/
        _Pages.Add(_Page);
    }
    return _Pages;
}

removed now unnecessary resize code from GetWebView
WebViewBrush GetWebViewBrush(WebView webView)
{
    /*// resize width to content
    var _OriginalWidth = webView.Width;
    var _WidthString = webView.InvokeScript("eval",
        new[] { "document.body.scrollWidth.toString()" });
    int _ContentWidth;
    if (!int.TryParse(_WidthString, out _ContentWidth))
        throw new Exception(string.Format("failure/width:{0}", _WidthString));
    webView.Width = _ContentWidth;

    // resize height to content
    var _OriginalHeight = webView.Height;
    var _HeightString = webView.InvokeScript("eval",
        new[] { "document.body.scrollHeight.toString()" });
    int _ContentHeight;
    if (!int.TryParse(_HeightString, out _ContentHeight))
        throw new Exception(string.Format("failure/height:{0}", _HeightString));
    webView.Height = _ContentHeight;

    // create brush
    var _OriginalVisibilty = webView.Visibility;
    webView.Visibility = Windows.UI.Xaml.Visibility.Visible;*/
    var _Brush = new WebViewBrush
    {
        SourceName = webView.Name,
        Stretch = Stretch.Uniform
    };
    _Brush.Redraw();

    // reset, return
    /*webView.Width = _OriginalWidth;
    webView.Height = _OriginalHeight;
    webView.Visibility = _OriginalVisibilty;*/
    return _Brush;
}

This is becoming a seriously epic question.
TL;DR;
Here is the updated project.
https://onedrive.live.com/redir?resid=EE99EF9560A6740E!110545&authkey=!AMcnB_0xKRhYHIc&ithint=file%2czip
Load and observe. there are 9 pages in the document.

*

*GetWebPages occasionally loads only one page, cropped

*the rest of the time, GetWebPages loads pages 1-5, part of 6 and 3 blank pages

This is pretty much all you need to know to answer this question.
I've put a bounty on this question. I'm looking for resolution of this issue, and if possible a way to add padding to each page so that the text does not run to the edges.

A: [Update]
The fact that it is cutting off at the exact same place with this new code is extremely strange. This would indicate that the data doesn't exist in the WebViewBrush. If you render the entire brush to a control does it render everything? If my theory is correct you should only see up to the page 6 cutoff. This is starting to smell like a video driver bug on the Surface pro. The Surface pro uses the Intel video chipset and uses shared i.e. system memory. You should have plenty to render a single instance of the brush (all nine pages). Keep in mind that even on better hardware this approach is still going to likely cause resource problems at large page counts.
If you have a chance can you please try side loading it on another machine with a video card from a different manufacturer to confirm that it does indeed work? I'm going to try to dig up a Surface Pro 1 and see if I can reproduce your findings.
I need to warn you about the known resource pitfalls of XAML printing before you head down that road. The XAML printing subsystem requires that you pass ALL of the pages to it before it will render. It then sends the document as a whole to the printer. This requires that every page be cached as XAML and then every page gets rendered as a bitmap. This all happens in main memory. You likely can get away with twenty pages or so but you will quickly run out of system resources once you get past that. Fifty to a hundred pages will likely cause the runtime to shut you down due to memory pressure. You will get even fewer pages on low resource devices.
Initially I thought your goal was to print HTML pages. The solution below is perfect for that. However, if your ultimate goal is to allow your users to print large documents from your app the real answer (and only solution for Windows Store apps) is to use Direct2D and DirectWrite. These technologies allow you to "stream" the pages to the printer cache. The printer cache is backed by disk and doesn't cause the same memory pressure problems (although you can still theoretically run out of disk space). Needless to say this is the ideal solution but does require a lot of expertise. You need to know something about C++ / CX as well as Direct2D to really be able to paginate the pages correctly.
Direct2Dapp printing sample
I hope this helps,
James

I took a close look at this today and I think that you are running into is resource limitations. I am not able to reproduce the issue on my workstation class machine and my colleague was not able to reproduce the problem on his workstation class laptop. What I see in your code is that you are creating a new brush for every page. Even though you are transforming the brush the entire WebView is getting transformed into a bitmap, a very big bitmap, for every page. This puts resource constraints on the XAML rich compositor. Since the compositor is D3D based you are likely running out of texture memory on your video card.
I think I have a solution for you. I'm not going to lie it is ugly but its working for me and I hope that it will work for you. Basically I'm rendering the page section via the brush to a hidden rectangle declared in the XAML. I then use RenderTargetBitmap to render the hidden rectangle. This has the effect of only rendering the portion of WebView that we need. Then I'm setting the RenderTargetBitmap as the source to an Image. I add the Images to the pages collection. The pages collection is set to your ItemsControl and and bob's your uncle.
The bulk of the changes are in GetWebPages:
async Task<bool> GetWebPages(WebView webView, Windows.Foundation.Size page)
{
    // how many pages will there be?
    var _Scale = page.Width / webView.Width; // now sourced directly from webview
    var _ScaledHeight = (webView.Height * _Scale); // now sourced directly from webview
    var _PageCount = (double)_ScaledHeight / page.Height;
    _PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);

    var _Brush = GetWebViewBrush(webView);

    for (int i = 0; i < (int)_PageCount; i++)
    {
        var _TranslateY = -page.Height * i;
        // You can probably optimize this bit
        _RenderSource.Height = page.Height;
        _RenderSource.Width = page.Width;
        Margin = new Thickness(5);

        _Brush.Stretch = Stretch.UniformToFill;
        _Brush.AlignmentY = AlignmentY.Top;
        _Brush.Transform = new TranslateTransform { Y = _TranslateY };
        _RenderSource.Fill = _Brush;

        RenderTargetBitmap rtb = new RenderTargetBitmap();

        await rtb.RenderAsync(_RenderSource);

        var _iPge = new Image
        {
            Source = rtb,
            Margin = new Thickness(10)
        };

        _Pages.Add(_iPge);
    }
    return true;
}

The entire modified project can be found here: http://1drv.ms/1y91iv7
Please give it a try and let me know if it works for you.
PS There are some layout issues and pagenation issues that I didn't try to fix.
I hope this helps,
James

A: Not a solution, but since I'm struggling with UWP printing myself, I'd thought I share my findings:
(1) Gray screen:
You use WebViewBrush.Redraw() to capture a "page" of your WebView. However, Redraw() happens asynchronously. Unfortunately we can't use await to wait for the WebViewBrush to capture the WebView.
I suspect you are processing the next page, but WebViewBrush has not yet captured the previous page. That would explain why it works when you add a breakpoint.
(2) Size limitation of WebViewBrush:
I'm seeing something similar For me, WebVewBrush stops working if my WebView is higher than 8000px. I assume it also depends on the width of the view and hence the total number of pixels.
My attempt here: resize the WebView to the page size and scroll from page to page using JavaScript. But this does not solve the gray page problem above.
(3) Memory constraints
Yes, that's a problem. I tried simply using a separate WebView for each page, but the app runs out of memory after 240 pages.
However, I was able to use 500 "plain" pages rendered as Rectangle.
I also tried to load and print a 500 page PDF with MS Edge and this works, so it is possible to print large documents.
For reference, here's my own question (I'll post an update should I ever find a solution):
How to wait for WebViewBrush.Redraw() to finish (UWP printing)?


text:
Q: Installing MOLUSCE 3.0.13 plugin for QGIS 2.18.0 on windows7? (Error This plugin is broken 13) I am trying to install MOLUSCE 3.0.13 plugin on a QGIS 2.18.0 but every time i try i get an error message saying:
The plugin is broken.
13
There is a screenshot so, does anyone have a solution?


text:
Q: Is it possible to call HttpListener.GetContext with a timeout? According to the HttpListener reference, a call to HttpListener.GetContext will block until it gets a HTTP request from a client.
I wonder if I can specify a timeout so that after the timeout the function will return. I think otherwise it's unreasonable, since you cannot garantee there will be a request to make this function return, then how can one terminate this call?
P.S. I know there is a async version of it (BeginGetContext) BUT the problem remains because the corresponding EndGetContext will block until an HTTP request arrives.
So as a result, there will be always one thread (if you do it multi-threaded) cannot return because it's blocked on waiting for a request.
Am I missing anything?
UPDATE:
I found this link to be useful. I also found that calling HttpListener.Close() actually terminates the waiting threads that created by the BeginGetContext()s. Somehow HttpListener.Close() fires the callbacks that BeginGetContext() registered. So before you do a HttpListener.EndGetContext(), do check if HttpListener has stopped.

A: Also if you want to do line by line in process handling waiting for a limited time the BeginGetContext returns a System.IAsyncResult exposing the AsyncWaitHandle property
var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
context.AsyncWaitHandle.WaitOne();

Above blocks the thread until the listener receives something valid as defined by the heders assigned to the listener or terminates due to some exception that terminates the listener thread and returns result back to ListenerCallback.
But the AsyncWaitHandle.WaitOne() can take timeout parameters
// 5 seconds timeout
bool success = context.AsyncWaitHandle.WaitOne(5000, true);

if (success == false)
{
    throw new Exception("Timeout waiting for http request.");
}

The ListenerCallback could contain a call to listener.EndGetContext or just call the listener.EndGetContext in line if no timeout or error indicated by the AsyncWaitHandle
public static void ListenerCallback(IAsyncResult result)
{
    HttpListener listener = (HttpListener) result.AsyncState;
    // Use EndGetContext to complete the asynchronous operation.
    HttpListenerContext context = listener.EndGetContext(result);
    HttpListenerRequest request = context.Request;
    // Get response object.
    HttpListenerResponse response = context.Response;
    // Construct a response.
    string responseString = " It Works!";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    // Write to response stream.
    response.ContentLength64 = buffer.Length;
    System.IO.Stream output = response.OutputStream;
    output.Write(buffer,0,buffer.Length);
    // Close the output stream.
    output.Close();
}

Not to forget to tell the listener to listen again using listener.BeginGetContext

A: The callback that invokes EndGetContext should never be called unless an HTTP request has already arrived, or the listener has failed (in which case EndGetContext will throw an exception).  Thus, it will not block if used properly.
BeginGetContext and EndGetContext--that is, asynchronous operations--are what you want.
Begin and End methods work such that Begin says "signal me when X is ready," and End says "give me that X about which you just signaled me."  Naturally, the latter will block in theory, but will return instantaneously.


text:
Q: Flexbox and the , , and  tags I've read in a few places that when using flexbox, you should have all content in a ,  and  tag for flexbox to work its magic. Is this true? Are these tags needed?

A: No. See the abstract of the spec:

The specification describes a CSS box model optimized for user
  interface design. In the flex layout model, the children of a flex
  container can be laid out in any direction, and can "flex" their
  sizes, either growing to fill unused space or shrinking to avoid
  overflowing the parent. Both horizontal and vertical alignment of the
  children can be easily manipulated. Nesting of these boxes (horizontal
  inside vertical, or vertical inside horizontal) can be used to build
  layouts in two dimensions.
CSS is a language for describing the rendering of structured documents
  (such as HTML and XML) on screen, on paper, in speech, etc.

Flexbox is part of CSS, which is a language independent of HTML. So saying it requires some HTML elements makes no sense.
Here you have a working example which doesn't use those elements:

div { display: flex; }
span { border: 1px solid; }
span:nth-child(1) { flex-grow: 1; }
span:nth-child(2) { flex-grow: 2; }
span:nth-child(3) { flex-grow: 3; }

  A
  B
  C


text:
Q: bitpack ascii string into 7-bit binary blob using SIMD Related: bitpack ascii string into 7-bit binary blob using ARM-v8 Neon SIMD - same question specialized for AArch64 intrinsics.  This question covers portable C and x86-64 intrinsics.

I would like to encode a char string as a 7-bit blob to gain a 12.5% reduction in memory.
I want to do it as fast a possible, i.e. with minimal latency when encoding large strings.
Here is the plain implementation of the algo:
void ascii_pack(const char* ascii, size_t len, uint8_t* bin) {
  uint64_t val;
  const char* end = ascii + len;

  while (ascii + 8 <= end) {
    memcpy(&val, ascii, 8);
    uint64_t dest = (val & 0xFF);

    // Compiler will perform loop unrolling
    for (unsigned i = 1; i <= 7; ++i) {
      val >>= 1;
      dest |= (val & (0x7FUL << 7 * i));
    }
    memcpy(bin, &dest, 7);
    bin += 7;
    ascii += 8;
  }

  // epilog - we do not pack since we have less than 8 bytes.
  while (ascii < end) {
    *bin++ = *ascii++;
  }
}

now, I would like to speed it up with SIMD. I came with SSE2 algo below.
My question:

*

*is it possible to optimize the internal loop that is sequential?

*will it improve the throughput when running on large strings?

// The algo - do in parallel what ascii_pack does on two uint64_t integers
void ascii_pack_simd(const char* ascii, size_t len, uint8_t* bin) {
  __m128i val;

  __m128i mask = _mm_set1_epi64x(0x7FU);  // two uint64_t masks

  // I leave out 16 bytes in addition to 16 that we load in the loop
  // because we store into "bin" full 16 bytes instead of 14. To prevent out of bound
  // writes we finish one iteration earlier.
  const char* end = ascii + len - 32;
  while (ascii <= end) {
    val = _mm_loadu_si128(reinterpret_cast<const __m128i*>(ascii));
    __m128i dest = _mm_and_si128(val, mask);

    // Compiler unrolls it
    for (unsigned i = 1; i <= 7; ++i) {
      val = _mm_srli_epi64(val, 1);                          // shift right both integers
      __m128i shmask = _mm_slli_epi64(mask, 7 * i);    // mask both
      dest = _mm_or_si128(dest, _mm_and_si128(val, shmask));  // add another 7bit part.
    }

    // dest contains two 7 byte blobs. Lets copy them to bin.
    _mm_storeu_si128(reinterpret_cast<__m128i*>(bin), dest);
    memmove(bin + 7, bin + 8, 7);
    bin += 14;
    ascii += 16;
  }

  end += 32;  // Bring back end.
  DCHECK(ascii < end);
  ascii_pack(ascii, end - ascii, bin);
}

A: The scalar trick (without requiring PEXT) which I referred to in the comments could be implemented like this:
uint64_t compress8x7bit(uint64_t x)
{
    x = ((x & 0x7F007F007F007F00) >> 1) | (x & 0x007F007F007F007F);
    x = ((x & 0x3FFF00003FFF0000) >> 2) | (x & 0x00003FFF00003FFF);
    x = ((x & 0x0FFFFFFF00000000) >> 4) | (x & 0x000000000FFFFFFF);
    return x;
}

The idea here is to concatenate together adjacent pairs, first concatenate 7-bit elements into 14-bit elements, then concatenate them into 28-bit elements, and finally concatenate them into one 56-bit chunk (which is the result).
With SSSE3, you could use pshufb to concatenate two of those 56-bit parts (before storing them) too.
SSE2 (and AVX2) can do the same thing as that scalar code with 64-bit elements, but this approach does not take advantage of any techniques that may be possible with special operations (which SSE2+ has plenty of, more with every version), there are probably better things to do than just implementing the scalar trick in SIMD.
For example just to throw something wild out there, gf2p8affineqb(0x8040201008040201, x) would put all the "discarded" bits in one place (namely the top byte of the result) and makes a solid 56-bit chunk out of the bits that we want to keep. But the bits do end up in a strange order (the first byte would contain bits 56, 48, 40, 32, 24, 16, 8, 0, in that order, listing the least significant bit first).
That order, strange as it is, can be easily unpacked using pshufb to reverse the bytes (you can also use this to insert the two zeroes) and then gf2p8affineqb(0x0102040810204080, reversedBytes) shuffles the bits back into the original order.
Here's a sketch of how that could work with actual AVX2+GFNI intrinsics. I'm not bothering to handle the extra parts at the end here, just the "main" loop, so the input text had better be a multiple of 32 bytes. Works on my PC ✔
void compress8x7bit(const char* ascii, size_t len, uint8_t* bin)
{
    const char* end = ascii + len;
    while (ascii + 31 < end) {
        __m256i text = _mm256_loadu_si256((__m256i*)ascii);
        __m256i transposed = _mm256_gf2p8affine_epi64_epi8(_mm256_set1_epi64x(0x8040201008040201), text, 0);
        __m256i compressed = _mm256_shuffle_epi8(transposed,
            _mm256_set_epi8(-1, -1, 14, 13, 12, 11, 10, 9, 8, 6, 5, 4, 3, 2, 1, 0,
                            -1, -1, 14, 13, 12, 11, 10, 9, 8, 6, 5, 4, 3, 2, 1, 0));
        _mm_storeu_si128((__m128i*)bin, _mm256_castsi256_si128(compressed));
        _mm_storeu_si128((__m128i*)(bin + 14), _mm256_extracti128_si256(compressed, 1));
        bin += 28;
        ascii += 32;
    }
}

void uncompress8x7bit(char* ascii, size_t len, const uint8_t* bin)
{
    const char* end = ascii + len;
    while (ascii + 31 < end) {
        __m256i raw = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_loadu_si128((__m128i*)bin)), _mm_loadu_si128((__m128i*)(bin + 14)), 1);
        __m256i rev_with_zeroes = _mm256_shuffle_epi8(raw,
            _mm256_set_epi8(7, 8, 9, 10, 11, 12, 13, -1, 0, 1, 2, 3, 4, 5, 6, -1,
                            7, 8, 9, 10, 11, 12, 13, -1, 0, 1, 2, 3, 4, 5, 6, -1));
        __m256i decompressed = _mm256_gf2p8affine_epi64_epi8(_mm256_set1_epi64x(0x0102040810204080), rev_with_zeroes, 0);
        _mm256_storeu_si256((__m256i*)ascii, decompressed);
        bin += 28;
        ascii += 32;
    }
}

Perhaps there is a nicer solution than using two 128-bit stores in the compressor and two 128-bit loads in the uncompressor. With AVX512 that would be easy since it has full-register byte-granular permutes, but AVX2 has vpshufb, which is not able to move bytes between the two 128-bit halves that make up a 256-bit vector. The uncompressor could do a funny load that starts 2 bytes before the start of the data it wants, like this: _mm256_loadu_si256((__m256i*)(bin - 2)) (and a slightly different shuffle vector), at the cost of having to avoid a potential out-of-bounds error with either padding or a special first iteration, but the compressor cannot (not cheaply) use a trick like that with a store that start 2 bytes earlier (that would destroy two bytes of the result).
By the way I have some test code here that you can use to verify that your bit-compression functions do the right thing (well sort of - as long as the function is a bit-permutation where some of the bits may be zeroed this works as a check, but this would not detect every possible bug in general):
uint64_t bitindex[7];
bitindex[6] = compress8x7bit(0xFFFFFFFFFFFFFFFF);
bitindex[5] = compress8x7bit(0xFFFFFFFF00000000);
bitindex[4] = compress8x7bit(0xFFFF0000FFFF0000);
bitindex[3] = compress8x7bit(0xFF00FF00FF00FF00);
bitindex[2] = compress8x7bit(0xF0F0F0F0F0F0F0F0);
bitindex[1] = compress8x7bit(0xCCCCCCCCCCCCCCCC);
bitindex[0] = compress8x7bit(0xAAAAAAAAAAAAAAAA);

for (size_t i = 0; i < 64; i++)
{
    if (i != 0)
        std::cout << ", ";
    if (bitindex[6] & (1uLL << i))
    {
        int index = 0;
        for (size_t j = 0; j < 6; j++)
        {
            if (bitindex[j] & (1uLL << i))
                index |= 1 << j;
        }
        std::cout << index;
    }
    else
        std::cout << "_";
}
std::cout << "\n";

A: You can improve the solution by @harold, if you replace the first two mask and shift steps by a vpmaddubsw and vpmaddwd (each using 1 instead of 4 uops) and the next step can be replaced by shifting every other 32bit element 4 to the left and afterwords shifting all 64bit elements 4 to the right. Of course, by using AVX2 instead of SSE, you can again double the throughput.
The final step of joining the lower and upper lane is likely most efficiently done by two separate stores which extract each lane directly to memory.
void ascii_pack32(char const* ascii, char* bin)
{
    const __m256i control = _mm256_set_epi8(-1, -1, 14, 13, 12, 11, 10, 9, 8, 6, 5, 4, 3, 2, 1, 0,
                                            -1, -1, 14, 13, 12, 11, 10, 9, 8, 6, 5, 4, 3, 2, 1, 0);

    __m256i input = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(ascii));

    // only necessary if high bits of input might be set:
    input = _mm256_and_si256(input, _mm256_set1_epi8(0x7f));

    __m256i t1 = _mm256_maddubs_epi16(_mm256_set1_epi16(0x8001), input);
    __m256i t2 = _mm256_madd_epi16(_mm256_set1_epi32(0x40000001), t1);
    __m256i t3 = _mm256_srli_epi64(_mm256_sllv_epi32(t2, _mm256_set1_epi64x(4)), 4);

    __m256i val = _mm256_shuffle_epi8(t3, control);
    _mm_storeu_si128(reinterpret_cast<__m128i*>(bin), _mm256_castsi256_si128(val));
    _mm_storeu_si128(reinterpret_cast<__m128i*>(bin+14), _mm256_extracti128_si256(val, 1));
}

Godbolt link with short testcode:
https://godbolt.org/z/hs7477h5W

A: SIMD unpack can benefit from blend instructions instead of and/andn/or because we can blend at dword / word / byte boundaries.  We only need to AND once at the end to clear the high bit of each byte.
#include <immintrin.h>

static inline
__m128i ascii_unpack7x8_sse4(__m128i v)
{
   __m128i separate_7B_halves = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, -1,
                                              7, 8, 9,10,11,12,13, -1);
   v = _mm_shuffle_epi8(v, separate_7B_halves);

   // separate each u64 qword into 2 u32 halves, with the good bits at the bottom
    __m128i shifted = _mm_slli_epi64(v, 4);
#ifdef __AVX2__
    v = _mm_blend_epi32(v, shifted, 0b1010);  // vpblendd is very efficient, 1 uop any port
#else
    v = _mm_castps_si128(_mm_blend_ps(        // blendps has extra bypass latency between integer insns, but is single-uop
               _mm_castsi128_ps(v), _mm_castsi128_ps(shifted), 0b1010) );
#endif

    // Separate each u32 into u16
    shifted = _mm_slli_epi32(v, 2);
    v = _mm_blend_epi16(v, shifted, 0b10101010);  // high halves of pairs from shifted

    // Separate each u16 into bytes, with one of two strategies
#if 0  // this strategy is simpler but worse
  //  shifted = _mm_add_epi16(v, v);  // v<<1
  //  v = _mm_blendv_epi8(v, shifted, _mm_set1_epi16(0xff00));
  //  v = _mm_and_si128(v, _mm_set1_epi8(0x7f));  // clear garbage from high bits
#else
    __m128i hi = _mm_and_si128(v, _mm_set1_epi16(0x3f80)); // isolate hi half
    v = _mm_and_si128(v, _mm_set1_epi16(0x007f));  // clear high garbage
    v = _mm_add_epi16(v, hi);        // high halves left 1 (x+=x), low halves stay (x+=0)

   // both ways need two vector constants and 3 instructions, but pblendvb can be slower and has an awkward requirement of having the control vector in XMM0
#endif

    return v;
}

With AVX2 available, clang compiles it to this nice asm.  Godbolt
# clang -O3 -march=x86-64-v3  (implies AVX2+BMI2, basically Haswell with generic tuning)
ascii_unpack7x8_sse4(long long __vector(2)):
        vpshufb xmm0, xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0,1,2,3,4,5,6],zero,xmm0[7,8,9,10,11,12,13],zero
        vpsllq  xmm1, xmm0, 4
        vpblendd        xmm0, xmm0, xmm1, 10            # xmm0 = xmm0[0],xmm1[1],xmm0[2],xmm1[3]
        vpslld  xmm1, xmm0, 2
        vpblendw        xmm0, xmm0, xmm1, 170           # xmm0 = xmm0[0],xmm1[1],xmm0[2],xmm1[3],xmm0[4],xmm1[5],xmm0[6],xmm1[7]
        vpand   xmm1, xmm0, xmmword ptr [rip + .LCPI0_1]       # in a loop, these constants would be in registers
        vpand   xmm0, xmm0, xmmword ptr [rip + .LCPI0_2]
        vpaddw  xmm0, xmm0, xmm1
        ret

With just SSE4.1, compilers need several movdqa instructions, as in GCC's output.  And out-of-order exec will have an extra 1 or 2 cycles of latency to hide because of bypass-forwarding delays for integer shifts forwarding to an FP blendps, on Intel CPUs.  (https://agner.org/optimize/).  But that's fine, we're doing this in a loop over an array, modern CPUs have deep enough out-of-order exec.
# gcc -O3 -march=x86-64-v2   # SSE4.2, Nehalem.  Actually only using SSE4.1
ascii_unpack7x8_sse4(long long __vector(2)):
        movdqa  xmm1, xmm0               # silly compiler wastes a MOV
        pshufb  xmm1, XMMWORD PTR .LC0[rip]
        movdqa  xmm0, xmm1               # save unshifted v
        psllq   xmm0, 4
        blendps xmm1, xmm0, 10           # 0b1010 = 0xA
        movdqa  xmm0, xmm1
        pslld   xmm0, 2
        pblendw xmm1, xmm0, 170          # 0b10101010 = 0xAA
        movdqa  xmm0, XMMWORD PTR .LC1[rip] # after inlining, probably a reg-copy
        pand    xmm0, xmm1                  # and two PAND xmm,xmm
        pand    xmm1, XMMWORD PTR .LC2[rip]
        paddw   xmm0, xmm1
        ret

If AVX2 is available, an __m256i version of this is straightforward and wouldn't need the blendps fallback.  That may be better than scalar pdep (BMI2).  AVX2 vpsrlvd or q (per-element shift counts) seem like they should help, but we find ourselves needing to move bits across dword boundaries, and it can only be left or right, not alternating directions.  (AVX512 has variable-count rotates (32 and 64-bit), and 16-bit variable-count shifts.  Rotates let you go right or left with the same instruction.)
The shift element size could be 64 each time; our blends drop bits that would get shifted into the low element of a pair.  For the final step, paddw is 1 byte smaller than psllw/d/q because it has no immediate operand.  And can run on more ports on most CPUs.  Especially Haswell, where shifts can only run on port 0, but paddw can run on port 1 or 5.  (This code has no instruction-level parallelism within one iteration, so we rely on out-of-order exec to overlap execution of multiple iterations.)
Skylake through Alder Lake run SIMD shifts on p01, SIMD inter adds on p015, blendps on p015, pblendw on p5 (p15 for Alder Lake), pblendvb as 1 uop for p015.  (Only the non-AVX encoding; vpblendvb is 2 uops for p015).  Zen 3 for example has plenty of throughput for all of these.
The final step avoiding _mm_blendv_epi8 has several advantages:

*

*Both ways need two vector constants and 3 instructions.  (And no difference in the minimum number of movdqa register-copies a compiler has to invent without non-destructive AVX instructions.)

*The AND/AND/ADD version has better ILP; two ANDs in parallel.

*SSE4.1 pblendvb can be slower (e.g. Haswell runs it as 2 uops for port 5) and has an awkward requirement of having the control vector in XMM0. Some compilers may waste instructions with hard-reg constraints.  (Maybe even when inlining into a loop, unlike when we look at how this helper function would compile on its own.)

*vpblendvb (the AVX encoding of it) is 2 uops (for any port) on newer Intel, or 3 on Alder Lake, presumably as the price for having 4 operands (3 inputs and a separate output).  Also the AVX version is slow on Alder Lake E-cores (4 uops, 3.23 cycle throughput) https://uops.info/.
AMD CPUs don't have this problem; for example Zen 3 runs vpblendvb as 1 uop for either of two ports.

*The only possible upside to the blend version is that the constants are easier to construct on the fly.  GCC12 has started preferring to construct some constants on the fly when AVX is available, but does a rather bad job of it, using 10-byte mov r64, imm64 / vmovq / vpunpcklqdq instead of 5-byte mov reg, imm32 / ... / vpbroadcastd or pshufd v,v,0.  Or instead of starting with an all-ones vector and shifting.
Actually, the constants for the non-blend way can be generated from an all-ones vector with psrlw xmm, 9 to get 0x007f, and then left shifting that 7-bit mask left by 7.  So with AVX, 3 total instructions for both masks, without memory access.  Unfortunately compilers don't know how to do this optimization so it's a moot point.
AVX-512F / BW, without AVX-512VBMI / AVX-512GFNI
If you have Ice Lake / Zen4 features, you want @Harold's answer; as I commented there, it's slightly better than AVX-512 vpmultishiftqb (parallel bitfield-extract within a qword).
But if not, with Skylake-X / Cascade Lake features (AVX-512BW and F) you have have masking and variable-count rotates.  This saves 2 instructions vs. the SSE4 version (built with AVX2); it feels like there should be room to save more, especially at the final step within 16-bit elements. But masking has byte granularity, and there is no vprolvw, and still no byte shift, unlike AArch64 which can shift elements in 2 directions at byte granularity.
Splitting things apart and doing different things, then merging with a merge-masking vmovdqa could work, but I don't think would help.
#ifdef __AVX512BW__
// pre-Ice Lake, without AVX-512VBMI or AVX512-GFNI
__m128i ascii_unpack7x8_avx512bw(__m128i v)
{
    // for YMM or ZMM, use VPERMW, or VPERMB if we have AVX512VBMI since unfortunately VPERMW isn't single-uop on Intel CPUs that support both.
   __m128i separate_7B_halves = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, -1,
                                              7, 8, 9,10,11,12,13, -1);
   v = _mm_shuffle_epi8(v, separate_7B_halves);

    v = _mm_slli_epi64(v, 4);      // 00000HGFE | DCBA0000  // dword halves
    v = _mm_rolv_epi32(v, _mm_set_epi32(2, 32-2, 2, 32-2));
                                   // 00HG|FE00 | 00DC|BA00  // u16 chunks of a u64
    v = _mm_mask_srli_epi16(v, (__mmask8)0b0101'0101, v, 2); // 00HG | 00FE | 00DC | 00BA

    // Separate each u16 into bytes
    __m128i hi = _mm_and_si128(v, _mm_set1_epi16(0x3f80)); // isolate hi half
    v = _mm_add_epi16(v, hi);     // high halves left 1 (x+=x), low halves stay (x+=0)
    // 0H0G | 0F0E | 0D0C | 0B0A  in each qword.
    return v;
}
#endif

Clang (Godbolt) optimizes the masked right-shift to a variable-count right shift, which is a good idea for a stand-alone function not in a loop especially when we're loading other constants.
This uses more non-immediate constants, but fewer uops.  A wider version of this using vpermw to unpack 14-byte chunks to 16-byte lanes might have to do something to introduce zero bits where they're needed, perhaps using zero-masking on the shuffle.  But I think we'd still need vpshufb within lanes, so it can zero those high bits.
Having those known zeros that we move around with shifts and rotates is what lets us only use one and and add at the end, unlike the blending version where elements end up with high garbage so we need to mask both ways.
# clang -O3 -march=x86-64-v4
ascii_unpack7x8_avx512bw(long long __vector(2)):
        vpshufb xmm0, xmm0, xmmword ptr [rip + .LCPI1_0] # xmm0 = xmm0[0,1,2,3,4,5,6],zero,xmm0[7,8,9,10,11,12,13],zero
        vpsllq  xmm0, xmm0, 4
        vprolvd xmm0, xmm0, xmmword ptr [rip + .LCPI1_1]
        vpsrlvw xmm0, xmm0, xmmword ptr [rip + .LCPI1_2]
        vpand   xmm1, xmm0, xmmword ptr [rip + .LCPI1_3]
        vpaddw  xmm0, xmm1, xmm0
        ret

These constants would of course be loaded into registers.
Just 6 uops; shifts run on port 0 or 1, shuffles on port 5, on Skylake, with VPAND and VPADD able to run on any of the 3 vector ALU ports.  So it's a good balance, not running into back-end throughput bottlenecks on a specific port.  (vs. 8 uops with clang's AVX build of the SSE4 version)
GCC using masking as requested, again the constant init will get hoisted out of loops, including k1.
# gcc -O3 -march=x86-64-v4
ascii_unpack7x8_avx512bw(long long __vector(2)):
        vpshufb xmm0, xmm0, XMMWORD PTR .LC0[rip]
        mov     eax, 85                   # 0x55
        vpsllq  xmm0, xmm0, 4
        kmovb   k1, eax
        movabs  rax, 4575727041462157184  # 0x3F803F803F803F80  silly to use a 64-bit immediate
        vprolvd xmm0, xmm0, XMMWORD PTR .LC3[rip]
        vpbroadcastq    xmm1, rax
        vpsrlw  xmm0{k1}, xmm0, 2
        vpand   xmm1, xmm0, xmm1
        vpaddw  xmm0, xmm0, xmm1
        ret

Same instructions doing the work, just setting up constants differently.  (Except for vpsrlw  xmm0{k1}, xmm0, 2 to shift some elements but not others.)

A: Backporting my arm64 answer to SSE2, we can simulate variadic shifts by mullo_epu16 and mulhi_epu16; first pack adjacent 7+7-bit values as consecutive:
// 0b'0aaaaaaa'0bbbbbbb + 0bbbbbbb = 0b'0aaaaaaa'bbbbbbb0
a0 = _mm_add_epi16(a, _mm_and_epi16(a, _mm_set1_epi16(0x7f)));

a0 =    0aaaaaaabbbbbbb0'0cccccccddddddd0'0eeeeeeefffffff0'0ggggggghhhhhhh0
a1 =    00000000aaaaaaab'000000cccccccddd'0000eeeeeeefffff'00ggggggghhhhhhh
a2 =    bbbbbb0000000000'dddd000000000000'ff00000000000000'0000000000000000
a3 =    0000000000000000'bbbbbb0000000000'dddd000000000000'ff00000000000000

a1 = _mm_mulhi_epu16(a0, kShift);  // 1 << {9,11,13,15}
a2 = _mm_mullo_epu16(a0, kShift);  // 1 << {9,11,13,15}
a3 = _mm_bsrli_si128(a2, 2);
return _mm_or_si128(a1,a3);


text:
Q: How to use the DBTable macro in slick I can't find any documentation for the use of DBTable type macros.
I just want to do something like this:
object Coffees extends DBTable("jdbc:h2:tcp://localhost/~/coffeeShop","COFFEES")

but i can't get it run....
Can anyone help me with an example.
THX
nilo

A: They don't exist yet. There is a prototype on github. https://github.com/xeno-by/typemacros-h2db Further work on this topic recently started.


text:
Q: OriendDB apply edge multiple times in a match-query guys. The question is how to apply a relationship (edge) multiple times between two vertices. Remark: The path, of course, can go through other cities.
In Cypher I can use asteriks * to do this and the query would look like this one:
MATCH path=(start:City{name:'London'})-[has_train|travelling_to*1..4]->(end:City{name:'Berlin'})
RETURN path

So what about OrientDb? Should I use traverse() in this case? Thank you for your answers!


text:
Q: Sync users over NFS I'm implementing a web server with configuration and user files shared over NFS (Amazon EFS) as described here:  https://serverfault.com/a/933566/81774
As part of my Apache configuration, I am running websites under different user names using mod_mpm_itk. How can I sync user names between servers without having to bake new user names into the web server AMI.
I'm assuming I can't just move /etc/passwd to NFS, as the server then won't boot without having NFS mounted?
Update based on comments:
There doesn't seem to be a way to load additional files with nsswitch.conf, only to query additional services according to this answer: https://unix.stackexchange.com/a/210587
The downside of an additional service is to introduce additional points of failure.
Is it a feasible option to copy /etc/passwd from NFS when the server starts up and re-read it with pwck as described here https://unix.stackexchange.com/a/102336 ?

A: If you don't want to introduce extra points of failure, you have to create the users locally. This is actually a very decent idea.
While you could copy the passwd file, I would recommend a local ansible playbook or puppet standalone manifest which can create the users locally if they are missing. You can keep the playbook on NFS.

A: You could try using pam_extrausers. It uses a separate /etc/passwd style list of user accounts, which supplements the standard authentication regimes. The equivalent files are /var/lib/extrausers/passwd, /var/lib/extrausers/shadow, and /var/lib/extrausers/group.
It would be safer to synchonise this whenever one of its user accounts was updated, leaving /etc/passwd and associated files managed per server.
On Debian-derived systems the package name is libnss-extrausers.
Although this is a PAM module, the configuration is applied in /etc/nsswitch.conf:
passwd:         compat extrausers
group:          compat extrausers
shadow:         compat extrausers

To create entries in these files it seems best to create them on your primary system as local users (none of the standard utilities can manage the entries). Then copy those entries from the existing passwd, shadow and group files to the equivalent ones in /var/lib/extrausers. Remember to fix the permissions on shadow to match the system one.
grep -E '^(user1|user2|user3):' /etc/passwd >/var/lib/extrausers/passwd
grep -E '^(user1|user2|user3):' /etc/shadow >/var/lib/extrausers/shadow
grep -Ew '(user1|user2|user3)'  /etc/group >/var/lib/extrausers/group

chmod u=rw,go=r   /var/lib/extrausers/passwd /var/lib/extrausers/group
chown root:shadow /var/lib/extrausers/shadow
chmod u=rw,g=r,o= /var/lib/extrausers/shadow

ls -l /var/lib/extrausers
total 12
-rw-r--r--  1 root root     21 Apr 18 15:36 group
-rw-r--r--  1 root root     49 Apr 18 15:37 passwd
-rw-r-----  1 root shadow  123 Apr 18 15:37 shadow

You can copy the files around using whatever technique you prefer. I like rsync with root equivalence:
for rhost in remote1 remote2 remote3 ...
do
    rsync -avR /var/lib/extrausers/* "$rhost":/
done


text:
Q: Hibernate how to prevent duplicate entry with generated id Is there a way to prevent duplicate data entry with hibernate on entities that have auto generated primary key?
To be more specific, i have a persistent object in the database and have a transient object (not inserted to the database yet) and those two objects are same with respect to equals and hashcode  methods. But, since the id of the entity class of those objects is annotated with generated value annotation, hibernate still creates a new instance for the transient object in the database. As a result the database has duplicate entries (with respect to equals and hashcode methods) with different primary keys.
Yes, I know if I make the PK not auto generated, of if I use UUID, then i would achieve my goal. But I just wanna ask why equals and hashcode methods do not work for the entities with auto generated primary key? Or am i doing something wrong?

A:
why equals and hashcode methods do not work

Hibernate doesn't respect equals()/hashCode() here, because there are no efficient ways to do so.
How can Hibernate check that object with the same identity (in terms of equals()) already exists in the database? Since equals() can contain arbitrary conditions, Hibernate can't turn it into SQL query, so that the only way to check it is to load all objects into memory and call equals() on them to compare them with the object you are going to save.
Therefore Hibernate uses primary keys to define objects' identity.

Or am i doing something wrong?

It's not clear what are you going to achieve. If you want Hibernate to update objects in the database with the state of objects you pass in, you need to use merge().
See also:

*

*13.1.3. Considering object identity

A: You primary key at the database level should use the same fields you use to test for equality at the application level. If you really need a surrogate key (for performance reasons, perhaps?) enforce a "unique index" over those fields and let hibernate throw and exception.

A: Enforce the constraint at DB level. Without this it is hard(impossible?) to avoid duplicates especially if your app is clustered.


text:
Q: SQL Server trigger to check if column value was changed to insert I have around 25 tables that each have 3 triggers (insert, update, delete) to generate logs on user actions. All these tables get updated each time there is an edit in the UI, though their value is not changed in the UI.
In such case I can't just check for if a column is updated, I need to check if previous updated value is not the same as the newly updated value so then I can insert to my log table. Also, I need to insert all updated table values to log table as a string separated by comma.
Is there any efficient way how to handle this?
ALTER TRIGGER [dbo].[Activity_Update]
ON [dbo].[Activity]
AFTER UPDATE
AS
BEGIN
    DECLARE @Names VARCHAR(8000)
    SET @result = ' '

    DECLARE @id INT;
    SELECT @id = i.ID FROM inserted i;

    IF UPDATE(deptNotes)
    BEGIN
        DECLARE @OldValue NVARCHAR(MAX)

        SELECT TOP 1 @OldValue = deptNotes
        FROM Activity
        WHERE id = @id
        ORDER BY Timestamp DESC

        IF (@OldValue != (SELECT i.deptNotes FROM inserted i))
        BEGIN
            IF ((SELECT i.deptNotes FROM inserted i) != ' ')
               SELECT @result =  @result + ',' + 'Modified dept. Notes'
            ELSE
               SELECT @result =  @result + ',' + 'Removed dept. Notes'
        END
   END

   IF UPDATE(deptActivityID)
   BEGIN
       DECLARE @OldValue1 NVARCHAR(MAX)

       SELECT TOP 1 @OldValue1 = deptActivityID
       FROM Activity
       WHERE id = @id
       ORDER BY Timestamp DESC

       IF (@OldValue1 != (SELECT i.deptActivityID FROM inserted i))
       BEGIN
           SELECT @result =  @result + ',' + 'Changed dept. Activity  '
       END
    END

    IF UPDATE(SubmissionDate)
    BEGIN
    declare @OldValue2 nvarchar(max)
    select Top 1 @OldValue2 = submissiondate from [Activity] where id=@id Order by Timestamp DESC

     If (@OldValue2 != (select i.submissiondate from inserted i))
     BEGIN
     Select @result =  @result + ',' + 'Changed application date - ' + '"' + (select cast(i.submissiondate as nvarchar(500)) from inserted i)+ '"'
     END
     END

     INSERT [Activity]
     (
       [deptActivityID],
       [deptNotes],
       [SubmissionDate],
       [Username],
       [Operation],
       [Comment]
       )
       SELECT
       v.deptActivityID,
       v.deptNotes,
       v.SubmissionDate,
       v.[LastEditBy],
       'update',
       @result
       FROM inserted v
       END
       GO

A: You can use the deleted table to find out what was the old value and inserted for the new value. Also note that INSERT, UPDATE and DELETE may affect more than one rows, so you trigger should handled that.
below trigger code will gives you list of rows for any change in deptNotes.
select  'deptActivityID ' + d.deptActivityID +
        ' Changed from ' + d.deptNotes + ' to ' + i.deptNotes
from    deleted d
        inner join inserted i   on  d.deptActivityID    = i.deptActivityID
where   d.deptNotes <> i.deptNotes

If your deptNotes may contains NULL value, you need to use ISNULL() to handle that


text:
Q: how to set spark conf for pyspark standalone ipython notebook I am running spark stand alone and starting pyspark from the command line so it opens an ipython notebook.  Here is how I start pyspark:
PYSPARK_DRIVER_PYTHON=ipython PYSPARK_DRIVER_PYTHON_OPTS="notebook" /usr/local/src/spark/spark-1.6.1-bin-hadoop2.6/bin/pyspark

Ipython notebook opens in my browser and there is already an SQLContext sc that I can start using.  However, I need to set a conf for the SparkContext.
conf = SparkConf().setAppName("Cloudant Spark")
conf.set("jsonstore.rdd.schemaSampleSize", -1)

sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)

However, sc already exists so it won't let me create another one.  I tried an sc.stop() first but that gives me an error when I try to use the new sqlContext.
My questions are:
1. How can I set the conf?
2. Is there a better/different way of connecting an Ipython notebook to pyspark standalone?


text:
Q: Uploaded File is not moving in specified folder in php I have a php file named abstract_submission and to process the form in that file I created submitted_abstract php file. but move_uploaded file function does not working. for files I created a folder named submissions. Does anyone have a solution to this?
I tried shifting insert query up and down in if statement but it doesn't work.
<?php

    $con = mysqli_connect("localhost",MYSQL_USER,MYSQL_PASSWORD,"svavpo_phicon");

    ini_set('display_errors', 1);
    ini_set('display_startup-errors', 1);
    error_reporting(E_ALL);

    $edit_state = false;

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

        $name = $_POST['name'];
        $email = $_POST['email'];
        $category = $_POST['category'];
        $subm_category = $_POST['subm_category'];
        $main_category = $_POST['main_category'];
        $title = $_POST['title'];
        $author = $_POST['author'];
        $body = $_POST['body'];
        $reference = $_POST['reference'];

        $file = $_FILES['file']['name'];
        $target = "submissions/".basename($_FILES['file']['name']);

        $sql = "INSERT INTO `sub_abstract`(`name`, `email`, `category`, `subm_category`, `main_category`, `title`, `author`, `body`, `reference`, `file`) VALUES ('$name','$email','$category','$subm_category','$main_category','$title','$author','$body','$reference','$file')";

        $result=mysqli_query($con,$sql);

        if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
        {
            echo "errro in updating db";
        }
        else
        {

            echo ("<script LANGUAGE='JavaScript'>
        window.alert('Abstract Submitted Succesfully !');
        window.location.href='../abstract_submission.php';
        </script>");
        }

    }

?>


text:
Q: inline keyboard on telegram error 400 bad request I wanna send a json encoded keyboard as reply markup but I get error 400 bad requset!
This is how json looks like:
{"inline_keyboard":[[{"text":"Play, Guitar, Play - \u003Cspan style=\"font-size:14px;\"\u003E Conway Twitty ","callback_data":"some url"}]]}

and this is how the code looks like:
 // Create keyboard
    $keyboard = json_encode([
        "inline_keyboard" => [
            $innerdata,
    ]], true);

    $url = "https://api.telegram.org/bot$token/sendMessage?chat_id=$chat_id&text=Choose&reply_markup=".$keyboard;
    $res = file_get_contents($url);
        break;

I've also tried deleting one of the [ ] but it didn't work.

A: I actually find the problem. It was a problem with data size. As Telegram says, the callback data should not be more than 64 bytes
And it can be fixed by:
if(strlen($callback_data) < 64){
//the rest of the code
}


text:
Q: rewritecond based on http status code Is there any way in apache to set a rewrite condition based on what http code response you're getting? The server in front of an oauth proxy (apache) that redirects (302) to my auth provider; however I don't want it to proxy anything in the the websocket directory -- I'd rather it 403 instead. This is all to prevent it from constantly trying to reauth which it isn't authorized and building up lots of state cookies for OpenIDC.
Thanks for the consideration.
Something like this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^my\.server\.co$
RewriteCond %{HTTP_RESPONSE} 302
RewriteCond %{REQUEST_URI}  ^/websocket
RewriteRule (.*) $1 [F,L,NC]

A: You should be able to use:
<Location /websocket>
    OIDCUnAuthAction 401
</Location>

As documented here in the configuration primitives:
# (Optional)
# Defines the action to be taken when an unauthenticated request is made.
# "auth" means that the user is redirected to the OpenID Connect Provider or Discovery page.
# "401" means that HTTP 401 Unauthorized is returned.
# "pass" means that an unauthenticated request will pass but claims will still be passed when a user happens to be authenticated already
# Useful in Location/Directory/Proxy path contexts that serve AJAX/Javascript calls and for "anonymous access"
# When not defined the default "auth" is used.
#OIDCUnAuthAction [auth|pass|401]

(well it would return a 401 status code instead of a 403)

A: Other solution
RewriteEngine on

ErrorDocument 403 /%{REQUEST_URI}/403.shtml
ErrorDocument 404 /%{REQUEST_URI}/404.shtml

RewriteCond %{REQUEST_URI} /([0-9]{3}+).shtml$ [NC]
RewriteRule (.*) $1 [R=%1,L]


text:
Q: Ensure all dependency dlls are packaged into executable I thought if you compile a Visual-studio 2013 Win32 project using /MT Code Generation->Runtime library then it will automatically package all dependency dll's - including 3rd party dll's - into the executable?
Currently certain users get an error when running my .exe. Its related to not having a 3rd party dll (OpenSSL):

The program can't start because LIBEAY32.dll is missing from your computer

This error has occurred for users using my .exe on Windows 10 OS's. How can I ensure all dependency dll's are packaged into my .exe?
I currently compile my application on my 64bit Windows 8.1 OS. The win32 visual-studio project is compiled using the following project properties:

*

*Character Set: Unicode char set

*Use of MFC: Use standard windows libraries

*Whole Program Optimisation: Use Link Time Code Generation

*Debug info format: none

*Code Generation->Runtime library: /MT

A: /MT indicates that you are using multithread, static version of the run-time library. This doesn't affect third party dependency, e.g. OpenSSL is still linked dynamically.
To check your dll's dependency I prefer Dependency Walker tool. It will show if some of dependency is missed.
To ensure all dependency linked into your .exe file use static linking for all your third party dependency, e.g. for OpenSSL you should use libeay32MT.lib library.

A: Nikita is right, use Dependency Walker and I'd add that you're missing some knowledge about what a DLL really is. No offence meant, I know dlls can be a pita. What is a DLL?
By definition a DLL is not included in your .exe but it is loaded at runtime and  could be shared amongst several applications. If you want to include it in your .exe it will require some extra non trivial work to embed them into your exe, unpack and load at runtime.
See this post
I'd suggest to use an installer instead, much easier to handle! Just create an installer (you know the click click click "yes-yes-I agree-Ok-Done" wizard installer) that will include your .exe and all needed dependency files. As a reference Inno setup is quite great.


text:
Q: How to disable destroy when escape is pressed in a GtkDialog in gtk? I made a GtkDialog object, but I want to disable or handle the escape press event, how can I do it?

A: Connect to the delete-event, and in the callback, check if the event has been triggered by the ESC key press. Returning TRUE stops event propagation (this is what you want to ignore the ESC key press), returning FALSE will propagate the event and close the dialog.

A: It is working if you:

bind the response signal to an event:
    def on_dialogBigLabel_response(self, widget, response_id):
        print('on_dialogBigLabel_response Widget: %s | response_id: %s' % (widget, response_id))

        if response_id == Gtk.ResponseType.OK:
            print('OK')
            self.dialogBigLabel.hide()
        else:
            print('Response: %i' % response_id)

Now the escape response is -4 and here we aren't hiding or destroying the dialog.


text:
Q: My Upgrade From ubuntu 12.04 to 12.10 got cancelled due to powercutoff
Possible Duplicate:
Lost power during upgrade, how do I recover?

My upgrade from Ubuntu 12.04 to 12.10 got cancelled due to the power being cut off, now Ubuntu is not starting.  What can I do? I run windows 7 and Ubuntu. So please help me to get out of this mess because all my files were in Ubuntu. And also I had installed a lot of apps in it. If I loose it I will be in trouble. Please help.

A: Press ctrl alt f1 and then login there. after that type as
 sudo dpkg-configure -a

A: 1] If you're able to boot, but after login Unity doesn't load:
 It's possible that your GPU drivers are interfering; or that your hw isn't 3d-capable. Please post the result of the following command (press CTRL+ALT+T) :
$ /usr/lib/nux/unity_support_test -p
A. If you're using nVidia drivers: Run the following command to remove them, and reboot:
$sudo apt-get purge nvidia-current
$sudo apt-get remove nvidia-current-updates
$sudo apt-get remove nvidia-experimental-304
Or just open Synaptic and search for nvidia, delete everything that you see now.
Reboot the system. See if everything's working. Run this command to check if Unity-3D will work:
$ /usr/lib/nux/unity_support_test -p
Reboot again. Reinstall latest nVidia drivers:
$ sudo apt-get install nvidia-current-updates
B. If using AMD/ATI GPU drivers: Run the following command to remove them, and reboot:
$ sudo apt-get purge fglrx
Don't reinstall them as ATI cards currently don't support Unity-3D.
2] If you're unable to boot:
Insert a Ubuntu 12.10 Live-CD/DVD and run the following commands:
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair
Boot-Repair will launch. Select the 'Recommended Repair'.
3] IF you fail to see the Grub:- Insert a Ubuntu 12.10 Live-CD/DVD and run the following commands:
$sudo mount /dev/sdXY /mnt # XY is the drive, eg. sda or sda1
$grub-install /dev/sdX#X is drive number
$update-grub
Reboot. Lemme know if it doesn't work as intended.


text:
Q: Nested foreach loops, PHP, how do I manipulate the values? foreach ($bing_array as $bing_array_val)
{
    foreach ($final_array as $final_array_val)
    {
        if ($final_array_val["link"] == $bing_array_val["link"])
        {

            $final_array_val["rank"] += $bing_array_val["rank"];
        }
    }
}

The above code has two foreach loops, which are nested.
It should test every bing_array["link"] against every final_array["link"] and if they are the same, the final_array["rank"] value should be += bing_array["rank"] but when I echo final_array, the ["rank"] values are unchanged.
I assume this is a syntax problem, where am I going wrong?
Thanks

A: You need to use the reference syntax (& prefix):
foreach ($final_array as &$final_array_val)
{
}
unset($final_array_val);

Note that the unset is required to break the reference to the last value.  Read more here.

A: Here is the actual code you need :
foreach ($bing_array as &$bing_array_val)
{
    foreach ($final_array as &$final_array_val)
    {
        if ($final_array_val["link"] == $bing_array_val["link"])
        {
            $final_array_val["rank"] += $bing_array_val["rank"];
        }
    }
    unset(&$final_array_val);
}
unset(&$bing_array_val);

In your initial code, each time you were looping on $final_array, it was creating a temporary value called $final_array_val containing the content. Then, you modified it, and then it was replaced for each occurence of the foreach.
By passing the variables by reference, instead of creating a new temporary variable in the foreach, you use the actual variable which will keep the modifications you have done to it.


text:
Q: LaTex Compiler in Springer Journal type misunderstands that "_" in biblio is a mathematical expression LaTex Compiler thinks that "_" in biblio file is a mathematical expression that represents the beginning of subscript letter. Which library should I use or what should I do? My sample code is as follows:
\begin{filecontents*}{example.eps}

gsave
newpath
  20 20 moveto
  20 220 lineto
  220 220 lineto
  220 20 lineto
closepath
2 setlinewidth
gsave
  .4 setgray fill
grestore
stroke
grestore
\end{filecontents*}

\RequirePackage{fix-cm}

\documentclass[smallextended]{svjour3}

\smartqed
\usepackage{graphicx}

\journalname{Journal of Cryptographic Engineering}

\usepackage[acronym,toc,shortcuts]{glossaries}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{lineno}
\usepackage{array}
\usepackage{longtable}

\begin{document}

\cite{10.1007/3-540-44983-3_4}

\bibliographystyle{spmpsci}
\bibliography{biblio}

\end{document}

My biblio file is as follows:
@InProceedings{10.1007/3-540-44983-3_4,
author="Aoki, Kazumaro
and Ichikawa, Tetsuya
and Kanda, Masayuki
and Matsui, Mitsuru
and Moriai, Shiho
and Nakajima, Junko
and Tokita, Toshio",
editor="Stinson, Douglas R.
and Tavares, Stafford",
title="Camellia: A 128-Bit Block Cipher Suitable for Multiple Platforms --- Design and Analysis",
booktitle="Selected Areas in Cryptography",
year="2001",
publisher="Springer Berlin Heidelberg",
address="Berlin, Heidelberg",
pages="39--56",
isbn = "978-3-540-44983-6",
doi = "10.1007/3-540-44983-3_4"
}


text:
Q: Is there an Arzela-Ascoli theorem for subharmonic functions? Hörmander in Analysis of linear partial differential equations II proves Proposition 16.1.2 on page 304 to the effect that a sequence of subharmonic functions converging to another subharmonic function in the distributional sense necessarily converges in the $L^p_{loc}$ sense. Note that the proposition assumes the existence of a limiting subharmonic function. Is there a version of the Arzela-Ascoli theorem in this context that would guarantee the existence of a limit for a suitable subsequence, and under what hypotheses? I am mainly interested in the real 2-dimensional case.
As a follow-up, can one get control over the set of points where the limiting function is $-\infty$?

A: Yes, there is such an analog. Let $U$ be a family of subharmonic functions in a region $D$ subject to
the following conditions:
a) For every compact $K\subset D$ there is a constant $C(K)$ such that $u(z)\leq C(K)$ for $z\in K$ and $u\in U$. And
b) For every $u\in U$ we have $u(z_0)>-C$ for some $z_0\in D$ and some real $C$.
Then there is a subsequence which converges to a subharmonic function. The convergence is in $L^1_{\mathrm{loc}}$ and in $D'$ and in many other senses.
In particular, Laplacians converge in the weak topology of measures.
If you remove the condition b), one has to add the possibility that the subsequence converges to $-\infty$ (uniformly on compact subsets).
Condition b) can be modified in various ways. For example, you can make $z_0$ depending on $u$ but restricted to some fixed compact $K$. All this is true in any dimension.
All this is contained in Theorem 4.1.9 (Hormander, vol. I), or with more details
about modes of convergence, in his book Notions of convexity, Birkhauser, Boston, 1994.


text:
Q: React Native: undefined is not an object (evaluating 'props.navigation.navigate') I'm learning React Native and by trying to run this code using Expo it gives me the Exception error:
undefined is not an object (evaluating 'props.navigation.navigate'), at line 17 on App.js (marked in the comment)
There are two files: App.js and Untitled1.js
App:
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native';

  function App(props) {
    return (

      <View style={styles.container}>
        <Text style={styles.logo}>APPetito</Text>

        <Text style={styles.loginText}>Welcome to our app!</Text>
        <Text style={styles.loginText}>Choose what do you want to do</Text>

// [ THE FOLLOWING LINE CONTAINS THE ERROR ]
        <TouchableOpacity onPress={() => props.navigation.navigate("Untitled1")} style={styles.loginBtn}>

          <Text style={styles.loginText}>I eat food</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.loginBtn}>
          <Text style={styles.loginText}>I sell food</Text>
        </TouchableOpacity>

      </View>
    );

  }
// here there are the const styles
export default App;

Untitled.js
import * as React from 'react';
import React, { Component } from "react";
import { StyleSheet, View, Text } from "react-native";
import Icon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from '@react-navigation/native';

function Untitled1(props) {
  return (
    <View style={styles.container}>
      <Icon name="check" style={styles.icon}></Icon>
      <Text style={styles.itWorks}>It works!</Text>
    </View>
  );
}

// here there are the const styles
export default Untitled1;

What can I do to solve the problem?

A: I think the problem is that you didn't create a Stack navigator in the first place to navigate between screens. Refer to react navigation docs to know more here
According to the docs you have to implement the stack navigator such as:
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

  function Home(props) {
    return (

      <View style={styles.container}>
        <Text style={styles.logo}>APPetito</Text>

        <Text style={styles.loginText}>Welcome to our app!</Text>
        <Text style={styles.loginText}>Choose what do you want to do</Text>

        <TouchableOpacity onPress={() => props.navigation.navigate("Untitled1")} style={styles.loginBtn}>

          <Text style={styles.loginText}>I eat food</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.loginBtn}>
          <Text style={styles.loginText}>I sell food</Text>
        </TouchableOpacity>

      </View>
    );

  }

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Untitled1" component={Untitled1} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

I have updated your code a little bit to help you understand the concept.


text:
Q: Finding arguments that go with methods in C++ dll's Ok, so I can use dumpbin.exe /exports library.dll to find all methods in the dll.
...but how do I find out which arguments to pass into them? Without a header file of course.

A: For the usual C-style exports (e.g., Windows API DLLs): You can't. This information is not stored in the DLL and is inevitably lost after compilation (unless you have the headers or debuging symbols).
C++ exports, on the other hand, store their signature as part of the mangled function name and you can view them using Dependency Walker or similar tools, or demangle them manually using the UNDNAME tool or DUMPBIN's /SYMBOLS option.


text:
Q: Importing from node_modules in Stylus with Laravel Mix I have a large Stylus project I need to port into Laravel Mix from vanilla Gulp.
The app.styl includes another framework.styl which @imports stuff from node_modules. I can't use the use and import flags (or at least I can't figure out how to) in Laravel Mix, because

*

*For some dependencies, I only need to import specific files inside the node_modules folder, not the whole thing

*With one dependency, I need to set a long list of variables inside of Stylus before importing it.

main.styl
@import "includes/framework.styl"

/* Other stuff */

includes/framework.styl
$variable = 1.5
$other = white
/* bunch more */

@import "jeet"
@import "foo/src/specific.styl"

ks-no-conflict = true
@import "kouto-swiss"

/* other stuff */

All of the @imports in framework.styl are from node_modules. The order in which these dependencies and files are loaded is important, as they can clash with one another if loaded in the wrong order.
However, when I run npm run dev, it complains it can't find any of the dependency locations inside framework.styl.
I've tried prefixing the @import paths with ~/, node_modules/,  ./node_modules/, ../../../../node_modules, etc.; nothing seems to work. It all leads to:
failed to locate @require file node_modules/jeet/styl/index.styl

With ../../../../node_modules and ../../../node_modules, I get the following;
Module build failed: Error: EISDIR: illegal operation on a directory, read
    at Error (native)

How can I either make Stylus find these dependencies in node_modules (my preferred solution), or in the alternative, replicate the above in Laravel Mix options?


text:
Q: Queue memory usage and weird GC behavior Here is a small console program i'm playing with to find out why my production app consumes too much memory:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Press key - 1"); Console.ReadLine();

            var q = new Queue<string>();
            for (int i = 0; i < 1000000; i++)
                q.Enqueue("test string" + i);
            Console.WriteLine("Press key - 2"); Console.ReadLine();

            q = null;
            Console.WriteLine("Press key - 3"); Console.ReadLine();

            GC.Collect();
            Console.WriteLine("Press key - 4"); Console.ReadLine();

            GC.Collect(2);
            Console.WriteLine("Press key - 5"); Console.ReadLine();
}}}

I'm running it and monitoring Windows task manager while pressing the key. Here is what i see in Memory column on each step:

*

*4 700K

*61 616K

*61 596K

*10 588K

*8 588K

The results vary slightly (just few Ks) from run to run but you get the picture. Can please someone explain what's going on here?
My environment: .NET4 (client profile), Windows 7 x64.

A: You found out why the jitter generates no code when you set a local variable to null.  The garbage collector already knows when you stop referencing an object, it doesn't need help like that.  There are many books about .NET that can explain this to you, Richter's "CLR via C#" is widely praised.


text:
Q: Isabelle simple double function Im brand new to Isabelle, and HOL programming in general.
One of the exercises in a text book is to:
Define a recursive function double :: nat ⇒ nat and prove double m = add m m.
Im Still trying to define it but i can't figure it out.,
Here is what i have done so far.
fun double :: "nat => nat"  where
"double 0 = 0" |  //my base case
"double (n) =  //I don't know what to do here

I have a function add defined as follows.
fun add :: "nat ⇒ nat ⇒ nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"

but i don't think I'm meant to use add in the definition of double.
Also an explanation with the answer would be greatly appreciated.
Thank you,
Rainy

A: Try to figure out how to express double (Suc n) in terms of double n and Suc. That willl give you a recursive definition.


text:
Q: How to Pass html:text value with html:link in struts 1.2 My jsp page display a list using logic iterate. every row displayed has a edit link too. when edit linked clicked Name will be changed to textbox so it can be edited.and sent along with commit link.  html:text value i need to send  with html:link.
part of my jsp is below,where I have
html:text  property="newId"  value="<%=modId%>"/> I want to pass this property as hashmap with html link as I am sending     "/> as param1   Please help. or suggest any other way to do this. Thanks .
####################################################################################
<logic:equal name="mode" value ="1">
 <bean:write name="display" property="productId"/>
<logic:notEqual name="edit" value="1">
<bean:write name="display" property="productName" />
</logic:notEqual>
<logic:equal name="edit" value ="1">
<logic:equal name="display" property="productName" value ="<%=modId%>">
<html:text  property="newId"  value="<%=modId%>"/>
</logic:equal>
 <logic:notEqual name="display" property="productName" value ="<%=modId%>">
<bean:write name="display" property="productName" />
</logic:notEqual>
</logic:equal>

<bean:define id="param1" name="display" property="productName"/>
<%
    String changedName=request.getParameter("changedName");
    System.out.println("  st: " + changedName);
    java.util.HashMap params = new java.util.HashMap();
    if(param1!=null)
        params.put("objectToEdit", param1);
        params.put("abc",param1);
        pageContext.setAttribute("paramsName", params);
%>
</logic:equal>

#####################################################################################

Same JSP HTML:LINK PArt
 #######################################

 <logic:equal name="edit" value ="1">
   <logic:equal name="display" property="productName" value ="<%=modId%>">
    " >
   </logic:equal>
</logic:equal>

A: Well I did it using java script.
hope my solution help someone
function modify(){
    var textBox = document.getElementById('editableTextBox');//text box name
    var newName = document.getElementById('editableTextBox').value;
    if(textBox!=null){
        var table = document.getElementsByTagName("table");
        var rows = table[3].rows;
        var rowCount=0;
        for(i=1;i<rows.length;i++){
            rowCount = i;
            var cells = rows[i].cells;

                     if(cells[1].hasChildNodes()){
           var nodeName = cells[1].childNodes[0].nodeName;
          if(nodeName=="INPUT"){
            break;
           }
        }
    }
    var reqCell =rows[rowCount].cells[cells.length-2];
    var oldLink = reqCell.childNodes[1].getAttribute("href"); //getOld link
    reqCell.childNodes[1].setAttribute("href",oldLink+"&newName="+newName)  //set href with appending text box value
}
}


text:
Q: How to leave the R browser() mode in the console window? I was trying to use the browser() command to debug earlier.
Right now, I kept getting the following in the console input window:
Browse[13]>

Is it possible to get out of this situation and just get back to  the normal console window?

A: You will actually need to first enter f press enter and then enter Q. The order is finish and then quit. Otherwise you might not leave the browsing.

A: Turn off global debugging
debuggingState(on=FALSE)

A: The help page ?browser says that typing c and hitting enter will get you out of the browser and let the function continue to run or typing Q and hitting enter will exit the browser and the function and take you back to the top-level prompt.


text:
Q: How to accelerate Beautifulsoup in Python? I tried to parse 50 000 url using Beautifulsoup in Python.
The parsing works in loop:
I figure out that time for parsing one page is 15 - 18 seconds. From page I grab around 20 elements.
Why does Beautifulsoup work so slow? How to accelerate Beautifulsoup in Python?

A: Make sure you understand your bottlenecks.
The very first and the main problem is not the HTML parsing - it is "The parsing works in loop".
Which means that the code is synchronous/blocking - you are not processing the next URL until you are done with the current one. This is absolutely not scalable.
To solve this, switch to an asynchronous approach - switch to, for example, Scrapy web-scraping framework - this is currently the most natural move for scaling web-scraping projects.
Also see:

*

*Speeding up beautifulsoup

A: Parallelize your processing.
e.g.
import Queue
import threading

# will execute parrallel
def taskProcess(q, url):
    q.put(beautifulSoupFunction(url))

urls = ["http://url1.com", "http://url2.com"]

q = Queue.Queue()

for u in urls:
    t = threading.Thread(target=taskProcess, args = (q,u))
    t.daemon = True
    t.start()

s = q.get()
print s


text:
Q: Can Acrobat's JS interface automate hyperlinking an existing, formatted listing of page numbers? I am unfamiliar with Acrobat's Javascript interface and would like to know if the following is even possible: am having no luck searching for existing examples. It's hard to believe no one else has had to do this, so I am hoping this is a search fail on my part.
I am looking for a way to examine the font styles of numbers in an existing PDF (these numbers all have a specific font / font size), then automatically hyperlink these numbers so they go to their corresponding PDF pages. I know I can do this manually with the Links tool; I have about 700 page numbers to hyperlink, thus the need for automation.
If that sounds like making an existing table of contents: that's exactly it, but there's more than one table (also a table of figures, illustrations, an index...)
Due to a long list of restrictions, I cannot re-export the full document from its original source with these already hyperlinked. I have to work with a final (heavily edited) PDF. I know that'd be the best solution but again, this is impossible for me.
Before I launch into hours of script creation, could someone confirm if Acrobat gives me the capacity to do this? From the Googling I've done it seems like I'm asking for too much.
Thanks in advance (if anyone has pointers I'd take those too).

A: Acrobat JavaScript has (unfortunately) very little access to the base of the document. It can find "words" on a page (words are strings of text, Acrobat believes belonging together). You can read out the "word", and its bounding box coordinates.
You can guess the font size based on the bounding box height, but you can not read it out. Neither can you the font nor its attributes.
In Acrobat JavaScript, you would loop through the pages, and on every page loop through the words, get the word and the coordinates. Then you would analyze that information to figure out whether it suits your need. To make a link target, you would create a view with its zoom coordinates.
For the source (from where you want to jump to the target), you would create a Button field, and as action set it to go to the according view. Existing views are not affected.
The alternative would be a production plug-in. You'd have to decide whether learning the Acrobat SDK would be worth the effort, however.


text: Q: How do I commit to my README file on Gitpod? Please pardon my possibly quite simple question. But how do I commit my changes to my README file on Gitpod? When I do git add . and then git commit -m "text" it just says "nothing to commit, working tree clean"?


text:
Q: I am trying to write a code in python to get the values from a multiline string and store it in dictionary enter image description hereThis is the string:
description = '''add DL3,DL1,DL5,DL6
id7
add DL2,DL3,DL4
id1
id2
id3
add DL3
id1
id2
id3
'''

output should be like :
action = [{process:add,dl_names:[DL3,DL1,DL5,DL6],id:[id7]},{process:add,dl_names:[DL2, DL3, DL4],id:[id1,id2,id3]},{process:add,dl_names:[DL3],id:[id1,id2,id3]}

code i am using:
description = '''add DL3,DL1,DL5,DL6
id7
add DL2,DL3,DL4
id1
id2
id3
add DL3
id1
id2
id3
'''

action = {}
con_des = description.splitlines()
#print(con_des)
add_index = []
for lines in con_des:
    if "add" in lines:
        process = "add"
        action["process"] = process
        add_index.append((con_des.index(lines)))
#print(add_index)

for index in add_index:
    temp = con_des[index].split(" ")
    temp_1 = temp[1].split(",")
    dl_list = []
    for dl in temp_1:
        dl_list.append(dl)
    action["dl_names"] = dl_list
    print(action)

But i am not getting the desired output, suggest me some approach

A: To fix your issues, I modified your split to be able to get all thedl_list so
temp[1:] and added a list to append your actions.
action = {}
con_des = description.splitlines()
add_index = []
count = 0
ids = []
actions = []
for lines in con_des:
    if "add" in lines:
        if count == 1:
            actions.append(action)
            action = {}
        ids = []
        process = "add"
        action["process"] = process
        temp = lines.split(" ")
        dl_names = "".join(temp[1:]).split(",")
        action["dl_names"] = dl_names
        action["Ids"] = ids
    else:
        ids.append(lines)
        count = 1
actions.append(action)
print(actions)

A: you can use this code:
#
import re

description = '''add DL3,DL1,DL5,DL6
id7
add DL2, DL3, DL4
id1
id2
id3
add DL3
id1
id2
id3
'''

action = []
item = {}
for line in description.splitlines():
    if re.search(r'^add', line):
        if item:
            action.append(item)
            item = {}
        process, dll = line.split(' ', 1)
        item['process'] = process
        item['dl_names'] = [dl.strip() for dl in dll.split(',')]
        item['id']=[]
    else:
        item['id'].append(line.strip())
if item:
    action.append(item)

print(action)