Q:

Looping through an array of strings containing approximately 3 million elements

I have a function that loops through an array of strings containing approximately 3 million lines of strings.  My problem is this loop is running too slowly and I want to know how to make it faster.
string[] words = { "Hello", "world", "!", "My", "name", "is", "Something", "."};
    List<MyClass> result = new List<MyClass>();

    for (int i = 0; i < words.Length; i++)
    {
        if (words[i] == "&&&")
        { }
        else if (words.Length > i + 2 && FileContains(words[i] + " " + words[i + 1] + " " + words[i + 2]))
        {
            result.Add(new MyClass(words[i] + " " + words[i + 1] + " " + words[i + 2]));
            words[i + 1] = "&&&";
            words[i + 2] = "&&&";
        }
        else if (words.Length > i + 1 && FileContains(words[i] + " " + words[i + 1]))
        {
            result.Add(new MyClass(words[i] + " " + words[i + 1]));
            words[i + 1] = "&&&";
        }
        else
            result.Add(new MyClass(words[i], Parent));

    }

And my FileContains function which loops through the array of strings:
public static bool FileContains(string Text)
{
    foreach (string line in ARRAYOFWORDS)  // Approximately 3 million strings
    {
        if (Text.ToLower() == line.Substring(0, line.LastIndexOf('|')))
        {
            return true;
        }
    }
    return false;
}

A:

Well you can optimize FileContains very simply - stop calling Text.ToLower() on every iteration!
In fact, at that point it's really simple to rewrite. Here's the code for the original question, which didn't have the Substring part:
public static bool FileContains(string text)
{
    // Variable name changed to save my eyes from the horror.
    return lines.Contains(text.ToLower());
}

If you store the lines in a HashSet<string> instead of an array or a list, it will be blazingly fast.
With the Substring part, I'd create a new HashSet<string> with just those substrings, assuming you want to look up more than once:
HashSet<string> lineStarts;

...

lineStarts = new HashSet<string>(lines.Select(x => x.Substring(0, x.IndexOf('|'));

Then use lineStarts within FileContains.
Note that using ToLower is a fairly crude approach to case sensitivity. You should think carefully about what this needs to do in terms of culture-sensitivity etc. See the relevant MSDN page for lots more information. (Ain't culture fun?)

A:

What is this for?  It looks like a string search function.  And you are storing the found results in an output.
As such, I recommend not using an array at all.  You should make use of string.IndexOf, which uses Boyer Moyer Search Algorithm under the hood, very fast.
Instead just make one BIG string with line breaks, for example...
string stringToSearch = "some line here\nanother line here\nand another line here\netc etc etc";

int matchIndex = 0;
while (matchIndex > -1)
{
    matchIndex = stringToSearch.IndexOf("string to search for");
    if (matchIndex > -1)
    {
        //use string functions to get matched word
    }
}

Something like that for search a string, would be astronomically faster.
You can load a file into a string in one move.  The TextReader object in the System.IO name space has a method called ReadToEnd which returns the entire file as a string with lines separated by new line characters "\n".
And, if you are dealing with a binary file, you can still search it string.IndexOf.  Just convert the binary file into a string with ASCIIEncoding.GetString(someByteArray), then convert your search for bytes to a string the same way.  Then search for the search bytes string in the converted file string.

A:

I can see a few issues here:

You are searching the array of lines for a string, then searching it again for a substring, on each iteration.  This is unnecessary.  Search for lines beginning with the substring, and for each, see if they match match either the longer or shorter string completely.
Since c# strings are immutable, any string transformation such as ToLower() or SubString() necessarily makes a transformed copy of the string.  In tight inner loops this can kill performance, so don't do this.
Consider using a HashSet<string> for your array of text.  You will need to add the substring before the last '|' for each line.  However, it's possible that building the HashSet will take longer than the searches, since you don't actually run many searches.
Consider parallelizing the searches -- though this is a little tricky, since a match on a preceding loop changes the logic on later loops (by writing the "&&&" characters into the word array).
Choose the right StringComparison for your needs.
line.Substring(0, line.LastIndexOf('|')) will throw an exception if the '|' character is not found.  Do you want this?
You lowercase the search strings but not the file lines, so if the file lines have any uppercase letters the searches will fail.  Is this desired?

Here's a prototype fix for 1, 2, 5 and 6.  It's a little gross but should be faster.  I also renamed your string array to FileLines:
    string[] words = { "Hello", "world", "!", "My", "name", "is", "Something", "." };
    List<MyClass> result = new List<MyClass>();
    StringComparison comparisonType = StringComparison.CurrentCulture; // Choose wisely.

    for (int i = 0; i < words.Length; i++)
    {
        if (words[i] == null)
            continue;
        var words3 = (words.Length > i + 2 ? words[i] + " " + words[i + 1] + " " + words[i + 2] : null);
        var words2 = (words.Length > i + 1 ? words[i] + " " + words[i + 1] : null);
        var lower3 = (words3 != null ? words3.ToLower() : null);
        var lower2 = (words2 != null ? words2.ToLower() : null);
        bool add3 = false;
        bool add2 = false;

        if (lower2 != null)
        {
            var length2 = lower2.Length;
            var length3 = (lower3 != null ? lower3.Length : -1);
            foreach (var possibleMatch in FileLines.Where(s => s.StartsWith(lower2, comparisonType)))
            {
                if (lower3 != null && possibleMatch.StartsWith(lower3, comparisonType) && MatchesLength(possibleMatch, length3))
                {
                    add3 = true;
                    break;
                }
                else if (!add2 && MatchesLength(possibleMatch, length2))
                {
                    add2 = true;
                    if (lower3 == null)
                        break;
                    // Otherwise do not break!  Continue to look for 3-word matches
                }
            }
        }

        if (add3)
        {
            result.Add(new MyClass(words3));
            words[i + 1] = null;
            words[i + 2] = null;
        }
        else if (add2)
        {
            result.Add(new MyClass(words2));
            words[i + 1] = null;
        }
        else
        {
            result.Add(new MyClass(words[i], Parent));
        }
    }

And then
    static bool MatchesLength(string possibleMatch, int length)
    {
        // Ignore anything after the last '|', if present
        return (possibleMatch.Length == length || possibleMatch.LastIndexOf('|') == length);
    }


Q:

Interfaces, Inheritance and the 'new' keyword

I am wondering if someone can please explain this to me:
class Program
{
    static void Main()
    {
        AnotherDerivedClass d = new AnotherDerivedClass();
        Console.WriteLine(d.PrintMessage());

        IMsg m = d as IMsg;
        //Why this prints BaseClass.
        //How does it know that IMsg is implemented in the BaseClass.
        Console.WriteLine(m.PrintMessage());

        IMsg n = d as DerivedClass;
        //Why this prints BaseClass and not DerivedClass
        Console.WriteLine(n.PrintMessage());

        Console.Read();
    }
}

public interface IMsg
{
    string PrintMessage();
}

public class BaseClass : IMsg
{
    public string PrintMessage()
    {
        return "BaseClass";
    }
}

public class DerivedClass : BaseClass
{
    public new string PrintMessage()
    {
        return "DerivedClass";
    }
}

public class AnotherDerivedClass : DerivedClass
{
    public new string PrintMessage()
    {
        return "AnotherDerivedClass";
    }
}

A:

You have replaced the implementation in your derived classes, not overridden them. If you use the BaseClass, the original implementation will be used.
You need to make the method in the base virtual:
public class BaseClass : IMsg
{

    public BaseClass()
    {

    }

    public virtual string PrintMessage()
    {
        return "BaseClass";
    }
}

and override in the derived class:
public class DerivedClass : BaseClass
{
    public DerivedClass()
    {

    }

    public override string PrintMessage()
    {
        return "DerivedClass";
    }
}

to get the behaviour you specified.


Q:

Issue replicating byte string in Java with ByteBuffer

I'm trying to duplicate a byte String that I produce in Objective-C (on iOS) in Java but am having trouble. Here's the string I want to produce:
"\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

I get that string from an array of 4 integers - [1,1,0,0] - where each integer has 4 bytes. After looking at a bunch of questions on here, I've attempted constructing that string in Java using ByteBuffer as follows:
ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putInt(1);
bytes.putInt(1);
bytes.putInt(0);
bytes.putInt(0);

String byteString = new String(bytes.array());

However that gives me:
"\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"

When I unpack that, the array of ints I get is [16777216, 16777216, 0, 0]. Obviously I'm doing something wrong, and I'm hoping someone can point me in the right direction.

A:

iOS is little-endian, so the least significant byte of a 4-byte integer comes first.
Java ByteBuffer defaults to big-endian, so the opposite applies.

The initial order of a byte buffer is always BIG_ENDIAN

You can change this with
bytes.order(ByteOrder.LITTLE_ENDIAN);


Q:

Insert sql file into sqlite - iphone

I am new to SQLite
I have a .sql script file, details.sql, given here:
SET DEFINE OFF;
Insert into Student(student_id, name, address) Values ('101', '123', 'Marthandam');
Insert into Student(student_id, name, address) Values ('102', 'Abc', 'Chennai');
Insert into Student(student_id, name, address) Values ('103', 'Xyz', 'TVM');
COMMIT;

I need to insert these queries from details.sql into the sqlite3 data base on an iPhone.  On the iPhone I have created a new DB for storage called Database.sql
Please give me the source code to insert the scripts into Database.sql.

A:

Could try something like this:
NSString *f = [NSString stringWithContentsOfFile:<path to details.sql> encoding:NSUTF8StringEncoding error:NULL];
for (NSString *l in [f componentsSeparatedByString:@"\n"]) {
   <call sqlite3_exec to execute each line of SQL>
}


Q:

Getting a CSS attribute from PHP

It's my first time asking here (I have visited the site several times, but never asked). Well, let's go to the question:
It happens that I'm developing a live image resizer (I know it already exists, but I'm doing my own for my own projects). It has three parameters: the image path (obviously), the size I want to resize and the extra margin I want to add. The idea is to resize the image inside a box with square dimentions. The problem is, the size I want to resize depends on the size of the outer box. For example, I have this HTML code:

The properties of "image_outer_box" are the following:
.image_outer_box
{
   height: 330px;
   width: 330px;
   border:solid 1px #737373;
}

The function I call is this:
liveResize($img, $size, $extramargin);

The problem here is when I send the $size, since I must be aware of the CSS properties of "image_outer_box" in order to make the right resize. And, as you can see, it's not only a matter of the size specified in "image_outer_box" but the margin I want to add. Actually, I wanted to add 15px of extra margin for the image and resize the image inside 300x300.
It's not critical to have a way to get the CSS attributes from this particular class, but it would help if I (and other developers) can apply the function without being aware of the CSS attributes of the container where the image will be placed.
If there's a way to make it, I would be great.
Thanks! (for the other times I came here to search a solution and I found it!!!)
EDIT: I found a way that doesn't require to get the CSS properties, but still I would like to have info for this matter. Thanks for those who tried to help 'til now!

A:

Do you want to actually store the resized image, or are you just trying to display it resized? If the latter is the case, the following solution might help:
HTML

CSS
.image_outer_box
  {
  margin:10px;
  height: 330px;
  width: 330px;
  border:solid 1px #737373;
  }

Of course, this doesn't allow you to manually set the width and height of the image, since that depends on our CSS entirely. Change the CSS, and the size of the image will automatically change as well. I like this method quite a bit, but it won't get very far if you want to store the image or if you want to be able to set the image size manually.


Q:

Browser is scaling page to 125%

I have a display with resolution 2560x1440. I have noticed that web page I am working on is scaled to 125%. So if border is set to 4px - it has 5px on the screen. It happens in Opera, Chrome, Firefox, but not in Edge.
I assume it is related to Windows font size settings (which is set to 125% on my computer).
How to disable this feature using CSS code (or in meta tag in head?) or at least in browser settings?
Sample code:

Results:

A:

Finally I found an answer.
For Firefox:
https://stackoverflow.com/a/24958483/6552578
Chrome:
https://productforums.google.com/forum/#!topic/chrome/_jmREHlt3ZE
Solution - need to edit desktop link to Chrome like that:
"C:\Program Files\Google\Chrome\Application\chrome.exe"  /force-device-scale-factor=1


Q:

Fail to relay email with Postfix

I want to relay mail to local SMTP to mandrillapp, with the /etc/postfix/main.cf
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

append_dot_mydomain = no

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:info@example.com:xxx
smtp_sasl_security_options = noanonymous

readme_directory = no

smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = test123.example.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = example.com, localhost, localhost.localdomain, localhost
relayhost = [smtp.mandrillapp.com]:587
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

and in the mail log
Apr 22 11:36:33 test123 postfix/pickup[4002]: 2CAA8122694: uid=0 from=<root@test123>
Apr 22 11:36:33 test123 postfix/cleanup[4008]: 2CAA8122694: message-id=<20140422153633.2CAA2938324@test123.example.com>
Apr 22 11:36:33 test123 postfix/qmgr[4003]: 2CAA8122694: from=<root@test123>, size=339, nrcpt=1 (queue active)
Apr 22 11:36:33 test123 postfix/smtp[4010]: 2CAA8122694: to=<foobar@gmail.com>, relay=smtp.mandrillapp.com[54.255.70.161]:587, delay=0.05, delays=0.01/0/0.02/0.01, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 242232323)
Apr 22 11:36:33 test123 postfix/qmgr[4003]: 223232323: removed

What would be the reason? I have checked the mandrillapp admin console and also can't find the email.

A:

There are a lot of things that might be wrong.
As you can see form the logs the message was successfully delivered by Postfix. Something inside Mandrillapp dropped your message or in the final destination, your foobar@gmail.com address.
The from field comes from a non valid FQDN in the domain part. So it's probably blocked on some antispam, perhaps in Mandrillapp or perhaps in Google. Have you checked your spambox in foobar@gmail.com to see if the message has gone there?
Another thing I would do is changing test123 for a domain name that you own, so it will not de blocked, tagged or scored high in spam tests.
If you don't have a FQDN just sent the email as your gmail account authenticating in Google Servers instead.


Q:

Scale images in listview to fit

I'm trying to make a listview where each item is an image. I want the listview to display the items horizontally. If the view box items won't fit horizontally in the window I want a horizontal scroll bar. If the list items won't fit vertically within the window I want the images to scale down so they fit. Instead of the images scaling to fit I seem to be getting a vertical scrollbar on the listview.
At the moment when the window is resized vertically it causes a vertical scrollbar to appear on the listview. I've tried various options around setting the image height to the height of the ancestor listview but I can't make it work correctly. How do I achieve my desired behaviour?
<Window x:Class="ViewBoxExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ViewBoxExample"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type=local:MainWindow}"
        Title="Viewbox Test"
        Height="400" Width="600">
    <Window.Resources>
        <DataTemplate x:Key="ItemTemplate" >
                <Border BorderBrush="Black" BorderThickness="2" >
                    <Image Margin="2" Source="image.png" />
                </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
       </Grid.RowDefinitions>
        <ListView VerticalAlignment="Stretch"
                  ItemTemplate="{StaticResource ItemTemplate}"
                  ItemsSource="{Binding Items}">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal">
                    </StackPanel>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
        <Grid Grid.Row="1" Height="100">
            <!--placeholder for more content-->
        </Grid>
    </Grid>
