text:
Q: Java swing graphics image related questions I am trying to write some programs where I load images to a panel.
Here are my 5 questions:
1> Is there any restriction on what kind(extension) of images can be loaded? I tried to load a .bmp file, it didn't load even after I renamed it with .jpg. However, some other file that were with extensions such as .png or .jpg loaded.
2>Is there a way I can cut an image through java to create a new image. Say, I have a 600x600 pixel image and I want to create a new image by selecting a 200x200 pixel from the middle of the original picture.
3>Is there a way I can resize an image?
4>Can I add an image to a scrollpane?
5> Can I rotate an image by an angle ,say 30 degree?
That's it. A little elaboration with examples will be nice. Thanks in advance.

A:
1> Is there any restriction on what kind(extension) of images can be
  loaded? I tried to load a .bmp file, it didn't load even after I
  renamed it with .jpg. However, some other file that were with
  extensions such as .png or .jpg loaded.

Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can "plug-in" support for additional formats. For example, plug-ins for TIFF and JPEG 2000 are separately available.
Check the Reading/Loading an image tutorial page

2>Is there a way I can cut an image through java to create a new
  image. Say, I have a 600x600 pixel image and I want to create a new
  image by selecting a 200x200 pixel from the middle of the original
  picture.

Two ways. Croping the image using Clipping with Graphics. But faster approach is to use  BufferedImage.getSubimage(int x, int y, int w, int h) method.
  BufferedImage image = ImageIO.read("image file");
  image = image.getSubimage(50, 50, 200, 200);

This will crop an image at location(x, y) == (50, 50) and size 200 x 200.

3>Is there a way I can resize an image?

The discussion about the various approach will take a size of a blog. Read through the The Perils of Image.getScaledInstance() article for good insight.
However, a quick approach for example: with cWidth and cHeight
BufferedImage tmpImage = new BufferedImage(cWidth, cHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)tmpImage.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(image, 0, 0, cWidth, cHeight, null);

There is working example done by MadProgrammer. It is also better to use external library such as this which does this works nicely.

4>Can I add an image to a scrollpane?

Direct adding is not suggested. use JLabel instead. Or use a custom component and override the paintComponent(Graphics g) function and draw inside it. There are some working example with these two approach. Generally working with JLabel is easier.
See this question answers. Mine including @MadProgrammer. And The custom painting official tutorial page.

5> Can I rotate an image by an angle ,say 30 degree?

Yes using the Graphics2D.rotate(double theta) function; There are actually much more things you can do with the Graphics2D API. Working examples are shown by MadProgrammer  here and here.


text:
Q: Angular Material setValidity message does not animate I'm using Angular material and am trying to accomplish validating a form using server-side validation. The fields are sent to my php framework, validated and if there are errors the application responds with a JSON of error messages associated with input fields. I then accomplish displaying errors to the user using:
$scope.errormessage = response.message;
$scope.myform.myinput.$setValidity('errormessage', false);

This works but the message is not being animated - it appears instantly. If I use ng-required the message is animated. Any ideas what I'm doing wrong or if there is some other way to approach this problem?
Angular material demo for messages is located here:
https://material.angularjs.org/latest/demo/input
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 404 error in Custom Magento configuration in admin I'm developing a custom SMS module in Magento 1.6.
I've setup the system.xml file to manage the related custom configuration fields.
The menu entry shows up, but when I click it, a 404 error page is shown instead of the expected configuration fields list.
Can you see any errors in my code?
<config>
<tabs>
    <mynew_tab translate="label">
        SMS Gateway Integration
        <sort_order>100</sort_order>
    </mynew_tab>
</tabs>
<sections>
    <smsconfig  translate="label">
        SMS Gateway Integration
        <sort_order>200</sort_order>
        <show_in_default>1</show_in_default>
        <show_in_website>1</show_in_website>
        <show_in_store>1</show_in_store>
        <tab>mynew_tab</tab>
        <groups>
            <sms_group translate="label">
                My Custom Configurations
                <comment>This is example of custom configuration.</comment>
                <sort_order>10</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>1</show_in_store>
                <fields>
                    <sms_enabled translate="label tooltip comment">
                        Is Enabled
                        <frontend_type>select</frontend_type>
                        <source_model>adminhtml/system_config_source_yesno</source_model>
                        <sort_order>0</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                        <comment>Enable this module.</comment>
                    </sms_enabled>
                    <sms_username translate="label tooltip comment">
                        Sender Email
                        <frontend_type>text</frontend_type>
                        <sort_order>1</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                        <comment>Username of the SMS gateway.</comment>
                    </sms_username>
                    <sms_password translate="label tooltip comment">
                        Sender Email
                        <frontend_type>text</frontend_type>
                        <sort_order>1</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                        <comment>Password of the SMS gateway.</comment>
                    </sms_password>
                </fields>
            </sms_group>
        </groups>
    </smsconfig>
</sections>

After ben's request, we placed the adminhtml.xml file. I placed the content of the XML file.
<config>
<acl>
    <resources>
        <admin>
            <children>
                <system>
                    <children>
                        <config>
                            <children>
                                <sms translate="title" module="sms">
                                    <title>SMS Gateway Section</title>
                                </sms>
                            </children>
                        </config>
                    </children>
                </system>
           </children>
       </admin>
   </resources>
</acl>

But till the 404 error comes...

A: A 404 error in system configuration often means that there is an issue with ACL. You are likely missing the appropriate acl node in your module's adminhtml.xml file:
<acl>
    <resources>
        <admin>
            <children>
                <system>
                    <children>
                        <config>
                            <children>
                                <smsconfig>
                                    <title>Your Section</title>
</...>

After adding the above you will need to log out and log back in for full admin role users and explicitly add this role to custom admin user roles.

A: Do what @benmarks said plus be sure to add the right children (in your case) smsconfig
(@benmarks used sms_config instead of smsconfig)

<acl>
    <resources>
        <admin>
            <children>
                <system>
                    <children>
                        <config>
                            <children>
                                <smsconfig>
                                    <title>Your Section</title>
</...>

clear cache, admin logout, admin login == works
Hint: If you get 404 look at the url (when you clicked on your tab):
/index.php/admin/system_config/edit/section/mymodulename_something/...
This url seems to point to mymodulename_something:

<?xml version="1.0"?>
<config>
    <tabs>
        <mymodulename translate="label" module="mymodulename">
            MyModuleName Awesome Label
            <sort_order>1</sort_order>
        </mymodulename>
    </tabs>
    <sections>
        <mymodulename_something translate="label" module="mymodulename">

so your adminhtml.xml would look like:

<?xml version="1.0"?>
<config>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <mymodulename_something translate="title" module="mymodulename">
                                        <title>have no idea where this is showing up btw</title>
                                    </mymodulename_something>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
</config>

A: Don't underestimate the need to log out and then log back in after making ACL changes. Even if you clear your cache, you will still 404 until you log out and log back in.


text:
Q: Is "Negative Repercussion" a correct collocation? Can I use the word "Negative" before the word "Repercussion? For example:

If they do not take such measures, there may well be a negative
  repercussion in terms of support for the whole process in some
  nationalist and republican communities.


text:
Q: Retrieve history from Google Chrome on Android Let us say that I am writing an Android application that needs to get the browsing history of Google Chrome. Does the Android API allow for this? Which versions? What code could do this?

A: Check the answer in this SO post:
Android read browser history
Basically, you need the Cursor interface for this purpose, and manifest permission:
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />


text:
Q: Why am I getting "script not responding" warning Why am I getting "script not responding" warning for script http://sstatic.net/so/js/master.js?v=5005:1 when viewing this question with Firefox 3.5.5
Edit 1: I flushed the cache. Still getting the same warning.
Edit 2: Running Firefox in safe mode does fix the problem.

A: That trailing colon is very bizarre and doesn't appear in our source code.
At any rate, if safe mode fixes it, one of the add-ins is at fault.


text:
Q: Doubt in a step of the proof of Rado-Kneser-Choquet theorem I am trying to prove Rado-Kneser-Choquet theorem, which states that if $f$ is sense preserving self homeomorphism of the unit circle $\partial D$. Then harmonic extension $F$ of $f$ is self homeomorphism of the unit disk D. I have some doubt in a step in between.
Let $D\subseteq \mathbb{C}$ be unit disk and $f:\partial D\to \partial D$ be sense preserving self homeomorphism of $\partial D$. Let $F$ be harmonic extension of $f$. In the proof it uses a statement: $F$ is locally injective (this is easily provable) and since $f$ is sense preserving, then $F$ is sense preserving throughout $D$.
Can anyone help me out with this. I am not able to prove this.


text:
Q: Minutiae-based fingerprint matching algorithm The problem
I need to match two fingerprints and give a score of resemblance.
I have posted a similar question before, but I think I've made enough progress to warrant a new question.
The input
For each image, I have a list of minutiae (important points). I want to match the fingerprints by matching these two lists.
When represented graphically, they look like this:

A minutia consists of a triplet (i, j, theta) where:

*

*i is the row in a matrix

*j is the column in a matrix

*theta is a direction. I don't use that parameter yet in my matching algorithm.

What I have done so far

*

*For each list, find the "dense regions" or "clusters". Some areas have more points than others, and I have written an algorithm to find them. I can explain further if you want.

*Shifting the second list in order to account for the difference in finger position between both images. I neglect differences in finger rotation. The shift is done by aligning the barycenters of the centers of the clusters. (It is more reliable than the barycenter of all minutiae)

*I tried building a matrix for each list (post-shift) so that for every minutia increments the corresponding element and it's close neighbours, like below.
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1

*By subtracting the two matrices and adding up the absolute values of all elements in the resulting matrix, I hoped to get low numbers for close fingerprints.
Results

*

*I tested a few fingerprints and found that the number of clusters is very stable. Matching fingerprints very often have the same number of clusters, and different fingers give different numbers. So that will definitely be a factor in the overall resemblance score.

*The sum of the differences didn't work at all however. There was no correlation between resemblance and the sum.

Thoughts

*

*I may need to use the directions of the points but I don't know how yet

*I could use the standard deviation of the points, or of the clusters.

*I could repeat the process for different types of minutiae. Right now my algorithm detects ridge endings and ridge bifurcations but maybe I should process these separately.

Question: How can I improve my algorithm ?
Edit
I've come a long way since posting this question, so here's my update.
I dropped the bifurcations altogether, because my thinning algorithm messes those up too often. I did however end up using the angles quite a lot.
My initial cluster-counting idea does hold up pretty well on the small scale tests I ran (different combinations of my fingers and those of a handful of volunteers).
I give a score based on the following tests (10 tests, so 10% per success. It's a bit naïve but I'll find a better way to turn these 10 results into a score, as each test has its specificities):

*

