Q:

UIScrollView with UITapGestureRecognizer and UIPageControl

I'm creating a horizontal scrolling tableview containing images.  I have the swiping functionality working great, and am able to add the images to the scrollView as so in cellForRowAtIndexPath:
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, tv.frame.size.width, 78)];
    [scrollView setContentSize:CGSizeMake(700, 78)];
    UIImage *footImage = [UIImage imageNamed:@"Foot.png"];
    UIImageView *footImageView = [[UIImageView alloc] initWithImage:footImage];
    footImageView.frame = CGRectMake(0, 0, 80, 78);
    footImageView.userInteractionEnabled = YES;
    [scrollView addSubview: footImageView];

    UIImage *handImage = [UIImage imageNamed:@"Hand.png"];
    UIImageView *handImageView = [[UIImageView alloc] initWithImage:handImage];
    handImageView.frame = CGRectMake(90, 0, 80, 78);
    handImageView.userInteractionEnabled = YES;
    [scrollView addSubview: handImageView];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightImage)];
    [scrollView addGestureRecognizer:tapGesture];
    NSLog(@"tapGesture added to scrollView");

    [[cell contentView] addSubview:scrollView];

    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 50, tv.frame.size.width, 50)];
    [pageControl setNumberOfPages:4];
    [[cell contentView] addSubview:pageControl];

My tapGesture is registering with the selector, hightlightImage, and just logging that its calling this method correctly.
- (void) highlightImage
{
    NSLog(@"tapping tapping");
}

What I REALLY am working for is the ability to highlight/select these images if tapped, and highlight/deselect them if tapped again.  I will have another button on screen that will navigate to the next page (irrelevant here).
Am I going down the right path here? Obviously I will populate an NSArray of UIImages and populate the scrollView that way, but just spiking it out for now.  If someone could give me some direction or an example of how to make each button separately selectable/de-selectable, that would be GREAT:)

A:

Use UIButton instead of UIImageView.
It's got built-in selected functionality.
get rid of your gestures and add highlightImage as the action to every button.
make your highlightImage into highlightImage:(id)sender
sender should be a button so you can just do
[sender setSelected:YES];


Q:

Cannot add object of type T to List in java

I have been learning generics in Java. Although I understand the concepts regarding type inference, parameterized classes and methods, I came across a strange scenario while experimenting.
I have implemented a Box class which can be used to hold items of type T. I am using List as an internal data structure for this abstraction. Following is my code:
public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T> void addItemToBox(T t){
        items.add(t);
    }
}

I am getting a compile time error at items.add(t) saying add(T) in List cannot be applied to (T). I am unable to figure out the cause of this error. Also, I don't understand why I can't add an item of type T to a list which is parameterized by T.

A:

You've made a local redeclaration of generic type variable <T> on your method addItemToBox that shadows the one on class Box<T>.
The <T> on your method is not the same  on List<T> items;
Your current code is 100% equivalent to:
public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T2> void addItemToBox(T2 t){
        items.add(t);
    }
}

If you see it that way, it should be clear why your code fails to compile.
Solution: remove the <T> in front of the method declaration
public void addItemToBox(T t)


Q:

Why wasn't the synchronous action executed until the asynchronous action completed?

I'm implementing Comet in ASP.NET MVC.  I used a timer to keep an async request in the server.  The async request will complete when the timer elapses after 1 minute and sends a response to the client (to avoid 404 error) and then reconnects to Async Controller.
I also want to execute some synchronous actions while the async request was holding, but the problem is:

When an async action was executed and hold by using timer, the sync action wasn't called until the async action (Comet long-live request) completed.

I did the test with Firefox 3.6 many times, but the result is always the same; it is so strange. Do you know why?
I have a sub-question:

To implement Comet, using a timer (response after some minutes elapsed) or thread (response after several time sleeping thread) to hold async request; which is better?

A:

I found the answer for my problems.
First,the reason why Sync action wasn't executed while Async action holding because session request block mechanic, Asp.net session block request so that all requests will be process one by one even you use concurrent request with Ajax Async Call. And the solution is disable session on controller you want to hold long-live request. Here is detail explanation: https://blogs.msdn.com/b/rickandy/archive/2009/12/17/session-less-mvc-controller.aspx
The second, when perform holding long-live request,using timer and thread sleeping are NOT different, because Asp.net thread pool will essentially create new thread to track time elapsed and call back to your timer elapsed event. It will decrease number of threads to serve request in thread pool because it born new thread to track timer event.


Q:

Printing a variable memory address in swift

Is there anyway to simulate the [NSString stringWithFormat:@"%p", myVar], from Objective-C, in the new Swift language?
For example:
let str = "A String"
println(" str value \(str) has address: ?")

A:

Note: This is for reference types.
Swift 4/5:
print(Unmanaged.passUnretained(someVar).toOpaque())

Prints the memory address of someVar.
(thanks to @Ying)

Swift 3.1:
print(Unmanaged<AnyObject>.passUnretained(someVar as AnyObject).toOpaque())

Prints the memory address of someVar.

A:

Swift 2
This is now part of the standard library: unsafeAddressOf.
/// Return an UnsafePointer to the storage used for `object`.  There's
/// not much you can do with this other than use it to identify the
/// object

Swift 3
For Swift 3, use withUnsafePointer:
var str = "A String"
withUnsafePointer(to: &str) {
    print(" str value \(str) has address: \($0)")
}

A:

Note that this answer was quite old. Many of the methods it describes no longer work. Specifically .core cannot be accessed anymore.
However @drew's answer is correct and simple:

This is now part of the standard library: unsafeAddressOf.

So the answer to your questions is:
println(" str value \(str) has address: \(unsafeAddressOf(str))")

Here is the original answer that was marked correct (for posterity/politeness):
Swift "hides" pointers, but they still exists under the hood. (because the runtime needs it, and for compatibility reasons with Objc and C)
There are few things to know however, but first how to print the memory address of a Swift String?
    var aString : String = "THIS IS A STRING"
    NSLog("%p", aString.core._baseAddress)  // _baseAddress is a COpaquePointer
   // example printed address 0x100006db0

This prints the memory address of the string, if you open XCode -> Debug Workflow -> View Memory and go to the printed address, you will see the raw data of the string.
Since this is a string literal, this is a memory address inside the storage of the binary (not stack or heap).
However, if you do
    var aString : String = "THIS IS A STRING" + "This is another String"
    NSLog("%p", aString.core._baseAddress)

    // example printed address 0x103f30020

This will be on the stack, because the string is created at runtime
NOTE: .core._baseAddress is not documented, I found it looking in the variable inspector, and it may be hidden in the future
_baseAddress is not available on all types, here another example with a CInt
    var testNumber : CInt = 289
    takesInt(&testNumber)

Where takesInt is a C helper function like this
void takesInt(int *intptr)
{
    printf("%p", intptr);
}

On the Swift side, this function is takesInt(intptr: CMutablePointer<CInt>), so it takes a CMutablePointer to a CInt, and you can obtain it with &varname
The function prints 0x7fff5fbfed98, an at this memory address you will find 289 (in hexadecimal notation). You can change its content with *intptr = 123456
Now, some other things to know.
String, in swift, is a primitive type, not an object.
CInt is a Swift type mapped to the C int Type.
If you want the memory address of an object, you have to do something different.
Swift has some Pointer Types that can be used when interacting with C, and you can read about them here: Swift Pointer Types
Moreover, you can understand more about them exploring their declaration (cmd+click on the type), to understand how to convert a type of pointer into another
    var aString : NSString = "This is a string"  // create an NSString
    var anUnmanaged = Unmanaged<NSString>.passUnretained(aString)   // take an unmanaged pointer
    var opaque : COpaquePointer = anUnmanaged.toOpaque()   // convert it to a COpaquePointer
    var mut : CMutablePointer = &opaque   // this is a CMutablePointer<COpaquePointer>

    printptr(mut)   // pass the pointer to an helper function written in C

printptr is a C helper function I created, with this implementation
void printptr(void ** ptr)
{
    printf("%p", *ptr);
}

Again, an example of the address printed: 0x6000000530b0 , and if you go through memory inspector you will find your NSString
One thing you can do with pointers in Swift (this can even be done with inout parameters)
    func playWithPointer (stringa :AutoreleasingUnsafePointer<NSString>)
    {
        stringa.memory = "String Updated";
    }

    var testString : NSString = "test string"
    println(testString)
    playWithPointer(&testString)
    println(testString)

Or, interacting with Objc / c
// objc side
+ (void)writeString:(void **)var
{
    NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"];
    *var = (void *)CFBridgingRetain(aString);   // Retain!
}

// swift side
var opaque = COpaquePointer.null()   // create a new opaque pointer pointing to null
TestClass.writeString(&opaque)
var string = Unmanaged<NSString>.fromOpaque(opaque).takeRetainedValue()
println(string)
// this prints pippo pluto


Q:

Jsf, Limitting on the number of caracteres to display?

I'm working on a jsf application. I have a dataTable, I use one column to render the description of a Pojo.
The problem is : This description it too long and the dataTable is not perfectly lisible.
Is there a way to limit the number of caracteres to render on the description column of this dataTable like : Description desc desc...

A:

If you are using JSF 2, you can use the function of:abbreviate from the OmniFaces project.
Put the JAR file in your WEB-INF/lib, configure the namespace accordingly in your XHTML file like this:
<html ... xmlns:of="http://omnifaces.org/functions">

and then you can use it on any String property, like this:
<h:column>
    <h:outputText value="#{of:abbreviate(someBean.myproperty, 20)}" />
</h:column>

See the demo here.


Q:

XAML style binding

I have a button, and I have a boolean property in a view-model called BooleanSwitch.
I want the text and forecolor of the button to be either:

green ON, when BooleanSwitch is true
red OFF, when BooleanSwitch is false

And I want it to change dynamically when the value changes.
Sure, I can do it in the codebehind.
But is there a XAML solution for this? I have tried the following:
<Style x:Key="SwitchButtonStyle" TargetType="Button">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=BooleanSwitch}" Value="true">
            <Setter Property="Foreground" Value="Red"/>
            <Setter Property="Content" Value="ON"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=BooleanSwitch}" Value="false">
            <Setter Property="Foreground" Value="#00AA00" />
            <Setter Property="Content" Value="OFF"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

<Button Click="button_Click" Style="{DynamicResource SwitchButtonStyle}" />

And the click method is just:
private void button_Click(object sender, RoutedEventArgs e)
{
    BooleanSwitch = !BooleanSwitch;
}

The code of the BooleanSwitch couldn't be simpler (.NET 4.5):
    private bool privateBooleanSwitch;
    public bool BooleanSwitch
    {
        get { return privateBooleanSwitch; }
        set
        {
            if (value == privateBooleanSwitch)
                return;

            privateBooleanSwitch= value;
            OnPropertyChanged();
        }
    }

When loaded, the triggers activate and the button is red with , but when I click the button, they no longer work...and I can see I'm probably not understanding well how DataTriggers work.
What am I doing wrong?
The button is a single purpose button but I've already found out I can't use a DataTrigger inside a specific element. I was thinking about creating another properties containing text & color and then binding those to the button properties but that just seems to me as unneccessary code tailoring, I'd rather use XAML for defining colors and texts.