</Window>

A:

Disable the vertical ScrollBar to make the ListView scale its items vertically:
<ListView ItemsSource="{Binding Items}"
          ItemTemplate="{StaticResource ItemTemplate}"
          ScrollViewer.VerticalScrollBarVisibility="Disabled">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

This works as well with the more light-weight ListBox.


Q:

Get Text of Custom Dialog (UserControl) from Parent UserControl

I have a UserControl as Parent and i am opening a custom dialog (user control) as shown in the code below:
        Window dialog = new Window
        {
            Title = "A Dialog Box",
            Content = new UserControlDialog(),
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.NoResize
        };
        dialog.ShowDialog();

How can i get the text from the textbox inside the UserControl Dialog?

A:

First, create a public property in your UserControlDialog control, let's say named Value. When the user does something in the dialog, set the value from the TextBox to the Value property:
Value = SomeTextBox.Text;

When the dialog window is closed, simply read the value from the dialog control:
...
dialog.ShowDialog();
string result = dialog.Value;

A better solution would be to data bind the Value property to the inner TextBox control, but to do this, you'd either need to implement the INotifyPropertyChanged Interface, or create the Value property as a DependencyProperty:
Inside the UserControlDialog control:
<TextBox Text="{Binding Value, RelativeSource={RelativeSource
    FindAncestor={x:Type YourLocalPrefix:UserControlDialog}}}" ... />


Q:

Would this be plausible for a metamorphic virus? Not repeatedly infecting same system

Would this be plausible for a metamorphic virus? When a new generation (for lack of better word) is created it would hard code a random file name, that would be checked to see if the system was infected,  that the old generation would create. Example
START

absolute path to file named aabb.txt is hard coded into first generation
checks to see if file exists
if exists that means current system has been infected, goto END
if does not exist this means it's on a new system
uses metamorphic engine to rewrite itself and hard
codes a randomly named file that will be used to tell if system is infected e.g. tk12.txt
creates the file e.g. tk12.txt
runs new generation
deletes itself (old generation)

END
So it's incorrect to call this random file a mutex because it's not a system object?

A:

Why not use a hashing algorithm against a dictionary?  Your dictionary is a list of one hundred words that are eight to ten letters long.  You pull a salt that is constant on the system you are hashing.  You then use the constant salt and hash a random dictionary word and use it as an identifier on the system.
Later the same virus hits a system.  It hashes all one hundred words at that time  using whatever the constant salt would be for that system (this can be determined by some list of variables, with an applied percentage scale).  Once all the words are hashed, the virus looks for the previous attack.  If it finds it, it kills itself.  If the previous attack is not found, the system is infected.
This would be especially brutal if done as a binary virus, i.e. a worm has to find a virus that hasn't done anything to the system yet, and together they do something.  If only one is present, nothing happens (the virus is dormant, the worm only triggers if the virus is present).


Q:

android Fragment issue with orientation change

I have activity and two layouts for it defined:

layout-large-land
layout

1st layout is for large screens in landscape mode, 2nd is for other cases.
The 1st layout contains:

fragment1
fragment2

The 2nd layout contains:

fragment1

When I start the app in landscape mode on large screen, the getSupportFragmentManager().findFragmentById() called in Activity.onCreate() correctly returns both fragments. After orientation change to portrait, getSupportFragmentManager().findFragmentById() returns not null for fragment2, but it should return null because this fragment is not defined in this layout. The problem is that the returned fragment object is incorrect and I get null pointer exceptions while accessing it. It should be null, shouldn't it?

A:

Actually... I don't think it should be null.
After your layout-large-land layout is displayed in the Activity, the Activity will add those both Fragments in the FragmentManager. Once you rotate your Activity, the FragmentManager retains it's state, and the Fragments inside it, and it still has that Fragment2 in it, and that is why findFragmentById() does not return null.
The Fragment2 will be there, but it won't be attached to the Activity, and you can check this by using fragment.isAdded() or fragment.isVisible().
If in your case, you want to know if your 2-pane (landscape) or 1-pane(portrait), maybe you should do the following check : findViewById(R.id.secondFragmentContainer)==null.


Q:

string splitting based on delimiters

My string is
 c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

I like to split this to separate words as
  "closely" "-monitored", "rights", "-of", "-way", "THIS", "_IS", "_A", "_CONSTANT"

Tried
 paste("\\-", strsplit(str3, "_|-"))

but it is not working.

A:

Here's an approach with perl-compatible regex:
vec <- c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

unlist(strsplit(vec, "(?<=[^-_])(?=[-_])", perl = TRUE))

# [1] "closely"    "-monitored" "rights"     "-of"        "-way"
# [6] "THIS"       "_IS"        "_A"         "_CONSTANT"


Q:

Merging features from equal attributes in QGIS 2.18.3?

I am working on a feature merge Operation, able to stick features together, if they have the same attributive values (e.g. TP_RKZ1 & TP_RKZ2 are empty so stick the multiple features to one single feature together if the following feature is not equal to the feature before [like in the Image]).