*Cluster-thingy (all the following don't use clusters, but minutiae. This is the only cluster-related approach I took)

*Mean i position

*Mean angle

*i variance

*j variance

*Angle variance

*i kurtosis

*j kurtosis

*Angle kurtosis

*j skewness

A statistical approch indeed.
Same finger comparisons give pretty much always between 80 and 100%. Odd finger comparisons between 0 and 60% (not often 60%). I don't have exact numbers here so I won't pretend this a statistically significant success but it seems like a good first shot.

A: Your clustering approach is interesting, but one thing I'm curious about is how well you've tested it.  For a new matching algorithm to be useful with respect to all the research and methods that already exists, you need to have a reasonably low EER.  Have you tested your method with any of the standard databases?  I have doubts as to the ability of cluster counts and locations alone to identify individuals at larger scales.
1) Fingerprint matching is a well studied problem and there are many good papers that can help you implement this.  For a nice place to start, check out this paper, "Fingerprint Minutiae Matching Based on the Local and Global Structures" by Jiang & Yau.  It's a classic paper, a short read (only 4 pages), and can be implemented fairly reasonably.  They also define a scoring metric that can be used to quantify the degree to which two fingerprint images match. Again, this should only be a starting point because these days there are many algorithms that perform better.
2) If you want your algorithm to be robust, it should consider transformations of the fingerprint between images.  Scanned fingerprints and certainly latent prints may not be consistent from image to image.
Also, calculating the direction of the minutiae points provides a method for handling fingerprint rotations.  By measuring the angles between minutiae point directions, which will remain the same or close to the same across multiple images regardless of global rotation (though small inconsistencies may occur because skin is not rigid and may stretch slightly), you can find the best set of corresponding minutia pairs or triplets and use them as the basis for rotational alignment.
3) I recommend that you distinguish between ridge line endings and bifurcations.  The more features you can isolate, the more accurately you can determine whether or not the fingerprints match.  You might also consider the number of ridge lines that occur between each minutiae point.
This image below illustrates the features used by Jiang and Yau.

*

*d: Euclidean distance between minutiae

*θ: Angle measure between minutiae directions

*φ: Global minutiae angle

*n: Number of ridge lines between minutiae i and j

If you haven't read the Handbook of Fingerprint Recognition, I recommend it.


text:
Q: Плавное скрытие блока если внутри него ничего нет Имею сайт с подгрузкой контента, но не очень нравится, что он появляется резко. Нажимаю на ссылку — и через 1 сек появляется блок. Хотелось бы, чтобы при вызове функции блок на 2 секунды скрывался, а потом появлялся.

A: Загрузить контент можно в скрытый div, затем показать его. Чтобы показать блок через 2 секунды применяем функцию setTimeout(showBum, 2000);, где showBum - пользовательская функция, в нашем случае показывает область с загруженным контентом, далее 2000 - 2 секунды в миллисекундах.

$('#but').on('click', function(){
  $('#time').show();
  setTimeout(showBum, 2000);
});

$('#but2').on('click', function(){
  $('#time').hide();
  $('#bum').hide();
});

function showBum(){
  $('#bum').fadeIn(1000);
}
#bum {
  font-size: 40px;
  display:none;
}
#time {
  display:none;
}

<input type="button" value="загрузить" id="but">
<input type="button" value="сброс" id="but2">

Через 2 секунды загрузится.

Бамбалей!

A: jQuery(document).ready(function($) {
    $('.navmenu .linked').on('click', function(){
        $('#BOOX').hide();
        $('#BOOX').fadeIn();
    })
});


text:
Q: Popup freezes Selenium Webdriver until the popup is manually closed I'm having problems automating tests on an internal website. In some cases, a popup will freeze the test until I manually close the popup. After the popup is opened, no code is run, not even System.out.println's.
driver.findElement(By.id("top_toolbarSALTkA7_Aras_Tbi_promote")).click();
System.out.println("test");

I have tried multiple ways of handling the popup, but no code at all is run after the click(), and it seems it never times out.
Tried:
1.
((JavascriptExecutor) driver).executeScript("return document.getElementById('top_toolbarSALTkA7_Aras_Tbi_promote', 'onClick')");

2.
Set<String> windowHandles = driver.getWindowHandles();
    for(String handle : windowHandles)
    {
        driver.switchTo().window(handle);
        if (driver.getTitle().contains(title))
        {
            System.out.println("- (Page title is: " + driver.getTitle() + ")");
            break;
        }
    }

3.
driver.switchTo().alert();

4.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

If I close the popup, the test will continue with the System.out.println and then continue until finshed.
I'm using Selenium Webdriver 2.48.2 with FireFox 31.0, programming is Java. Any ideas what can be done? (It's not possible to change the website)

A: Finally found the solution!!! Found it in the Selenium official user group: https://groups.google.com/forum/#!searchin/selenium-users/popup%7Csort:relevance/selenium-users/eDqPiYoJ9-Q/kRI67cCVe5wJ
Solution is to start a new thread that waits a couple of seconds, and then presses enter (or in my case first tabs to the "OK" button). Just call the function before the popup is opened.
    public static final void prepareToPressEnterKey(int seconds, int tabs) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Runnable() {

        public void run() {

            try {
                Robot robot = new Robot();

                for (int i=0; i<tabs; i++)
                {
                    robot.keyPress(KeyEvent.VK_TAB);
                    TimeUnit.SECONDS.sleep(1);
                    robot.keyRelease(KeyEvent.VK_TAB);
                }

                robot.keyPress(KeyEvent.VK_ENTER);
                TimeUnit.SECONDS.sleep(1); //press for 1 sec
                robot.keyRelease(KeyEvent.VK_ENTER);
            } catch (AWTException | InterruptedException e) {
                System.out.println("Prepare to Press Enter Exception");
            }
        }
    },
            seconds,
            TimeUnit.SECONDS);
    scheduledExecutorService.shutdown();
}

Still, if there are any better solutions I'd very much like to know. Thanks!

A: Just disable popup. I mean you need to call the next script inside the current browser context (executeScript - I guess in your, Java binding case):
document.alert = window.alert = alert = () => {};


text:
Q: How Do I Rename a List Instance's Field's StaticName in FeatureUpdating? I am creating a custom WSP in Visual Studio. This solution has several custom content types with custom fields as well as a list instance with content types enabled. Unfortunately, i need to change the static name of a few of my fields & deploy to several different servers.
I have tried the following code:
Feature.Web.Template.xml
<Feature xmlns="http://schemas.microsoft.com/sharepoint/">
    <UpgradeActions>
        <VersionRange BeginVersion="0.0.0.0" EndVersion="1.0.0.1">
            <CustomUpgradeAction Name="RenameField">
                <Parameters>
                    <Parameter Name="FieldID">{060A9145-5D22-4D6C-A049-2438D8E0CDD8}</Parameter>
                    <Parameter Name="NewName">ProductDescription</Parameter>
                </Parameters>
            </CustomUpgradeAction>

            <CustomUpgradeAction Name="RenameField">
                <Parameters>
                    <Parameter Name="FieldID">{FBDDC10E-4872-4A4D-98C1-E2FD19658D24}</Parameter>
                    <Parameter Name="NewName">DiscussionAccessOther</Parameter>
                </Parameters>
            </CustomUpgradeAction>
        </VersionRange>
    </UpgradeActions>
</Feature>

Feature.EventReceiver.cs
public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
{
    SPWeb web = (SPWeb)properties.Feature.Parent;

    switch ( upgradeActionName ) {
        case "RenameField":
            RenameField(web, new Guid(parameters["FieldID"]), parameters["NewName"]);
            break;
    }
}

protected void RenameField(SPWeb web, Guid fieldId, string newName) {
    if ( web.Fields.Contains(fieldId) ) {
        RenameField(web.Fields[fieldId], newName);
    }

    foreach ( SPList l in web.Lists ) {
        if ( l.Fields.Contains(fieldId) ) {
            RenameField(l.Fields[fieldId], newName);
        }

        if ( l.ContentTypesEnabled ) {
            foreach ( SPContentType ct in l.ContentTypes ) {
                if ( ct.Fields.Contains(fieldId) ) {
                    RenameField(l.Fields[fieldId], newName);
                }
            }
        }
    }
}

private void RenameField(SPField field, string newName) {
    field.StaticName = newName;
    field.Update();
}

This updates the field in the field gallery, but not the list instance. What am i missing?
Thanks.

A: Couple of things:

*

*You should be updating SPContentType.FieldLinks, and not SPContentType.Fields. The latter is only a construct that represents the merge between the field's list definition and any specific modifications for that content type in that list.

*Try using SPField.Update(boolean) to propagate changes down the hierarchy from the site-level definitions.


text:
Q: Send to using batch file Hi i have a main folder that contains two folders "active" and "confirmed".
The subfolders under these two folders are identical. I want to be able to select the files i need to send to the confirmed folder through the windows context menu but i can't get this code to work.
for %%i in (%*) do (
    REM Takt the path of each file and save it as source.
    source=%%i
    REM Change the word "active" in the path to "confirmed".
    destnation=%%i:active=confirmed%

    REM Move the file to the confirmed subtree.
    move /-Y source destination
)

A: You need to use the SET command to assign a string to a variable. You also cannot do string substitution with a FOR variable.  You also need to use delayed expansion to reference your variables inside a code block.
Give this a try.
@echo off
for %%I in (%*) do (
    REM Take the path of each file and save it as source.
    set "destination=%%~dpI"
    REM Change the word "active" in the path to "confirmed".
    setlocal enabledelayedexpansion
    set "destination=!destination:active=confirmed!"
    REM Move the file to the confirmed subtree.
    move /-Y "%%~I" "!destination!"
    endlocal
)


text:
Q: Usercontrol's PropertyChangedCallback not fired I'm having really hard time trying to make listbox multiselection bindable, basically the same as this article : http://blogs.microsoft.co.il/miziel/2014/05/02/wpf-binding-listbox-selecteditems-attached-property-vs-style/
This is my class for the listbox :
public partial class ListBoxMultipleSelection : UserControl
{
    public ListBoxMultipleSelection()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public static readonly DependencyProperty ItemSourceProperty =
    DependencyProperty.Register("ItemSource", typeof(ObservableCollection<string>), typeof(ListBoxMultipleSelection), new PropertyMetadata(new ObservableCollection<string>()));
    public ObservableCollection<string> ItemSource
    {
        get { return (ObservableCollection<string>)this.GetValue(ItemSourceProperty); }
        set { this.SetValue(ItemSourceProperty, value); }
    }

    private static ListBox list;
    private static bool _isRegisteredSelectionChanged = false;