A:

Me.
Dumb.
Guess what.
public abstract class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

I actually implemented the interface INotifyPropertyChanged but forgot to mention it in the class definition.
public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Instead of looking for a mistake here, I was certain there must be a mistake in my understanding of WPF triggers. Thanks to LPL.


Q:

How to write a html gui (django) for a python server module

What's the way to go to build a HTML gui for eg a multiplexed tcp server in python?
I am familiar with building websites with Django, but the thing i don't understand is, how is the tcp server part communicating with the Django related views? How could i implement the data sharing (do i see the wood for the trees)?
The problem for me is the mapping between the stateless "get an leave" and the "state full" py module "running as a daemon".
greetings
edit my standalone application skeleton:
#!/usr/bin/python

from django.core.management import setup_environ
import settings
setup_environ(settings)

from myapp.models import fanzy

def main():
    for each in fanzy.objects.all():
        print each.id, each.foo

if __name__ == '__main__':
    main()

A:

Django is just Python, so anything you've written in Python can be imported and referenced in the 'views' that you write for Django to serve back as HTTP responses.
In answer to another part of your question, the way a HTTP server handling TCP connections communicates with the python framework is most commonly through a protocol called WSGI. This is a good place to get more knowledge about the principles of WSGI. This is another.
With regards to running a background process and serving up a view of that processes' activities, it may be better to keep the two problems separate. You could write data to a file or a database and then access and serve this data via your web application.
These are just general comments, because your question is not totally clear. Please feel free to respond with further questions.


Q:

QPushButton is not changing the background-color proper

I have a problem with a QPushButton.
I use QT 4.8 and the Designer.
I configured the button to be "flat" and "checkable".
The button should be red if not checked and green if checked.
To style the button I use a stylesheet.
      QPushButton:default{
         background-color: red;
             color: red;
      }

      QPushButton:checked{
         background-color: green;
             color: black;
      }

Now the problem. If the button is unchecked it is gray. When I press the button he turns green like it should.
I tried different other pseudo-states, like !checked, or tried to change to a normal button. But it's always the same. In default state the stylesheet isn't working. If I presse, hover or what ever the button it is changing like I want it.
Any body encountered the same problem and has a solution?
To explain it a little bit further. The color attribute is working correct.
The text is always red, except I push the button then it's black.
So the style sheet is in use but, just the background-color attribute is not working.
I tried different styles, like motif, cde, cleanlooks etc and it's always the same.

A:

I found this in QPushButton Class Reference. "This property's default is false. If this property is set, most styles will not paint the button background unless the button is being pressed. setAutoFillBackground() can be used to ensure that the background is filled using the QPalette::Button brush." Because of this I found the following solution.
First of all I kept the style sheet option for checked
     QPushButton:checked{
         background-color: green.
     }

The I used a palette and set the background color and the setAutoFillBackground function.
     palette_red->setColor(window.button->backgroundRole(), QColor(255, 0, 0, 127));
     window.button->setAutoFillBackground(true);
 window.button->setPalette(*palette_red);

I use the toggle signal to catch changes.
When the button is toggle is TRUE the style sheet starts working.
To not get double (green over red) colors the setAutoFillBackground has to be turned off again.
     window.button->setAutoFillBackground(false);

The not toggled state is nearly the same.
I needed to turn on the setAutoFillBackground and set the palette again.
     window.button->setAutoFillBackground(true);
     window.button->setPalette(*palette_red);

It's a solution, it works but I am still open for further inputs.


Q:

How to convert IP address range to CIDR in Java?