To get this behavior, I created the following code, which is actually already selecting the features in the mentioned way. The only missing part is the "merge process". Here I am not able to figure out the misbehavior of the used geom = geom.combine(feature.geometry) syntax.
Any suggestions?
"""APPROACH"""
"""Loop comparing attribute ID_RKZ1 & ID_RKZ2 values of the actual feature with the following feature and add the feature to the selectedFeatures using the
   myWorkLay.select () function and if it is not equal add last equal feature to the selectedFetures
   and perform the merge of all equal features"""
for i in range(0,len(myAttributes)-1):
    if myAttributes[i][1] == myAttributes[i+1][1] and myAttributes[i][2] == myAttributes[i+1][2]:
        print "My items {0} | {1} are equal".format(myAttributes[i],myAttributes[i+1])
        'Select feature because of feature-id'
        myWorkLay.select([myAttributes[i][0]])
        #print "%s"%myAttributes[i][0]
    else:
        print "!My items {0} | {1} are not equal!".format(myAttributes[i],myAttributes[i+1])
        'Select feature because of feature-id'
        myWorkLay.select([myAttributes[i][0]])
        print myWorkLay.selectedFeatureCount()
        #print myWorkLay.setSelectedFeatures()
        'Iterate through all selected features and merge them'
        for feature in myWorkLay.selectedFeatures():
             print feature.geometry()
             if geom == None:
                geom = feature.geometry()
             else:
                geom = geom.combine(feature.geometry())
        myWorkLay.removeSelection()
        geom = None

Here the result of my selection and
 10 ' => result of print myWorkLay.selectedFeatureCount()
 ' following the output of print feature.geometry()
<qgis._core.QgsGeometry object at 0x000000001C1742F0>
<qgis._core.QgsGeometry object at 0x000000001C174400>
<qgis._core.QgsGeometry object at 0x000000001C174378>
<qgis._core.QgsGeometry object at 0x000000001C1742F0>
<qgis._core.QgsGeometry object at 0x000000001C174400>
<qgis._core.QgsGeometry object at 0x000000001C174378>
<qgis._core.QgsGeometry object at 0x000000001C1742F0>
<qgis._core.QgsGeometry object at 0x000000001C174400>
<qgis._core.QgsGeometry object at 0x000000001C174378>
<qgis._core.QgsGeometry object at 0x000000001C1742F0>

A:

I didn't test the following code but, since it seems you are able to create the selection successfully, I only edited the code part where you need to merge the features:
"""APPROACH"""
"""Loop comparing attribute ID_RKZ1 & ID_RKZ2 values of the actual feature with the following feature and add the feature to the selectedFeatures using the
   myWorkLay.select () function and if it is not equal add last equal feature to the selectedFetures
   and perform the merge of all equal features"""
for i in range(0,len(myAttributes)-1):
    if myAttributes[i][1] == myAttributes[i+1][1] and myAttributes[i][2] == myAttributes[i+1][2]:
        print "My items {0} | {1} are equal".format(myAttributes[i],myAttributes[i+1])
        'Select feature because of feature-id'
        myWorkLay.select([myAttributes[i][0]])
        #print "%s"%myAttributes[i][0]
    else:
        print "!My items {0} | {1} are not equal!".format(myAttributes[i],myAttributes[i+1])
        'Select feature because of feature-id'
        myWorkLay.select([myAttributes[i][0]])
        print myWorkLay.selectedFeatureCount()
        #print myWorkLay.setSelectedFeatures()
        'Iterate through all selected features and merge them'
        for feature in myWorkLay.selectedFeatures():
            if geom == None:
                 geom = feature.geometry()
             else:
                geom = geom.combine(feature.geometry())
             """ After this step the geom need to be assigned to a
                 QgsFeature  object and added to a QgsVectorObject
                 So something like the following code:"""
        newFeature = QgsFeature()
        values = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
        newFeature.setGeometry(geom)
        newFeature.setAttributes(values)
        myWorkLay.startEditing()
        myWorkLay.addFeature(newFeature, True)
        myWorkLay.removeSelection()
        myWorkLay.commitChanges()
        geom = None

        myWorkLay.removeSelection()


Q:

How to start a interactive Chef client just like start a rails by "rails console"?

In chef workstation client, I want to start an interactive console to debug and check the role/recipe, or use search api, e.g.
 chef-client > nodes=search ("node","name:*")
 chef-client > puts "#{nodes}"

...
Just like in rails, use "rails console" to load all your rails environment into irb.
How to do it?

A:

The "shef" tool may be what you're looking for, it starts an IRB session in your chef environment where you can do things like search, browse and manipulate your nodes, roles, etc.    There's even a debugger to step through your recipes using the "breakpoint" resource.
Here's a real basic example
chef > nodes.list
=> [node[db1-production], node[worker1-production], node[app1-production]]
chef > nodes.show('app1-production').class
 => Chef::Node

etc.. check out the OpsCode wiki page about it: http://wiki.opscode.com/display/chef/Shef


Q:

How to show something only when user prints?

What I Know
Now I know how to add a print stylesheet in the webpage to design the print layout. Its something like:
<link rel="text/css" href="/css/print.css" media="print" />

But I don't want that.
In this blog go to any article or post and print preview the page (with Google Chrome). Now if you go down the page (in save PDF mode) you will see that extra text is appended which is (This story was originally published at Digital Inspiration.. ..This printer friendly version is made available for your personal and
noncommercial use only). You can see that message only if you print(-preview), not on the webpage normally.
What I Tried to find out
When I view the page source of the page then there is only two stylesheets attached out of one is main and one is for webfont. For JavaScript, there is only one main JavaScript file attached and the rest are for webfont, CSS3 MediaQueries, HTML5-Shiv and for ads which I don't suspect to be contain any print related stuffs. When I tried find those both main CSS and JavaScript files (with CTRL-F feature), the search for printer friendly didn't matched anything.
What I didn't tried
I haven't asked site owner how he did it, nor going to ask ;)
Question
How did he did that? Is here JavaScript involved? or CSS? In [noscript] tag the text inside that tag are only shown if user has javascript disabled. Is there something same for printing? Something like [onlyonprint] tag?

A:

He's using  the :after pseudo-element:
#content:after {
    content: "This story was originally published at Digital Inspiration...";
    font-size: 90%;
    font-style: italic;
    line-height: 1.5em;
    margin: 3em 0;
}

This exists in his print stylesheet.


Q:

Increase readability & maintainability : omit < > for many variable declaration possible?

The question seems very abstract.  I will ask by an example instead.
Introduction
Assume that I have many types of game objects.
They are Bullet, Rocket, Enemy, Zone, ... .
They are all nicely created & deleted & managed by pools, e.g.
Pool<Bullet> poolBullet ;
Pool<Rocket> poolRocket ;

The game logic would manage object in form of Pool_Handle< xxx >, e.g.
Pool_Handle< Bullet >  bullet = poolBullet.create() ;
Pool_Handle< Rocket>  rocket = poolRocket .create() ;

Problem
Now, I look at the refactoring.
For example, if my old code was ...
Bullet* functionA(Rocket* rocket){
    for(int n=0;n<rocket->zones.size();n++){
        Zone* zone = rocket->zones.get(n);
        Bullet* return_value =zone.functionB();
    }
}

... it would become ...
Pool_Handle<Bullet> functionA(Pool_Handle<Rocket> rocket){
    for(int n=0;n<rocket->zones.size();n++){
        Pool_Handle<Zone> zone = rocket->zones.get(n);
        Pool_Handle<Bullet> return_value =zone.functionB();
    }
}

Notice that they are now Pool_Handle everywhere.
After reading and editing these thousands line codes for a few days, I have grown accustomed to  Pool_Handle even more than any game objects.  It might be a word that I type fastest now.
Question
How to retain readability and maintainability to equal level of the old code, and if possible, how to reduce time of typing for the variable template?
I don't expect a perfect answer, because every solution I found has some trade-off.
My poor solutions
/**  remedy 1 **/
template <class TT> using H = Pool_Handle<TT>; //remedy line
H<Bullet> bullet ; //alleviate symptom, better but not perfect

/**  remedy 2 **/
using H_Bullet  = Pool_Handle<H_Bullet>; //remedy line
H_Bullet bullet ; //looks good, but have limitations

/** remedy 3 **/
auto bullet;  //concise, but can't be used everywhere, sometimes also reduce readability

The second solution seems to be nice, but introduces several limitations.

I have to declare a line for Bullet, Rocket, ... and so on, one by one

If there is a new type of game object, I will have to add another line manually.

If a game object is renamed, e.g. Bullet -> MetalBullet,
I will also have to change the remedy line to H_MetalBullet manually.

Therefore, it lowers overall maintainability.

Are there any better approaches?
(Edit) You can assume c++11, c++14, whatever.
(Edit) A platform independent solution is favorable.
Edit 1 (To clarify even more why the second solution is not perfect)
In the second solution,  I have to add "another" line after declare a new class.
The line is ...
using H_Bullet  = Pool_Handle<H_Bullet>;

Where should I place it?

inside Bullet.h ;
It will create bad coupling, because Bullet should not know about the Handle at all.

inside some high-level header that is included by every game logic files ;
The result is that there are 2 different places that has some definitions about Bullet.
More places -> Less maintainability.

Both places will yield a certain minor disadvantage :
When I call some automatic refactoring I have to call twice, on both Bullet and H_Bullet.

A:

What's wrong with a header that just forward declares the types you're interested in? It will only change when you add new types to your system that need handles, and if you rename / add something it will break gracefully.
types_fwd.hpp
template <typename> Pool;
template <typename> Pool_Handle;

class Bullet;
class Rocket;

using H_Bullet = Pool_Handle<Bullet>;
using H_Rocket = Pool_Handle<Rocket>;

The only other option would be to invert things and forward declare the pool and handle and include / add that to each header that introduces new types that need handles.


Q:

Repeat list endlessly (Zip a finite list with an Infinite repeating sequence)

UserList is a list of dictionaries, like:
[
  {Name:"Alex",Age:25},
  {Name:"Peter",Age:35},
  {Name:"Muhammad",Age:28},
  {Name:"Raul",Age:29}
]