    ///
    /// SelectedItems Attached Dependency Property
    ///
    public static readonly DependencyProperty SelectedItemsProperty =
    DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
    typeof(ListBoxMultipleSelection),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
    new PropertyChangedCallback(OnSelectedItemsChanged)));

    public static IList GetSelectedItems(DependencyObject d)
    {
        return (IList)d.GetValue(SelectedItemsProperty);
    }

    public static void SetSelectedItems(DependencyObject d, IList value)
    {
        d.SetValue(SelectedItemsProperty, value);
    }

    private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!_isRegisteredSelectionChanged)
        {
            var listBox = (ListBox)d;
            list = listBox;
            listBox.SelectionChanged += listBox_SelectionChanged;
            _isRegisteredSelectionChanged = true;
        }
    }

    private static void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        IEnumerable listBoxSelectedItems = list.SelectedItems;
        IList ModelSelectedItems = GetSelectedItems(list);
        ModelSelectedItems.Clear();
        if (list.SelectedItems != null)
        {
            foreach (var item in list.SelectedItems)
                ModelSelectedItems.Add(item);
        }
        SetSelectedItems(list, ModelSelectedItems);
    }
}

And the XAML for the usercontrol/listbox :
<Grid>
    <ListBox SelectionMode="Multiple"
             local:ListBoxMultipleSelection.SelectedItems="{Binding DataContext.SelectedItems}"
             ItemsSource="{Binding DataContext.ItemSource, ElementName=MultiListBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

The problem is "listBox_SelectionChanged" is never fired and so nothing is updated correctly. Any idea ?
Thank you


text:
Q: How do I set-up a Windows 7 using schedule-task to run a bookmark or specific URL I am in need of running several php links on a regularly scheduled interval. I am not able to do it on the host through a typical cron set-up because of the memory, data, and time (out) required. The php script take approximately 1-2 hours to run and needs to be run every 4-5 hours. I was planning on using Windows 7 task scheduler to run the link(s) needed and just create a new name for each task, such as URL at 12:00, URL at 4:00 pm, URL at 8pm, etc..
Can someone tell me if it is possible to run a bookmark (or specific URL) on a schedule using Windows 7 or other program?

A: It's very easy to do this.
Selecting your browsers location, I will use internet explorer for the example
both 32 bit & 64 bit machines (running this command in a 64 bit machine will run 64 bit internet explorer)
"C:\Program Files\Internet Explorer\iexplore" http://www.domain.com

32 Bit Internet Explorer (for use on 64 bit machines)
"C:\Program Files (x86)\Internet Explorer\iexplore" http://www.domain.com

You can just stick that command into the task schedule and it'll do it.

A: Will the Firefox Reload Every addon work for you?

Reloads web pages every so many seconds or minutes. The function is accessible via the context menu (menu you get when you right click on a web page) or via tab context menu (just in Firefox 4.0)

A: You could setup Cygwin or PowerShell scripts to run your URL with curl or wget on your Windows 7.


text:
Q: How can I fix my GPT? I just migrated from a 120 GB SSD drive to a 600 GB SSD drive. As I was lazy and didn't want to reinstall Mac OS X (Lion), I chose the following migration path:

*

*I created at GPT on the 600 GB target disk with exactly the same three partitions as they are present on my old disk, using gdisk. I placed the third partition (that holds the Lion Recovery System) at the end of the disk, such that there is empty space between the system partition (holding the "Macintosh HD" labeled FS) and the recovery partition. I chose this setup as I wasn't sure whether I wanted to expand my system partition later or use the new space for a separate filesystem.

*I plugged my old 120 GB SSD into a linux box and saved three images, one for each partion, using dd

*Then I plugged my new 600 GB SSD into the same box and wrote the three images to the three newly created partitions, again, using dd
Then I installed the 600 GB SSD back in my Macbook Pro and started up the system. Everything works fine, with the exception that it seems to take forever for the computer to decide what partition to boot from - before the early password prompt (I use full disk encryption) I now have to stare at a white screen for about 10 seconds.
Disk Utility reports that something is wrong with the partition table that might cause trouble when booting the system:

Now, fortunately, up to now they only delay booting, but don't prevent it ;) Don't be confused by the screenshot, in the meantime I created another partition holding a filesystem labelled "Storage HD".
What did I miss? Is there a boot flag or something like that for a GPT partition that I didn't set? Disk Utility is unable to "repair" anything. Also, when I boot with a Lion Installation Media and use Disk Utility from there, it doesn't report any error at all.
I am aware of the recovery from TimeMachine / old disk / etc options of the Mac OS X Installer. I'm not interested in alternative ways to migrate a Mac OS X installation, but want to understand what exactly is going on here.

A: A PRAM / NVRAM reset (⌘-⌥-P-R on startup) fixed the delay. The Disk Utility error report remains. Started again from my old drive, the error is reported there as well... probably it was there before the migration.


text:
Q: Finding the Bernoulli distribution using its characteristic function I have managed to calculate that the characteristic function for the Bernoulli distribution is equal to
$\phi(t)=(pe^{it}+1-p)^n$
But now I'd like to derive the Bernoulli distribution using this result. I have found the following formula to do it:
$p_X(k)=\frac{1}{2\pi}\int\limits_{-\infty}^{\infty}e^{-ikt}\phi(t)dt$
This integral is pretty awful after inserting the Bernoulli distribution into it. I have noticed that after removing $2\pi$ and the integral sign with $dt$ I will get what I need, but I don't think this is the right way of doing that. How to find the Bernoulli distribution using its characteristic function?

A: In the terminology I learned, that's the characteristic function of the Binomial distribution; Bernoulli is the special case $n=1$. Note that$$\begin{align}\phi(t)&=\sum_{k=0}^n\binom{n}{k}(1-p)^{n-k}p^ke^{ikt}\\\implies P(X=k)&=\binom{n}{k}(1-p)^{n-k}p^k[0\le k\le n\land k\in\Bbb Z].\end{align}$$Since the distribution is discrete, you can only use an integral to obtain it if you're proficient in the Dirac delta, viz.$$\frac{1}{2\pi}\int_{-\infty}^\infty e^{i(k^\prime-k)t}dt=\delta(k^\prime-k).$$


text:
Q: "I think black and white matches/fits/fits in/suits better." If I want to say that I think that a photography looks better in black and white colours, can also use these words?

*

*I think black and white suits better.

*I think black and white matches better.

*I think black and white fits better.

*I think black and white fits in better.

I know theoretically how to use these kind of words in terms of clothes(because in my English lessons we were talking about these words describing clothes only), but I'm not sure how to use them talking for example about photographs.

A: When I read your first sentence, I thought for a moment you were referring to black and white suits, and that you thought them better.
"Black and white" can be misread or misheard as a plural noun noun phrase.
You could avoid that saying "I think this photo would look better in black and white."
If you are already talking about photos and the option of using black and white, there's no possibility of confusion, and your suggested sentences could be used, but they would be clearer with a direct object for each of the verbs, for example:
"I think black and white suits the subject matter better."
"I think black and white fits the mood better."
"I think black and white matches the scene better."

A: Added to Jack's contribution,  I suggest you also take a close look at your options.
 "fits in" may be regarded as tautology. Since  to fit already shows that it is into  something.


text:
Q: Android studio code formatting not following the settings I want to copy my project to another directory on my windows 10 PC but whenever I copy the project and open it from the other directory the code formatting settings do not apply to the code formatting. Whenever I format my code with the code formatting shortcut(ctrl + alt + L) the tabbing is turned to 1 space and the code becomes very hard to read. Changing the settings or resetting them to default does not change anything. I also tried to replace the files for code styles but that also does not work. What would you suggest me to do?

A: AndroidStudio should be the same as IntelliJ IDEA. There you can override formatter settings in Settings -> Editor -> Code Style. There you can set Tab size and Indent (I personally suggest 4 spaces).


text:
Q: Menus - Open items in new tab/window? I have 3.1.2 running with the Boldy theme.
Site link.
I have a menu that has a number of external links listed in the items.
By default, these items do NOT load in a new tab/window.
There is no option in the Admin --> Appearance --> Menus, to tick a box to say open in new window.
How do I get them to do this?

A: In your WordPress admin panel, go to Appearance > Menus. Select Screen Options in the top right corner. Enable the property Link Target. Now you can set your link target element in your external link.


text:
Q: Call apply-like function on each row of dataframe with multiple arguments from each row I have a dataframe with multiple columns.  For each row in the dataframe, I want to call a function on the row, and the input of the function is using multiple columns from that row.  For example, let's say I have this data and this testFunc which accepts two args:
> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
> df
  x y z
1 1 3 5
2 2 4 6
> testFunc <- function(a, b) a + b

Let's say I want to apply this testFunc to columns x and z.  So, for row 1 I want 1+5, and for row 2 I want 2 + 6.  Is there a way to do this without writing a for loop, maybe with the apply function family?
I tried this:
> df[,c('x','z')]
  x z
1 1 5
2 2 6
> lapply(df[,c('x','z')], testFunc)
Error in a + b : 'b' is missing

But got error, any ideas?
EDIT: the actual function I want to call is not a simple sum, but it is power.t.test.  I used a+b just for example purposes.  The end goal is to be able to do something like this (written in pseudocode):
df = data.frame(
    delta=c(delta_values),
    power=c(power_values),
    sig.level=c(sig.level_values)
)

lapply(df, power.t.test(delta_from_each_row_of_df,
                        power_from_each_row_of_df,
                        sig.level_from_each_row_of_df
))

where the result is a vector of outputs for power.t.test for each row of df.

A: Here is an alternate approach.  It is more intuitive.
One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data
operations on columns are possible still for dataframes:
as.data.frame(lapply(df, myFunctionForColumn()))

To operate on rows, we make the transpose first.
tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))

The downside is that I believe R will make a copy of your data table.
Which could be a memory issue.  (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)
Also, a related question, is how to operate on each individual cell in a dataframe.
newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))

A: data.table has a really intuitive way of doing this as well:
library(data.table)

sample_fxn = function(x,y,z){
    return((x+y)*z)
}

df = data.table(A = 1:5,B=seq(2,10,2),C = 6:10)
> df
   A  B  C
1: 1  2  6
2: 2  4  7
3: 3  6  8
4: 4  8  9
5: 5 10 10

The := operator can be called within brackets to add a new column using a function
df[,new_column := sample_fxn(A,B,C)]
> df
   A  B  C new_column
1: 1  2  6         18
2: 2  4  7         42
3: 3  6  8         72
4: 4  8  9        108
5: 5 10 10        150

It's also easy to accept constants as arguments as well using this method:
df[,new_column2 := sample_fxn(A,B,2)]

> df
   A  B  C new_column new_column2
1: 1  2  6         18           6
2: 2  4  7         42          12
3: 3  6  8         72          18
4: 4  8  9        108          24
5: 5 10 10        150          30