I am trying to convert the IP address range into the CIDR notation in Java. Can someone provide an example of how this can be achieved?
I used the SubnetUtils for converting the CIDR to IP address range, but I can't figure out the other way round.
For example: (using http://ip2cidr.com/)

Input 1: 5.10.64.0
Input 2: 5.10.127.255
Result: 5.10.64.0/18

Thanks,
Dhaval

A:

import java.util.ArrayList;
import java.util.List;

public class RangeToCidr {
    public static List<String> range2cidrlist( String startIp, String endIp ) {
        // check parameters
        if (startIp == null || startIp.length() < 8 ||
            endIp == null || endIp.length() < 8) return null;
        long start = ipToLong(startIp);
        long end = ipToLong(endIp);
        // check parameters
        if (start > end) return null;

        List<String> result = new ArrayList<String>();
        while (start <= end) {
            // identify the location of first 1's from lower bit to higher bit of start IP
            // e.g. 00000001.00000001.00000001.01101100, return 4 (100)
            long locOfFirstOne = start & (-start);
            int maxMask = 32 - (int) (Math.log(locOfFirstOne) / Math.log(2));

            // calculate how many IP addresses between the start and end
            // e.g. between 1.1.1.111 and 1.1.1.120, there are 10 IP address
            // 3 bits to represent 8 IPs, from 1.1.1.112 to 1.1.1.119 (119 - 112 + 1 = 8)
            double curRange = Math.log(end - start + 1) / Math.log(2);
            int maxDiff = 32 - (int) Math.floor(curRange);

            // why max?
            // if the maxDiff is larger than maxMask
            // which means the numbers of IPs from start to end is smaller than mask range
            // so we can't use as many as bits we want to mask the start IP to avoid exceed the end IP
            // Otherwise, if maxDiff is smaller than maxMask, which means number of IPs is larger than mask range
            // in this case we can use maxMask to mask as many as IPs from start we want.
            maxMask = Math.max(maxDiff, maxMask);

            // Add to results
            String ip = longToIP(start);
            result.add(ip + "/" + maxMask);
            // We have already included 2^(32 - maxMask) numbers of IP into result
            // So the next round start must add that number
            start += Math.pow(2, (32 - maxMask));
        }
        return result;
    }

    private static long ipToLong(String strIP) {
        String[] ipSegs = strIP.split("\\.");
        long res = 0;
        for (int i = 0; i < 4; i++) {
            res += Long.valueOf(ipSegs[i]) << (8 * (3 - i));
        }
        return res;
    }

    private static String longToIP(long longIP) {
        StringBuffer sb = new StringBuffer();
        sb.append(longIP >>> 24).append(".")
          .append((longIP & 0x00FFFFFF) >>> 16).append(".")
          .append(String.valueOf((longIP & 0x0000FFFF) >>> 8)).append(".")
          .append(String.valueOf(longIP & 0x000000FF));

        return sb.toString();
    }
}

A:

The open-source IPAddress Java library can do this for you.  Disclaimer: I am the project manager of the IPAddress library.
Here is sample code to do it:
static void toPrefixBlocks(String str1, String str2) {
    IPAddressString string1 = new IPAddressString(str1);
    IPAddressString string2 = new IPAddressString(str2);
    IPAddress one = string1.getAddress(), two = string2.getAddress();
    IPAddressSeqRange range = one.toSequentialRange(two);
    System.out.println("starting with range " + range);
    IPAddress blocks[] = range.spanWithPrefixBlocks();
    System.out.println("prefix blocks are " + Arrays.asList(blocks));
}

This is how you would use IPAddress to produce the range from the original CIDR string:
static String[] toRange(String str) {
    IPAddressString string = new IPAddressString(str);
    IPAddress addr = string.getAddress();
    System.out.println("starting with CIDR " + addr);
    IPAddress lower = addr.getLower(), upper = addr.getUpper();
    System.out.println("range is " + lower + " to " + upper);
    return new String[] {lower.toString(), upper.toString()};
}

For your example, we run this code:
String strs[] = toRange("5.10.64.0/18");
System.out.println();
toPrefixBlocks(strs[0], strs[1]);

The output is:
starting with CIDR 5.10.64.0/18
range is 5.10.64.0/18 to 5.10.127.255/18

starting with range 5.10.64.0 -> 5.10.127.255
prefix blocks are [5.10.64.0/18]


Q:

Perl - Value of variable not working in a condition

I created this function.
When I print my variable my $bios_current, it shows $VAR1 = '200';
But my condition if ( $bios_current->responseCode() ne 200) considers that it is not 200.
Could you help me ? Is it a type problem ?
sub check_thermalshutdown_settings {
  my $host = shift;
  if ($host->get_property('summary.hardware.model') eq "ProLiant DL360 Gen9") {
    my $error="";
    my $bios="";
    try {
      my $ilo = get_ilo_address($host->name);
      my $client = REST::Client->new();
      $client->setHost("https://$ilo");
      $client->addHeader("Authorization", "Basic blabla==");
      eval {
        local $SIG{ALRM} = sub { };
        alarm 3;
        #$client->GET("/redfish/v1/Systems/1/Bios/");
        my $bios_current = $client->GET("/redfish/v1/Systems/1/Bios/");
        print Dumper $bios_current->responseCode;
        alarm 0;
      };
      if ( $bios_current->responseCode() ne 200) {
        $bios = "none";
        $error = "Redfish API returned code ".$client->responseCode();
        print Dumper $client->responseCode();
        } else {
        my $json = decode_json($client->responseContent());
        #print Dumper $client->responseContent();

        #$bios = $json->{'Bios'}->{'Settings'}->{'ThermalShutdown'};
        $bios = $json->{'ThermalShutdown'};
        #print Dumper $bios;
        print Dumper $json->{'ThermalShutdown'};
        print "API call is ok\n";
        print  Dumper  $client->setHost("https://$ilo");

      }
    } catch {
      $bios = "none";
      $error=$_;
    };

A:

You problem has nothing to do with type.
The first thing every Perl coder should learn is the following two statements should appear at the top of every script.
use strict;
use warnings;

These two statements catch a multitude of errors one of which is the cause of your problem.
If you take a look at your eval block
eval {
    local $SIG{ALRM} = sub { };
    alarm 3;
    #$client->GET("/redfish/v1/Systems/1/Bios/");
    my $bios_current = $client->GET("/redfish/v1/Systems/1/Bios/");
    print Dumper $bios_current->responseCode;
    alarm 0;
};

You will see that the variable $bios_current is introduced with the my modifier this restricts the lifetime of the variable to the current scope, in this case the eval block.
So by the time your if statement is run the variable no longer exists and Perl helpfully creates a new empty one for you, Perl then tries to call responseCode() on the empty variable, this fails and normally would terminate the program, however you are inside a try() block at this point so instead of displaying the error the code jumps to the catch bloc instead.


Q:

Cast to ObjectId failed for value "{ id: '5f1c64aa177bf9379491ecc8' }" at path "_id" for model "User"

I'am trying to make simple todoapp with Nestjs.
I have two module one is User and Task. Task module works just fine i can add new task, findbyId method works fine.I can add new User but when i've tried to findbyId in user model this happen {"statusCode":500,"message":"Internal server error"} error.
user.schema.ts:
export const UserSchema = new mongoose.Schema({
    email: {type:String},
    nickname:{type:String, required:[true, 'Nickname is required']},
    password:{type:String, required:[true, 'Password is required']},
    tasks: { type:Array },
    updateAt:{type:Date, default:Date.now},
})

user.service.ts:
async getOne(id:string): Promise<User>{
    return await this.userModel.findById(id).exec();
    }

task.schema.ts
export const TaskSchema = new mongoose.Schema({
    title: { type:String, required:true},
    user: {type:String ,required:true},
    description: {type:String, required:false},
    category: {type:String,required:true},
    updateAt:{type:Date, default:Date.now}
})

task.service.ts
async getOne(id: string): Promise <Task>{
    return await this.taskModel.findById(id).exec();
}

Thank you for your time !

A:

Seems like your id value in the getOne method is not actually a string, but rather an Object containing:
{ id: '5f1c64aa177bf9379491ecc8' }
So you could change this to call findById with the actual id:
async getOne(idHolder: any): Promise <Task>{

    return await this.taskModel.findById(idHolder.id).exec();
}


Q:

Trouble with a sortedInsert into a singly LinkedList.of Objects with attributes Java

This method will create a new Node object and insert it in order by the 3rd value in the CSV(i.e. KYZ98765, ABC12345, etc.)  it works except for the last node insert...
Here is my code:
void sortedInsert(Node new_node)
{
     Node current;

    /* Locate the correct node before inserting. */

    //System.out.println(current.data);
    if(head.next == null)
    {
        new_node.next = head;
        head = new_node;
        System.out.println("Inserted head: \n" + head.data.toString());
    }else
    {
        current = head;

        while (current.data.getbLnum().compareTo(new_node.data.getbLnum())>=0)
        {
            System.out.println("here again");
            current = current.next;
        }
        new_node.next = current.next;
        current.next = new_node;
        System.out.println("Inserted: \n" + current.next.data.toString());
    }

 }

Here is the output:
FundManagerLicense   FundManagerLastname   FundManagerFirstname
  ABC12345               Wonch                Bob
 FundManagerLicense   FundManagerLastname   FundManagerFirstname
  ZYK98765               Ferguson                Jesus
 FundManagerLicense   FundManagerLastname   FundManagerFirstname
  GYZ98765               Ferguson                Jose
 FundManagerLicense   FundManagerLastname   FundManagerFirstname
  KYZ98765               Ferguson                Jimmi
This is my input in the order each element is fed to the sortedInsert:
BROKER,ADD,KYZ98765,Jimmi,Ferguson,321-131,0.02
BROKER,ADD,ABC12345,Bob,Wonch,321-112,0.1
BROKER,ADD,GYZ98765,Jose,Ferguson,321-111,0.02
BROKER,ADD,ZYK98765,Jesus,Ferguson,321-141,0.02
Can anyone see what is going wrong?

A:

Try it this way.
private int compare(Node n1, Node n2) {
    return n1.data.getbLnum().compareTo(n2.data.getbLnum());
}

void sortedInsert(Node newNode) {
    Node prev = null;
    Node next = head;

    while (next != null &&
            compare(newNode, next) >= 0) {
        prev = next;
        next = next.next;
    }

    if (prev == null) head = newNode;
    else prev.next = newNode;
    newNode.next = next;
}

It should be fairly self-explanatory, go through the list, keeping track of the nodes that will come before (prev) and after (next) the inserted node, until next is null, or until newNode cannot come after next. Then insert the new node and, if necessary, make it the head.


Q:

Converting a row of a pandas dataframe into a dataframe itself (instead of a series)?

I have a df that I'm iterating over, like so
for _, row in df.iterrows():
       process(row)

The function process takes the argument and itself does an iterrows() on it. It does this because it is normally passed a dataframe. However, I'd like to pass a single row to process and still have it function normally. The problem is that row is a Series, and not a dataframe. And Series can not be iterated over with an .iterrows() method. I tried converting the row to a dataframe like so
row = row.to_frame()
but that doesn't seem to preserve the indices, columns, etc.
Is there a way to do this easily? Or should I re-write the process function to be able to handle a single Series/row?

A:

You can transpose the output of to_frame:
s.to_frame().T

That said, this seems a strange thing to require, a refactor of process may be a good idea. But perhaps you can get away with chunkifying into smaller dataframes:
for chunk in np.array_split(df, 50):  # 50 chunks
    process(chunk)


Q:

Get properties from dynamic object using startswith

I want to get all properties from json that StartsWith particular text
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);

So now below is what i get in results
{"abc" : "Text", "abcde" : "Text2","prop" : "myprop"}

Is it possible to do something like
results.Where(x => x.StartsWith("abc"))

A:

You could simply use results.GetType().GetProperties(), which will give you an array of properties present in the deserialized JSON object.
You could then iterate over that array to get the PropertyInfo objects whose Name starts with whatever string you want, and call GetValue() to obtain the properties' values of interest.
Or you simply don't deserialize at all, but parse the object and treat it as JSON:
var jObject = JObject.Parse(jsonString);

foreach (var rootProperty in jObject)
{
    if (rootProperty.Key.StartsWith("whatever"))
    {
        var valueOfInterest = rootProperty.Value;
    }
}


Q:

Systemd service is inactive (dead), but only after many weeks

I have a custom systemd service that scans the filesystem with inotify and creates files upon certain events.
The service works fine for many days, sometimes even for several weeks. Then suddenly it is stopped. It is configured to use Restart=always, so I would expect the service to self-recover upon failure, but this isn't happening.
I would like to know how to determine why the service is not recovering itself and how to fix the issue.
Here is the service config:
[Unit]
Description=Sets a PID limit (pids.max) for each container in the docker host
After=docker.service
Wants=docker.service

[Service]
Type=simple
Restart=always
StartLimitInterval=0
RestartSec=5
ExecStart=/opt/scripts/container-pid-limit.sh
StandardError=journal

And the contents of the file /opt/scripts/container-pid-limit.sh
#!/bin/bash -x
MAX_PIDS=5000
CGROUPS_DIR=/sys/fs/cgroup/pids/docker/
CONTAINERS_DIR=/srv/docker_root/containers/

set_limit() {
  limit=$(grep -ir label $CONTAINERS_DIR/$1/config.v2.json | jq -r '.Config.Labels["com.xyz.pid_limit"]')

  if [[ ! $limit -gt 0 ]] ; then
    limit=$MAX_PIDS
  fi

  echo "CONTAINER: $c LIMIT $limit FILE $f"
  echo $limit > $f;
}

# set pids.max for already created containers
for f in $(find $CGROUPS_DIR -mindepth 2 -name pids.max); do
  c=$(dirname $f | xargs basename)
  set_limit $c
done

# monitor cgroup dir for newly created dirs
inotifywait --event create,isdir --monitor --quiet --format "%w%f" $CGROUPS_DIR | while read -r line; do
  c=$(basename $line)
  set_limit $c
done

Sample output of systemctl status before failure:
● container-pid-limit.service - Sets a PID limit (pids.max) for each container in the docker host
   Loaded: loaded (/etc/systemd/system/container-pid-limit.service; static; vendor preset: enabled)
   Active: active (running) since Wed 2019-06-05 08:44:38 UTC; 14min ago
 Main PID: 277527 (container-pid-l)
    Tasks: 3
   Memory: 2.3M
      CPU: 79ms
   CGroup: /system.slice/container-pid-limit.service
           ├─277527 /bin/bash /opt/scripts/container-pid-limit.sh
           ├─277892 inotifywait --event create,isdir --monitor --quiet --format %w%f /sys/fs/cgroup/pids/docker/
           └─277893 /bin/bash /opt/scripts/container-pid-limit.sh

Sample output of systemctl status after failure:
● container-pid-limit.service - Sets a PID limit (pids.max) for each container in the docker host
   Loaded: loaded (/etc/systemd/system/container-pid-limit.service; static; vendor preset: enabled)
   Active: inactive (dead)

EDIT: I am trying to use systemctl status and systemctl show to identify when the service was started and eventually stopped, but it seems to me that when the service fails all the history is lost:
Reference:
https://unix.stackexchange.com/questions/368767/how-do-i-see-when-a-systemd-service-was-started-stopped-restarted
Sample output of systemctl show:
Type=simple
Restart=always
NotifyAccess=none
RestartUSec=5s
TimeoutStartUSec=1min
TimeoutStopUSec=45s
RuntimeMaxUSec=infinity
WatchdogUSec=0
WatchdogTimestampMonotonic=0
FailureAction=none
PermissionsStartOnly=no
RootDirectoryStartOnly=no
RemainAfterExit=no
GuessMainPID=yes
MainPID=0
ControlPID=0
FileDescriptorStoreMax=0
NFileDescriptorStore=0
StatusErrno=0
Result=success
ExecMainStartTimestampMonotonic=0
ExecMainExitTimestampMonotonic=0
ExecMainPID=0
ExecMainCode=0
ExecMainStatus=0
ExecStart={ path=/opt/scripts/container-pid-limit.sh ; argv[]=/opt/scripts//container-pid-limit.sh ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
Slice=system.slice
MemoryCurrent=18446744073709551615
CPUUsageNSec=18446744073709551615
TasksCurrent=18446744073709551615
Delegate=no
CPUAccounting=no
CPUShares=18446744073709551615
StartupCPUShares=18446744073709551615
CPUQuotaPerSecUSec=infinity
BlockIOAccounting=no
BlockIOWeight=18446744073709551615
StartupBlockIOWeight=18446744073709551615
MemoryAccounting=no
MemoryLimit=18446744073709551615
DevicePolicy=auto
TasksAccounting=no
TasksMax=18446744073709551615
UMask=0022
LimitCPU=18446744073709551615
LimitCPUSoft=18446744073709551615
LimitFSIZE=18446744073709551615
LimitFSIZESoft=18446744073709551615
LimitDATA=18446744073709551615
LimitDATASoft=18446744073709551615
LimitSTACK=18446744073709551615
LimitSTACKSoft=8388608
LimitCORE=18446744073709551615
LimitCORESoft=0
LimitRSS=18446744073709551615
LimitRSSSoft=18446744073709551615
LimitNOFILE=4096
LimitNOFILESoft=1024
LimitAS=18446744073709551615
LimitASSoft=18446744073709551615
LimitNPROC=7869937
LimitNPROCSoft=7869937
LimitMEMLOCK=65536
LimitMEMLOCKSoft=65536
LimitLOCKS=18446744073709551615
LimitLOCKSSoft=18446744073709551615
LimitSIGPENDING=7869937
LimitSIGPENDINGSoft=7869937
LimitMSGQUEUE=819200
LimitMSGQUEUESoft=819200
LimitNICE=0
LimitNICESoft=0
LimitRTPRIO=0
LimitRTPRIOSoft=0
LimitRTTIME=18446744073709551615
LimitRTTIMESoft=18446744073709551615
OOMScoreAdjust=0
Nice=0
IOScheduling=0
CPUSchedulingPolicy=0
CPUSchedulingPriority=0
TimerSlackNSec=50000
CPUSchedulingResetOnFork=no
NonBlocking=no
StandardInput=null
StandardOutput=journal
StandardError=journal
TTYReset=no
TTYVHangup=no
TTYVTDisallocate=no
SyslogPriority=30
SyslogLevelPrefix=yes
SyslogLevel=6
SyslogFacility=3
SecureBits=0
CapabilityBoundingSet=18446744073709551615
AmbientCapabilities=0
MountFlags=0
PrivateTmp=no
PrivateNetwork=no
PrivateDevices=no
ProtectHome=no
ProtectSystem=no
SameProcessGroup=no
UtmpMode=init
IgnoreSIGPIPE=yes
NoNewPrivileges=no
SystemCallErrorNumber=0
RuntimeDirectoryMode=0755
KillMode=control-group
KillSignal=15
SendSIGKILL=yes
SendSIGHUP=no
Id=container-pid-limit.service
Names=container-pid-limit.service
Requires=sysinit.target system.slice
Wants=docker.service
Conflicts=shutdown.target
Before=shutdown.target
After=basic.target systemd-journald.socket system.slice docker.service sysinit.target
Description=Sets a PID limit (pids.max) for each container in the docker host
LoadState=loaded
ActiveState=inactive
SubState=dead
FragmentPath=/etc/systemd/system/container-pid-limit.service
UnitFileState=static
UnitFilePreset=enabled
StateChangeTimestampMonotonic=0
InactiveExitTimestampMonotonic=0
ActiveEnterTimestampMonotonic=0
ActiveExitTimestampMonotonic=0
InactiveEnterTimestampMonotonic=0
CanStart=yes
CanStop=yes
CanReload=no
CanIsolate=no
StopWhenUnneeded=no
RefuseManualStart=no
RefuseManualStop=no
AllowIsolate=no
DefaultDependencies=yes
OnFailureJobMode=replace
IgnoreOnIsolate=no
NeedDaemonReload=no
JobTimeoutUSec=infinity
JobTimeoutAction=none
ConditionResult=no
AssertResult=no
ConditionTimestampMonotonic=0
AssertTimestampMonotonic=0
Transient=no
StartLimitInterval=0
StartLimitBurst=5
StartLimitAction=none

A:

SystemD Restart-Always is not meant to be a loop. It's about failure-handling.
RTFM on StartLimitBurst


Q:

How to calculate air resistance?

What is the best way to calculate or take into account air resistance?
I have an assignment which goes as:

Drop an object by itself and with a parachute, calculate air resistance for the parachute. It is assumed the object itself has no air resistance

Im kinda confused how to proceed with this since we have no course text book and there are no lessons just assignments

A:

Your teacher or professor that assigned the practical experiment to you wants to help you put air resistance into perspective, so you'll have to make a clear distinction between just the fall and the fall with parachute. If you can access a height of about 40 feet, this will be enough to provide the clearance to record the time efficiently and also provide a good difference between the two cases. Weigh the combined mass of mass+parachute+strings with a precise and sensitive weight meter. Drop the ordinary mass first (for reference) couple of times and average the time observed. Now do the same for the mass plus parachute and average also.
Air resistance is a negating force on a moving object, hence the difference in net force on the body without parachute and that with parachute is the air resistance force.
Using $F=\frac {md}{t^2}$ you can calculate the net force on the mass with parachute and $F=9.8m$ for just the mass.


Q:

Installing Cython encountered loop dependency

I am installing cython to my python.
I unzipped the tar.gz and did the build-install routine.
Then, setup.py told me:
Traceback (most recent call last):
  File "setup.py", line 238, in <module>
    compile_cython_modules(cython_profile, cython_compile_more, cython_with_refnanny)
  File "setup.py", line 170, in compile_cython_modules
    from Cython.Distutils import build_ext
ImportError: No module named Cython.Distutils

So it means, I need cython to install cython?
Or did I miss something important?

A:

The reason lays in 'rz' command which did not commit a intact transfer but gave no error.
The package I unzipped was a broken one uploaded by others. I downloaded another and finally got it right.
suggestion: use following command to check your package's integrity first.
>md5sum sth.tar.gz                show checksum
>du -h st.tar.gz                  show human-readable file size

And thanks Kevin Guan for the suggestions and help.


Q:

Equation Numbers Appearing Below Equations

I am new to LaTex, but I am trying to make it so that my equation numbers are aligned with my equations. However, what keeps happening (and I can't explain why) is my equation numbers start appearing below my equations at about the 10th equation. The first 9 equations seem to be okay though, but I haven't really changed anything in regards to my formatting so I am not able to explain what the problem is. Additionally, I am not sure how you would go about getting some extra space before the equation numbers because it appears to be fairly cluttered.
Like I said, I am fairly new to LaTex so my code is probably gross, but if somebody has any recommendations I would be happy to hear them.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{lipsum}
\usepackage[margin=1in, includefoot]{geometry}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{enumitem}
\usepackage{ stmaryrd }
\usepackage{comment}

\begin{document}

\begin{align}
    \min_{L_{t}} \quad & \sum_{i=1}^I\sum_{j=1}^J\sum_{t=1}^T(a + b L_{t}^{ij}) G_{t,PostDispersal}^{ij} \\
    \text{s.t.} \quad & j_{t,k} = sj_{t-1,k-1}  & k=2,...,kmax; \quad \forall i,j,t \\
    \quad & j_{t,1} = dJ_{t-1} + \tilde{d}\mathcal{G}_{t-1} & \forall i,j,t  \\
    \quad & J_{t} = \sum_{k=1}^{kmax} j_{t,k}  & \forall i,j,t \\
    \quad & S_{t} = \max\left\{S_{t-1} + sj_{t-1,kmax} - G_{t-1,NewGrowth}, 0\right\} & \forall i,j,t \\
    \quad & R_{t} = G_{t-1,PostTreatment} & t=1, ... ,T; \quad \forall i,j \\
    \quad & \mathcal{G}_{t} =  \mathcal(1-\tilde{d})\mathcal{G}_{t-1} + R_{t} & \forall i,j,t \\
    \quad & G_{t,B4Dispersal} = G_{t-1,PostTreatment} & \forall i,j,t \\
    \quad & D_{t}^{(i,j)_n \shortrightarrow(i,j)} = \lambda\sum_{(o,p) \in N}G_{t,B4Dispersal} & \forall i,j,t \\
    \quad & D_{t}^{(i,j)\shortrightarrow(i,j)} = \lambda\mathcal{N}G_{t,B4Dispersal} & \forall i,j,t \\
    \quad & G_{t,PostDispersal} = \max\left\{G_{t,B4Dispersal}+D_{t}^{(i,j)_n\shortrightarrow(i,j)} -D_{t}^{(i,j)\shortrightarrow(i,j)}, 0\right\} & \forall i,j,t & \tag{11}\\
    \quad & G_{t,NewGrowth} = \frac{G_{t,PostDispersal}^{2}} {G_{t,PostDispersal}^{2} + a^2} S_{t}  & \forall i,j,t & \tag{12}\\
    \quad & G_{t,PostTreatment} = (1-L_{t})G_{t,NewGrowth} & \forall i,j,t & \tag{13}\\
    \quad & \sum_{i=1}^I\sum_{j=1}^J\sum_{t=1}^TbL_{t}^{ij} \le B & \forall i,j,t & \tag{14}
\end{align}
\begin{align*}
    S_{0},R_{0},\mathcal{G}_{0}, J_{0},G_{0,PostTreatment} \ge 0
\end{align*}

\end{document}

A:

It happens because equation  (11) is to long. You can solve the problem using \mathrlap from mathtools with  the last part of this equation. It took the opportunity to add some code simplification and a few improvements to the layout:
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[margin=1in, includefoot]{geometry}
\usepackage{mathtools, nccmath}
\usepackage{amssymb}
\usepackage{ stmaryrd }
\usepackage{lipsum}
\usepackage{enumitem}
\usepackage{comment}

    \begin{document}

\begin{alignat}{2}
    \min_{L_{t}} \quad & \sum_{i=1}^I\sum_{j=1}^J\sum_{t=1}^T(a + b L_{t}^{ij}) G_{t, \text{PostDispersal}}^{ij} \\
    \text{s.t.} \quad & j_{t,k} = sj_{t-1,k-1} & k=2,...,k_{\max}; \quad &\forall i,j,t \\
     & j_{t,1} = dJ_{t-1} + \tilde{d}\mathcal{G}_{t-1} & & \forall i,j,t \\
     & J_{t} = \sum_{k=1}^{\mathclap{k_{\max}}} j_{t,k} & & \forall i,j,t \\
     & S_{t} = \max\left\{S_{t-1} + sj_{t-1,k_{\max}} - G_{t-1,\text{NewGrowth}}, 0\right\} & & \forall i,j,t \\
     & R_{t} = G_{t-1,\text{PostTreatment}} & t=1, ... ,T; \quad & \forall i,j \\
     & \mathcal{G}_{t} = \mathcal(1-\tilde{d})\mathcal{G}_{t-1} + R_{t} & & \forall i,j,t \\
     & G_{t,\text{B4Dispersal}} = G_{t-1,\text{PostTreatment}} & & \forall i,j,t \\
     & D_{t}^{(i,j)_n \shortrightarrow(i,j)} = \lambda\sum_{\mathclap{(o,p) \in N}}G_{t,\text{B4Dispersal}} & & \forall i,j,t \\
     & D_{t}^{(i,j)\shortrightarrow(i,j)} = \lambda\mathcal{N}G_{t,\text{B4Dispersal}} & & \forall i,j,t \\
     & G_{t,\text{PostDispersal}} = \max\Bigl\{G_{t,\text{B4Dispersal}}+D_{t}^{(i,j)_n\shortrightarrow(i,j)} -\mathrlap{D_{t}^{(i,j)\shortrightarrow(i,j)}, 0\Bigr\}} && \forall i,j,t \\
     & G_{t,\text{NewGrowth}} = \frac{G_{t,\text{PostDispersal}}^{2}} {G_{t,\text{PostDispersal}}^{2} + a^2} S_{t} && \forall i,j,t \\
     & G_{t,\text{PostTreatment}} = (1-L_{t})G_{t,\text{NewGrowth}} & & \forall i,j,t \\
     & \smash[b]{\sum_{i=1}^I\sum_{j=1}^J\sum_{t=1}^T}bL_{t}^{ij} \le B & & \forall i,j,t
\end{alignat}
\useshortskip
\begin{align*}
    S_{0},R_{0},\mathcal{G}_{0}, J_{0},G_{0,\text{PostTreatment}} \ge 0
\end{align*}

\end{document}


Q:

Two form values are not being saved

I have this signup for with devise:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

<%= f.label :email %>

  <%= f.email_field :email %>

<%= f.label :password %>

  <%= f.password_field :password %>

<%= f.label :password_confirmation %>

  <%= f.password_field :password_confirmation %>

  <%= f.fields_for :profile, resource.build_profile do |t| %>

        <%= t.label :type, "Are you an artist or listener?" %>

Artist: <%= t.radio_button :type, "Profile::Artist", :id => "artist_button" %>

Listener: <%= t.radio_button :type, "Profile::Listener", :id => "listener_button" %>

  <% end %>

<%= f.submit "Sign up", :id => "new_user_submit" %>

<% end %>

Then I have some JQuery that inserts a field dynamically:
$("#artist_button").click(function() {
        if ($('input#user_name').parent().hasClass('field')){
            $('input#user_name').parent().remove();
        }
        $(".before").before('
Artist or Band/Group Name
<input id="user_name" name="user[name]" size="30" type="text">
');
    });

However, the type attribute that is nested in the user form and the name attribute that is inserted dynamically are not being saved to the database. The values are being entered as null.
Why is this? How can I fix this?
UPDATE:
The name attribute was not attr_accessible and that was causing it to not be saved to the db. However, the type attribute, which is nested inside the user form, is attr_accessible but is still not being saved to the db.

A:

Try putting in your User Model:
attr_accessible :profiles_attributes

along with the rest of devises attr_accessible(email,remeber_me,etc) , do not delete what you have!


Q:

I would like to do printFrequency method in java

I would like to create a method called printFrequency that adds up, and prints, the total number of occurrences of each possible value (0, 1, ..., 9) for my code.
import java.util.Random;

public class Array {

    int[] array;
    int size = 0;

    public Array(int s) {
        size = s;
        array = new int[size];
    }

    public void print() {
        for (int i = 0; i < size; i++)
            System.out.printf("%d,", array[i]);
        System.out.println();
    }

    public void fill() {
        Random rand = new Random();
        for (int i = 0; i < size; i++)
            array[i] = rand.nextInt(10);

    }

    public void sort() {
        for (int i = 0; i < size; i++) {
            int tmp = array[i];
            int j = i;

            for (; j > 0 && (tmp < array[j - 1]); j--)
                array[j] = array[j - 1];
            array[j] = tmp;
        }
    }

    public void printFrequency() {

    }
}

I would like the output for the printFrequency method to be like this:
Frequencies:
There are 2, 0's
There are 0, 1's
There are 0, 2's
There are 0, 3's
There are 3, 4's
There are 0, 5's
There are 2, 6's
There are 1, 7's
There are 0, 8's
There are 2, 9's

I don't know exactly how to start with it and what loop to use for it or if there is easier way to do it.

A:

I would like to create a method called printFrequency that adds up, and prints, the total number of occurrences of each possible value (0, 1, ..., 9)

Assuming that you want to calculate the frequencies of the number present in the array, here is one solution using a fixed length array which acts as a count bucket for each of the numbers through 0 - 9.
Here is the code snippet:
private static void printFrequency() {
    int[] countArray = new int[10];
    for(int x : array) {
        countArray[x]++;
    }

    System.out.print("Frequencies: ");
    for(int i = 0; i < 10; i++) {
        System.out.print("There are " + countArray[i] + ", " + i + "'s ");
    }
}


Q:

JavaScript If/Else Conditions & Comparisons - Differences

Okay, here's my short question:
I know that === and !== operators will compare the types and then the values, and that == and != will cast the types and then just compare the values.
What about if(myVar) and if(!myVar)?
Is there any difference in the behavior from if(myVar == true) and if(myVar == false)?

A:

Yes, there is a difference. For example:
if('true' == true) {
    alert("This doesn't happen");
}

if('true') {
    alert("But this does happen.");
}

The reason? They're both converted to numbers for comparison. 'true' is converted to NaN and true is converted to 1.
Avoid this silliness and never write == true or == false.

A:

Yes, there is a difference. As you already mentioned, if you compare a value with ==, type conversion takes places.
If the values are not of the same type, they will both be converted to either strings or numbers.  If one of the values is a boolean and the other is not, both values will be converted to numbers.
The comparison algorithm is defined in section 11.9.3 of the specification. The important step is here:

7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

So true is converted to a number first and later myVar will be converted to a number as well.

If you only have if(myVar) though, then the value is converted to a boolean:

2. If ToBoolean(GetValue(exprRef)) is true, then

ToNumber [spec] and ToBoolean [spec] can return very different results.

Note: If myVar is actually a boolean, then there is no difference between if(myVar == true) and if(myVar).


Q:

Tool for building intelligent agent?

Suggest me any open source based platform/IDE/framework/toolkit for developing intelligent agent. I don't have any background in this area, would like to use a tool or any tutorial in building intelligent agent.

A:

If you don't have any background at all, I suggest you start with something simple.
I had quite a good experience with dmangame, a simple Python engine where you can script the behaviour of agents.
The good point is that the installation is very simple, you know where to code your Python scripts for AI, there is a nice API for it. And you've got a nice graphical interface to see directly what you code.
Edit : By the way, look at this similar question


Q:

Measure execution time of Java with JVMTI

For the profiler which I implement using JVMTI I would like to start measuring the execution time of all Java methods. The JVMTI offers the events:

MethodEntry
MethodExit

So this would be quite easy to implement, however I came across this note in the API:

Enabling method entry or exit events will significantly degrade performance on many platforms and is thus not advised for performance critical usage (such as profiling). Bytecode instrumentation should be used in these cases.

But my profiling agent works headless, which means the collected data is serialized and sent via socket to a server application displaying the results. How should I realize this using byte code instrumentation. I am kind of confused how to go on from here. Could someone explain to me, if I have to switch the strategy or how can I approach this problem?

A:

I don't know about the Sun JVM but the IBM JVM goes into what we call FullSpeedDebug mode when you request the MethodEntry/Exit events.... FSD slows down execution quite a bit.
As you say you can use BCI as my profiler does but unless you are selective about which methods you instrument you will also see a slow down. For example my profiler inserts a if(profiling) callProfilerHook() on every entry and all of the possible exits in a method all object creates and some other areas as well.... These additional checks can slow down execution by over 50%...
As for how to BCI... well I wrote my own C library to do it... it's technically not hard (hint just delete the StackMapTable) but I may take you a while.. Alternatively you can use ASM et. al.
Finally... you callBackHook will add overhead and on small methods render the reported CPU/Clock time meaningless unless you perform some sophisticated overhead calculation... even if you do this your callback code affects the shape of the processor L1 caches and the  Java code becomes less efficient because it has less room..
My profiler basically ignores the reported times as I visualize the execution in an interesting way... I'm looking to understand the flow of all of the code, in fact in most cases what code is running (most Java projects have no idea of the millions on lines of third-party code running in their app)


Q:

How can I build this simple C++/SWIG/C# project in Visual Studio 2010?

I need help setting up a simple C++/C# SWIG project.  I am having a hard time putting together a C++ project that uses the SWIG bindings.  I'm using Visual Studio 2010 and the most recent version of SWIG.
My code is simply:
cpp_file.h:
#pragma once
class cpp_file
{
public:
    cpp_file(void);
    ~cpp_file(void);

    int times2(int arg);
};

cpp_file.cpp
#include "cpp_file.h"
cpp_file::cpp_file(void)
{
}
cpp_file::~cpp_file(void)
{
}
int cpp_file::times2(int arg)
{
return arg * 2;
}

And my SWIG interface file is:
cpp_file.i
/* cpp_file.i */
%module cpp_file
%{
/* Put header files here or function declarations like below */
extern int times2(int arg);
%}
extern int times2(int arg);

I can compile this project fine.  I then run the SWIG command to generate the wrapper:
swig -csharp "C:/pathToFile/cpp_file.i"

I don't know what to do at this point.  I can't find any tutorials or documentation that explains what to do in Visual Studio 2010.
When I add the *cpp_file_wrap.c* file that SWIG generates to my Visual Studio 2010 project and attempt to build the project, I get two linker errors.

error LNK1120: 1 unresolved externals
error LNK2001: unresolved external symbol _times2

The first error message points to my dll file.  The second error points to some object file (*.obj).  The symbol that the error message mentions "_times2" is no where to be found in my project.
How can I move forward with my simple project?  Is there some tutorial or some documentation that explains this process step-by-step?  I can't find anything that involves C++ with SWIG, C#, Visual Studio 2010, and .Net v4.0.

A:

Step-by-Step instructions to completely build in the VS2010 IDE:

Create a solution with two projects:

C# Console Application
C++ Win32 Console Application (Name=cpp, DLL, empty project).  If you choose a different name, don't use the name of a class in your project and update the .i file %module name to match.

Create a folder in the C# project called Generated.
Add your .cpp, .h, and .i file to the DLL with the modifications below.

Note the whole class has to be exported. Replace <project> with the name of the project.  There will be a preprocessor definition <project>_EXPORTS already defined for your DLL project (see Project, Properties, C++, Preprocessor).
The module name cannot match a class name in the module.
%include <windows.i> helps SWIG understand certain "Window-isms" like __declspec.

cpp_file.h
#pragma once

#ifdef <project>_EXPORTS
#define <project>_API __declspec(dllexport)
#else
#define <project>_API __declspec(dllimport)
#endif

class <project>_API cpp_file
{
public:
    cpp_file(void);
    ~cpp_file(void);

    int times2(int arg);
};

cpp_file.i
%module cpp

%{
#include "cpp_file.h"
%}

%include <windows.i>
%include "cpp_file.h"

Select cpp_file.i, Properties, General, Item Type as Custom Build Tool.
Select Apply to create the Custom Build Tool property group.
In Custom Build Tool, General, Command Line enter:
swig -csharp -c++ -outdir GeneratedFolderPath cpp_file.i
In Outputs, enter cpp_file_wrap.cxx, and click OK to close the dialog.
Right-click cpp_file.i and Compile.  This should create four files: three in the C# Generated folder and one in the C++ project.
Create a Generated Files filter in the C++ project and add cpp_file_wrap.cxx to it.
Add the three Generated files to the C# project's Generated folder.
Right-click the C# project and add the C++ project as a dependency.
In the C# project's Properties, Build tab, change the Output Path from bin\Debug to ..\Debug or whatever the relative path to the C++ Project output directory is.  The .exe and .dll need to be in the same directory.
In the C# project's Main, add the lines:
var cpp = new cpp_file();
Console.WriteLine(cpp.times2(5));
Build the solution.
Run the C# project.

Good luck!  Let me know if you get it to work.  I can expand on anything unclear.


Q:

Conflicting changes to the role x of the relationship y have been detected

I am having the exception

Conflicting changes to the role x of the relationship y have been detected.

Every time I add my entity to my context
Database.MyEntitys.Add(MyEntity);

The class MyEntity contain this property :
public virtual ICollection<DetailInfo> Group { get; set; }

The DetailInfo class is pretty simple:
public class DetailInfo:BaseEntity {
    public virtual Detail Detail { get; set; }
    public decimal Total { get; set; }
    public virtual MyEntity MyEntity { get; set; }
}

The DatabaseContext is also simple:
public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity> {
    public MyEntityConfiguration() {
        HasMany(e => e.Group).WithRequired(s => s.MyEntity).WillCascadeOnDelete(true);
    }
}

public class DetailInfoConfiguration : EntityTypeConfiguration<DetailInfo> {
    public DetailInfoConfiguration() {
        HasRequired(x => x.MyEntity).WithMany(s => s.Group);
        HasRequired(x => x.Detail);
        HasKey(s => s.ID);
        ToTable("DetailInfo");
    }
}

On the Database side the table MyEntity has a primary key to the column ID. The DetailInfo has also a primary key called ID. DetailInfo contains 2 FK, one to MyEntity and one to Detail which is another entity.
In the problematic scenario, the MyEntity is new has a new Detail. I am expecting a new entry for MyEntity with a new Detail and having all FK correctly setup.
Edit:
here is the Insert:
public virtual int Insert(MyEntity myEntity) {

    if (myEntity.Group != null && myEntity.Group.Count() == 0) {
        myEntity.Group = null;
    }

    if (myEntity.Group != null) {
        foreach (var g in myEntity.Group)
        {
         if (g.PropertyOneToOne != null) {
                if (g.PropertyOneToOne.ID == 0) {
                    myEntity.PropertyOneToOne = null;
                }
                else {
                    if (!Database.PropertyOneToOnes.Local.Any(e => e.ID == g.PropertyOneToOne.ID)) {
                        Database.PropertyOneToOnes.Attach(g.PropertyOneToOne);
                    }
                    myEntity.PropertyOneToOne = Database.PropertyOneToOnes.Local.Single(e => e.ID == g.PropertyOneToOne.ID);
                }
            }
            else {
                myEntity.PropertyOneToOne = null;
            }
        }
    }
    Database.MyEntitys.Add(myEntity);
}

A:

The problem is this one:
MyEntity has an ID of 0 since it's a new MyEntity.
The Group is also new and contain a reference to MyEntity.
So, MyEntity contains a list of Group which contain a reference back to MyEntity.
The problem is that MyEntity.Group.MyEntity seems to be "new and not the same" as MyEntity. When adding MyEntity to the context, it found a conflict.
To solve the problem I set Group.MyEntity to NULL and keep the reference of Group inside the list of MyEntity. When saving, MyEntity reference (ID) is set into the Group table.
I am not sure it's the cleanest way to do it, but the problem is finally solved.


Q:

How can I use apply properly in R in this dataframe column?

I have a dataframe  column with NA, I want to how can I use  apply (or lapply, sapply, ...) to the column.
I've tried with apply and lapply, but it return an error.
The function I want to apply to the column is:
a.b <- function(x, y = 165){
  if (x < y)
    return('Good')
  else if (x > y)
    return('Bad')
}

the column of the dataframe is:
   data$col = 180 170  NA  NA 185 185
When I use apply I get:
apply(data$col, 2, a.b)
 Error in apply(data$col, 2, a.b) :
   dim(X) must have a positive length

I have try dim(data$col) and the return is NULL and I think it is because of the NA's.
I also use lapply and I get:
lapply(data$col, a.b)
Error in if (x < y) return("Good") else if (x > y) return("Bad") :
  missing value where TRUE/FALSE needed

This is for a course of R for beginners that I am doing so I am sorry if I made some mistakes. Thanks for taking your time to read it and trying to help.

A:

apply is used on a matrix, not a vector. Try:
a.b <- function(x, y = 165){
  if (is.na(x)){
    return("NA")
  } else if (x < y){
    return('Good')} else if (x > y){
    return('Bad')}
}
data$col=sapply(data$col,a.b)


Q:

Why is $\lim_\limits{x\to 0}\frac{\sin(6x)}{\sin(2x)} = \frac{6}{2}=3$?

Why is $\lim_\limits{x\to 0}\frac{\sin(6x)}{\sin(2x)} = \frac{6}{2}=3$?
The justification is that $\lim_\limits{x\to 0}\frac{\sin(x)}{x} = 1$
But, I am not seeing the connection.
L'Hospital's rule? Is there a double angle substitution happening?

A:

$$\frac{\sin(6x)}{{\sin(2x)}} =\frac{\sin(6x)}{6x} \cdot \frac{2x}{{\sin(2x)} }\cdot \frac{6}{2} $$

A:

You don't need to know any special limits or derivatives, you can do it with trig identities:
From
$$\sin3\theta=\sin(\theta+2\theta)=\sin\theta\cos2\theta+\cos\theta\sin2\theta=\sin\theta\cos2\theta+2\sin\theta\cos^2\theta$$
we have, letting $\theta=2x$,
$${\sin6x\over\sin2x}={\sin2x(\cos4x+2\cos^22x)\over\sin2x}=\cos4x+2\cos^22x$$
and thus
$$\lim_{x\to0}{\sin6x\over\sin2x}=\lim_{x\to0}(\cos4x+2\cos^22x)=\cos0+2\cos^20=1+2=3$$
(The final evaluation relies, of course, on knowing that the cosine function is continuous.)

A:

As user Daniel has written you can express the ratio $\frac{\sin 6x}{\sin 2x}$ in a way which makes it amenable to the use of standard limit $$\lim_{x\to 0} \frac{\sin x}{x} = 1\ .$$ Notice that $$\lim_{x\to 0} \frac{\sin x}{x} = \lim_{x\to 0} \frac{\sin 2x}{2x} = \lim_{x\to 0} \frac{\sin 6x}{6x}\ .$$ As long as the argument $x$ is not equal to zero (and $\sin 2x \neq 0$) you can prolong the ratio $\frac{\sin 6x}{\sin 2x}$ as follows.
$$\frac{\sin 6x}{\sin 2x} = \frac{\sin 6x}{6x} \cdot \frac{6x}{2x} \cdot \frac{2x}{\sin 2x} = \underbrace{\frac{\sin 6x}{6x}}_{\to 1} \cdot \frac{6}{2} \cdot \underbrace{\frac{1}{\frac{\sin 2x}{2x}}}_{\to\frac{1}{1}} \to 1 \cdot 3 \cdot 1 = 3 \ .$$ Hence you obtain the result $$\lim_{x\to 0}\frac{\sin 6x}{\sin 2x} = 3 \ .$$


Q:

Getting seconds from chronometer to an integer

I'm creating game that will increase it's level every 10 seconds, the users will see the time (using chronometer) and the level they currently at.
I'm trying to create an integer that will be incremented every 10 seconds as shown on the chronometer.
I didn't find a guide here that is answering my needs.
I tried to guess that the chronometer is running as milliseconds, which wasn't the case.
Inside my Class:
private Chronometer chronometer;

Inside my onCreate (used XML):
chronometer=findViewById(R.id.timer);

Trying to converte the chronometer to seconds (only attempted first try):
        int timeChecker=(int) (SystemClock.elapsedRealtime() - chronometer.getBase());
        if (timeChecker==10){
            lvl++;
            lvlcount.setText(lvl+"");
        }

I've wanted to increase the level every 10 second and than change the TextView with the previous level.

A:

First, the elapsedRealTime() and chronometer.getBase() are in millisecond units so the delta is also in milliseconds:
long timeDeltaFromStartInMs = (SystemClock.elapsedRealtime() - chronometer.getBase());

Next, assuming the chronometer is never reset for this discussion then the number of levels elapsed is (integer division truncates):
int numLevelsElapsed = (int) (timeDeltaFromStartInMs / 10000);

Assuming the initial level starts at 0 then it's simply:
lvlcount.setText(Integer.toString(numLevelsElapsed));

If the level has an initial non-zero value (from some previous play):
lvlcount.setText(Integer.toString(initialLevelCnt+numLevelsElapsed));

Might be a few other nuances to your problem - if so feel free to comment.


Q:

Translation of 何かにつけて

父は何かにつけて、若いころ外国で過ごした思い出を語る。

Is this sentence best translated as "My father would sometimes talk about his memories as a young man travelling abroad".
If yes, what is the difference between 何かにつけて and something simpler like 時々、時に etc.?

A:

Is this sentence best translated as "My father would sometimes talk about his memories as a young man travelling abroad."?

I would definitely have to say NO.  The word choice of "sometimes" does not reflect the meaning and nuance of 「何かにつけて」 at all.
That translation basically says "Someone does something at a certain frequency."  It sounds very neutral and it is that neutrality that is the problem here because the expression 「何かにつけて」 is not neutral.  It is indeed fairly negative.
「何かにつけて～～する」 means "to never miss a chance (to do something)", "to take every opportunity (to do something)", etc.
This father speaks about his memories more often than his family want to listen.  That is the nuance of the original Japanese sentence and the expression 「何かにつけて」
.


Q:

MVC3 Json: A potentially dangerous Request.Form value was detected from the client

I use...
$.post("/StoreHtml", { 'html': $("#txtHtml").val(), , function (data) { });

... to store html user enters, but method above fails with an

"A potentially dangerous Request.Form
  value was detected from the client".

How do I encode the html before sending it? ... and how do I decode it in vb.net?
Thanks!
Mojo

A:

If I use escape(htmlString) in the clintside (javescript) and HttpUtility.UrlDecode(htmlStringEncoded, System.Text.Encoding.Default()) in server side, then it works.
Any better suggestions or is this the best way?
Thx.


Q:

Setting The Rowfilter On Load

How can I set the Row filter to a value so when the form loads it filters by that columns value in devexpress gridview.

A:

I thought you were using the ASPxGridView.  If you are using a Winforms grid, the code should be:
gridView1.ActiveFilterCriteria = new DevExpress.Data.Filtering.BinaryOperator("Status", "P");


Q:

How to get links using selenium and scrape using beautifulsoup?

I want to collect articles from this particular website. I was using Beautifulsoup only earlier but it was not grabbing the links. So I tried to use selenium. Now I tried to write this code. This is giving output 'None'. I have never used selenium before, so I don't have much idea about it. What should I change in this code to make it work and give the desired results?
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

base = 'https://metro.co.uk'
url = 'https://metro.co.uk/search/#gsc.tab=0&gsc.q=cybersecurity&gsc.sort=date&gsc.page=7'

browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
wait = WebDriverWait(browser, 10)
browser.get(url)

link = browser.find_elements_by_class_name('gs-title')
for links in link:
    links.get_attribute('href')
    soup = BeautifulSoup(browser.page_source, 'lxml')
    date = soup.find('span', {'class': 'post-date'})
    title = soup.find('h1', {'class':'headline'})
    content = soup.find('div',{'class':'article-body'})
    print(date)
    print(title)
    print(content)

    time.sleep(3)
browser.close()

I want to collect the date, title, and content from all the articles on this page and other pages also like page no 7 to 18.
Thank you.

A:

Instead of using Selenium to get the anchors, I tried to extract the page source first with the help of Selenium and then used Beautiful Soup on it.
So, to put it in perspective:
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

base = 'https://metro.co.uk'
url = 'https://metro.co.uk/search/#gsc.tab=0&gsc.q=cybersecurity&gsc.sort=date&gsc.page=7'

browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
#wait = WebDriverWait(browser, 10) #Not actually required
browser.get(url)
soup = BeautifulSoup(browser.page_source, 'html.parser') #Get the Page Source
anchors = soup.find_all("a", class_ = "gs-title") #Now find the anchors

for anchor in anchors:
    browser.get(anchor['href']) #Connect to the News Link, and extract it's Page Source
    sub_soup = BeautifulSoup(browser.page_source, 'html.parser')
    date = sub_soup.find('span', {'class': 'post-date'})
    title = sub_soup.find('h1', {'class':'post-title'}) #Note that the class attribute for the heading is 'post-title' and not 'headline'
    content = sub_soup.find('div',{'class':'article-body'})
    print([date.string, title.string, content.string])

    #time.sleep(3) #Even this I don't believe is required
browser.close()

With this modification, I believe you can get your required contents.


Q:

How to change in Gradle time to live for artifact caches?

I am interesting in reducing time between refresh of SNAPSHOT versions of dependencies in Gradle.
How can I configure it and what is the default value?

A:

Snapshots treated in Gradle as changing modules.
There is an explanation available how to configure it in the Gradle documentation


Q:

Bootstrap 4 fixed top navbar inside column

I'm trying to create a layout with a sidebar on the left side and on the right side a fixed top navigation bar and under that my site content.
What I have:

test

                        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">

                        </button>

                                    Home

 main content

https://jsfiddle.net/0ka85tmn/1/
I can't seem to get the navigation bar correctly. It doesn't stay inside my column. I have played around with position attribute but can't get it working.
Anyone can help?

A:

Using position:fixed takes the navbar out of the normal document flow and makes it relative to the entire page, so it's not longer contained by it's parent. For that reason you need to specifically set the position of the navbar...
.navbar {
    position: fixed;
    width: 100%;
    top: 0;
    left: 33.3333%;
    z-index: 1;
}

Also, there's no reason to contain it in a row and col-12.
Demo: http://www.codeply.com/go/5bPIH8Tbiw


Q:

Backing up an Oracle 10G Express on Windows 2000 Server

Oracle 10G Express installed on Windows 2000 Server Enterprise Edition.
I am trying to automate backups and on Oracle's website I have found the following documentation.
http://docs.oracle.com/cd/B25329_01/doc/admin.102/b25107/backrest.htm
Activate Archive Log

SQLPLUS -> CONNECT SYS/password AS SYSDBA
SHUTDOWN IMMEDIATE
STARTUP MOUNT
ALTER DATABASE ARCHIVELOG;
ALTER DATABASE OPEN;

Backup the Database
Then using the backup.bat file provided by Oracle: D:\oraclexe\app\oracle\product\10.2.0\server\BIN\BACKUP.BAT, I can backup the database either manually or with Scheduled tasks
Using a test server, I have been able to backup and restore the database using the backup.bat and restore.bat files provided.  I have not seen anything however about recycling those backups.
Questions:

Does Oracle provide a script to cleanup backup files that are no longer needed?
or What can I do to avoid filling up the D: drive with backup files?
Is there a better method to backup Oracle 10G Express?

Thank you

A:

I don't have the 10g version of Express Edition installed, but if it is like the 11g version, then your first question is answered in the comments section of the Backup.bat file itself.
For 11g this means the comments indicate that No cleanup script is needed because the script automatically keeps two backups in the Flash Recovery Area.  Whether there is a better method or not will depend on what your recovery requirements are.


Q:

Eastpak backpack as small luggage with Ryanair?

The dimensions permitted for Ryanair's small hand luggage are 35x20x20. An Eastpak backpack is about 45x38x11. Will it be allowed on board?
Please refer your personal experiences on this subject.
EDIT: What if I carry it nearly empty and folded into 2 parts, so that it'll fit? (I really need to take a backpack with me, but there's no room in my other luggage, that's why I'm asking these questions)

A:

45x38x11 cm is above the size that Ryanair say they will definitely allow in the cabin (35x20x20 cm) but below the maximum size of hand luggage (55x40x20 cm) so if it's your only piece of hand luggage you might be allowed to take it on, and if not it will be carried in the hold for free.
In my experience, when they insist that passengers gate check their luggage they are mainly looking for the big wheely suitcases which just fit in the cage at all. The main limitation is on overhead locker space, so if your bag looks like it will fit under the seat in front of you then you're probably OK.


Q:

Aging algorithm for insurance policy

This may sound very simple, but these parts of my brain are a bit rusty from disuse.  I need to report on insurance policies, stating whether a policy is current, in advance/credit, or behind/in arrears.  Am I correct in presuming it is as simple as below, providing the monthly payments remain constant?
Received = Tally of all monthly payments on the policy.
Expected = Policy age in months x monthly premium.
If Received < Expected, policy is in arrears.
If Received > Expected, policy is paid in advance.
If Received == Expected, policy is current.

A:

If there are no changes to the premium, and no interest charged on late payments, then yes you are correct.  That doesn't typically align with reality though.
There could however be nuances (fencepost errors) arising from when a premium is supposed to be paid (e.g. you pay at the end of the month for the previous month's coverage).


Q:

Read one file name "Only" and skip to next directory - PHP

I have the following code which reads all filnames from each directory, but I want it to read one filename "only" and skip to the next directory.
<?php
$dir = "/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file . "<br>";
    }
    closedir($dh);
  }
}
?>

How can I read only one filename, then skip to the next directory to read "only" first filename and so on.  Please let me know if you require any more information.

A:

if it doesn't matter which file you read then just put a break; in your while loop or don't even go in a loop just take the $file = readdir($dh);
PS: In linux OS be aware of . and .. Also look up scabdir() function


Q:

Smart pointers usage

I have a project and I want make smart pointers usage better.
The main idea is to use them when returning new object from function. The question is what smart pointer to use? auto_ptr or shared_ptr from boost? As I know, auto_ptr is slower but it can fall back to the 'pure' pointer.
And if I'll use smart pointer in place where I don't need it, would it make the perfomance slower?

A:

What makes you think auto_ptr is slower than shared_ptr? Typically I would expect the reverse to be true, since shared_ptr needs to update the reference count.
As for which you should use, different smart pointers imply different ownership semantics. Ownership implies the responsibility to delete the object when it is no longer needed.

A raw pointer implies no ownership; a program that uses smart pointers correctly may still make use of raw pointers in a lot of places where ownership is not intended (for example, if you need to pass an optional reference to an object into a function, you would often use a raw pointer).
scoped_ptr implies single (ie, non-shared), non-transferable ownership.
auto_ptr implies single (ie, non-shared) transferable ownership. This is the smart pointer I would use to return a newly constructed object from a function (the function is transferring the object to its caller). auto_ptr suffers from the disadvantage that due to limitations of the language when auto_ptr was defined, it is difficult to use correctly (this has given it a very bad reputation, though the intended purpose of a smart pointer with single, transferable ownership semantics was and is both valid and useful).
unique_ptr has the same semantics as auto_ptr, but uses new C++0x features (rvalue references) to make it a lot safer (less prone to incorrect use) than auto_ptr. If you are developing on a platform where unique_ptr is available, then you should use it instead of auto_ptr.
shared_ptr implies shared ownership. In my opinion this is over-used. It does have many valid uses, but it should not simply be used as a default option.

I would also add that shared_ptr is often used with STL containers because the other smart pointer classes do not achieve their intended function in that context (due to copying of values internally within the container). This often leads to use of shared_ptr where shared ownership is not really the intended meaning. In these cases, I suggest (where possible) using the boost pointer-container classes (ptr_vector, ptr_map and so on), which provide the (commonly desired) semantics of a container with transferable, but single (non-shared) ownership.
You should always think about the ownership of your objects: in most cases, with a clean system design, each object has one obvious owner, and ownership does not need to be shared. This has the advantage that it is easy to see exactly where and when objects will be freed, and no reference counting overhead is needed.
[edited to note the new unique_ptr]


Q:

look for words on html with python

im trying to make a python3 script that looks for words say like "ArduinoON" etc on a web page. but its not going that good. I know how to do it with php but not with python. here is how i did it with php and how im trying to do it with python.
Here is how i did it in php.
    <?php
$data = file_get_contents('http://192.168.0.200:9090');
$regex = '/Switch1On/';

if (preg_match($regex, $data)) {
   echo 'on';
} else {
   echo 'off';
}
?>

My python code
 import urllib.request

x = urllib.request.urlopen('http://192.168.0.200:9090/')
if "ArduinoOn" in x:
     print ("True")

Could any one help me?

A:

If you are looking for a text string in the html page, you can use Python requests module. This is probably the easiest way to do it.
import requests

r = requests.get('http://192.168.0.200:9090/')
if "ArduinoOn" in r.text:
    print ('True')


Q:

How to set specific bits?

Let's say I've got a uint16_t variable where I must set specific bits.
Example:
uint16_t field = 0;
That would mean the bits are all zero: 0000 0000 0000 0000
Now I get some values that I need to set at specific positions.
val1=1; val2=2, val3=0, val4=4, val5=0;
The structure how to set the bits is the following
0|000|  0000| 0000 000|0

val1 should be set at the first bit on the left. so its only one or zero.
val2 should be set at the next three bits. val3 on the next four bits. val4 on the next seven bits and val5 one the last bit.
The result would be this:
1010 0000 0000 1000
I only found out how to the one specific bit but not 'groups'. (shift or bitset)
Does anyone have an idea how to solve this issue?

A:

There are (at least) two basic approaches. One would be to create a struct with some bitfields:
struct bits {
    unsigned a : 1;
    unsigned b : 7;
    unsigned c : 4;
    unsigned d : 3;
    unsigned e : 1;
};

bits b;

b.a = val1;
b.b = val2;
b.c = val3;
b.d = val4;
b.e = val5;

To get the 16-bit value, you could (for one example) create a union of that struct with a uint16_t. Just one minor problem: the standard doesn't guarantee what order the bit fields will end up in when you look at the 16-bit value. Just for example, you might need to reverse the order I've given above to get the order from most to least significant bits that you really want (but changing compilers might muck things up again).
The other obvious possibility would be to use shifting and masking to put the pieces together into a number:
int16_t result = val1 | (val2 << 1) | (val3 << 8) | (val4 << 12) | (val5 << 15);

For the moment, I've assumed each of the inputs starts out in the correct range (i.e., has a value that can be represented in the chosen number of bits). If there's a possibility that could be wrong, you'd want to mask it to the correct number of bits first. The usual way to do that is something like:
uint16_t result = input & ((1 << num_bits) - 1);

In case you're curious about the math there, it works like this. Lets's assume we want to ensure an input fits in 4 bits. Shifting 1 left 4 bits produces 00010000 (in binary). Subtracting one from that then clears the one bit that's set, and sets all the less significant bits than that, giving 00001111 for our example. That gives us the first least significant bits set. When we do a bit-wise AND between that and the input, any higher bits that were set in the input are cleared in the result.


Q:

When to use a spinner vs a form object

When  is using a spinner object appropriate, rather than using a standard text entry object (a.k.a. form, or text box)?
I am looking for information on "best practices" in GUI.

A:

I am thinking that the spinner object should be used only where it makes sense to click small incremental values up and down, e.g. small numbers like the number of copies for a print job.


Q:

Is there any hint or official data on how powerful Roshi is after the Saiyan Saga?

In Dragon Ball and Dragon Ball Z saiyan saga, we knew Roshi was the most powerful fighter of the Z fighters at the early time he trained Goku and Krilin, or when he won the tournament, and In Dragon Ball Z we knew he was already weaker than Tien, Yamcha and Krilin when he was measured with the scouter by Bulma. Is there any hint/official data on how powerful Roshi became after that? In Dragon Ball Fukkatsu no F we saw he was able to fight Freezer soldiers with a similar grade of difficulty than Krilin so even if we dont know exactly how strong he is by that point, we know he became stronger since Dragon Ball Z

A:

Master Roshi's power level was 139 back in the Saiyan arc, and also 180 when getting serious as it is stated in the 31th issue of Weekly Jump in 1991.
[Bottom middle]

A slight increase of power level of Master Roshi was stated in the movie pamphlet of the The Tree of Might, which is 350.
[Bottom middle]

In episode 89 of Dragon Ball Super, Goku is impressed that Roshi has been hiding his power for so long. Even Tien with his Four Witches Technique wasn't enough to stop Roshi. He might been using all of his power due to the effect of Yurin's withcraft. In conclusion, Roshi is indeed getting stronger, he is capable of fighting Frieza's soldiers but he will wear out faster compared to other earthling fighters.


Q:

OP_RETURN with bitcoind not working

I have created a raw transaction with the following hexstring which decodes to:
{
   "lock_time":0,
   "size":248,
   "inputs":[
      {
         "prev_out":{
            "index":1,
            "hash":"2fb04bcfcc164fbb9d5ad740c891e2599d904920386ab4e7f39bc1c87431218e"
         },
         "script":"483045022100c727a635fbd5e689888e60a10c6ce45855abb7ceeb2235004d815edae2555abb022059839448cdd52733280b6fdde09ee87b06ba090357e50fea178d8fe41d811ba9012103f515b50b5e7693b4d8fe3d5d25346f989b42ab43f65a0106808f844deff55f08"
      }
   ],
   "version":1,
   "vin_sz":1,
   "hash":"096328dc269ea7a060eb1c16ce8629cf81a5cff5766eb3f2ec97d81344854327",
   "vout_sz":3,
   "out":[
      {
         "script_string":"OP_DUP OP_HASH160 98ac2448db3e1a08cce87052513280cb20bafbf5 OP_EQUALVERIFY OP_CHECKSIG",
         "address":"1EvFvmzhiFWhaRfvvZupxxQvTMHJ79GGdb",
         "value":1,
         "script":"76a91498ac2448db3e1a08cce87052513280cb20bafbf588ac"
      },
      {
         "script_string":"OP_DUP OP_HASH160 f3223f468b6b81b4104b5b880d23b246c9c76711 OP_EQUALVERIFY OP_CHECKSIG",
         "address":"1PAaE9hEh1RNpoGuSJ6fw6wajziLptJSVv",
         "value":99998,
         "script":"76a914f3223f468b6b81b4104b5b880d23b246c9c7671188ac"
      },
      {
         "script_string":"OP_RETURN 68656c6c6f20776f726c64",
         "value":0,
         "script":"6a0b68656c6c6f20776f726c64"
      }
   ]
}

When I enter the command
bitcoind sendrawtransaction <hex-string>

I get the following message:
error: {"code":-26,"message":"64: dust"}

Will this be anything to with standard transactions? I am currently using 0.9.3 branch of the bitcoin client.

A:

The issue is this output:
  {
     "script_string":"OP_DUP OP_HASH160 98ac2448db3e1a08cce87052513280cb20bafbf5 OP_EQUALVERIFY OP_CHECKSIG",
     "address":"1EvFvmzhiFWhaRfvvZupxxQvTMHJ79GGdb",
     "value":1,
     "script":"76a91498ac2448db3e1a08cce87052513280cb20bafbf588ac"
  },

See the "value":1? That means that the output is worth 1 satoshi. It's worthless, because it would cost more to spend this than it's worth. See this answer for more.
To solve this, remove that output.


Q:

How to make PHP 5.2 compatible with future versions

I am writing a CMS in version 5.2 but I am worried whether or not it will be compatible with PHP 5.3 or future versions for that matter.
What things I should watch out for or there is nothing to worry about ?
P.S: Please don't suggest that I should use PHP 5.3 instead as that's not the question asked.

A:

PHP takes a very conservative approach to backwards compatibility. Most code will continue to work for quite a while - I've seen PHP3 code that's still OK in 5.3.
You should keep an eye on the lists of backwards incompatible changes.


Q:

How do I place tkinter buttons in a specific area?

I am making a program for finding booking contacts with ease. When I type in all of this information, the buttons stay to the top left of the window.

How can I get them in the middle of the screen? Better, how would I place them where-ever I want in general? (Don't worry about the webbrowser import for that is for later in the program.)
import webbrowser
from tkinter import *
from tkinter import ttk

root = Tk()
root.title('GUI Booking')
root.geometry('600x400')
root.resizable(width=False, height=False)

style = ttk.Style()
style.configure("TButton",
                font="TkDefaultFont",
                height=20,
                width=20,
                padding=10)
main_frame = Frame()
main_frame.grid(row=0, columnspan=4)

# Starting Window
button_location = ttk.Button(main_frame, text='Location').grid(row=1, column=3)
button_name = ttk.Button(main_frame, text='Name').grid(row=2, column=3)
button_email = ttk.Button(main_frame, text='Email').grid(row=3, column=3)

root.mainloop()

A:

use the .place option instead of .grid:
...
Button = Button(something, text='Something', command=Something)
Button.place(x=value(e.g:2), y=value(e.g:2))
...


Q:

Generate new line number for each mapping

I need to create a new line number of each unit in my mapping table. Please check the below sample data and expected result.
Lines table
+--------+------------+------+------+
| FileId | linenumber | code | unit |
+--------+------------+------+------+
|      1 |          1 | A    | NULL |
|      1 |          2 | B    | NULL |
|      1 |          3 | C    | NULL |
+--------+------------+------+------+

map table
+------+------+
| code | unit |
+------+------+
| A    | c1   |
| A    | c2   |
| B    | c3   |
| B    | c4   |
| B    | c5   |
+------+------+

expected result
+--------+------------+------+------+
| FileId | Linenumber | code | unit |
+--------+------------+------+------+
|      1 |          1 | A    | c1   |
|      1 |          2 | B    | c3   |
|      1 |          4 | A    | c2   |
|      1 |          5 | B    | c4   |
|      1 |          6 | B    | c5   |
+--------+------------+------+------+

Code A has two units (c1 and c2), unit c1 will be updated in line number 1 and c2 unit should be inserted as new line with line number after the last available linenumber in lines table. Same process should happen for all the codes
My current approach
if object_id('tempdb..#lines') is not null drop table #lines
if object_id('tempdb..#map') is not null drop table #map
if object_id('tempdb..#Files') is not null drop table #Files
if object_id('tempdb..#Maptemp') is not null drop table #Maptemp

create table #lines(FileId int, linenumber int, code varchar(10), unit varchar(10))
create table #map(code varchar(10), unit varchar(10))
insert into #lines values (1,1,'A',null), (1,2,'B',null),(1, 3,'C',null)
insert into #map values ('A','c1'),('A','c2'),('B','c3'),('B','c4'),('B','c5')

select FileId, MaxLinenum = max(linenumber) into #Files
    from #lines
    group by FileId

select row_number()over(partition by code order by (select null)) Rn,* into #Maptemp
    from #map

select l.FileId,l.Linenumber,l.code, m.unit
    from #lines l
    inner join #Files f on l.FileId = f.FileId
    inner join #Maptemp m on m.code = l.code
    where m.rn = 1
union all
select l.FileId, f.MaxLinenum +row_number()over(partition by f.FileId order by (select null)),l.code, m.unit
    from #lines l
    inner join #Files f on l.FileId = f.FileId
    inner join #Maptemp m on m.code = l.code
    where m.rn > 1

It works fine, but I feel I have done little too much of coding for this. So is there a better way to achieve this ?

A:

This is my try.. You may need some changes according your actual schema.
DECLARE @MAXLINE INT = (SELECT MAX(linenumber) FROM #lines)

SELECT L.FileId
    ,CASE WHEN M.SNO = 1 THEN L.linenumber
        ELSE
            @MAXLINE + ROW_NUMBER() OVER (PARTITION BY CASE WHEN M.SNO<>1
                THEN 1 END ORDER BY M.CODE ,M.UNIT)
        END LINE_NUMBER
, M.code
, M.unit
FROM #lines L
INNER JOIN
(
    SELECT ROW_NUMBER() OVER(PARTITION BY CODE ORDER BY(UNIT)) SNO,*
    FROM #map
)M ON L.code = M.code

Result:
FileId  LINE_NUMBER code    unit
1       1           A       c1
1       2           B       c3
1       4           A       c2
1       5           B       c4
1       6           B       c5


Q:

SQL Server Select from a table returned by a query as list of table names

If I have these tables below:
PLAYERS
ID    Name
==    ===========
1     Mick
2     Matt

COACHES
ID    Name
==    ===========
1     Bill
2     Don

And I have a script below to find all tables that has a column called "Name":
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

Which returns the following:
table_name
===========
PLAYERS
COACHES

How can I select all the rows from both tables returned by the query above?

A:

You will have to use dynamic sql, try something like this:
declare @t table( tablename varchar(50))
declare @sql varchar(max)
set @sql = ''

insert into @t
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

select @sql = @sql + 'Select * From ' + tablename + ' union ' from @t

--remove the trailing 'union'
Select @sql = substring(@sql, 1, len(@sql) - 6)

exec (@sql)

The above script creates and executes the following sql
select * from coaches
union
select * from players

Since we are using union here, it is important that all your tables that have name as column is of same structure.
See more about dynamic sql from http://msdn.microsoft.com/en-us/library/ms188001.aspx


Q:

Converting C# byte to BitArray

Is there any predefined function available to convert a byte into BitArray?
One way would be to inspect every bit of the byte value and then perform bitwise operation. I was wondering if there is any way which is more straightforward than this.

A:

Yes, using the appropriate BitArray() constructor as described here:
var bits = new BitArray(arrayOfBytes);

You can call it with new BitArray(new byte[] { yourBite }) to create an array of one byte.

A:

if you have a byte number or even an integer, etc.
BitArray myBA = new BitArray(BitConverter.GetBytes(myNumber).ToArray());

Note: you need a reference to System.Linq

A:

Solution is simple, just two instructions (which are marked in following code), simply convert byte to binary using Convert.ToString(btindx,2), zero pad  the resultant string to 8 bits (or lengths 8),strBin.PadLeft(8,'0'); and concatenate all binary strings to form a bit stream of your byte array, If you like, you can also form an array of strings to separate each byte's binary representation.
    byte[] bt = new byte[2] {1,2};

    string strBin =string.Empty;
    byte btindx = 0;
    string strAllbin = string.Empty;

    for (int i = 0; i < bt.Length; i++)
    {
        btindx = bt[i];

        strBin = Convert.ToString(btindx,2); // Convert from Byte to Bin
        strBin = strBin.PadLeft(8,'0');  // Zero Pad

        strAllbin += strBin;
    }


Q:

PowerPoint-like resizable picture and text boxes as .NET controls

I'm looking for a way to implement a surface (in C#, Windows Forms) where the user can add pictures and text in resizable boxes (with resize handles) - like in PowerPoint. Does anyone know a ready-made control (preferably free) that can do that?
This is what I mean:
Text box http://www.freeimagehosting.net/uploads/4d88f329f2.png
Thanks

A:

Here is a C# implementation of a Rect Tracker
http://www.codeproject.com/KB/miscctrl/CSharpRectTracker.aspx