RowColorList is a list of colors: [#bcf,#fc0]
The new UserList should contain one RowColor for every name, taken in sequence from RowColorList:
[
  {Name:"Alex",Age:25,RowColor:#bcf},
  {Name:"Peter",Age:35,RowColor:#fc0},
  {Name:"Muhammad",Age:28,RowColor:#bcf},
  {Name:"Raul",Age:29,RowColor:#fc0}
]

I tried the following code:
UserList.Zip(RowColorList,(user,color) => user.Add("RowColor",color))

With this code, the new UserList will only contain as many entries as are in RowColorList. I would like him to start from the beginning of RowColorList again, whenever the available colors are used up. How?

A:

You can create a function to return an infinite enumerable of Color / string (or whatever the type of RowColor is), by using yield return as a lazy generator:
public IEnumerable<Color> InfiniteColors()
{
    while (true)
    {
        foreach (var color in RowColors)
        {
            yield return color;
        }
    }
}

This can then be used with any of the Linq IEnumerable extension methods such as Zip.
UserList.Zip(InfiniteColors(),(user,color) => user.Add("RowColor",color))

Edit - Explanation
The reason why InfiniteColors doesn't hang is because the state machine will yield back to the caller after each result, and Zip will terminate on the first enumerable to complete, which is because the other collection being zipped is finite (i.e. UserList)
Obviously you shouldn't try and Zip the InfiniteColors enumerable with itself, nor should you try and materialize InfiniteColors, i.e. don't call InfiniteColors.ToList() or such :-):

A:

Something like this should do the trick:
var i = 0;
var l = RowColorList.Count;
UserList.ForEach(user => user.Add("RowColor", RowColorList[(i++) % l]));

The % operator will guarantee "cyclic" access to the RowColorList.


Q:

java file handling and exceptions

The standard way of handling file reading and writing in java goes something like this:
try
{
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
    oos.writeObject(h);
    oos.close();
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}

But I'm bothered by that code, because it could be possible here that the file is never closed if an exception is thrown. Sure we could add a finally clause and initialise the ObjectOutputStream outside the try block. However, when you do that you need to add another try/catch block INSIDE the finally block again...that's just ugly. Is there a better way of handling this problem?

A:

use apache commons io
http://commons.apache.org/proper/commons-io/
look at their FileUtils class.  Full of gold.  Gold I say....

A:

This is not the standard way at all. This is the bad way.
The way I use most of the time is this one :
ObjectOutputStream out = null;
try {
    out = new ObjectOutputStream(new FileOutputStream("file.dat"));
    // use out
}
finally {
    if (out != null) {
        try {
            out.close();
        }
        catch (IOException e) {
            // nothing to do here except log the exception
        }
    }
}

The code in the finally block can be put in a helper method, or you can use commons IO to close the stream quietly, as noted in other answers.
A stream must always be closed in a finally block.
Note that JDK7 will make it much easier with the new syntax, which will automatically close the stream at the end of the try block :
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) {
    // use out
}

A:

This why I use commons-io's IOUtils.closeQuitely(...)
try
{
...
}
finally
{
   IOUtils.closeQuietly(costream);
}


Q:

liminf and limsup

let $x_n$ be a series and :
$b<=x_n<=c$ for all but a finite number of n, show that $b<=\liminf{x_n}$
My approach :
So since $x_n$ is bounded by the interval $[b,c]$ $x_n$ it's greatest lower bound could be at max $b$ right? Since lower bounds for $x_n$ has a greatest point, and that greatest point is in the closure of $x_n$ and since we are in a closed interval in real numbers only, that would be $b$.
It all seems proving this is quite easy in this way, but How would I prove it mathematically?
Help.

A:

Choose $N$ so that $k\geqslant N$ implies $x_k\geqslant b$. Then $\inf_{k\geqslant N} x_k\geqslant b$, and so $$\liminf_{n\to\infty} x_n = \lim_{n\to\infty}\inf_{k\geqslant n}x_k\geqslant b. $$


Q:

How to save base64 image using node js?

I am saving the base64 image using nodejs, it save my image at exact path, but show me the error.
Please help me to find the error.

Here is my code
var express = require('express');
var router = express.Router();

const fs = require('fs');
const mime = require('mime');

const path = './uploads';

router.post('/register', (req, res, next) => {
  const base64Image = req.body.image;

  const matches = base64Image.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  response = {};
  if (matches.length !== 3) {
    return new Error('Invalid input String');
  }

  response.type = matches[1];
  response.data = new Buffer(matches[2]);
  let decodedImg = response;
  let imageBuffer = decodedImg.data;
  let type = decodedImg.type;
  let extension = mime.extension(type);
  let fileName = 'image.' + extension;

  try {
    fs.writeFileSync(path + '/' + fileName, imageBuffer, 'utf8');
    return res.send({ status: 'success' });
  } catch (e) {
    next(e);
  }

  return;

});

module.exports = router;

Any solution appreciated!

A:

The mistake you made is when you are creating a buffer you are not specifying an encoding. You should create buffer like this:

new Buffer() is deprecated use Buffer.from() instead.

let buff =  Buffer.from(m[2],'base64');  // encoding type base64
Basic code snippet
const fs =  require('fs')
let a =  'base64ImageString'
let m =  a.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);

let b =  Buffer.from(m[2],'base64');
fs.writeFile('image.png',b,function(err){
 if(!err){
 console.log("file is created")
 }
 });

Also, when you writing a buffer to file you don't have to pass encoding type, but if writing string you have to.

Check this out for a demo
https://repl.it/repls/GrimOfficialLocations

But it is not advised to send an image as base64 string. It is
  inefficient for large images. base64 roughly takes 33% more bits than
  its binary equivalent. I recommend you to check this out:
  Upload base64 image with Ajax


Q:

Batch convert mono WAV to stereo verbatim

I have a bunch mono .wav files which I need to convert to stereo in order to run thru lame.
Lame can't encode stereo mp3s from mono input so that's what I need to do.
I don't need any modifications to the data made other than duplicating channel into two.
I've tried to use sox and it seems to alter sound data in eerie ways by up-downsampling and changing bit depths in between as well as running filters I don't need.
So please recommend me some tool to batch convert .wav files from mono to stereo.
I'm on linux.

A:

sox input.wav output.wav channels 2


Q:

Woocommerce change order of $product->get_categories

I need order the results of "$product->get_categories()" with the slug.
The template use this code:
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );

//And after...

<?php echo $product->get_categories( ', ', '' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' ) . ' ', '' ); ?>

I've seen in a tutorial, that I can use this code,but doesn't work (in functions.php):
function wptt_cat_order( $args ){

    $args['orderby'] = 'slug';
    $args['order'] = 'ASC';
    return $args;

} // wptt_cat_order
add_filter( 'woocommerce_product_subcategories_args', 'wptt_cat_order' );

Other question I have is(but not is so important than the other question), why he uses the $cat_count in "_n()" function and not "get_the_terms( $post->ID, 'product_cat' )"? first is only a number O_O.

A:

Simple answer: you can't use that method to order the categories.
You're going to need to write your own loop using wp_get_post_terms(), which allows you to pass arguments (such as orderby). Something like the following should work (but I haven't tested it):
$args = array(
    'orderby' => 'name',
);
$product_cats = wp_get_post_terms( $product->id, 'product_cat', $args );
$cat_count = sizeof( $product_cats );

echo '' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' );
for ( $i = 0; $i < $cat_count; $i++ ) {
    echo $product_cats[$i]->name;
    echo ( $i === $cat_count - 1 ) ? '' : ', ';
}
echo '';


Q:

How do I use CSS to centre this content?

Apologies for the slightly vague question, but the content is quite specific. I've been playing with a number of different approaches, and I'm really struggling to achieve the desired results.
So I have a collection of photos to display, and this collection will either have one or two photos. These need to be displayed alongside each other and centred on the page. If there is only one photo, then it should be shown on its own and centred on the page. Each photo comes with a title that needs to be displayed above it, and a description that needs to be shown below it.
So it'll either look like this (but centred):

Or it'll look like this (but centred):

I've played with an outer container div with a margin of auto 0, and I've played around with tables, but I'm struggling with (a) getting them centred, and then (b) being able to have one or two photos (although I could potentially deal with this in code, as this is an MVC view).
I'm a little rusty with CSS, so any and all help and advice much appreciated!

A:

One way to solve this is to text-align:center a containing element and text-align:left the children, for example see demo or code below.
HTML

Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua.

Title

Description

Title

Description Description Description Description

CSS
ul {
    list-style-type:none;
    text-align:center;
}

li {
    text-align:left;
    display:inline-block;
    vertical-align:top;
    max-width:150px;
    margin-right:10px;
}


Q:

Joomla 2.5 Private Messaging

I am using joomla 2.5.7. When i am trying to select user in private message component, it shows only admin users. Registered users are not available. I want to use private messaging for registered users. Suggest me what i am doing wrong?

A:

If you're referring to the Private Messaging component that comes standard with Joomla, then this is only available to admins, as it's an admin component and registered users won't be able to enter the backend to check their messages.
If you are looking for a PM component, then I would highly recommend UddeIM which is free and also integrates with lots of other 3rd party extensions such as Kunena and Community Builder.
Just on a side note, you should update your Joomla version to 2.5.14
Hope this helps


Q:

How can I handle DLL errors in VBA?

The API declaration:
Private Declare Function CallWindowProc Lib "user32.dll" Alias "CallWindowProcA" ( _
                         ByVal lpPrevWndFunc As Long, _
                         ByVal HWnd As Long, _
                         ByVal msg As Long, _
                         ByVal wParam As Long, _
                         ByVal lParam As Long) As Long

will crash Excel when provided with a non-existent function pointer for the lpPrevWndFunc parameter.
Similarly,
Private Declare Sub RtlMoveMemory Lib "kernel32" (ByRef Destination As LongPtr, _
                                                  ByRef Source As LongPtr, _
                                                  ByVal Length As Long)

isn't happy when Destination or Source don't exist.
I think these errors are memory access violations. I assume Windows tells the caller that it's doing something it can't1 - perhaps it sends a message to Excel and there's no handler for it? MSDN has this to say about it:

System errors during calls to Windows dynamic-link libraries (DLL) or
  Macintosh code resources do not raise exceptions and cannot be trapped
  with Visual Basic error trapping. When calling DLL functions, you
  should check each return value for success or failure (according to
  the API specifications), and in the event of a failure, check the
  value in the Err object's LastDLLError property. LastDLLError always
  returns zero on the Macintosh.
  (emphasis my own)

But in these instances I have no values to check for errors, I just get a crash.
1: Provided it catches the error which it might not always, if say a memory rewrite is valid but undefined. But certainly writing to restricted memory or calling fake pointers should be caught before they're executed right?
I'm most interested in:

What causes this crash (both how it is triggered, and what exactly the mechanism is behind it - how does Excel know it needs to be crashing?). What is the message channel over which these errors are being communicated, and can I intercept them with VBA code?
Whether the crash can be pro-actively (i.e. sanitising inputs etc.) or retro-actively (handling errors) prevented.

I think (1) will likely shed light on (2) and vice-versa

Anyway, if anyone knows how to handle API errors like these without Excel crashing, or how to avoid them happening, or anything that would be fab. On Error Resume Next doesn't seem to work...
Sub CrashExcel()
    On Error Resume Next 'Lord preserve us
    'Copy 300 bytes from one non existent memory pointer to another
    RtlMoveMemory ByVal 100, ByVal 200, 300
    On Error Goto 0
    Debug.Assert Err.LastDllError = 0 'Yay no errors
End Sub

Motivation
There are 2 main reasons I'm asking about this:

Developing code (the process of debugging etc.) is made much harder when Excel crashes every time I make a mistake. This is not something that can be solved by simply getting it right myself (and exposing a different interface to client code, which uses my existing correct implementations of API calls) because I rarely get it right first time!
I would like to create robust code which is able to handle errors in user input (e.g. invalid function pointers or memory write locations). This can be dealt with to an extent by, for example, abstracting function pointers away into callable classes, but that's not a general solution for other kinds of dll errors (and still doesn't deal with 1.)