A: @user20877984's answer is excellent. Since they summed it up far better than my previous answer, here is my (posibly still shoddy) attempt at an application of the concept:
Using do.call in a basic fashion:
powvalues <- list(power=0.9,delta=2)
do.call(power.t.test,powvalues)

Working on a full data set:
# get the example data
df <- data.frame(delta=c(1,1,2,2), power=c(.90,.85,.75,.45))

#> df
#  delta power
#1     1  0.90
#2     1  0.85
#3     2  0.75
#4     2  0.45

lapply the power.t.test function to each of the rows of specified values:
result <- lapply(
  split(df,1:nrow(df)),
  function(x) do.call(power.t.test,x)
)

> str(result)
List of 4
 $ 1:List of 8
  ..$ n          : num 22
  ..$ delta      : num 1
  ..$ sd         : num 1
  ..$ sig.level  : num 0.05
  ..$ power      : num 0.9
  ..$ alternative: chr "two.sided"
  ..$ note       : chr "n is number in *each* group"
  ..$ method     : chr "Two-sample t test power calculation"
  ..- attr(*, "class")= chr "power.htest"
 $ 2:List of 8
  ..$ n          : num 19
  ..$ delta      : num 1
  ..$ sd         : num 1
  ..$ sig.level  : num 0.05
  ..$ power      : num 0.85
... ...

A: I came here looking for tidyverse function name - which I knew existed. Adding this for (my) future reference and for tidyverse enthusiasts: purrrlyr:invoke_rows (purrr:invoke_rows in older versions).
With connection to standard stats methods as in the original question, the broom package would probably help.

A: Use mapply
> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
> df
  x y z
1 1 3 5
2 2 4 6
> mapply(function(x,y) x+y, df$x, df$z)
[1] 6 8

> cbind(df,f = mapply(function(x,y) x+y, df$x, df$z) )
  x y z f
1 1 3 5 6
2 2 4 6 8

A: If data.frame columns are different types, apply() has a problem.
A subtlety about row iteration is how apply(a.data.frame, 1, ...) does
implicit type conversion to character types when columns are different types;
eg. a factor and numeric column. Here's an example, using a factor
in one column to modify a numeric column:
mean.height = list(BOY=69.5, GIRL=64.0)

subjects = data.frame(gender = factor(c("BOY", "GIRL", "GIRL", "BOY"))
         , height = c(71.0, 59.3, 62.1, 62.1))

apply(height, 1, function(x) x[2] - mean.height[[x[1]]])

The subtraction fails because the columns are converted to character types.
One fix is to back-convert the second column to a number:
apply(subjects, 1, function(x) as.numeric(x[2]) - mean.height[[x[1]]])

But the conversions can be avoided by keeping the columns separate
and using mapply():
mapply(function(x,y) y - mean.height[[x]], subjects$gender, subjects$height)

mapply() is needed because [[ ]] does not accept a vector argument. So the column
iteration could be done before the subtraction by passing a vector to [],
by a bit more ugly code:
subjects$height - unlist(mean.height[subjects$gender])

A: A really nice function for this is adply from plyr, especially if you want to append the result to the original dataframe.  This function and its cousin ddply have saved me a lot of headaches and lines of code!
df_appended <- adply(df, 1, mutate, sum=x+z)

Alternatively, you can call the function you desire.
df_appended <- adply(df, 1, mutate, sum=testFunc(x,z))

A: New answer with dplyr package
If the function that you want to apply is vectorized,
then you could use the mutate function from the dplyr package:
> library(dplyr)
> myf <- function(tens, ones) { 10 * tens + ones }
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mutate(x, value = myf(tens, ones))
  hundreds tens ones value
1        7    1    4    14
2        8    2    5    25
3        9    3    6    36

Old answer with plyr package
In my humble opinion,
the tool best suited to the task is mdply from the plyr package.
Example:
> library(plyr)
> x <- data.frame(tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
  tens ones V1
1    1    4 14
2    2    5 25
3    3    6 36

Unfortunately, as Bertjan Broeksema pointed out,
this approach fails if you don't use all the columns of the data frame
in the mdply call.
For example,
> library(plyr)
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
Error in (function (tens, ones)  : unused argument (hundreds = 7)

A: You can apply apply to a subset of the original data.
 dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
 apply(dat[,c('x','z')], 1, function(x) sum(x) )

or if your function is just sum use the vectorized version:
rowSums(dat[,c('x','z')])
[1] 6 8

If you want to use testFunc
 testFunc <- function(a, b) a + b
 apply(dat[,c('x','z')], 1, function(x) testFunc(x[1],x[2]))

EDIT To access columns by name and not index you can do something like this:
 testFunc <- function(a, b) a + b
 apply(dat[,c('x','z')], 1, function(y) testFunc(y['z'],y['x']))

A: Others have correctly pointed out that mapply is made for this purpose, but (for the sake of completeness) a conceptually simpler method is just to use a for loop.
for (row in 1:nrow(df)) {
    df$newvar[row] <- testFunc(df$x[row], df$z[row])
}

A: Many functions are vectorization already, and so there is no need for any iterations (neither for loops or *pply functions).  Your testFunc is one such example.  You can simply call:
  testFunc(df[, "x"], df[, "z"])

In general, I would recommend trying such vectorization approaches first and see if they get you your intended results.

Alternatively, if you need to pass multiple arguments to a function which is not vectorized, mapply might be what you are looking for:
  mapply(power.t.test, df[, "x"], df[, "z"])

A: A data.frame is a list, so ...
For vectorized functions do.call is usually a good bet. But the names of arguments come into play. Here your testFunc is called with args x and y in place of a and b. The ... allows irrelevant args to be passed without causing an error:
do.call( function(x,z,...) testFunc(x,z), df )

For non-vectorized functions, mapply will work, but you need to match the ordering of the args or explicitly name them:
mapply(testFunc, df$x, df$z)

Sometimes apply will work - as when all args are of the same type so coercing the data.frame to a matrix does not cause problems by changing data types. Your example was of this sort.
If your function is to be called within another function into which the arguments are all passed, there is a much slicker method than these. Study the first lines of the body of lm() if you want to go that route.


text:
Q: Save and restore instance state of an Activity manually I have a download activity in my app, where users can download some content. The activity is called from the main activity, and retrieves the list of available files to download over the network.
To avoid fetching the whole list again when the download activity is recreated e.g. because of rotation, I override onSaveInstanceState() to store the list in a Bundle and evaluate the Bundle passed to the onCreate() method. That works well for rotation.
However, I would like to be able to implement the same behavior if the user hits Back and later returns to the download activity. Android in this case does not call onSaveInstanceState(), hence nothing gets saved.
My idea was to override onBackPressed() and include a call to onSaveInstanceState().

*

*Will this work at all?

*Can I just do onSaveInstanceState(new Bundle()), or do I have to initialize the new bundle somehow?

*Will Android store the bundle and pass it to onCreate() for the next instance of the Activity it creates, or do I have to take care myself of storing the Bundle and passing it to the new instance (if so, how)?

UPDATE:
Simply adding
@Override
public void onBackPressed() {
    onSaveInstanceState(new Bundle());
    super.onBackPressed();
}

gives me the following exception:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
for the call to onBackPressed(). (Swapping the two lines does nothing, presumably because there is nothing left to save.)

A:
Will this work at all?

No.

Will Android store the bundle and pass it to onCreate() for the next instance of the Activity it creates

No.

do I have to take care myself of storing the Bundle and passing it to the new instance (if so, how)?

No.
Store your model data in a file or database, with a process-level cache (e.g., a custom singleton) to minimize disk I/O. Load your data out of the cache where available, or reload it from disk if needed.

A: I finally came up with the solution described below.
A word on usage: this will keep the state of the download activity in main memory, where it will occupy space. Also, Android may kill a background app at any time, typically if it runs low on memory. If that happens, the state information will be lost.
For my particular use case I decided I could live with these limitations: the state information written by my app is in the kilobyte range, and if the state information is lost, it can be recreated (it just takes time to fetch the list from the server). YMMV.
In the onStop() method of the download activity, do:
Bundle outState = new Bundle();
this.onSaveInstanceState(outState);

Store outState in a place where it can be retrieved when needed. In my case, the BroadcastReceiver which processes the download manager events was the place to put it.
To bring up the Activity from the BroadcastReceiver, do the following:
Intent downloadIntent = new Intent(context, DownloadActivity.class);
downloadIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
downloadIntent.putExtra("savedInstanceState", savedInstanceState);
context.startActivity(downloadIntent);

In the onCreate() method of the download activity, do:
@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle state = savedInstanceState;
    if (state == null)
        state = this.getIntent().getBundleExtra(Const.KEY_SAVED_INSTANCE_STATE);
    super.onCreate(state);
}


text:
Q: Is it undefined behavior to redeclare a variable within enclosed scope? #include <iostream>
using namespace std;

int main() {
    int i = 0;
    if(true) {
        int i = 5;
        cout << i << '\n';
    }
    return 0;
}

Tried running the above code on Ideone to see if its legal. The results perplex me:

*

*We have a compilation error (1), (2)

*Or this code prints 5 as expected (1)

*Or it prints nothing (1), (2)
As you can see from my links this same code behaves radically differently each time it is compiled on Ideone! This smells like undefined behavior (UB).
OK C++ is known for its unintuitive behaviors BUT! - I admit its just my intuition but I wouldn't expect even C++ to make redeclaring a variable in an inner scope UB! Id expect either shadowing or mandatory compilation error.
Is my code really UB according to the C++ standard, or is it just a peculiarity of Ideone and/or gcc? If its UB, is it UB because I redeclared i or for some other reason I'm failing to notice now?

A:
Is it UB to redeclare a variable within enclosed scope?

No, it is not.
The compiler error you are seeing is most likely caused by the fact that the outer i is declared but not used.
Otherwise, your code is just fine.
It works fine for me at https://ideone.com/AwVJqZ as well as my desktop.

A: There is no undefined behavior, the standard allows name hiding, it is covered in [basic.scope.hiding]:

A declaration of a name in a nested declarative region hides a declaration of the same name in an enclosing declarative region; see [basic.scope.declarative] and [basic.lookup.unqual].

and [basic.scope.declarative] says:

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.
  In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
  To determine the scope of a declaration, it is sometimes convenient to refer to the potential scope of a declaration.
  The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name.
  In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (containing) declarative region.

and gives the following example:

[ Example: In
int j = 24;
int main() {
  int i = j, j;
  j = 42;
}

the identifier j is declared twice as a name (and used twice). The
  declarative region of the first j includes the entire example. The
  potential scope of the first j begins immediately after that j and
  extends to the end of the program, but its (actual) scope excludes the
  text between the , and the }. The declarative region of the second
  declaration of j (the j immediately before the semicolon) includes all
  the text between { and }, but its potential scope excludes the
  declaration of i. The scope of the second declaration of j is the same
  as its potential scope. — end example  ]

Why you see such variable results from IDEone, I don't know. It does not provide a lot of knobs for figuring out what is going on. Wandbox is one of several alternatives that provide a lot of knobs and does not exhibit the same variability for this case.


text:
Q: jstl c:set is not working on js code in jsp file I have a JSON from a service. I am appending a html block by JSON value and I have to check some values for appropriate display.
I am trying to set discountValue variable but it not working with js variable. How can I solve it?
  if (data!="")
                {
                    $.each(data,function(index,element){
                        var intDiscount=parseInt(10);
                        console.log("intDiscount::"+intDiscount);

                        var strIndex='';
                        strIndex+='
';
                        strIndex+='<c:set var="discountValue" value="'+intDiscount+'"/>';
                        console.log("${discountValue}");
...
...
...
...
                 }
                 $('#visilabs-FavouriteCategoryTopSeller').append(strIndex);

Console log:
intDiscount::10
0

A: I have solved it with using if condition with js:
if(element.discount>0){
                            strIndex+=                      '           '+'% '+intDiscount+'';
                        }

Thanks everyone


text:
Q: launch4j: "The process cannot access the file..." I just upgraded to Win 7, and now my launch4j setup isn't working anymore.
Clues?
Using the launch file below, I get these errors:
 [exec] launch4j: Compiling resources
 [exec] launch4j: Linking
 [exec] launch4j: Wrapping
 [exec] launch4j: H:\Documents\QueryAnalyzerFaker\QueryAnalyzerFaker\.\batchexport.exe (The process cannot access the file because it is being used by another process)
 [exec] launch4j: java.io.FileNotFoundException: H:\Documents\QueryAnalyzerFaker\QueryAnalyzerFaker\.\batchexport.exe (The process cannot access the file because it is being used by another process)

Here's the launch configuration
<launch4jConfig>
  <dontWrapJar>false</dontWrapJar>
  <headerType>console</headerType>
  <jar>.\batchexport.jar</jar>
  <outfile>.\batchexport.exe</outfile>
  <errTitle></errTitle>
  <cmdLine></cmdLine>
  <chdir></chdir>
  <priority>normal</priority>
  <downloadUrl>http://java.com/download</downloadUrl>
  <supportUrl></supportUrl>
  <customProcName>false</customProcName>
  <stayAlive>false</stayAlive>
  <manifest></manifest>
  <icon>.\1326449361_table_money.ico</icon>
  <jre>
    <path>C:\Program Files (x86)\Java\jre6</path>
    <minVersion>1.6.0</minVersion>
    <maxVersion></maxVersion>
    <jdkPreference>jreOnly</jdkPreference>
    <maxHeapSize>1024</maxHeapSize>
  </jre>
</launch4jConfig>

A: The problem appears to be caused by some interference between the synchronization service for the destination drive (network drive) and launch4j.
I resolved it by building on the local c: drive, then adding an Ant target for copying the output to the desired folder on the network drive.


text:
Q: Update data from server periodically design I had a problem about how to design updater for my program. Which the best order to update data from the server? (absolutely multithreading)
Thread {
   Timer {
      result = downloaddata(url)
   }
}

or
Timer {
   Thread {
     result = downloaddata(url)
   }
}

A: And who manges the timer in the second solution? Should it be again the main thread? I would suggest the first option.
In android the Thread will be implemented in a Service.
Also, think of whether you really need periodic updates. If the changes are relatively rare, then push notifications from the server might be better solution for your needs (they will greatly reduce the number of calls to the server, thus consumed resources).

A: I suggest BroadCastereciever .. where it runs periodiacally and also in the Background.. you don't have create a Thrad there,.. and doing something in timer is not preferred because Timer is not that reliable.. IF your application goes to background it might get ended without any clue..


text:
Q: OpenLibrary.org returns blank image, how to detect and replace them? For some book covers OpenLibrary.org returns a blank image ie not a 404. Example: http://covers.openlibrary.org/b/oclc/237889032-M.jpg  How, could I go about detecting and replacing these images? Would prefer to do this in the client code but willing to do it server side if needed.
Using: Meteor/React

A: This works but is not what I was looking for. I added the following to the div containing the image element. The styling should of course be moved into a css file but for simplicity I left it inline for the answer.

    No
Cover
Image
Found

I do not consider this a good solution as it will take a lot more manual testing to make sure there are not cases where the text is visible when it should not been. However, it is a quick and dirty solution to what seems to be a some what complex problem.


text:
Q: Why do I need to specify :location=>some_url(@object) in respond_with in the case of POST I am implementing a RESTful API using RoR. Here my UsersController:
class ApplicationController < ActionController::API
    [...]
end

module Api
  module V1
    class UsersController < ApplicationController

      respond_to :json

      def create
        @user = User.new(user_params)
        @user.save
        respond_with @user, :location => api_v1_user_url(@user)
      end

      def show
        @user = User.find(params[:id])
        respond_with @user
      end

    end
  end
end

If I omit the @user param from :location => api_v1_user_url(@user) in UsersController#create i.e. I have it like so:
respond_with @user, :location => api_v1_user_url

I get the following error:
ActionController::UrlGenerationError in Api::V1::UsersController#create
No route matches {:action=>"show", :controller=>"api/v1/users", :format=>"json"} missing required keys: [:id]

I just added the @user param to api_v1_user_url on a hunch after I saw this error and it works.
My question is what is going on here? I do not understand why I need to pass @user when most of the examples I've seen do not involve passing the object @user to the :location attribute.
The output of rake routes is a follows:
$ rake routes
Ignoring bcrypt-3.1.7 because its extensions are not built.  Try: gem pristine bcrypt-3.1.7
          Prefix Verb   URI Pattern                      Controller#Action
    api_v1_users GET    /api/v1/users(.:format)          api/v1/users#index {:format=>"json"}
                 POST   /api/v1/users(.:format)          api/v1/users#create {:format=>"json"}
 new_api_v1_user GET    /api/v1/users/new(.:format)      api/v1/users#new {:format=>"json"}
edit_api_v1_user GET    /api/v1/users/:id/edit(.:format) api/v1/users#edit {:format=>"json"}
     api_v1_user GET    /api/v1/users/:id(.:format)      api/v1/users#show {:format=>"json"}
                 PATCH  /api/v1/users/:id(.:format)      api/v1/users#update {:format=>"json"}
                 PUT    /api/v1/users/:id(.:format)      api/v1/users#update {:format=>"json"}
                 DELETE /api/v1/users/:id(.:format)      api/v1/users#destroy {:format=>"json"}
    static_index GET    /static/index(.:format)          static#index
            root GET    /                                static#index

Another place I've seen this (just to name another one):

*

*Embracing REST with mind, body and soul

A: The reason being is that api_v1_user_url or api_v1_user_path are for a single instance and you need to pass the id of that user it should look for and render. Hence why you got the error you go.
In the examples you probably saw api_v1_users_url or api_v1_users_path which renders all the users. Notice the users_ vs user_


text:
Q: Prevent public access to env file I just found that Laravel 5 may output sensitive data and can lead to further exploitation of many hosts:
https://www.google.com/search?q=intext%3ADB_PASSWORD+ext%3Aenv&gws_rd=ssl
I want to know the way to secure my .env file. Can I use below code in .htaccess file to protect my .env file from browser view?
# Protect .env
<Files .env>
Order Allow,Deny
Deny from all
</Files>

Will my above code in .htaccess work and protect my .env file?

A: This isn't a vulnerability, and isn't even remotely an issue provided someone installs Laravel correctly - the webroot is the public folder, not the repository/project root.
The config files and .env file in laravel are not contained in the webroot, therefore you only need to ensure your webroot is path/to/project/public.
The google query you provided is literally just a bunch of people who didn't read the documentation before installing Laravel.

A: If you execute the
config:cache

command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null.
so in the live server, you can delete .env file after you execute config:cache command

A: Hello you can create a

.htaccess

file at the same place and write the below code.
# Disable index view
Options -Indexes

# Hide a specific file
<Files .env>
    Order allow,deny
    Deny from all
</Files>

A: IMHO best way to protect a config file from browsing is to put it outside of the public dir. Protecting it via .htaccess could be deceptive, if something fails your file will become publicly available.

A: I'd like to point out your solution only helps on shielding the actual .env file. When enabling debug mode, while using the Whoops handler (and other error handlers possibly as well), the environment variables will also be shown to the visitor when an error occurs (this can even be a 404).
To sum up what others have said in this thread. An .env file is a security issue if:

*

*You've installed laravel inside the publicly available directory, this can be public, www or public_html for instance. Make sure the folder public, contained in the laravel installation is the only folder made public through the webserver. Alternatively you can protect the .env file using .htaccess; but that's not an actual solution.

*You've enabled debug mode and the error handler shows a debug mode with all environment variables. Disable debug mode or configure it so it will only be enabled for specific users or ips. This prevents sharing environment variables on debug pages.

A: This worked for me. Just go into the root folder (using SSH terminal).
cd ./youre_project

After chmod 700 .env
If you try to access .env  file from public url you will got:
https://youre_profject.com/.env

Forbidden
You don't have permission to access this resource.


text:
Q: Convergence in distribution and normality of the limit Let $Z=(Z_1,Z_2)$ be a bivariate standard normal vector and $Y_{1,n},Y_{2,n}$ two sequences of real valued random variables with finite variance such that $Y_{1,n}\xrightarrow{d}Z_1$ and $Y_{2,n}\xrightarrow{d}Z_2$ (in distribution) for $n\rightarrow\mathbb{N}$. Assume further that
\begin{align*} \operatorname{E}\left[Y_{1,n}\right]=\operatorname{E}\left[Y_{2,n}\right]=\operatorname{E}\left[Z_1\right]=\operatorname{E}\left[Z_2\right]=0 ,\end{align*}
\begin{align*} \operatorname{Var}\left(Y_{1,n}\right)\xrightarrow{n\rightarrow\infty}1, \operatorname{Var}\left(Y_{2,n}\right)\xrightarrow{n\rightarrow\infty}1\end{align*} and
\begin{align*}
\operatorname{Cov}\left(Y_{1,n},Y_{2,n}\right)\xrightarrow{n\rightarrow\infty}\operatorname{Cov}\left(Z_1,Z_2\right).\end{align*} Does now hold that
\begin{align*}
\left(Y_{1,n},Y_{2,n}\right)\xrightarrow{d}\left(Z_1,Z_2\right)
\end{align*}for $n\rightarrow\infty$?

A: This is not even true for constant sequences. If $Y_{1,n} := Y_1$ is a Normal(0,1) random variable, and $Y_{2,n} = BY =: Y_2$ where B is a Bernoulli(1/2) random variable (taking values in $\{1,-1\}$), then this sequence satisfies all the convergence hypotheses since the sequences are constant in $n$.
We have that $Cov(Y_1, Y_2) = 0$, but the vector fails to be a bivariate normal distribution. You can see their distribution here. So they can't converge to the Normal$(diag(1,1))$
bivariate normal distribution.


text:
Q: Flask Application returning ImportError: No module named user_auth.views I'm in the beginning stages of a Flask application. The problems I'm having is that whenever I attempt to run the application I get:
app/application/___init___.py, line 11 in <module>
from user_auth.views import auth
ImportError: No module named user_auth.views

I have no idea what the problem is. The import for the home.view did this as well, then it stopped and worked fine on the local server. Been trying to figure this out for the longest, there aren't that many moving parts in the application as of yet, so not sure why this is happeninng. File structure and code below:
|app
|-application
|--__ init __.py
|--home
|--user_auth
|----forms.py
|----views.py
|----templates
|----static
My application/__ init __.py file:
from flask import Flask

app = Flask(__name__)

app.config.from_object('_config')

from home.views import home
from user_auth.views import auth

app.register_blueprint(home)
app.register_blueprint(auth)

My application/user_auth/views.py
from flask import Blueprint

auth = Blueprint('auth', __name__,
                    url_prefix='/user_auth',
                    template_folder='templates',
                    static_folder='static')

A: You're missing an __init__.py file under ./user_auth/ to make user_auth a module.
There's more information about modules in the docs.


text:
Q: How can I give specific number by group of identical values in a select clause? I have this :

Person
Dinner

Paul
Apple

Alfred
Banana

John
Apple

Jimmy
Banana

Johnny
Strawberry

I want to give a specific number for each distinct value in the Dinner column in a select clause like this :

Person
Dinner
Group

Paul
Apple
1

Alfred
Banana
2

John
Apple
1

Jimmy
Banana
2

Johnny
Strawberry
3

I tried this get the groups :
SELECT case when (lag(Dinner) OVER (ORDER BY id) = Dinner) or (lead(Dinner) OVER (ORDER BY Dinner) = Dinner) then 1 else 0 end,* FROM restaurant ORDER BY Dinner desc)

And it gives me this :

Person
Dinner
Group

Paul
Apple
1

John
Apple
1

Alfred
Banana
0

Jimmy
Banana
0

Johnny
Strawberry
1

It only gives me 1 or 0 because of the case when case.
I'm pretty sure there's easier way to do it, but I didn't find any.
Any help ?

A: Why not use DENSE_RANK?
SELECT Person,
       Dinner,
       DENSE_RANK() OVER (ORDER BY Dinner ASC) AS [Group]
FROM (VALUES('Paul','Apple'),
            ('Alfred','Banana'),
            ('John','Apple'),
            ('Jimmy','Banana'),
            ('Johnny','Strawberry'))V(Person, Dinner);


text:
Q: Unable to use File.WriteAllBytes() in asp.net MVC, cannot choose method from method group did you intend to invoke the method? I'm trying to create a copy of a file i have in my database as a byte array, I'm looking for the easiest way to do this, and on SO and everywhere else the answer seems to be:
File.WriteAllBytes(string newfilepath, byte[] theFile);
However I'm unable to use pretty much anything from the File class, and as soon as I type in File. intellisense draws a red line underneath it and says:
cannot choose method from method group did you intend to invoke the method?
I realise this is a very generic question, and the solution is most probably a very simple one, but I can't figure it out for the life of me. Any ideas?
And here is the code where I try to create the file:
    var labProcessOrderLetter = from obj1 in context.LabArticles
                                join obj2 in context.ProcessLabs
                                on obj1.ProcessForLabID equals obj2.ID
                                where obj1.ID == _articleId
                                select obj2.LetterAttachment;

    byte[] thePDFLetter = (byte[]) labProcessOrderLetter.FirstOrDefault();

    var uploadPath = Server.MapPath("~/_TEMP/PDF");
    var tempfilename = Guid.NewGuid().ToString();
    var tempfilenameandlocation = Path.Combine(uploadPath, Path.GetFileName(tempfilename));

    File.WriteAllBytes( tempfilenameandlocation, thePDFLetter);

EDIT: Obviously I have already imported the System.IO namespace, and nowhere in my project I have a method or class called File, or even beginning with File.

A: It sounds like you have a method that's visible to you (in the same class, say) called File. This will be chosen in preference to System.IO.File. So you need to fully qualify the name:
System.IO.File.WriteAllBytes(tempfilenameandlocation, thePDFLetter);

(In fact, enough clues were in the question. It's Controller.File that's in scope)

A: A controller has a File already defined, for outputting files in a nice way. Just fully qualify it with System.IO.File


text:
Q: how can I do from px to vh in array js var states = [{ $zIndex: 4, width: 568, height: 568, top: 0, left: 0, $opacity: 1 },]

I want the width to be 100vh
I tried doing vh next to the number but error occurs

A: Pass the width as a string. Eg width: "100vh"

A: Try using width: '100vh'
var states = [{ $zIndex: 4, width: '100vh', height: 568, top: 0, left: 0, $opacity: 1 },]


text:
Q: polynomial ring, and some kind of algebraic number over the ring. Let $k$ be a field, consider the ring $ k[X,Y]/(X^2-Y^3) $ I was proving something but I need to prove the existence of an element in the ring of fractions of $ k[X,Y]/(X^2-Y^3) $  such that satisfy a monic polynomial with coefficients in $ k[X,Y]/(X^2-Y^3) $ , but an element that does not belong to the ring $ k[X,Y]/(X^2-Y^3) $. How Can I find that element?

A: The element  $x/y\in \operatorname {Frac} (k[x,y])=\operatorname {Frac}(k[X,Y]/(X^2-Y^3)) \:$  satisfies  $T^2-y=0$.


text:
Q: How do i compile a static library (fat) for armv6, armv7 and i386 I know this question has been posed several times, but my goal is slightly different with regard to what I have found searching the web. Specifically, I am already able to build a static library for iPhone, but the final fat file I am able to build only contains arm and i386 architectures (and I am not sure to what arm refers: is v6 or v7?). I am not able to compile specifically for armv6 and armv7 and them merge both architectures using lipo. The lipo tool complains that the same architecture (arm, not armv6 or armv7) is present in both the armv6 and armv7 libraries.
Can someone explain exactly how to build for armv6 and armv7, and them merge these libraries into a fat file using lipo?
EDIT: I need to build not using Xcode but compiling directly a traditional unix library.

A: Just use libtool to link the two arm6 and arm7 versions together - its what XCode does. However you will have problems if you try to combine these static libraries into a new super-library. If you need to do that then read this.
If you are doing this already, that would be why lipo is complaining that your "armv6" library contains both armv6 and armv7. My post has a fix that will probably be easier for you since you don't use XCode, but basically you use lipo -extract to make sure you have a thin armv6 library and a thin armv7 library before you go any further.

A: There doesn't seem to be a need to extract from the fat library before rejoining any more (as described in jamie's answer). I'm using the final 4.0 SDK from apple, which appear to create the fat armv6/armv7 libraries by default.
I was previously specifying the architecture for the input lib like so:
$DEVROOT/usr/bin/lipo -arch arm $PROJECT_DIR/buildlib/Release-iphoneos/lib.a -arch i386 $PROJECT_DIR/buildlib/Release-iphonesimulator/lib.a -create -output $PROJECT_DIR/buildlib/lib.a