Specifically, I'm trying to develop a friendly interface to wrap WinAPI timers. These require callback functions to be registered with them, which (given the limitations of VBA) have to come in the form of Long function pointers (generated with the AddressOf keyword).
The callbacks come from user code and may be invalid. The whole point of my wrapping is to improve stability of the API calls, and this is one area that needs improvement.
The memory copy problem is probably out of scope of this question, it's to do with making generators in VBA, but I think the same error handling techniques would be applicable there too, and it makes for an easier example.
I also get errors and crashes from the Timer API generating too many unhandled messages for Excel. Once again I wonder, how does Windows tell Excel "Time to crash now", why can't I intercept that instruction and deal with the error myself (i.e. Kill all the Timers I made & flush the message queue)?

A:

From a comment:

Surely if I make an erroneous API call, something's gotta let Excel/my code know that it was bad

Not necessarily.  If you ask an API function (e.g. RtlMoveMemory) to overwrite memory at a location for which you supply a pointer, it will cheerfully attempt to do so.  Then a number of things could happen:

If the memory is not writable (e.g. code), then you will be lucky enough to get an access violation which will terminate the process before it can do any more damage.
If the memory happens writable, it will be overwritten and thus corrupted, after which all bets are off.

From your comment:

I'm designing code to attach user supplied callback functions

An alternative would be to design an interface with methods that your client code can implement. Then require the client to pass an instance of a class that implements that interface.
If your clients are VBA, then an easy way to define an interface is to create a public VBA class module with one or more empty methods.  By convention, you should name this class with an I (for interface) prefix - e.g. IMyCallback.  The empty method(s) (Subs or Functions) can have any signature you want, but I'll keep it simple:
Example:
Class module name: IMyCallback

Option Explicit

Public Sub MyMethod()

End Sub

Alternatively, and better if your clients use languages other than VBA, you can use IDL to define the interface, compile it into a type library, and reference the type library from your VBA project.  I won't go into that any further here but ask another question if you want to follow it up.
Then your clients should create a class (VBA class module) that implements this interface in whatever way they choose, e.g. by creating a class module ClientCallback:
Class module name: ClientCallback

Option Explicit

Implements IMyCallback

Private Sub IMyCallback_MyMethod()
    ' Client adds his implementation here
End Sub

You then expose an argument of type IMyCallback and your client can pass an instance of his class.
Your method:
Public Sub RegisterCallback(Callback as IMyCallback)
    ...
End Sub

Client code:
Dim objCallback as New ClientCallback
RegisterCallback Callback
…

You can then implement your own callback function that is called from a Timer, and safely call the client code via the interface.

A:

Some of these Windows API calls can be dangerous.  If you want to ship Windows API functionality as a library feature then it would be courteous not to expose you clients to such danger.  So, you are best to implement your own interface layer.
Below is code that ships the Windows Timer API as a library feature that is safe for use because it passes string names of callback code instead of pointers.
This code was first published on my blog.  Also on that blog post I discuss alternatives to Application.Run if you want options.
Option Explicit
Option Private Module

'* Brought to you by the Excel Development Platform blog
'* First published at https://exceldevelopmentplatform.blogspot.com/2019/05/vba-make-windows-timer-as-library.html

Private Declare Function ApiSetTimer Lib "user32.dll" Alias "SetTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long, _
                        ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Private Declare Function ApiKillTimer Lib "user32.dll" Alias "KillTimer" (ByVal hWnd As Long, ByVal nIDEvent As Long) As Long

Private mdicCallbacks As New Scripting.Dictionary

Private Sub SetTimer(ByVal sUserCallback As String, lMilliseconds As Long)
    Dim retval As Long  ' return value

    Dim lUniqueId As Long
    lUniqueId = mdicCallbacks.HashVal(sUserCallback) 'should be unique enough

    mdicCallbacks.Add lUniqueId, sUserCallback

    retval = ApiSetTimer(Application.hWnd, lUniqueId, lMilliseconds, AddressOf TimerProc)
End Sub

Private Sub TimerProc(ByVal hWnd As Long, ByVal uMsg As Long, ByVal idEvent As Long, _
        ByVal dwTime As Long)

    ApiKillTimer Application.hWnd, idEvent

    Dim sUserCallback As String
    sUserCallback = mdicCallbacks.Item(idEvent)
    mdicCallbacks.Remove idEvent

    Application.Run sUserCallback
End Sub

'****************************************************************************************************************************************
' User code below
'****************************************************************************************************************************************

Private Sub TestSetTimer()
    SetTimer "UserCallBack", 500
End Sub

Private Function UserCallBack()
    Debug.Print "hello from UserCallBack"
End Function


Q:

Changing letters in string to letter and number of frequency-python

I'm looking for the solution to my problem. I want to make a program where someone inputs string and I cover it into something like this:
'ZZZZYYYZZ' -> 'Z4Y3Z2'

I'm open for any suggestions.
The code I did:
def compress(s):
    e={}
    if s.isalpha():
        for i in s:
            if i in e:
                e[i] += 1
            else:
                e[i] = 1
    else:
        return None

    return ''.join(['{0}{1}'.format(k,v)for k,v in e.items()])

s=input("Write string: ")
compress(s)

This produces the wrong output
Write string: ZZZZYYYZZ
Y3Z6

A:

Grouping of unsorted data into chunks is a job for itertools.groupby.
>>> from itertools import groupby
>>>
>>> s = 'ZZZZYYYZZ'
>>> ''.join('{}{}'.format(c, len(list(g))) for c, g in groupby(s))
'Z4Y3Z2'

Detrails on what groupby produces here:
>>> [(c, list(g)) for c, g in groupby(s)]
[('Z', ['Z', 'Z', 'Z', 'Z']), ('Y', ['Y', 'Y', 'Y']), ('Z', ['Z', 'Z'])]

~edit~
Slight memory optimization without intermediary lists:
>>> ''.join('{}{}'.format(c, sum(1 for _ in g)) for c, g in groupby(s))
'Z4Y3Z2'

~edit 2~

Instead of C1 can we have just C?

>>> s = 'XYXYXXX'
>>> to_join = []
>>> groups = groupby(s)
>>>
>>> for char, group in groups:
...:    group_len = sum(1 for _ in  group)
...:    if group_len == 1:
...:        to_join.append(char)
...:    else:
...:        to_join.append('{}{}'.format(char, group_len))
...:
>>> ''.join(to_join)
'XYXYX3'


Q:

Is there an order-preserving bijection of reals with complexity classes?

We can easily prove there are $c:=\beth_1$ computational complexity classes for positive-valued functions of one positive-integer variable. To prove there are at least $c$ classes, we note each $e^{an},\,e^{bn}$ with $a>b>0$ are in different complexity classes. To prove there are at most $c$ classes, we note any function $f$'s class is determined by its $\aleph_0$ values on $\mathbb{N}$, giving an upper bound of $c^{\aleph_0}=c$.
But does there exist a map from $\mathbb{R}$ to functions, say $F(x)=n\mapsto f(n)$, such that $x<y\implies F(x)\in o(F(y))$, with the image of $F$ including representatives of all complexity classes?

A:

No, there isn't.
Suppose there was such map $F$. Let $f(x) = \sup \{(F(y)(x-y))^2 : y \in [0, x]\}$. For any $x \in \mathbb{R}$, $f$ is not in the complexity class of $F(x)$ since $f$ grows at least as fast as $y \mapsto (F(x)(y))^2$.


Q:

Comparing two arrays in vb.net

I need to do Reverse Intersection operation with two arrays and save the result in a different array
Eg: Array A {1, 2, 3}; Array B {1, 2, 3, 4, 5, 6} Resultant Array Should be {4, 5, 6}
I Tried out the following logic but didn't work
int k = 0;
int a[2] = {1,10};
int p[10];
int roll[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int i = 0; i < 2; i++)
{
    for (int j = 1; j <= 10; j++)
    {
        if (a[i] == roll[j])
        {
            break;
        }
        else
        {
            p[k] = 0;
            p[k] = roll[j];
            k++;
        }
    }
}

I need it for my vb.net project

A:

I don't understand how that C# code is related to your VB.NET problem, if you only want to find integers which are in one array and not in the other, use Enumerable.Except:
Dim intsA = {1, 2, 3}
Dim intsB = {1, 2, 3, 4, 5, 6}
Dim bOnly = intsB.Except(intsA).ToArray()


Q:

How to have localized style when writing cell with xlwt

I'm writing an Excel spreadsheet with Python's xlwt and I need numbers to be formatted using "." as thousands separator, as it is in brazilian portuguese language.
I have tried:
style.num_format_str = r'#,##0'

And it sets the thousands separator as ','.
If I try setting num_format_str to '#.##0', I'll get number formatted as 1234.000 instead of 1.234. And if I open n document in OpenOffice and format cells, I can set the language of the cell to "Portuguese (Brazil)" and then OpenOffice will show the format code as being "#.##0", but I don't find a way to set the cell's language to brazilian portuguese.
Any ideas?

A:

The thousands separator (and the decimal "point" etc) are recorded in the XLS file in a locale-independent fashion. The recorded thousands separator is a comma. How it is displayed depends on the user's locale. OpenOffice calc allows the user to override the default locale (Tools / Options / Languages / Locale setting).
With xlwt, write your num_format_str as "#,###.00" and your data as float("1234567.89"), like this:
import xlwt
b = xlwt.Workbook()
s = b.add_sheet('x')
style = xlwt.easyxf("", "#,###.00")
s.write(0, 0, 1234567.89, style)
b.save("locale_fmt_demo.xls")

Open the output file with OO Calc and try various locale settings. I got these results:
English (Australia): 1,234,567.89
Portuguese (Brazil): 1.234.567,89
French (France):     1 234 567,89


Q:

Firebase database retrieve datas

Hi guys im very new with app development ,any ideas how im i able to store my Latitude and Longitude of my users positions with its names and plot in my google maps?
I used this code below and it is working fine it plot the multiple marker as expected , my problem is ,i have my datas from firebase data base please see images
2 users with positions :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private GoogleMap googleMap;
    private MarkerOptions options = new MarkerOptions();
    private ArrayList<LatLng> latlngs = new ArrayList<>();
    private ArrayList<String> Names = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        latlngs.add(new LatLng(12.334343, 33.43434)); //some latitude and logitude value
        latlngs.add(new LatLng(10.334343, 32.43434)); //some latitude and logitude value
        Names.add("Name 1"); //some latitude and logitude value
        Names.add("Name 2"); //some latitude and logitude value

}

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
      //  LatLng sydney = new LatLng(-34, 151);
       // mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
      //  mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        for (LatLng point : latlngs) {
            options.position(point);
            options.title(String.valueOf(Names));
            options.snippet("someDesc");
            googleMap.addMarker(options);
        }

    }
}

A:

you get data from firbase database and store it in list you want to publish marker on map
you can use this Method
public ArrayList<MarkerOptions> publishMarker(GoogleMap googleMap, int recourceMarker) {
    ArrayList<MarkerOptions> markerOption = new ArrayList<>();
    for (LatLng point : latlngs) {
        MarkerOptions markerOptions = new MarkerOptions().position(point);

  markerOptions.icon(BitmapDescriptorFactory.fromResource(recourceMarker));
        markerOption.add(markerOptions);
        googleMap.addMarker(markerOptions).setTag(point);
        googleMap.addMarker(markerOptions);
    }
    return markerOption;
}

then call method in on mapReady Method
ArrayList<MarkerOptions> markerOptions=publishMarker(mMap, R.drawable.map_marker);
 if (markerOptions!=null&&markerOptions.size() > 0)this.mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(markerOptions.get(0).getPosition(), 15));


Q:

How Wordpress calculated ID of the created category?

Let's say I've created few categories with ID 2,3,4. Then I've deleted these categories. And when I'm creating new category after that, it has ID 5, not 2, as it may seems. So, where is WP store start value from which categories ID count starts?

A:

This is not done by wordpress. it is done by mysql. because id column is selected as primary key and auto increment . thats why when you delete and then insert another category or post and comment . this id is not repeat again .


Q:

Looping through to find element by xpath and then click on each element found

Web page I am trying to automate contains a list of 100+ links (teachers' names), clicking on which loads the list of students registered under that teacher. My task is to click on each link to make sure students information loads (on same page), click browser back button, click on 2nd teacher name and so on till end of the last link (teacher's name).
from selenium import webdriver
import time
driver=webdriver.Ie()
driver.get('I load my main page')
tablecontent=driver.find_elements_by_xpath("//table/tbody/tr/td/a") #see html code  provided below
tablelen=len(tablecontent) #find number of links on main page.
#loop through each link
for i in range(2,tablelen):
  driver.find_element_by_xpath("//table/tbody/tr[i]/td/a").click() #plug in i value to tr
  time.sleep(2)
  driver.back()

Above code generates below error
Traceback (most recent call last):
  File "C:/Python27/syn_xpath.py", line 14, in <module>
    driver.find_element_by_xpath("//table/tbody/tr[i]/td/a").click()
NoSuchElementException: Message: Unable to find element with xpath == //table/tbody/tr[i]/td/a

If I replace tr[i] by tr[2] (or any integer value within the brackets), it recognizes the element and clicks on it. E.g., driver.find_element_by_xpath("//table/tbody/tr[2]/td/a").click() works just fine. Any idea why passing integer value to tr via i (in a for loop) does not work?
HTML code:

Teacher	School

Teacher1	XYZ High School

Teacher2	ABC School

Teacher3	International School

A:

You need to format the xpath string.
By doing
"//table/tbody/tr[i]/td/a"

it is literally putting tr[i] into the xpath, not tr[1] etc.,
Instead of
driver.find_element_by_xpath("//table/tbody/tr[i]/td/a").click()

do
x_path = "//table/tbody/tr[{0}]/td/a".format(i)
driver.find_element_by_xpath(x_path).click()

This replaces the {1} in the string with the value you provide in the format function, so in this case it will replace {1} with 1, 2 etc. and will make your xpath selector work as expected.


Q:

UIButton Memory Management - How to manage it?

I have nearly 45 UIButtons in my view, i know that the buttons have not been allocated to the memory, somehow the compiler alloc/release it, but i noticed that the device become slower at this view, so... What should i do to avoid memory leek with the UIButton ??
Here is how i put my buttons into my view:
in myView.h:
UIButton *btn1;

in myView.m :
btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setTitle:@"btn1" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
btn1.backgroundColor = [UIColor clearColor];
btn1.frame = CGRectMake(  arc4random() % 920, arc4random() %600+50  , 65, 65);
[self.view addSubview:btn1];

and how i remove it:
for(UIButton* b in [self.view subviews]){
    [b removeFromSuperview];
    b = nil;

}

A:

Memory leaks by themselves will not produce a significant slow-down of your app. Their effect is filling up the memory and, if in sufficient number, the operating system will kill your app due to excessive memory use. (If the operating system did not kill your app, then you could have a slow down, but since it kills the app, no issue).
In any case, if you are worried by memory leaks, you could fire Instruments and see whether it detects any memory leaks when your view is displayed.
Possibly the reason why you view is slow is that is has to load into memory 45 images, reading them from disk (which is slow). You might think of pre-loading them, and see if this improves things.
An easy way to preload an image is to instantiate it through imageNamed:
 UIImage* img = [UIImage imageNamed:@"myButton1.png"];

You could call that method for all of your buttons and collect all the relevant calls in another method that you could call, e.g., at startup, or at any other moment when it makes sense for you.
EDIT:

when i enter the view and exit and reenter the view and so on

Just a note: you do not need to remove the buttons from their superview (in normal conditions): this will be done by the framework when removing the superview. Could be this that is slowing down the app?
Besides, if the problem happens when exiting/entering the view, could you try and "cache" the whole view (like: instantiating it just once, then displaying it when it is needed).


Q:

C# AES and RSA File Encryption - How to use IV?

I'm writing a program at the moment that works under the following scenario:

I've got some confidential log files that I need to backup to a server.
I have a program that generates these log files every day.
These log files would rarely if ever need to be opened.
I have only one RSA public/private key pair.
The program has only the RSA public key.
I generate a random AES key each time the program makes one of these confidential files.
The program uses this AES key to encrypt the log file.
I then use the RSA public key to encrypt the AES Key
I then backup both the AES encrypted file and RSA encrypted AES key to the server.

As far as I understand, that protocol is fitting for my use case.
The issue I'm having is coding it up in C#. I ran into needing an Initialization Vector(IV) for my AES encryption, I tried to encrypt this along with the AES key by using the public RSA key on both. But the 512(2 * 256) size is larger than RSA is happy to encrypt. So I figured out since I created the Initialization Vector randomly each time just like the AES Key, I can add the IV to the front of the AES ciphertext. However, I'm not sure where the code to do this would be inserted in my functions
Any help in the right direction to the "protocol" or other ways to write the IV to the ciphertext would be great. Thank you in advance.
static public Tuple<byte[], byte[]> EncryptAES(byte[] toEncryptAES, RSAParameters RSAPublicKey)
    {
        byte[] encryptedAES = null;
        byte[] encryptedRSA = null;

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;
                AES.Mode = CipherMode.CBC;
                AES.GenerateIV();
                AES.GenerateKey();
                encryptedRSA = RSAEncrypt(AES.Key, RSAPublicKey);

                using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    ms.Write(AES.IV, 0, AES.KeySize); //DOESNT WORK HERE
                    //Can't use CS to write it to the stream else it will encrypt along with file
                    cs.Write(toEncryptAES, 0, toEncryptAES.Length);
                    cs.Close();
                }
                encryptedAES = ms.ToArray();
            }
        }
        return new Tuple<byte[], byte[]>(encryptedAES, encryptedRSA);
    }
    static public byte[] DecryptAES(byte[] toDecryptAES, byte[] AESKeyAndIV, RSAParameters RSAPrivateKey)
    {
        byte[] AESKey = RSADecrypt(AESKeyAndIV, RSAPrivateKey);

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;
                AES.Key = AESKey;
                ms.Read(AES.IV, 0, AES.KeySize); //Not sure if can read MS here
                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    //Would I need to move 0 to 256?
                    cs.Write(toDecryptAES, 0, toDecryptAES.Length);
                    cs.Close();
                }
                return ms.ToArray();
            }
        }
    }