This fails on the later SDKs, but removing the architecture from the (now fat) arm lib works fine:
$DEVROOT/usr/bin/lipo $PROJECT_DIR/buildlib/Release-iphoneos/lib.a -arch i386 $PROJECT_DIR/buildlib/Release-iphonesimulator/lib.a -create -output $PROJECT_DIR/buildlib/lib.a

Lipo must now be able to detect the architectures in the fat libraries.

A: Make sure to have your build settings set to Valid Architectures: armv6 armv7 and Architectures: Optimized (armv6 armv7). This should result in a binary optimized for both v6 & v7. If you're not sure it worked out, just set the Architectures: Standard (armv6) and compare the file sizes. Optimized should produce double the size (when I remember rightly).
You also always can use lipo -info on your binary to see all the included architecures.
Running it on a distribution build of my app gives me:
ullrich ~/Code/.../build/Distribution-iphoneos/My.app (streaming)$ lipo -info My
Architectures in the fat file: My are: armv6 armv7

A: Here is a good solution I found: Static Libs With Support to iOS 5 and Arm64
Edited:
The solution is to build different architectures separated then bind them using lipo, by using command line (or Rakefile).
First build the binary with arm using xcodebuild:
xcodebuild -project 'StaticLibDemo.xcodeproj' -configuration 'Release' -sdk 'iphoneos7.0' clean build ARCHS='armv7 armv7s' IPHONEOS_DEPLOYMENT_TARGET='5.0' TARGET_BUILD_DIR='./build-arm' BUILT_PRODUCTS_DIR='./build-arm'

Note that you must set IPHONEOS_DEPLOYMENT_TARGET='5.0' and ARCHS='armv7 armv7s', it's recommended to set build and product dirs to make the things more clear, take a look at Build Setting Reference for more details what this flags means.
Next build for arm64:
xcodebuild -project 'StaticLibDemo.xcodeproj' -configuration 'Release' -sdk 'iphoneos7.0' clean build ARCHS='arm64' IPHONEOS_DEPLOYMENT_TARGET='7.0' TARGET_BUILD_DIR='./build-arm64' BUILT_PRODUCTS_DIR='./build-arm64'

Note the difference on ARCHS and IPHONEOS_DEPLOYMENT_TARGET. We also need to build for simulator, in this case we have to change the sdk to iphonesimulator7.0 and build in two steps first for i386:
xcodebuild -project 'StaticLibDemo.xcodeproj' -configuration 'Release' -sdk 'iphonesimulator7.0' clean build ARCHS='i386' IPHONEOS_DEPLOYMENT_TARGET='5.0' TARGET_BUILD_DIR='./build-i386' BUILT_PRODUCTS_DIR='./build-i386'

Now the tricky part! If you just change the ARCHS to x86_86 depending on your Xcode setting you will got an error like: "x86_64 is not a valid arch". To avoid this just add VALID_ARCHS='x86_64':
xcodebuild -project 'StaticLibDemo.xcodeproj' -configuration 'Release' -sdk 'iphonesimulator7.0' clean build ARCHS='x86_64' VALID_ARCHS='x86_64' IPHONEOS_DEPLOYMENT_TARGET='7.0' TARGET_BUILD_DIR='./build-x86_64' BUILT_PRODUCTS_DIR='./build-x86_64'

Finally we just have to create a fat binary with all the 5 architectures:
lipo -create './build-arm/libStaticLibDemo.a' './build-arm64/libStaticLibDemo.a' './build-i386/libStaticLibDemo.a' './build-x86_64/libStaticLibDemo.a' -output 'libStaticLibDemo.a'

The author created a working example of this, you can get it: https://github.com/diogot/StaticLibDemo

Here is the Link to the post: Static Libs With Support to iOS 5 and Arm64
All credits go to Diogo Tridapalli.


text:
Q: Dynamically add inputs with their own ng-models I have a need for users to be able to add new account codes to a form, and have the ability to alter each individual code before sending the form to the server. My markup looks like this:

<md-content id="acctCodeSection{{$index}}" ng-repeat="amt in acctCodeSegments">

  <md-content>

    <md-input-container>
      FF
      <input ng-model="userInputAcctCodes.ff" class="aCodesInputs" maxlength="2" auto-advance />
    </md-input-container>

    <md-input-container>
      XXXX
      <input ng-model="userInputAcctCodes.program" class="aCodesInputs" maxlength="4" auto-advance />
    </md-input-container>

  </md-content>

</md-content>

<md-content>
  <md-button ng-click="copyAcctCode()">Add</md-button>
</md-content>

The ng-repeat here is tied to an array in the controller, which is iterated via a function:
$scope.acctCodeSegments = [1];
$scope.codeHolder = [];
$scope.userInputAcctCodes = {
  ff: '', program: ''
};

//'Add button functionality'
$scope.copyAcctCode = function(){

  //Add new acct code segment to markup
  let addIndex = $scope.acctCodeSegments.slice(-1)[0]+1;
  $scope.acctCodeSegments.push(addIndex);

  let acData = $scope.userInputAcctCodes;

  //Push current model values to holding array
  $scope.codeHolder.push({
    ff: acData.ff, type: acData.program
  };

  //Wipe original model
  $scope.userInputAcctCodes = {
     ff: '', program: ''
  };
};

What I'm struggling to come up with is an decent way to make the original markup use the model data that is pushed to the codeHolder array, while the new markup uses the original data model. Basically I need a way to alter the ng-models in each input tag. I could probably do this with Jquery, but that would get really messy and horrible really quick.
I concede that my approach here may not be the best way either, as its about my 5th attempt at refining how it's done :)
Does anyone have any ideas for how to accomplish this?

A: If you change ng-model of your inputs with the following
<md-content id="acctCodeSection{{$index}}" ng-repeat="amt in acctCodeSegments">

  <md-content>
    <md-input-container>
      FF
      <input ng-model="amt.ff" class="aCodesInputs" maxlength="2" auto-advance />
    </md-input-container>
    <md-input-container>
      XXXX
      <input ng-model="amt.program" class="aCodesInputs" maxlength="4" auto-advance />
    </md-input-container>
  </md-content>

</md-content>

it would enable you to alter the ng-models in each input tag. You can easily add a new row by pushing a new item to your acctCodeSegments array.


text:
Q: Import error for my compiled truffle contract in my app.js I'm getting a compilation error

"./src/App.js Module not found: You attempted to import
  ../../build/contracts/Lottery.json which falls outside of the project
  src/ directory. Relative imports outside of src/ are not supported.
  You can either move it inside src/, or add a symlink to it from
  project's node_modules/."

My project is using the react truffle box.
In my app.js I imported my Lottery.json file which is in my contract like this:
import Lottery from '../../build/contracts/Lottery.json';

I got the Lottery.json file in my build folder by running the truffle compile command
Any idea why my Lottery.json file is not being imported into my frontend?
Thanks!


text:
Q: I want to increment a cell reference of a formula I have a sheet with player names that change every 19 rows and I want to be able to quickly drag the row down and have it auto paste the formula with it adding 19 rows and pasting the data in for that row.
"Sheet 1"
B2 - =Sheet2!B2
B3 - =Sheet2!B21

and I want to drag the formula in B2 down as many times and it makes the formula essentially,
B29 - =Sheet2!B517

I've attached a sample sheet for reference.
https://docs.google.com/spreadsheets/d/1tyJfjO5tErGSPBQaLswagHCy8mhJf7m9QM7ZJyU2I68/edit?usp=sharing
Are there any formulas I can plug in or shortcuts to use and cut down the time by not having to manually add 19?
Thank you

A: Use the OFFSET function.
For your example, you could use
=OFFSET(Sheet2!$B$2,(ROW()-2)*19,0)

This will result in the cell references you want with the caveat that the formulas won't be as transparent as bare cell references.
If you want to customize this for other uses, just know that the ROW() function returns the row number of the cell that holds the formula. Because your first formula is in row 2, I used (ROW()-2) as the factor of 19 to ensure that there is no offset on the first formula (just Sheet2!$B$2). For the next row (3), the formula will return Sheet2!B2 offset by 1*19 rows. The next will be offset by 2*19 rows, etc.


text:
Q: Создание эффекта печатной машинки Здравствуйте.
Недавно я решил вернуться к обучению С++, но так как уровень моих знаний катастрофически низок, я снова пришел сюда :) Сегодня хочу попробовать сделать что-то вроде печатной машинки. Звучит громко, но объясню в чём суть. Консольное приложение на С++. Пользователь вводит свой текст, а после этого поле очищается и компьютер начинает печатать текст с интервалом в четверть (к примеру) секунды между символами.
Так как пришел я сюда, чтоб учиться, попробую высказать свои идеи. Из того, что я знаю, тут нужен Sleep, скорее всего использование массивов и циклов. Вроде как это должно быть несложно. В голове у меня промелькнула идея о том, что каждый символ из текста должен вноситься в массив. Или заменять переменную. То есть символом текста каждый раз заменяется значение переменной, а с интервалом в четверть секунды оно выводится на экран, пока есть символы во введенном тексте.
Буду благодарен тем, кто поможет немного разобраться, а лучше подтолкнет к решению.
UPDATE
 #include <iostream>

#include <Windows.h>
using namespace std;

int main()
{
    char string str[];
    cout << "Type your text";
    cin >> str;
    for (int i = 0; i<=str.Length - 1; i++)
    {
        cout << str[i];
        Sleep(200);
    }
    system("pause");
}

Вот что вышло у меня. Это выдает ошибки. Что здесь неправильно?
A: Вместо
char string str[];

напишите просто
string str;

А вместо
str.Length

str.length()

Перед дальнейшими вопросами рекомендую почитать этот ресурс.
A: Спасибо за комментарии. Кроме того, что ответил avp (спасибо за ресурс) нужно было дописать ещё и #include <string>
A: #include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;
int main()
{
    string str;
    cout << "Enter the String: " << endl;
    getline(cin, str);

    for (int i = 0; i <= str.length() - 1; i++)
    {
        cout << str[i];
        Sleep(200);
    }
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}

Вот так выглядит. Я тоже ради интереса решил сделать. То, что нужно =)
A: Это же легко, вот тебе на C# вариант:
static void Main(string[]args)
{
    Console.WriteLine("Введите строку");
    string str = Console.ReadLine();          // считываем строку
    for (int i = 0; i <= str.Length - 1; i++) // запускаем цикл до тех пор, пока не будет достигнут последний символ нашей строки
    {
        Console.Write(str[i]);    // выводим 1 символ, с каждой итерацией он возрастает, и выводится следующая буква
        Thread.Sleep(300);        // засыпаем на 0.3 секунды.
    }
    Console.Read();               // ждем нажатия клавиши
}


text:
Q: How to implement consumption peer to peer with sarama library? Now, I try to use Shopify/sarama library(kafka go client) to implement multiple consumers in the same consumer group, and I found several consumer groups with same client did not work.
I have the following testing:
Suppose the topic have 3 partitions, and the group Id is "groupId":
1. TEST1
(1)
newClient, err := sarama.NewClient(brokerList, &cfg)

(2)
group1, err := sarama.NewConsumerGroupFromClient(groupId, newClient)
group2, err := sarama.NewConsumerGroupFromClient(groupId, newClient)
group3, err := sarama.NewConsumerGroupFromClient(groupId, newClient)

The testing is try to use a kakfa client(newClient) to create multiple groups, and the program will block one group, and the other two groups will not response, it seems to block the following code:
group.Consume(ctx, strings.Split(topics, ","), consumer)
and then a moment later, the program rebalance (setup/clean up) repeatly, the result is that the consumer consumed all partitions, not each consumer consume per partition.
2. TEST2
(1)
newClient1, err := sarama.NewClient(brokerList, &cfg)
group1, err := sarama.NewConsumerGroupFromClient(groupId, newClient1)

(2)
newClient2, err := sarama.NewClient(brokerList, &cfg)
group2, err := sarama.NewConsumerGroupFromClient(groupId, newClient2)

(3)
newClient3, err := sarama.NewClient(brokerList, &cfg)
group3, err := sarama.NewConsumerGroupFromClient(groupId, newClient3)

In this testing, we can see each consumer group with a new client, the result indicates that each consumer will consume a partition, which accord with expection.
So, How I can implement multiple consumer groups bind the same kafka client, rather than creating a new client per consumer group?

A: This isn't the recommended way to run multiple consumers. Compile one Go app with only one consumer. Run three processes instead. They will rebalance by using the same consumer group, but they will no longer not block one another within the same process.


text:
Q: Precise Failure property of Half-minimum distance decoder By half min decoder, I mean a decoder that is 1) efficient 2) always corrects if there are less than or equal to d/2 errors and 3) always fails if there are more than d/2 errors. Can such hypothetical decoders exist?
Say we have a $q$-ary code of length $n$ and minimum distance $d$. If one uses a traditional half-minimum distance decoder that corrects all errors of upto $\lfloor\frac{d}{2}\rfloor$ precisely, then is the corrected vector $\underline{ALWAYS}$ wrong if the number of errors in the vector before correction is $\lfloor\frac{d}{2}\rfloor + 1$? If not, then for what fraction of error vectors beyond half min distance does the decoder always fail?

A: There are several misconceptions in your notions about what happens
with bounded-distance decoders, and especially in the case
when the number of errors is exactly equal to $\frac{d}{2}$ where $d$
is the minimum distance of the code.
Suppose that $\mathbf c$ is the transmitted codeword and $\mathbf r$
is the received word.
By definition, a $t$-error-correcting bounded-distance decoder produces the
unique codeword
$\hat{\mathbf{c}}$ (if
such a codeword exists) that is at distance $t$ or less from the received
word $\mathbf{r}$. Here, $t \leq \frac{d-1}{2}$ where $d$ is the minimum
distance of the code.

*

*If $t$ or fewer errors have occurred, then
the codeword $\hat{\mathbf{c}}$ that the decoder produces
is $\mathbf c$, and the decoder has operated exactly as we
want it to operate: it has determined the transmitted codeword
correctly.