A:

You where quite close, write out the IV before you create the CryptoStream
static public Tuple<byte[], byte[]> EncryptAES(byte[] toEncryptAES, RSAParameters RSAPublicKey)
{
    byte[] encryptedAES = null;
    byte[] encryptedRSA = null;

    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Mode = CipherMode.CBC;
            AES.GenerateIV();
            AES.GenerateKey();
            encryptedRSA = RSAEncrypt(AES.Key, RSAPublicKey);

            ms.Write(AES.IV, 0, AES.KeySize); //Move the write here.

            using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(toEncryptAES, 0, toEncryptAES.Length);
                cs.Close();
            }
            encryptedAES = ms.ToArray();
        }
    }
    return new Tuple<byte[], byte[]>(encryptedAES, encryptedRSA);
}

For the decrypt, make sure you loop over the read till you have fully read the byte[] for the IV, Stream.Read is not guaranteed to read all the bytes you asked it to read. I usually make a static method ReadFully to ensure all bytes are read.
private static byte[] ReadFully(Stream stream, int length)
{
    int offset = 0;
    byte[] buffer = new byte[length];
    while(offset < length)
    {
        offset += stream.Read(buffer, offset, length - offset);
    }
    return buffer;
}

Then just use that method to read in the IV. You also want to use cs.Read not cs.Write to read out the encrypted data and put the stream in to read mode, however it is easier to just use .CopyTo and copy the data to a new MemoryStream.
static public byte[] DecryptAES(byte[] toDecryptAES, byte[] AESKeyAndIV, RSAParameters RSAPrivateKey)
{
    byte[] AESKey = RSADecrypt(AESKeyAndIV, RSAPrivateKey);

    using (MemoryStream source = new MemoryStream(toDecryptAES))
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Key = AESKey;
            var iv = ReadFully(source, AES.KeySize);
            AES.IV = iv;
            AES.Mode = CipherMode.CBC;

            using (var cs = new CryptoStream(source, AES.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using(var dest = new MemoryStream())
                {
                    cs.CopyTo(dest);
                    return dest.ToArray();
                }
            }
        }
    }
}

For other readers, note that RSAEncrypt and RSADecrypt are wrappers for calls to the RSACryptoServiceProvider.


Q:

Participating with "flight following"

What is the proper procedure for participating with "flight following" when leaving a non-control towered airport?

A:

You can request Flight Following at anytime.
Personally, I wouldn't be in a hurry to request it as soon as you depart. Wait until you're established on course, in a cruise-attitude (instead of a climb), and everything is settled and running smoothly. Then know your position, and how you're going to report it. Know where you're going (both by name and ICAO identifier), and try to anticipate any questions they might ask.
Look for the Center/Approach/Depature where you are (look in your chart supplement for an airport close to you), and call up with:
You: "Seattle Center; November 12345: VFR, with request"
translation: Calling Seattle Center, this is N12345. I'm VFR (so you haven't heard from me before... don't be surprised!), and I have a request.
Center: "November 12345: Say request."
You: "November 12345 is SkyHawk, 10 mi. South of Harvey Field, 4,500 feet. Request VFR Flight Following to Friday Harbor"
translation: I'm a Cessna Skyhawk, my location and altitude will help you find me. I'm asking for FF to this other airport."
Center: "N345: Squawk 4532 and Ident."
You: (Set your transponder to 4532, press the Identify Button), and say "4532 and Ident, N345"
Center: "N345: Radar Contact, 11 mi. south of Sierra Four Tree, at 4,500. Traffic at your 1o'clock, 5 mi. North Bound, Altitude indicates 3,000."translation: I found you on my radar scope, and am describing the position I see you. (If you disagree, speak up!). You have traffic ahead and slightly to your right. Their transponder indicates 3,000 feet, but I cannot independently verify that.


Q:

Vector of objects of derived classes with different templates

Considering the base class below:
template <typename T>
class food {
public:
    T quantity;
};

Now deriving two classes with different template instances:
class cheese: public food<float> {
}
class chocolate: public food<int> {
}

In the main function, I need to create a list of 'food' instances
int main () {
    vector<food*> bucket;
}

Because I don't know what kind of food would be thrown into bucket. However, compiling this code would generate error:
error: missing template arguments before ‘*’ token

Thus, what can I do about this?

Now I need to define member functions for the derived classes:
class cheese: public food<float> {
    float get_q() {return quantity};
}
class chocolate: public food<int> {
    int get_q() {return quantity};
}

The problem is, the compiler would say class food has no member get_q if I call:
bucket.push_back(new cheese);
bucket.push_back(new chocolate);
bucket[0]->get_q();

in main, even if I change the Quantity interface like this
template <typename T>
class Quantity{
public:
    T quantity;
    virtual T get_q() = 0;
};

It seems that the compiler does need to see get_q() defined in food, but that's not possible if food is not a template, right?
Sorry I am a new C++ programmer, a lot of things are not clear for me...

A:

food<float> and food<int> are different types, they cannot be used as if they were polymorphic.
food* does not name a type, since an argument is required for the template (which is what the compiler is telling you)

Either you provide a common base to all food<> types (and you probably need that if the types are really related), or you will need some kind of type erasure wrappers, such as boost::any or boost::variant.

boost::any example :
#include <vector>
#include <boost/any.hpp>

template <typename T>
class food {
public:
    T quantity;
};

class cheese: public food<float> {
};

class cholocate: public food<int> {
};

int main()
{
    std::vector<boost::any> v;
    v.push_back(food<float>());
    v.push_back(food<int>());
}


Q:

Difference between maximum and minimum?

If I have a problem such as this:
We need to enclose a field with a fence.  We have 500m of fencing material and a building is on one side of the field and so won’t need any fencing.  Determine the dimensions of the field that will enclose the largest area.
This is obviously a maximizing question, however what would I do differently if I needed to minimize the area? Whenever I do these problems I just take the derivative, make it equal to zero and find x, and the answer always seems to appear - but what does one do differently to find the minimum or maximum?

A:

The Extreme Value Theorem guarantees that a continuous function on a finite closed interval has both a maximum and a minimum, and that the maximum and the minimum are each at either a critical point, or at one of the endpoints of the interval.
When trying to find the maximum or minimum of a continuous function on a finite closed interval, you take the derivative and set it to zero to find the stationary points. These are one kind of critical points. The other kind of critical points are the points in the domain at which the derivative is not defined.
The usual method to find the extreme you are looking for (whether it is a maximum or a minimum) is to determine whether you have a continuous function on a finite closed interval; if this is the case, then you take the derivative. Then you determine the points in the domain where the derivative is not defined; then the stationary points (points where the derivative is $0$). And then you plug in all of these points, and the endpoints of the interval, into the function, and you look at the values. The largest value you get is the maximum, the smallest value you get is the minimum.
The procedure is the same whether you are looking for the maximum or for the minimum. But if you are not regularly checking the endpoints, you will not always get the right answer, because the maximum (or the minimum) could be at one of the endpoints.
(In the case you are looking for, evaluating at the endpoints gives an area of $0$, so that's the minimum).
(If the domain is not finite and closed, things get more complicated. Often, considering the limit as you approach the endpoints (or the variable goes to $\infty$ or $-\infty$, whichever is appropriate) gives you information which, when combined with information about local extremes of the function (found also by using critical points and the first or second derivative tests), will let you determine whether you have local extremes or not. )


Q:

Android Custom Camera - Crop image inside Rectangle

I have a custom camera app which have a centered rectangle view, as you can see below:

When I take a picture I want to ignore everything outside the rectangle. The view hasn't any connection with the Camera Preview or SurfaceView in my XML view, as follows:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
    android:id="@+id/preview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <SurfaceView
        android:id="@+id/cameraview"
        android:name="com.kut.camera.KutCameraFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <View android:id="@+id/viewTamanho"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="400px"
        android:layout_marginTop="300px"
        android:layout_marginStart="70px"
        android:layout_marginEnd="70px"
        android:background="@drawable/border" />

    <RelativeLayout
        android:id="@+id/rel_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alpha="1"
            android:background="@android:color/black"
            android:orientation="vertical"
            android:padding="10dp" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <TextView
                    android:id="@+id/textViewReferan"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:text="Evidência"
                    android:textColor="@android:color/white"
                    android:textSize="16sp" />

                <Button
                    android:id="@+id/button_exit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentTop="true"
                    android:background="@android:color/transparent"
                    android:text="Sair"
                    android:textColor="#2799CF" />
            </RelativeLayout>

            <LinearLayout
                android:id="@+id/progress_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:gravity="center"
                android:orientation="vertical"
                android:visibility="gone" >

                <ProgressBar
                    android:id="@+id/progressBar1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/islem_value_textView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Carregando..." />

            </LinearLayout>
        </LinearLayout>

        <RelativeLayout
            android:id="@+id/RelativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:alpha="0.9"
            android:background="@android:color/black"
            android:padding="10dp" >

            <ImageView
                android:id="@+id/imageView_foto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:src="@drawable/camera" />

            <ImageView
                android:id="@+id/imageView_photo"
                android:layout_width="80dp"
                android:layout_height="100dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="5dp"
                android:layout_marginEnd="5dp"
                android:padding="5dp"
                android:scaleType="fitCenter"
                android:src="@drawable/fotoicon" />
        </RelativeLayout>
    </RelativeLayout>
</FrameLayout>

Can somebody help me how to crop the image properly? I tried to create a new Bitmap based on my XML but obviously it didn't work, something like:
Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        //.../
        Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length);
        Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, 70, 400, imagemOriginal.getWidth() - 70,
                imagemOriginal.getHeight() - 400);
        //.../
    }

I put those initial values for x and y, and tried to subtract (based on XML values from View referring to marginTop, Bottom, etc...) from width and Height but I hadn't success because I don't know how to match View coordinates with the image coordinates taken from Camera. Also, it seems for me Bitmap.createBitmap does limited crop, apparently I can't crop it to a rectangle directly.

A:

To control cropping, you must control the picture size and the rectangle size.
It is very important to a) choose the picture size with same aspect ratio as the preview, and b) make sure that the preview is not distorted on the screen. If you prepare your app for a wide range of devices, both tasks are not trivial. To achieve the latter, you need to control both preview size and the SurfaceView size. I have explained this in more detail elsewhere.
To keep it simple, I suggest to ignore the tablets that may have natural Landscape orientation. On phones, the captured image will be "rotated" 90° even if you set camera orientation to portrait (which only effects preview). Don't expect setRotation() to fix this for you: by the book, it is allowed to simply set the EXIF flag for the captured image.
You set the margins for viewTamanho in px. This may not scale well on variety of screens. I suggest setting the dimensions of this view programmatically, as certain percent of the preview surface. You can use support library to define this in XML, but I am afraid this will not give you enough control.
With all this at hand, let's say that we have preview of 1280×720, picture of 2560×1440, our screen is 1280×800, and the rectangle is in the middle, 616×400 pixels (which is more or less the size scaled from your screenshot).
The actual preview size on screen will be probably 1000x562, padded on the right and left with black margins of 79px. Then the following code will produce the expected captured picture:
public void onPictureTaken(byte[] data, Camera camera) {
    //.../
    Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length); // 2560×1440
    float scale = 1280/1000F;
    int left = (int) scale*(imagemOriginal.getWidth()-400)/2;
    int top = (int) scale*(imagemOriginal.getHeight()-616)/2;
    int width = (int) scale*400;
    int height = (int) scale*616;
    Matrix rotationMatrix = new Matrix();
    rotationMatrix.postRotate(90);
    Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, left, top, width, height, rotationMatrix, false);
    //.../
}


Q:

Select all body elements except two ids

I need to select all body elements except two ids and apply css rules to them. I am using this code and it works for one id, but when second one is added the code does not work anymore.
This code works:
body>*:not(#frm){
filter: blur(3px);
pointer-events: none;
}

I have tried this, but it does not work:
body>*:not(#frm,#dte2){
  filter: blur(3px);
  pointer-events: none;
}

and this
body>*:not(#frm),(#dte){
  filter: blur(3px);
  pointer-events: none;
}

So my question is how do you select 2 ids?

A:

The problem with selecting two IDs for a :not() negation is that #frm would match the criteria for not being #dte, and #dte would match the criteria for not being #frm.
What you need to do is chain two :not() pseudo-selectors together as body>*:not(#frm):not(#dte):

body>*:not(#frm):not(#dte) {
  filter: blur(3px);
  pointer-events: none;
}

Frm

Dte

Other


Q:

How to pass groovy variable to shell script in Jenkinsfile?

In the Jenkinsfile under script section, I am using the following code to return output something like the following.
deleting 1
deleting 2
deleting 3

I have tried the following script but it seems to be not working.
script {
       prdirectory_lists = ['1','2','3']
       def size3 = prdirectory_lists.size()

        for(k=0;k<size3;k++){
        sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting prdirectory_lists[k] ')
        //sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting ${prdirectory_lists[k]} ')
        //sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo "deleting ${prdirectory_lists[k]}" ')
         }
}

A:

You have to use the correct String Interpolation which is "${variable}" to access the value of a variable.
sh(returnStdout: true, script: 'ssh user1@192.168.1.12 echo deleting "${prdirectory_lists[k]}" ')

The official Jenkins documentation has some good examples for this: String interpolation


Q:

Drawing a segment with dashes

I need to draw an horizontal segment with dashes on it for a doc I'm writing.
I need to subdivide the segment length this way: given l, then length of the segment and n the fraction of the remaining length at each step, the first dash should be at first=l/n from the left, the second at 1/n + (l-first)/n and so on (until the division returns a number less than one)
What tool could I use to draw this automatically, without using a programming language?
Or... what script could do this?
I need and image in png/jpg as the final result.

A:

if you need to do it programmitically, then maybe Logo programming language is your tool. it can also be done rather easily with LATEX and TikZ package, in this case you can consult with the TEX-LATEX site, also have a look at library for image creation, all the answers there link to usefull resources, which could be a bit overkill for what you need, but will work. if it's not have to be done programmiticaly, you can just create the image with Gimp or InkScape, though if you need to create many such dashed lines, it would be better to automate the process, and i don't know if these tools has batch action capability like photoshop.


Q:

how to get more than one minumum value from an int array?

I am trying to get at least 5 minimum values from an array of int's. My code attached works but it skips few values!
public static void main(String[] args) {
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int min = 0;
    int index = 0;
    String output = "";
    for (int x = 0; x < 5; x++){
        min = array[x];
        index++;
        for(int i = index, limit = array.length; i < limit; ++i){
            if(array[i] <= min){
                min = array[i];
                index = i + 1;
                break;
            }
        }
        output += index + "\t";
    }
    System.out.println(output);
}

A:

Arrays.sort(array);
return Arrays.copyOfRange(array, 0, 5);

If you don't want to mutate the array passed in (ie you want to leave it unsorted), add this line first:
int[] array = Arrays.copyOf(array);

A:

Perhaps you could sort the array using Arrays.sort() and then take the first five values:
Arrays.sort(array);

Now array[0] to array[4] contain the lowest 5 values.


Q:

Java Android table not displayed

I made the following code :
TableLayout tableLayout = (TableLayout) tmpView.findViewById(R.id.tableLayout);
    TableRow tableRow;
    TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
    for (int i = 0; i < modules.length(); i++) {
        tableRow = new TableRow(this.getActivity());
        tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
        TextView title = null;
        TextView grade = null;
        try {
            title = new TextView(this.getActivity());
            title.setText(modules.getJSONObject(i).getString("title"));
            grade = new TextView(this.getActivity());
            grade.setText(modules.getJSONObject(i).getString("grade"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tableRow.addView(title);
        tableRow.addView(grade);
        tableLayout.addView(tableRow, lp);
}

But nothing displayed on the screen.
Do you know why it's not working ?

A:

Solution found, TableLayout declared dynamically then set on the view


Q:

Why is this int comparison failing?

Value of unparsedString at the breakpoint:
101010ten十ten, needle21Turn this character 45 degrees either way and you have the x used for the Roman numeral ten.* As a primitive, this character sometimes keeps its meaning of ten and sometimes signifies needle, this latter derived from the kanji for needle (Frame 292). Since the primitive is used in the kanji itself, there is no need to worry about confusing the two. In fact, we shall be following this procedure regularly.Two needles crossing marks the spot, or you can use the Roman character for ten (rotated 45 degrees).I scared away ten vampires with a single cross!15ジュウ、ジッ、ジュッとお、と十分(じっぷん): 10 minutes
十字路(じゅうじろ): crossroads
五十音(ごじゅうおん): the Japanese syllabary
十分(じゅうぶん): enough
十(じゅう): 10, ten
十(とお): 10, ten
十日(とおか): ten days, the tenth day of the month
二十歳(はたち): 20 years old, 20th year
二十日(はつか): twenty days, twentieth day of the month十字架 (じゅうじか), 十文字 (じゅうもんじ), 十 (と), 十 (とお)

ParseKanji method:
 protected Kanji parseKanji(String unparsedString) {
    Kanji kanji = new Kanji();
    String[] fields = unparsedString.split("\u001F");

    int onI = findKatakanaIndex(fields); //17 while debugging
    int kunI = onI + 1;  //18, also checked

    kanji.setMeaning(fields[3]);
    kanji.setCharacter(fields[4]);
    kanji.setJH(fields[onI - 2]);
    kanji.setJTPL(fields[onI - 1]);
    kanji.setOnReading(fields[onI]);

    if (fields.length < kunI){ //returns false
    kanji.setKunReading(fields[onI + 1]);
    } else {
    Log.d("MyTests",  fields.length + " < " + kunI);
    Log.d("MyTests",  kanji.getCharacter() + " does not have a kun Reading");
    }

    return kanji;
}

Logcat:
21 < 18
十 does not have a kun Reading

Note that I previously was comparing by using onI + 1 and the output from logcat was:
21 < 171
十 does not have a kun Reading

A:

21 < 18
十 does not have a kun Reading

This is what it should be printing. Your log statement is wrong though, since it is in the else block you want it to print "21 >= 18".
21 < 171
十 does not have a kun Reading

Was there a chance that 17 or 1 was being represented as a String back when you were using the + operator? That would cause this error as well. You can see that it added 17 and 1 to make "171" rather than 18.


Q:

Create local json in Codepen for AngularJS

The following tutorial points to an external json file. But it is blocked by CORS policy. How can I declare the object locally in order to populate the web table?
Codepen: https://codepen.io/centem/pen/Rwbmmdy
Thank you.
var app = angular.module('myApp', []);
    app.controller('myController',
        function ($scope, $http) {

            var request = {
                method: 'get',
                url: 'https://www.encodedna.com/angularjs/tutorial/birds.json',
                dataType: 'json',
                contentType: "application/json"
            };

            $scope.arrBirds = new Array;

            $http(request)
                .success(function (jsonData) {
                    $scope.arrBirds = jsonData;
                    $scope.list = $scope.arrBirds;
                })
                .error(function () {

                });
        });

A:

Simply declare the variable you want with the json data:
$scope.list = [
{
   "ID": "001",
   "Name": "Eurasian Collared-Dove",
   "Type": "Dove"
},
{
    "ID": "002",
    "Name": "Bald Eagle",
    "Type": "Hawk"
},
{
    "ID": "003",
    "Name": "Cooper's Hawk",
    "Type": "Hawk"
},
{
    "ID": "004",
    "Name": "Bell's Sparrow",
    "Type": "Sparrow"
},
{
    "ID": "005",
    "Name": "Mourning Dove",
    "Type": "Dove"
},
{
    "ID": "006",
    "Name": "Rock Pigeon",
    "Type": "Dove"
},
{
    "ID": "007",
    "Name": "Abert's Towhee",
    "Type": "Sparrow"
},
{
    "ID": "008",
    "Name": "Brewer's Sparrow",
    "Type": "Sparrow"
},
{
    "ID": "009",
    "Name": "Canyon Towhee",
    "Type": "Sparrow"
},
{
    "ID": "010",
    "Name": "Black Vulture",
    "Type": "Hawk"
}];