*If $d-t$ or more errors have occurred, there might be
a different (unique) codeword $\hat{\mathbf{c}}$ that is
at distance $t$ or less from $\mathbf r$, and in this case,
the decoder will produce $\hat{\mathbf{c}}$. This event is
called a decoder error. The occurrence of such an event
is not something that the decoder can detect, and the
wrong codeword is thus sent on to its destination.

It is also possible that there is no codeword at distance $t$
or less from $\mathbf r$, and in this case, the decoder will
not produce a codeword at all, but will provide an indication
to the effect that there is no codeword at distance $t$ or less
from $\mathbf r$.

*If $t < \frac{d-1}{2}$, then in the "no-man's-land"
where the number of errors is more than $t$ and less than $d-t$,
the $t$-error-correcting bounded-distance decoder
will always fail and indicate that there is no codeword
within distance $t$ of the received word. It might be
that the actual number of errors is smaller than $\frac{d-1}{2}$
and so $\mathbf c$ is the unique codeword that is closest
to the received word $\mathbf r$. It might even be that the
decoder is able to determine that this is the case, but since
it is constrained to correct no more than $t$ errors, it
nonetheless indicates that $\mathbf r$ cannot be decoded
into a codeword at distance $t$ or less from $\mathbf r$.

*When $d$ is an even number, and exactly $\frac{d}{2}$ errors
have occurred, there might be two codewords that are at distance
$\frac{d}{2}$ from the received word: the codeword $\mathbf{c}$ actually transmitted and another codeword $\hat{\mathbf c}$. Thus, a
$\frac{d}{2}$-error-correcting bounded distance decoder does not
exist in the sense that no decoder can guarantee that
all possible patterns of $\frac{d}{2}$ or fewer errors will result in the
transmitted codeword being determined correctly.
Variations of decoders such as list decoders that produce
a list of most likely transmitted
codewords can be used in such cases,
but these are not called bounded-distance decoders
in the sense described above.


text:
Q: Turn off auto numbering in OneNote for Windows 10 Is it possible to turn off auto-numbering in the new OneNote for Windows 10? I have looked through the settings, there's an option to turn off auto-capitalisation, but nothing for this. Searched everywhere and still found no answers.
It's really annoying, because whenever I type '1. ' it automatically creates a numbered list, and there's no way to stop it. It takes a long time to get around it. It is the same for letters and with brackets, eg 'a) '.
Are there any ways to disable this setting? I like the new OneNote, and don't want to use the older 2016 version as it doesn't have some of the new features.

A: Just hit Ctrl+Z to undo the start of the list as soon as it starts it. The icon that pops up also allows you disable auto numbering if you check it's menu.

Alternatively check your options. The advanced options to have a check box for automatic numbering and adding of list bullets.


text:
Q: cannot access /dev/video*: No such file or directory So I'm working on a zynq z7000 card and I made a Linux Kernel on it. I put a Linaro as a Root File System. I managed to boot the card however I can only use mouse and keyboard usb devices. I tried webcam and flash drives but they are not working. when I use :
lsusb

I get the webcam device
...
Bus 001 Device 005: ID 046d:0805 Logitech, Inc. Webcam C300

However when I try
ls /dev/video*

I get
ls: cannot access /dev/video*: No such file or directory

I've used these configurations to build my image.

A: You need to make sure if v4l2 framework and UVC Class driver are enabled in your kernel configuration(defconfig file). Or can enable using menuconfig. Make sure the following are there:
1. CONFIG_VIDEO_V4L2=y
2. CONFIG_VIDEO_V4L2_COMMON=y
3. CONFIG_VIDEO_DEV=y
4. CONFIG_USB_VIDEO_CLASS=y


text:
Q: how to write regex for list of items sharing the same roots So I have a list of keywords:
['xxxxl','xxxl','xxl','xl','xxxxt','xxxt','xxt','xt']
In bigquery, I want to write a regex, inside the following sql code
SELECT my_column
FROM table
REGEXP_CONTAINS(lower(my_column),regex)

so that my output table contains only the values that don't match any of the items in keywords list.
Thanks

A: Below is for BigQuery Standard SQL
#standardSQL
WITH `project.dataset.lookup_table` AS (
  SELECT ['xxxxl','xxxl','xxl','xl','xxxxt','xxxt','xxt','xt'] keywords
)
SELECT my_column
FROM `project.dataset.table`,
  (SELECT STRING_AGG(LOWER(keyword), '|') exclude_pattern
  FROM `project.dataset.lookup_table`,
  UNNEST(keywords) keyword)
WHERE NOT REGEXP_CONTAINS(LOWER(my_column), exclude_pattern)

You can test / play with above using below simplified example
#standardSQL
WITH `project.dataset.lookup_table` AS (
  SELECT ['xxxxl','xxxl','xxl','xl','xxxxt','xxxt','xxt','xt'] keywords
), `project.dataset.table` AS (
  SELECT 'xxxxl' my_column UNION ALL
  SELECT 'abc'
)
SELECT my_column
FROM `project.dataset.table`,
  (SELECT STRING_AGG(LOWER(keyword), '|') exclude_pattern
  FROM `project.dataset.lookup_table`,
  UNNEST(keywords) keyword)
WHERE NOT REGEXP_CONTAINS(LOWER(my_column), exclude_pattern)

with output
Row my_column
1   abc


text:
Q: Location of user data files in iOS simulator for XCODE 4.5? With XCODE 4.5 / Mountain Lion where are the user data files for the iOS simulator stored?
Previously they were in ~/Library/Application Support/iPhone Simulator/[OS version]/Applications/[appGUID]/, but no more.
I have XCODE 4.5.1.
Help appreciated.

A: OK, the joke's on me! In this version of the OS, the folder ~/Library is hidden. The data files were there all the time.
To permanently unhide it, in Terminal enter the following command:
chflags nohidden ~/Library


text:
Q: active tab based on checkbox i have this code for tabs and what i want is that tab2 is disable by default and is only enabled if user checks checkbox1 on tab1
Any help on this?

Tab 3

Tab 2

Tab1

Testo

                                            <input type="checkbox"id="cb1"> check1

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                        Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                        when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                        It has survived not only five centuries, but also the leap into electronic typesetting,
                        remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
                        sheets containing Lorem Ipsum passages, and more recently with desktop publishing software
                        like Aldus PageMaker including versions of Lorem Ipsum.

thanks in advance

A: This method works just fine, you need to add a trigger for when the checkbox is set to check if the tab is enabled or not, removing the value from data-toggle will disabled the tab, simply add it again to enable. As shown below. To have tab 2 disabled by default, omit the value from data-toggle in the HTML directly.
I took the liberty of adding the bootstrap dependencies to this snippet assuming you have them available in your project.

function toggle_tab2() {
  if ($('#tab2').attr("data-toggle") != '') {
    $('#tab2').attr("data-toggle","");
    console.log('tab2 disabled');
  }
  else {
    $('#tab2').attr("data-toggle","tab");
    console.log('tab2 enabled');
  }
}
<link href=http://getbootstrap.com/dist/css/bootstrap.min.css rel=stylesheet>

Tab 3

Tab 2

                      Tab1

                      Testo

                                            <input type="checkbox"id="cb1" onclick="toggle_tab2();"> check1

                                                Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                                                when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                                                It has survived not only five centuries, but also the leap into electronic typesetting,
                                                remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
                                                sheets containing Lorem Ipsum passages, and more recently with desktop publishing software
                                                like Aldus PageMaker including versions of Lorem Ipsum.


text:
Q: Why doesn't flow detect my null check? Having this simple code (you can try the Flow online REPL here):
// @flow
class Foo {
  id: string
  serialNumber: number

  constructor(alpha: ?Object, beta: ?Object) {
    if (!alpha && !beta) return
    if (!alpha && beta) return
    if (alpha && !beta) return

    this.id = alpha.id // flow complains about alpha might be null or undefined
    this.serialNumber = beta.serialNumber // flow complains about beta
  }
}

From my perspective, all my possible branches should be covered with a null check. Why is flow still complaining?
Background: both params can be null. I only want to assign the values, if both parameters are defined.
I know, this can be written tighter, but I am curious why Flow isn't capable of checking this.
Interestingly, this version works:
/* @flow */
class Foo {
  id: string
  serialNumber: number

  constructor(alpha: ?Object, beta: ?Object) {
    if (!alpha || !beta) return

    this.id = alpha.id
    this.serialNumber = beta.serialNumber
  }
}


text:
Q: Windows 10 DNS issue, switching between default and custom DNS server I am having problems with my internet. The problem switches between I cannot access the internet using the default DNS settings (which I solve by setting my DNS server to Google (8.8.8.8 and 8.8.4.4)), and these settings not working and needing to switch back to the default DNS settings.
This is happening everyday. I am on Windows 10 (OS build 14393.447).
Any advice on how to fix this?

A: I enabled IPv6 and the issue went away.


text:
Q: Python loading multiple JSON values on one line I have a file (not a valid JSON file) that looks similar to this:
[[0,0,0],[0,0,0],[0,0,0]]["testing", "foo", "bar"]

These are two (or more), non-delimited, valid JSON values that I need to load in from STDIN. I tried just using the following (in Python 3.7):
for line in sys.stdin:
    stripped = line.strip()
    if not stripped: break
    x = loads(stripped)

But that gave the error
json.decoder.JSONDecodeError: Extra data: line 1 column 118 (char 117)
which makes sense, as it can only load one JSON value at a time. How would I go about loading in multiple of these values from STDIN when they are not delimited? Is there a way to check if the JSON loader successfully completed a load and then start another one from the same line?


text:
Q: level set of function f coincides with that of |▽f|,M splits? M is a complete Riemannian manifold,f is a function on M with no critical points.If the level set of f coincides with the level set of |▽f|,then M must be topologically the product RXN?

A: The hypothesis implies that $|\nabla f|^2=F(f)$ for some function $F:R\to R$ which is never zero on the image of $f:M\to R$. Then, if $G:R\to R$ is a primitive of $1/\sqrt{F}$ we have
$\nabla [G(f)]=\frac{\nabla f}{\sqrt{F(f)}}$, hence $\vert\nabla G(f)\vert=1$ and $G(f)=z:M\to R$ is a smooth solution of the "eikonal" equation on the whole $M$, hence $z$ (up to a constant) must be the "signed" distance function to a fixed sublevel $N$ of $f$.
Using "adapted" coordinates $M$ given by $(z,x_1,\dots,x_n)$, where $\{x_i\}$ are coordinates on $N$, it is well defined a correspondence between the points of any two different sublevels which is a diffeomorphism and the metric on $M$ can be written as $g(s,x)=dz^2+g_s(x)$ where $g_s$ is the metric on the sublevel $\{z=s\}$. It is then clear that topologically $M$ is the product of $R$ with $N$.