text:
Q: How to Select All CheckBox of a Column by DataGrid Header CheckBox in WPF DataGrid I have a DataGrid with one CheckBoxColumn. In the header of that CheckBoxColumn I have added a CheckBox to Select all CheckBoxes of that Datagrid Row.
How can I achieve that?
My XAML Code for WPF dataGrid:
    <DataGrid AutoGenerateColumns="False" CanUserAddRows="False"  Grid.RowSpan="2" Height="130" HorizontalAlignment="Left" IsReadOnly="False" Margin="189,340,0,0" Name="dgCandidate" TabIndex="7" VerticalAlignment="Top" Width="466" Grid.Row="1" >
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="colCandidateID" Binding="{Binding CandidateID}" Header="SlNo" MinWidth="20" IsReadOnly="True" />
            <DataGridTextColumn x:Name="colRegistraion" Binding="{Binding RegisterNo}" Header="Reg. No." IsReadOnly="True"  />
            <DataGridTextColumn x:Name="colCandidate" Binding="{Binding CandidateName}" Header="Name" MinWidth="250" IsReadOnly="True"  />

            <DataGridTemplateColumn>
                <DataGridTemplateColumn.Header>
                    <CheckBox Name="chkSelectAll" Checked="chkSelectAll_Checked" Unchecked="chkSelectAll_Unchecked"></CheckBox>
                </DataGridTemplateColumn.Header>
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate >
                        <CheckBox x:Name="colchkSelect1" Checked="colchkSelect1_Checked" Unchecked="colchkSelect1_Unchecked" ></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>

    </DataGrid>

A: Convert your Candidate class into something like this:
public class Candidate : DependencyObject
{
    //CandidateID Dependency Property
    public int CandidateID
    {
        get { return (int)GetValue(CandidateIDProperty); }
        set { SetValue(CandidateIDProperty, value); }
    }
    public static readonly DependencyProperty CandidateIDProperty =
        DependencyProperty.Register("CandidateID", typeof(int), typeof(Candidate), new UIPropertyMetadata(0));
    //RegisterNo Dependency Property
    public int RegisterNo
    {
        get { return (int)GetValue(RegisterNoProperty); }
        set { SetValue(RegisterNoProperty, value); }
    }
    public static readonly DependencyProperty RegisterNoProperty =
        DependencyProperty.Register("RegisterNo", typeof(int), typeof(Candidate), new UIPropertyMetadata(0));
    //CandidateName Dependency Property
    public string CandidateName
    {
        get { return (string)GetValue(CandidateNameProperty); }
        set { SetValue(CandidateNameProperty, value); }
    }
    public static readonly DependencyProperty CandidateNameProperty =
        DependencyProperty.Register("CandidateName", typeof(string), typeof(Candidate), new UIPropertyMetadata(""));
    //BooleanFlag Dependency Property
    public bool BooleanFlag
    {
        get { return (bool)GetValue(BooleanFlagProperty); }
        set { SetValue(BooleanFlagProperty, value); }
    }
    public static readonly DependencyProperty BooleanFlagProperty =
        DependencyProperty.Register("BooleanFlag", typeof(bool), typeof(Candidate), new UIPropertyMetadata(false));
}

in MainWindow.xaml:
<DataGrid ItemsSource="{Binding CandidateList}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding CandidateID}"/>
        <DataGridTextColumn Header="RegNr" Binding="{Binding RegisterNo}"/>
        <DataGridTextColumn Header="Name" Binding="{Binding CandidateName}"/>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Checked"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate>
                    <CheckBox IsChecked="{Binding BooleanFlag}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

in MainWindow.xaml.cs:
    public MainWindow()
    {
        DataContext = this;
        CandidateList.Add(new Candidate()
        {
            CandidateID = 1,
            CandidateName = "Jack",
            RegisterNo = 123,
            BooleanFlag = true
        });
        CandidateList.Add(new Candidate()
        {
            CandidateID = 2,
            CandidateName = "Jim",
            RegisterNo = 234,
            BooleanFlag = false
        });
        InitializeComponent();
    }
    //List Observable Collection
    private ObservableCollection<Candidate> _candidateList = new ObservableCollection<Candidate>();
    public ObservableCollection<Candidate> CandidateList { get { return _candidateList; } }
    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var item in CandidateList)
        {
            item.BooleanFlag = true;
        }
    }
    private void UnheckBox_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var item in CandidateList)
        {
            item.BooleanFlag = false;
        }
    }

A: Strictly speaking the model should not know about the view and so the solution proposed by blindmeis, where the model change is updating every row in the datagrid, breaks the MVVM/Presentation Design pattern. Remember that in MVVM the dependency flow is View -> ViewModel -> Model so if you are referencing controls in your view model (or control codebehind) then you have effectively broken the pattern and you will probably run into issues further down the track.

A:
I have added CheckBox to Select all CheckBox in Datagrid Row

if you mean select all checkbox in datagrid column, then i would say: simply update your itemssource collection with checked/unchecked.
public bool SelectAll
{
  get{return this._selectAll;}
  set
  {
     this._selectAll = value;
     this.MyItemsSourceCollection.ForEach(x=>x.MyRowCheckProperty=value);
     this.OnPropertyChanged("SelectAll");
  }
}

xaml
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox isChecked="{Binding SelectAll}"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate >
                    <CheckBox IsChecked="{Binding MyRowCheckProperty}"></CheckBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

i dunno if the xaml bindings are right, but i hope you can see my intention

A: It turns out that this is quite a lot harder to get right than one would hope.
The first problem is that you can't just bind the view model to the column header because it doesn't have the view model as its data context, so you need a binding proxy to correctly route the binding to the view model.
public class BindingProxy : Freezable
{
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register(
        "Data",
        typeof(object),
        typeof(BindingProxy),
        new UIPropertyMetadata(null));

    public object Data
    {
        get { return this.GetValue(DataProperty); }
        set { this.SetValue(DataProperty, value); }
    }

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }
}

Now create a binding proxy in your data grid's resources:
<DataGrid.Resources>
    <aon:BindingProxy
        x:Key="DataContextProxy"
        Data="{Binding}" />
</DataGrid.Resources>

Then the column needs to be defined as:
<DataGridTemplateColumn>
    <DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <CheckBox
                Command="{Binding
                    Data.SelectAllCommand,
                    Source={StaticResource DataContextProxy}}"
                IsChecked="{Binding
                    Data.AreAllSelected,
                    Mode=OneWay,
                    Source={StaticResource DataContextProxy},
                    UpdateSourceTrigger=PropertyChanged}"
                IsThreeState="True" />
        </DataTemplate>
    </DataGridTemplateColumn.HeaderTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox
                IsChecked="{Binding
                    Path=IsSelected,
                    UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Note that there needs to be a binding to both the check box's IsChecked dependency property and its Command property and the IsChecked binding is OneWay. The IsChecked binding gets the check box to display the current state of the items and the Command binding performs the bulk selection. You need both.
Now in the view model:
public bool? AreAllSelected
{
    get
    {
        return this.Items.All(candidate => candidate.IsSelected)
        ? true
        : this.Items.All(candidate => !candidate.IsSelected)
            ? (bool?)false
            : null;
    }

    set
    {
        if (value != null)
        {
            foreach (var item in this.Items)
            {
                item.IsSelected = value.Value;
            }
        }

        this.RaisePropertyChanged();
    }
}

And the SelectAllCommand property is an implementation of ICommand where the Execute method is:
public void Execute(object parameter)
{
    var allSelected = this.AreAllSelected;

    switch (allSelected)
    {
        case true:
            this.AreAllSelected = false;
            break;
        case false:
        case null:
            this.AreAllSelected = true;
            break;
    }
}

Finally your row item view models (i.e. the things in Items) need to raise PropertyChanged on the main view model each time the value of IsSelected changes. How you do that is pretty much up to you.


text:
Q: Setting up a controller property after the model hook I need to set a controller property after the model hook. I can think of two ways to do this:
model(params) {
  return this.store.findRecord('user', 1);
},

afterModel(model, transition) {
  model.get('profile').then(profile => {
    this.set('profile', profile);
  });
},

setupController(controller, model) {
  controller.set('model', model);
  controller.set('profile', this.get('profile'));
},

The other approach. i.e. skip setupController:
model(params) {
  return this.store.findRecord('user', 1);
},

afterModel(model, transition) {
  model.get('profile').then(profile => {
    this.controller.set('profile', profile);
  });
},

Both seem to work.
Are there any added advantages / disadvantages with either approach? Clearly, the latter is shorter. But does it feel "clean" to set the controller property in an afterModel hook?
EDIT: the relationship/association between user and profile is async.

A: As another poster pointed out, you can access model.profile, but that won't work from code if profile is an async association:
// models/user.js
profile: belongsTo('profile', { async: true })

The reason is that model.profile will return a promise rather than a value. To solve that, you can use the afterModel hook as you suggested, but all you need is
afterModel(model, transition) {
  return model.get('profile');
},

That will issue the async call and pause the transition until it is completed, at which point the profile may be accessed as model.profile as usual. If for some reason you really want to access the profile as a controller property to avoid having to prefix it with model., just define an alias in your controller:
profile: Ember.computed.alias('model.profile')

If there is more than one such property, then the following should do the job:
return Ember.RSVP.Promise.hash(this.getProperties('profile', ...));

You could also implement this right in the model hook, although it's a bit less readable:
model() {
  return this.store.findRecord('user', 1) .
    then(user => user.get('profile') .
      then(() => user)
    );
}

What this says is, find the user, and then when found get his profile (which will cause the async request to fire), then when that is found return the user from the promise, so it is correctly set into model.

A: You don't need any of those code, because controller has access to model via this.model. In any controller's method you can just call this.get('model.profile'). In template you may use {{model.profile}}.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compile any swift file in a given folder? I use actual folders for my Xcode projects containing my .swift files. I dragged the folder into Xcode but it appears that my swift classes are not being built. I went to my target, went to Build Phase, went to Compile Source and added the missing folder to the references to be built.
My swift files are still not being built.
Which flag could I add to the folder (in Compile Source) for force it to compile every .swift files within it (including the ones in subfolders) ?
I couldn't find any info about it so far, any ideas ?

A: TLDR Use Groups, not Folder References.
Folder References in Xcode are made mainly for resources. When you create a folder reference, Xcode won't care about the contents. They are helpful when copying resources that should keep their directory structure.
To organize source code files, you need Groups. Groups are logical project folders and most of the time they are backed up by a file system folder anyway.
See also Difference between folder and group in Xcode?


text:
Q: D3 drag and mouseup events I am using d3 to select rectangle. I am trying to get both a drag end and mouseup event to fire on the rectangle. It looks like the drag events block mouseup events. (They do not block mouse over events) I have bound a mouse up and a drag event  to the rectangle. When I click on the rectangle, the mouseup event doesn't fire, only the drag end fires. I have tried different combinations of event.stopPropagation() and preventDefault() to control which events fire. I also tried setting the drag event to null. None of these work. How do I get both the drag end and mouseup to fire on mouseup?
var target = d3.select('#test');
target.on('mouseup', (d) => alert('mouseup'))
 .call(d3.drag()
   .on("start", function () {
     console.log('start')
   })
   .on("drag", function () {
     console.log('drag');
   }).on("end", function () {
     alert('end');
     //d3.select(window).on('click.drag', null);
   })
);

<div id='test' />

#test { background:red; position:absolute; height:40px; width:40px; }

This functionality worked in D3 v3 but it does not work in v4
Edit:
To clarify, my problem was that the mouseup events are disabled on the page (and for that matter all elements) when the drag events trigger. I wanted to identify the target element when you drag from one shape onto another (hence the need for mouseup).

A: When you click on one element and drag to another, I wanted to detect what that second element is. Mouseup doesn't trigger when you drag an object, but mouseover and mouseout do. I used those functions to set a mouseover_obj variable. That way after you drag, when the drag end event executes, you can access that object. If it's not null, then its value that is the shape your mouse is over.
Here's some code:
JsFiddle for D3 Mouseup while Drag
var mouseover_node = null;
var svg = d3.select('body').append('svg').attr('width', 1000).attr('height', 1000);
var rect = svg.selectAll('rect')
  .data([0, 2, 3])
  .enter().append('rect')
  .attr('x', function(x) { return +x * 0; })
  .attr('y', function(y) {  return +y * 120; })
  .attr('width', function() { return 100; })
  .attr('height', function() { return 100; })
  .attr('fill', function(x) {  if(x == 0){return'red';}else return 'blue'; });

rect.on("mouseover", (d) => {this.mouseover_node = d})
  .on("mouseout", (d) => {this.mouseover_node = null})
  .call(d3.drag()
    .on("start", function () {
        console.log('start');
        return false;
        })
    .on("drag", function () {
        console.log('drag');
        })
    .on("end",  (sourceElement,index,svgItems) => {
        console.log('end drag with mouseover: ' + this.mouseover_node);
        })
);

A: In my experience you should just be able to add mouse down logic into the drag started event. Have you tried that in this case? If it's a more complicated use of mouse down and doesn't work with the drag started event, please add the specifics.


text:
Q: My python program exits instead of looping I've been working with Python on and off for the last year and found a 'spam program' on YouTube which I then tried to rewrite so that it will repeat for a defined amount. But even if I enter a five the program will still only write one time and then exit. And I don't know what I did wrong.
import pyautogui
import time

f = open("E:\Documents\Coding-Projekte\Python\Spammer\spamtext", 'r')

count = int(input("How often to write the text: "))

time.sleep(5)

def spam():
    print("Start Spam")
    if count > 0:
        for word in f:
            if ":" in word:
                pyautogui.typewrite(word)
                pyautogui.press("enter")
                time.sleep(0.5)
                pyautogui.press("enter")
                count - 1
                print("wrote line")
                spam()
            else:
                pyautogui.typewrite(word)
                pyautogui.press("enter")
                count - 1
                print("wrote line")
                spam()
    else:
        exit()

spam()

A: Replace if count > 0: with for repetition in range(count):.


text:
Q: Using CloseableHttpClient with try-with-resources I've been searching for a completed example of CloseableHttpClient with try-with-resources. I am confused on if closing CloseableHttpClient also closes the CloseableHttpResponse object that will be created when I call httpclient.execute(post). Do I need to wrap CloseableHttpResponse in a try-with-resources too?
Example:
try(CloseableHttpClient httpclient = HttpClients.custom().build()) {
    HttpPost post = new HttpPost(url);
    CloseableHttpResponse res = httpclient.execute(post);

    // do something with res
} catch (Throwable e) {
    // do something with error
}

A: If you want for the reponse to take part in the try-with-resource you do. Although as you catch the Exceptions already, you can end with } - no additional catch required.
Technically it's not a requirement as the implementation for close () in CloseableHttpResponse is empty
You need to close CloseableHttpResponse to release the resources, as per httpcomponents documentation (https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html)
Oh. Don't catch Throwable - this is bad style and can cause really hard to find errors.


text:
Q: Haskell shift right Still working on trying to implement Boyer Moore algorithm.
Due in a few hours and I can't get this pesky shift part working.
It works if there is a 1:1 match i.e
boyerMoore "hello" "hello"
but it doesn't work for "howareyou" "are"
I'm almost certain my problem lies within the boyMoore area with the ifs.
I'm pretty sure that it's something in the boyerMoore function itself and not the shift methods. Just wondering if I am calling it in the right way or if I am over looking something? Appreciate any help.
Also sorry for asking so many questions today, just want this assignment over and done with as it is our last one.
boyerMoore :: String -> String -> Bool
boyerMoore [] _ = False
boyerMoore mainString patternString =
    let
    patternLength = (length patternString)
    position = getPosition patternString (take patternLength(mainString))
    in if (mainString == patternString)
        then True
        else
                if position > -1
                then boyerMoore (patternString) (drop position(mainString))
                else boyerMoore (patternString) (drop patternLength(mainString))

getPosition :: String -> String -> Int
getPosition [] _ = -1
getPosition mainString patternString = shift patternString mainString (length patternString)

shift :: String -> String -> Int -> Int
shift [] _ _ = -1
shift textString patternString lengthVariable =
    if (last patternString) == (last textString)
    then lengthVariable - (length patternString)
    else shift (init patternString) textString lengthVariable

A: Your final equation for boyerMoore starts
boyerMoore mainString patternString =

but the recursive calls at the end both have the form
boyerMoore patternString (drop foo mainString)

My knowledge of Boyer-Moore is rusty, but I doubt you want to swap patternString with mainString like that.
Secondly, I think you may be confusing the last() function on the page you link to with Haskell's last function. last gives back the final element of the list you give it, whereas last(), despite the notation, takes two arguments: a character to look for, and the pattern string to look in.


text:
Q: Recover data after reformat Is it possible to recover data after a hard drive has been reformatted and windows reinstalled on the drive? As a friend has forgot to back up some important word documents.

A: Yes. The simplest way to understand a reformat is to think of a hard drive as a book, the folders are chapters and files are pages. Windows explorer is just a contents page. So, all a reformat does is remove the contents page. And since you can't see the contents, you can't get access the pages (files / folders), but this doesn't mean it doesn't exist.
However, since you've re-installed Windows, it is possible it's overwritten some of your 'old' pages (files /folders).
I suggest a search for "free hard drive recovery" into a search engine like this.

A: It is indeed possible. I'd recommend TestDisk, as it is free and has an extensive featureset. It also works on most OS's.

A: That's possible.
There's a similar question on Android Enthusiasts that covers just this:
Data Recovery - How to Restore Deleted / Formatted Files on HD Micro SD Card
You can also search for file carving or have a look at the forensics wiki


text:
Q: Draggable list into html5 table has bug There are two lists of items need to be mapped into a table. I've create the table and draggable list item followed by reference-style link to Accessing table cell data within list items with Javascript.
The current situation
I have two lists, and need to be filled into two columns(with different ids); ideally, the the credit card list item can only be put into credit card column, vice versa for api list and api field.
The current issue

*

*When I dragged items from api list to api field, it displayed double text.

*Two list items can drag into different fields. How can I make the list items limited into matched table column?

Here is the JsFiddle along with some sample code:
$("#ccField li").draggable({
  appendTo: "body",
  helper: "clone",
  cursor: "move",
  revert: "invalid"
});

$("#apiField li").draggable({
    appendTo: "body",
    helper: "clone",
    cursor: "move",
    revert: "invalid"
});

ccDroppable($("#creditCardApiTable table td"));

apiDroppable($("#creditCardApiTable table td"));

function ccDroppable($elements) {
    $elements.droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-drop-hover",
        accept: ":not(.ui-sortable-helper)",

        over: function (event, ui) {
            var $this = $(this);
        },
        drop: function (event, ui) {
            var $this = $(this);
            $("").text(ui.draggable.text()).appendTo(this);
            $("#ccList").find(":contains('" + ui.draggable.text() + "')")[0].remove();
        }
    });
}

function apiDroppable($elements) {
    $elements.droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-drop-hover",
        accept: ":not(.ui-sortable-helper)",

        over: function (event, ui) {
            var $this = $(this);
        },
        drop: function (event, ui) {
            var $this = $(this);
            $("").text(ui.draggable.text()).appendTo(this);
            $("#apiList").find(":contains('" + ui.draggable.text() + "')")[0].remove();
        }
    });
}

A: Is this what you are looking for?
http://jsfiddle.net/ryaL3xpk/3/
$("#ccField li").draggable({
    appendTo: "body",
    helper: "clone",
    cursor: "move",
    revert: "invalid"
});

$("#apiField li").draggable({
    appendTo: "body",
    helper: "clone",
    cursor: "move",
    revert: "invalid"
});

function droppableField($element, $accept) {
    $element.droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-drop-hover",
        accept: $accept,
        over: function (event, ui) {
            var $this = $(this);
        },
        greedy:true,
        tolerance:'touch',
        drop: function (event, ui) {
            var $this = $(this);
            $this.text(ui.draggable.text()).appendTo(this);
        }
    });
}

droppableField($('#creditCardApiTable table td .ccDropField'), '#ccField li');
droppableField($('#creditCardApiTable table td .apiDropField'), '#apiList li');

So basically, you allow each span to be droppable, and each accepts different draggable field.


text:
Q: How to switch to different JRE in command line from teamcity My teamcity build configuration uses Java8 but for one of my command line I have to switch to Java7 . How can I achieve this in a command line Teamcity step.
Thanks for suggestions in advance

A: Wrap your command line step in a shell script. In the shell script , change the JAVA_HOME and PATH variables to point to JRE7 instead of JRE8, as required
It would be of the form
export JAVA_HOME=<path for java>
export PATH=<path for java bin>:$PATH


text:
Q: what's the allusion of socketpair api's interface? socketpair(int family, int type, int protocol, int* sockfd) from sys/socket.h.
unp states the family should be AF_LOCAL, the protocol should be 0, since then why should the interface require such parameters? why not simplify it as socketpair(int type, int *sockfd) ?
I believe there must be story here, but I just don't know why.
Thank you for telling me the story ;)

A: You should read that statement "AF_LOCAL" (or _UNIX) is currently the only protocol that implements socketpair().
The interface is generic and one could provide implementation for other types of sockets. For instance it would not be too hard to implement support for AF_INET by creating two sockets connected to each other using localhost IP. The only gotcha is that there would be little practical use for it. Unix sockets are better for local connections and changing existing socketpair API is too much trouble now.


text:
Q: how to retrieve bmp file type using mimetype Ive got a following code for recognizing image types in Java from another post here on stackoverflow.
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(path);
System.out.println(mimeType);

It works fine , for jpeg , gif or png.
But the output for BMP picture is NULL. Anyone help ? :)


text:
Q: Check if each value within list is present in the given Django Model Table in a SINGLE query So let's say I want to implement this generic function:
def do_exist(key:str, values:list[any], model: django.db.models.Model) -> bool

Which checks if all the given values exist within a given model's column named key in a SINGLE query.
I've implemented something like this
from django.db.models import Exists
def do_exist(key, values, model):
    chained_exists = (Exists(model.objects.filter(F(key)=value)) for value in values)
    qs = model.objects.filter(*chained_exists).values("pk")[:1]
    # Limit and values used for the sake of less payload
    return len(qs) > 0

It generates a pretty valid SQL query, but the thing that scares me is that if I try to append evaluating method call to qs like .first() instead of [:1] or .exists() MYSQL connection drops.
Does anyone have a more elegant way of solving this?

A: If you know you're passing in N pks, then a count() query filtered by those pks should have exactly N results.
def do_exist(model, pks):
    return model.objects.filter(pk__in=pks).count() == len(pks)

A: qs = MyModel.objects.filter(id__in=pks)

This gives you a queryset that you can apply .all() etc to

A: In Django, you can use "entry__in" to filter down a queryset based on a list of entries.
results = Model.objects.filter(id__in = pks)

A: res = MyModel.objects.filter(id__in=pks)


text:
Q: Extremely simple code not working in HtmlUnit I'm working with HtmlUnit 2.9 (the stable version that was released this month). Do you have any idea why the following code is not working?
public class Main {

    public static void main(String[] args) {
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
        webClient.setCssEnabled(true);
        webClient.setCssErrorHandler(new SilentCssErrorHandler());
        webClient.setThrowExceptionOnFailingStatusCode(false);
        webClient.setThrowExceptionOnScriptError(false);
        webClient.setRedirectEnabled(false);
        webClient.setAppletEnabled(false);
        webClient.setJavaScriptEnabled(false);
        webClient.setPopupBlockerEnabled(true);
        webClient.setTimeout(60000);
        webClient.setPrintContentOnFailingStatusCode(false);

        System.out.println("This is printed on screen");
        try {
            webClient.getPage("http://www.2cash.info/index.php");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("This is NEVER printed on screen");
    }
}

I'm also adding the result of jstack. Notice I've marked a section that gets repeated constantly:
2011-08-26 03:15:45
Full thread dump Java HotSpot(TM) Server VM (20.1-b02 mixed mode):

"Attach Listener" daemon prio=10 tid=0x09520400 nid=0x5363 waiting on condition [0x00000000]
   java.lang.Thread.State: RUNNABLE

"JS executor for com.gargoylesoftware.htmlunit.WebClient@a7c45e" daemon prio=10 tid=0x6feb7400 nid=0x5356 waiting on condition [0x6fcfe000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor.run(JavaScriptExecutor.java:166)
    at java.lang.Thread.run(Thread.java:662)

"Low Memory Detector" daemon prio=10 tid=0x70204c00 nid=0x5352 runnable [0x00000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" daemon prio=10 tid=0x70202800 nid=0x5351 runnable [0x00000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" daemon prio=10 tid=0x70200800 nid=0x5350 waiting on condition [0x00000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" daemon prio=10 tid=0x09514c00 nid=0x534f runnable [0x00000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" daemon prio=10 tid=0x09503400 nid=0x534e in Object.wait() [0x70798000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x76af2ff0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
    - locked <0x76af2ff0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)

"Reference Handler" daemon prio=10 tid=0x09501c00 nid=0x534d in Object.wait() [0x707e9000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x7675cc58> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:485)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
    - locked <0x7675cc58> (a java.lang.ref.Reference$Lock)

"main" prio=10 tid=0x09482400 nid=0x5349 runnable [0xb6c34000]
   java.lang.Thread.State: RUNNABLE
    at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.getSlot(ScriptableObject.java:2603)
    at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.defineProperty(ScriptableObject.java:1699)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.configureConstantsPropertiesAndFunctions(JavaScriptEngine.java:350)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.configureClass(JavaScriptEngine.java:330)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.init(JavaScriptEngine.java:199)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.access$000(JavaScriptEngine.java:79)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$1.run(JavaScriptEngine.java:146)
    at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:537)
    at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:538)
    at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.initialize(JavaScriptEngine.java:157)
    at com.gargoylesoftware.htmlunit.WebClient.initialize(WebClient.java:1141)
    at com.gargoylesoftware.htmlunit.WebWindowImpl.setEnclosedPage(WebWindowImpl.java:109)
    at com.gargoylesoftware.htmlunit.html.FrameWindow.setEnclosedPage(FrameWindow.java:102)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:200)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:179)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:221)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:106)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:433)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
    at com.gargoylesoftware.htmlunit.html.BaseFrame.<init>(BaseFrame.java:73)
    at com.gargoylesoftware.htmlunit.html.HtmlInlineFrame.<init>(HtmlInlineFrame.java:46)
    at com.gargoylesoftware.htmlunit.html.DefaultElementFactory.createElementNS(DefaultElementFactory.java:288)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.startElement(HTMLParser.java:506)
    at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
    at org.cyberneko.html.HTMLTagBalancer.callStartElement(HTMLTagBalancer.java:1136)
    at org.cyberneko.html.HTMLTagBalancer.startElement(HTMLTagBalancer.java:742)
    at org.cyberneko.html.filters.DefaultFilter.startElement(DefaultFilter.java:136)
    at org.cyberneko.html.filters.NamespaceBinder.startElement(NamespaceBinder.java:278)
    at org.cyberneko.html.HTMLScanner$ContentScanner.scanStartElement(HTMLScanner.java:2652)
    at org.cyberneko.html.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2022)
    at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:908)
    at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:499)
    at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:452)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:789)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:225)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:179)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:221)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:106)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:433)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)

    <THIS_SECTION_IS_PRINTED_AS_IF_IT_WERE_IN_A_LOOP>
    at com.gargoylesoftware.htmlunit.html.BaseFrame.loadInnerPageIfPossible(BaseFrame.java:149)
    at com.gargoylesoftware.htmlunit.html.BaseFrame.loadInnerPage(BaseFrame.java:99)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.loadFrames(HtmlPage.java:1760)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:194)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:440)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
    </THIS_SECTION_IS_PRINTED_AS_IF_IT_WERE_IN_A_LOOP>

    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
    at main.Main.<init>(Main.java:42)
    at main.Main.main(Main.java:23)

"VM Thread" prio=10 tid=0x094fe000 nid=0x534c runnable

"GC task thread#0 (ParallelGC)" prio=10 tid=0x09489800 nid=0x534a runnable

"GC task thread#1 (ParallelGC)" prio=10 tid=0x0948ac00 nid=0x534b runnable

"VM Periodic Task Thread" prio=10 tid=0x70207000 nid=0x5353 waiting on condition

JNI global references: 1234

I think there is some kind of loop regarding the automatic loading of frames. If that is the case, is there any way to disable that behaviour to break the loop?
Thanks in advance!

A: Well, although it is a horrible solution (workaround, actually...), I finally decided to disable the automatic loading of frames in HtmlUnit as adviced by one of the developers of HtmlUnit. This is what I did in detail:

*

*Downloaded the HtmlUnit source

*Downloaded maven from here

*Commented the content (the body of the method, not the declaration) of the loadFrames() method of the HtmlPage class located in htmlunit-2.9/src/main/java/com/gargoylesoftware/htmlunit/html

*Compiled this custom code skipping tests with: mvn -Dmaven.test.skip=true clean compile package

*Got the new htmlunit-2.9.jar located in htmlunit-2.9/artifacts and replaced the current htmlunit-2.9.jar library file

*This step might be the most delicate one as it will depend on each application. However, I'll show you the changes I needed to do to my application.

You know how my original code was (look at the question). That would download all frames and iframes from a page. I'm adding an example on how to get a page with frames just loading the frames you want:
try {
    HtmlPage page = webClient.getPage("http://www.w3schools.com/HTML/tryit.asp?filename=tryhtml_noframes");
    HtmlInlineFrame frame = page.getFirstByXPath("//iframe[@name='view']");
    page = webClient.getPage(page.getFullyQualifiedUrl(frame.getSrcAttribute()));
    System.out.println(page.asXml());
} catch (Exception e) {
    e.printStackTrace();
}

After this library change, the content of the frame will be empty once the getPage() method finishes. Notice it won't be null, looks like it is just returning an empty frame. What we need to do is to download the content of the frames we are interested in manually, that's why I'm performing a getPage() again.
Well this is how I managed to selectively download frames and iframes with HtmlUnit. Any ideas on how to improve this will be appreciated. Anyway, I hope there will be added some way to disable the loading of the frames in HtmlUnit itself in the future, maybe adding a method such as getPage(URL url, boolean downloadFrames) or something.
Hope this helps someone out there!

A: When I open this site in my browser it does not ever finish loading the page. This might be the problem why HtmlUnit crashes, too. Tested with Chrome and FF.
Try loading a more simple site instead and you may know if this crash is site-depended.


text:
Q: Não mostrar banner com data de expiração vencida Estou tentando mostrar em meu site banner´s que não estejam com data de expiração vencidas, tenho em meu banco um banner com as seguinte datas:
A data atual é: 2015-02-07
Data de Expiração: 2015-02-08
O script que fiz está assim:
<?php if ($totalRows_rsBanner > 0) {  ?>
<?php do {
            $imagem = substr($row_rsBanner['imagem'],3);
            $url = $row_rsBanner['url'];

            $DataAtual = date("Y-m-d"); // data atual
            $timestamp_DataAtual = strtotime($DataAtual); // converte para timestamp Unix

            $DataExpiracao = $row_rsBanner['data_expiracao']; // data de expiração do anúncio
            $timestamp_DataExpiracao = strtotime($DataExpiracao); // converte para timestamp Unix

?>
            <?php if ($timestamp_DataAtual > $timestamp_DataExpiracao){ ?>

<a href="<?php echo $url; ?>"><img src="<?php echo $imagem; ?>">

            <?php } ?>
            <?php } while ($row_rsBanner = mysql_fetch_assoc($rsBanner)); ?>
<?php } ?>

O campo de data_expiracao está com o formato Date.

A: O seu sinal de comparação estava invertido.
Mais uma dica: use o objeto \DateTime para trabalhar com as datas. Assim fica mais fácil comparar datas.
<?php

if ($totalRows_rsBanner > 0) {
    do {
        $imagem        = substr($row_rsBanner['imagem'],3);
        $url           = $row_rsBanner['url'];
        $DataAtual     = new \DateTime(); // sem argumentos = data atual
        $DataExpiracao = new \DateTime($row_rsBanner['data_expiracao']); // data de expiração do anúncio
        if ($DataAtual < $DataExpiracao) { ?>

<a href="<?php echo $url; ?>"><img src="<?php echo $imagem; ?>">

        <?php }
    } while ($row_rsBanner = mysql_fetch_assoc($rsBanner));
}


text:
Q: Transformation in data.table using .SD, lapply and a function returns only one row I am using the flights14.csv data to test some code in data.table.
In particular, I want to convert all integer variables to numeric.
> glimpse(flights)
Observations: 253,316
Variables: 17
$ year      <int> 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014,...
$ month     <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
$ day       <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
$ dep_time  <int> 914, 1157, 1902, 722, 1347, 1824, 2133, 1542, 1509, 1848, 1655, 1752, 1253, 1907, 1720, 1733, 1640, 1714, 1611, 553, 62...
$ dep_delay <int> 14, -3, 2, -8, 2, 4, -2, -3, -1, -2, -5, 7, 3, 142, -5, 18, 25, -1, 191, -7, -7, -8, -2, -3, 44, -1, 3, -5, 26, 52, 55,...
$ arr_time  <int> 1238, 1523, 2224, 1014, 1706, 2145, 37, 1906, 1828, 2206, 2003, 2120, 1351, 2223, 1819, 2024, 2001, 2036, 1910, 739, 81...
$ arr_delay <int> 13, 13, 9, -26, 1, 0, -18, -14, -17, -14, -17, -5, 1, 133, -26, 69, 36, 1, 185, -6, 0, -17, 15, 1, 42, -2, 12, 24, 46, ...
$ cancelled <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
$ carrier   <chr> "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA",...
$ tailnum   <chr> "N338AA", "N335AA", "N327AA", "N3EHAA", "N319AA", "N3DEAA", "N323AA", "N328AA", "N5FJAA", "N3HYAA", "N5CFAA", "N332AA",...
$ flight    <int> 1, 3, 21, 29, 117, 119, 185, 133, 145, 235, 172, 177, 178, 181, 256, 199, 211, 291, 300, 301, 303, 305, 307, 313, 317, ...
$ origin    <chr> "JFK", "JFK", "JFK", "LGA", "JFK", "EWR", "JFK", "JFK", "JFK", "JFK", "EWR", "JFK", "JFK", "JFK", "JFK", "JFK", "JFK", ...
$ dest      <chr> "LAX", "LAX", "LAX", "PBI", "LAX", "LAX", "LAX", "LAX", "MIA", "SEA", "MIA", "SFO", "BOS", "LAX", "BOS", "ORD", "IAH", ...
$ air_time  <int> 359, 363, 351, 157, 350, 339, 338, 356, 161, 349, 161, 365, 39, 345, 35, 155, 234, 232, 214, 142, 143, 139, 145, 139, 1...
$ distance  <int> 2475, 2475, 2475, 1035, 2475, 2454, 2475, 2475, 1089, 2422, 1085, 2586, 187, 2475, 187, 740, 1417, 1521, 1372, 733, 733...
$ hour      <int> 9, 11, 19, 7, 13, 18, 21, 15, 15, 18, 16, 17, 12, 19, 17, 17, 16, 17, 16, 5, 6, 6, 7, 8, 10, 14, 10, 11, 13, 16, 17, 18...
$ min       <int> 14, 57, 2, 22, 47,

My code is the following:
> data <- flights[, lapply(.SD, function(x){ifelse(is.integer(x), as.numeric(x), x)})]

The transformation is performed successfully but only one record is returned.
> glimpse(data)
Observations: 1
Variables: 18
$ year      <dbl> 2014
$ month     <dbl> 1
$ day       <dbl> 1
$ dep_time  <dbl> 914
$ dep_delay <dbl> 14
$ arr_time  <dbl> 1238
$ arr_delay <dbl> 13
$ cancelled <dbl> 0
$ carrier   <chr> "AA"
$ tailnum   <chr> "N338AA"
$ flight    <dbl> 1
$ origin    <chr> "JFK"
$ dest      <chr> "LAX"
$ air_time  <dbl> 359
$ distance  <dbl> 2475
$ hour      <dbl> 9
$ min       <dbl> 14
$ speed     <dbl> 6.89415

Could you explain to me this result and tell me how to fix the code?
Your advice will be appreciated.

A: library(data.table)
flights <- fread("https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv")
needed_names <- names(c(do.call(c,c(flights[,lapply(.SD,class)])))[c(do.call(c,c(flights[,lapply(.SD,class)])))=="integer"])

flights[, c(needed_names) := lapply(.SD, as.numeric), .SDcols = needed_names]

str(flights)
Classes 'data.table' and 'data.frame':  253316 obs. of  11 variables:
 $ year     : num  2014 2014 2014 2014 2014 ...
 $ month    : num  1 1 1 1 1 1 1 1 1 1 ...
 $ day      : num  1 1 1 1 1 1 1 1 1 1 ...
 $ dep_delay: num  14 -3 2 -8 2 4 -2 -3 -1 -2 ...
 $ arr_delay: num  13 13 9 -26 1 0 -18 -14 -17 -14 ...
 $ carrier  : chr  "AA" "AA" "AA" "AA" ...
 $ origin   : chr  "JFK" "JFK" "JFK" "LGA" ...
 $ dest     : chr  "LAX" "LAX" "LAX" "PBI" ...
 $ air_time : num  359 363 351 157 350 339 338 356 161 349 ...
 $ distance : num  2475 2475 2475 1035 2475 ...
 $ hour     : num  9 11 19 7 13 18 21 15 15 18 ...
 - attr(*, ".internal.selfref")=<externalptr>


text:
Q: Sending a text message in localhost with PHP So I'm trying to send a text message to my phone using PHP. I'm able to send a message to my email, but it won't send to my phone. I have exim4 installed if that helps. I'm somewhat of a beginner with this kind of thing, so any help is appreciated. I tried sending the message to ##########@vtext.com
The php code is in mail.php, while the html is in test.html, FYI.

    <form method='post' action='mail.php'>
        To: <input name='to' type='text'>

        From: <input name='email' type='text'>

        Subject: <input name='subject' type='text'>

        Message:
<textarea name='message' rows='15' cols='40'></textarea>

        <input type='submit' value="Send Email">
    </form>

<?php

    $email = $_POST['email'];
    $to = $_POST['to'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    mail($to, $subject,
    $message, "From:" . $email);
?>

A: Depending on the service provider for you phone you have they generally give every phone number a email address. For example 12345678@vtext.com. That will send a text right to your phone for free without any other services. Youll need to make sure your email system is set up correctly as well as ported correctly inside your local host. You can always try a regular email to make sure it works.
http://www.makeuseof.com/tag/email-to-sms/
You can use any php send mail script and easily send messages.
Other wise youll need a mobile gateway to send texts and those usually charge a fee or if they are free are a pain to deal with from my experience.


text:
Q: Custom ormlite query implementation based on class interface I'd like to extend certain ORMLite methods based on the object's implementation. E.g.,
I have an interface:
public interface IHaveTimestamps
{
    DateTime CreatedOn { get; set; }
    DateTime UpdatedOn { get; set; }
}

Now I'd like to override the Db.Insert<T>() method only if T implements IHaveTimestamps and for other instances of T, it should perform the Insert based on the default behaviour.
This is so that I can centralise setting the CreatedOn and UpdatedOn values, rather than doing that manually everywhere.
Can I do this by overloading the Insert/Update method so that all I would need to do is update the models to inherit from the interface and all the DB operations will take care of itself, or would I need to do something like this:
public static class DbExtensions
{
    public static long MyInsert<T> (this IDbConnection dbConn, T obj, bool selectIdentity = false) where T : IHaveTimestamps {
        obj.CreatedOn = DateTime.UtcNow;
        obj.UpdatedOn = DateTime.UtcNow;
        return dbConn.Insert<T>(obj);
    }

    public static long MyUpdate<T> (this IDbConnection dbConn, T obj) where T : IHaveTimestamps {
        obj.UpdatedOn = DateTime.UtcNow;
        return dbConn.Update<T>(obj);
    }
}

A: Have a look at OrmLite Global Insert/Update Filters which already allows you to do something like this, e.g:
public interface IAudit
{
    DateTime CreatedDate { get; set; }
    DateTime ModifiedDate { get; set; }
    string ModifiedBy { get; set; }
}

OrmLiteConfig.InsertFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.CreatedDate = auditRow.ModifiedDate = DateTime.UtcNow;
};

OrmLiteConfig.UpdateFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.ModifiedDate = DateTime.UtcNow;
};


text:
Q: how to archive download multiple files from database in php Actually i got the zipfile. But i did't need total files from the table.i want to selected userid files... I try to code bellow, i used php and mysql.
    <?php

    function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
    {
        $zip = new ZipArchive();
        if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
            exit("cannot open <$archive_file_name>\n");
        }

        foreach($file_names as $files)
        {
            $zip->addFile($file_path.$files,$files);
            //echo $file_path.$files,$files."
";
        }
        $zip->close();
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=$archive_file_name");
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile("$archive_file_name");
        exit;
    }
    require_once("config.php");
    $cqurfetch=mysql_query("SELECT * FROM albums where user_id='$user_id' and accept='1'");
    while($row = mysql_fetch_array($cqurfetch))
    {
       $file_names[] = $row['user_album_images'];
    }
       $archive_file_name=time().'.gallery.zip';
       $file_path="/uploads/";
       zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>

A: After Many trails i have got one answer for your question.
Only 'user_id' files are zipped and stored in that zip folder.
Example:-
<?php
require_once("config.php");

  $user_id = 49 ;  //Just For your reference
  $accept = 1 ;     //Just For your reference

    $sql = "SELECT * FROM albums where user_id='$user_id' and accept='$accept'";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
     $array[] = $row["user_album_images"];
     echo "user_album_images: " .$row["user_album_images"]. "
"; //This is also just for your reference
     }
    }
    else{
    echo "fail";
    }

 $file= "/uploads/gallery.zip"; //Zip file path
 $zip = new ZipArchive;
 echo "*****zip started.*****\n";
  if ($zip->open($file, ZipArchive::CREATE) === TRUE) {
    foreach($array as $key => $value)
{
     $zip->addFile("/".$value);
            }
     $zip->close();
     echo '^^^^^^Zip ended^^^^^^';
  }
?>

I have tested this code in my local system,this is working as like your requirement.
Hope this helps


text:
Q: Continue running code in background ASP.NET I need to run the code every 15 seconds in background which is not effect on server.
I have below a sample table for auction data.
--------------------------------------------------------------
AID           STARTDATE               ENDDATE
-------------------------------------------------------------
1             18-7-2013 12:00 PM     20-7-2013 12:00 PM
2             19-7-2013 12:00 PM     21-7-2013 12:00 PM
3             19-7-2013 01:00 PM     21-7-2013 12:00 PM
4             19-7-2013 01:00 PM     22-7-2013 12:00 PM

i need to check in table for get the item which is present date is greater than start date,
then i will get the data through the web request that auction store in local db, it will be loop for every 15 secs until the present date is greater than enddate.
Some time 2 auction start at same time then i need to run two thread simultaneously.
What is the best way to get an update every 15 seconds for all items which are currently in running auction mode and store in our database?
Thank you in advance...

A: You can't do that reliably in ASP.NET/IIS.  The whole process by default doesn't start until the first request from the web server is received, then the whole process shuts down after the specified inactivity time (usually 20 minutes).  If you need a process to run every 15 seconds, you have to initial a request from the client side every 15 seconds, most likely using some sort of javascript to do the request.
Best solution is to update your your auction database with a windows service, separate from the website.

A: Where are you hosting your website? If you are on your own server, create a cron job that makes a request to your backend every 15 seconds.
If you are using cloud providers (or providers without the "cloud" catchphrase), they might offer cron job functionality. But they rarely let you implement 15-second intervals, which, if it comes from a different site, some providers might interpret as DOS attacks.


text:
Q: How to create a border that will outline div minus the margins Ok, I have an issue. I am using the 960 gs and as you can see from the code it is a complicated layout for me at least. Part of my issue was everything was supposed to have a 10px gutter. But some divs didn't. So to achieve the layout I wanted i had to add a top margin of 10px to some of the divs. Well then I needed to add a hover effect padding color change to the divs. Well as you can see on the divs where I added 10px a border goes around the margin too. Not achieving what I want. I set up a class and some jquery where it would remove the margin but then when you hover over those divs they move/shift. Again not achieving the effect that I want. Please help - either how can I fix my grid system so I don't have to add a top margin or how can I add a padding that doesn't include my margins. My HTML is below but I put all my code, js and css on jsfiddle, please see: http://jsfiddle.net/penrysh/mr99962t/

Bulletin Board

Take 5

Learning Break

Take 5

More content...

Take 5

Long Term

Learning

Long Term Learning

More content...

Long Term Learning

Career Insight: Highlight your work!

Create a Sharepoint blog where you can link to, upload, and discuss your work. It all becomes part of your professional portfolio.

What is the Learning and Development Network?

Featured Courses

Our Values

More content...

My Learning

More content...

A: Please take a look at this jsFiddle, I believe this is what you require. What I've done is that I've set a margin-top of 10px for each element with the results1 class and removed all the previous margin-top of 10px which you had set for different elements. Since you're setting the border for the results1_hover class, the margin-top needs to be applied to it as well and not to its child-container.


text:
Q: Creating a new rdd from another rdd in Python I am completely new to pysparks and rdd. I am trying to understand how rdd works and I am having problems accessing part of the data in a rdd. I would like to select a few columns from an existing rdd and create a new rdd.
An example below:
user_rdd = [Row(id=u'1', first_name=u'Steve', last_name=u'Kent', email=u's.kent@email.com'),Row(id=u'2', first_name=u'Margaret', last_name=u'Peace', email=u'marge.peace@email.com')]

display(user_rdd)

| email                 | first_name | id | last_name
| s.kent@email.com      | Steve      | 1  | Kent
| marge.peace@email.com | Margaret   | 2  | Peace

How to select 2 columns from user_rdd and create a new rdd like below?
| id | first_name | last_name | full_name
| 1  | Steve      | Kent      | Steve Kent
| 2  | Margaret   | Peace     | Margaret Peace

A: Here's probably the simplest way to do what you are after (although your RDD looks like it was derived from a DataFrame)
from pyspark.sql import Row

user_rdd = sc.parallelize([
    Row(id=u'1',
        first_name=u'Steve',
        last_name=u'Kent',
        email=u's.kent@email.com'),
    Row(id=u'2',
        first_name=u'Margaret',
        last_name=u'Peace',
        email=u'marge.peace@email.com')
])

new_rdd = user_rdd.map(lambda row: Row(
        first_name=row.first_name,
        last_name=row.last_name,
        full_name=row.first_name + ' ' + row.last_name))

new_rdd.take(2)

A: You can try this:
sc = SparkContext(conf=conf)
user_rdd = [Row(id=u'1', first_name=u'Steve', last_name=u'Kent', email=u's.kent@email.com'),
            Row(id=u'2', first_name=u'Margaret', last_name=u'Peace', email=u'marge.peace@email.com')]
rdd = sc.parallelize(user_rdd).map(lambda x: Row(fullname=' '.join([x['first_name'], x['last_name']]), **x.asDict()))
print(rdd.collect())

A: Not sure why you want to do it through an RDD because a list of rows is essentially a DataFrame and it is easier to select a column and concatenate it there. It is also more efficient than using RDDs.
from pyspark.sql import Row
from pyspark.sql.functions import concat_ws

user_rdd = [Row(id=u'1', first_name=u'Steve', last_name=u'Kent', email=u's.kent@email.com'),Row(id=u'2', first_name=u'Margaret', last_name=u'Peace', email=u'marge.peace@email.com')]

user_df = spark_session.createDataFrame(user_rdd)

user_df.select(user_df.id, user_df.first_name, user_df.last_name,  concat_ws(' ',user_df.first_name, user_df.last_name).alias('full_name')).show()

This will give you the output as DataFrame:
+---+----------+---------+--------------+
| id|first_name|last_name|     full_name|
+---+----------+---------+--------------+
|  1|     Steve|     Kent|    Steve Kent|
|  2|  Margaret|    Peace|Margaret Peace|
+---+----------+---------+--------------+


text:
Q: ssh-agent not starting in OpenSuSE desktop It seems that ssh-agent is not starting on my OpenSuSE system. When I run pgrep -fl ssh-agent, the result is blank. On my Linux Mint laptop, I get 1785 /usr/bin/ssh-agent /usr/bin/dbus-launch --exit-with-session x-session-manager.
How do I fix this? Can anyone with OpenSuSE check to see if it's not started up by default, or if I maybe messed something up?
things tried...
I've tried adding the following to .xinitrc,
if test -S "$SSH_AUTH_SOCK" -a -x "$SSH_ASKPASS"; then
      ssh-add < /dev/null
fi

and my .xsession file contains,
ssh-agent {
  ssh-add &
  startkde
}

but neither of these things seems to do anything. Thanks in advance!!

A: OK, so yesterday I installed the new 12.2RC2 ("GM") and 12.1 on separate partitions, both using KDE.
After I upgraded everything to the latest packages and enabled the SSHD service, I restarted and generated a private/public key pair with ssh-keygen
On both machines the sshd was running - but ssh-add output an error about not being able to connect to authorization agent or something.
So I ran ssh-agent -k where the -k flag "killed" the current running agent and then re-ran ssh-agent to restart it.
Then I restarted the PCs (you might be able to just restart the sshd service instead) and it was working! I could then issue ssh-add without any errors.
It looks like on KDE desktops ssh-agent is not initialized properly when you first start the sshd service, it works fine on other DE like GNOME or XFCE.


text:
Q: Creating a manual backup. Are applications and virtual directories supported? Let's say I have created the following in IIS:
1. A website called 'MyMusicBlog'.
2. Added an application 'Umbraco'.
3. Added a virtual directory called 'services'.
4. Added an application 'RssService' below the services.
5. Added an application 'RestService' below the services.
so the following url's are available:

*

*http://www.mymusicblog.com/umbraco

*http://www.mymusicblog.com/services/rssservice

*http://www.mymusicblog.com/services/restservice
Now when I want to manually create a backup using the 'backupManager' provider in msdeploy.exe I see that the deployment package that is created does not contain the content for the application 'Umbraco' and services 'RssService' and 'RestService'.
What I tried:
msdeploy.exe -verb:sync -source:backupManager -dest:backupManager=MyMusicBlog

What Elliott Hamai says about it:
http://www.iis.net/learn/publish/using-web-deploy/web-deploy-automatic-backups
I wonder whether Web Deploy supports the scenario where you want to manually create and restore a backup for an IIS application.
Who has tried to do this and succeeded? Or did you find a workaround?
It seems to me that I can create a deployment package and 'restore' the content if needed. In that way you use a deployment package as a 'backup' package. But ideally you would expect Web Deploy to support manual backups for these kind of sites.


text:
Q: Should Svelte libraries include external: ['svelte'] in rollup.config.js? ("Function called outside component initialization" getContext in {#each}) Can anyone tell me why this app is running into a "Function called outside component initialization" error? (Update: Found the cause of this specific error, but still have questions below about best practices for using rollup with svelte libraries.)
It seems to only be happening when I call getContext (or onMount, etc.) from a component (which should be allowed) inside of an {#each} loop. But only happens if I include external: ['svelte'] in the library, so this may be as much a rollup question than a Svelte question.
Here's my code (which you can clone from here and try for yourself):
  "dependencies": {
    "my-new-component": "file:packages/my-new-component",
    …
  }

src/App.svelte:

<FieldArray let:names>
  {#each names as name, i}

{name}: <UsesContext />

  {/each}
</FieldArray>

packages/my-new-component/src/FieldArray.svelte:

<button on:click={handleClick}>Blow up</button>

<slot names={names} />

packages/my-new-component/src/UsesContext.svelte:

{context}

Pretty basic stuff, right?
What am I doing wrong?
I understand that setContext can only be called synchronously during component initialization (in the top level of the


text:
Q: SquidGuard holding navigation This is my first question within ServerFault. So I beg you pardon if the question here is a little out of context or too long. I haven't found anything on the internet so I'm recurring to you.
I'm using a pfSense Firewall v2.2.4 in a virtual machine powered by VirtualBox over a Windows 2003 Server x64 to route internet among approximately 60 LAN users and apply filters to content that can be viewed by them. I've implemented NTLM authentication with Samba and then using its authenticated username to apply my rules in SquidGuard. Everything is working like a charm, except for one thing : some users had reported slow connection through proxy. My machine and some others, which has their internet traffic routed through NAT, doesn't show this behaviour.
I've tried to isolate the problem and found that when I restart Squid services the slowness vanishes instantly. Searching over web I found something related to url_rewrite_children Squid parameter. The default is 16 start=8 idle=4 for this version of squidGuard. So I raised them to 32 start=25 idle=5 within squidguard_configurator.inc and spent a bunch of time monitoring the services states through command ps axu | grep -i squidguard.
The results, when everything seems OK, shows 25 squidGuard processes, which is the expected behaviour but, for some reason, after an interval of 100~120 mins approx, Squid starts 5 more squidGuard processes and then the navigation through proxy slows down. It looks like squidGuard rewriter processes froze or passing through an overload but the processor and memory indicators doesn't show anything weird and system logs doesn't show anything different either.
I've created a Cron task that reconfigure squid every 15 mins with the command squid -k reconfigure and other Cron task which restart squid services through command /usr/local/etc/rc.d/squid.sh restart. It works, but I think that isn't the ideal solution.
Is there something that I can check or change in squid or squidGuard config files to get rid of this problem ?
My pfSense version is 2.2.4-RELEASE (amd64) built on Sat Jul 25 19:57:37 CDT 2015 (FreeBSD 10.1-RELEASE-p15), my squid3 package is on version 0.4.7 and squidGuard-devel package is on version 1.5.10.
pfSense is running over a virtual machine with Intel(R) Xeon(R) CPU E5-2420 v2 @ 2.20GHz - 4 CPUs: 1 package(s) x 4 core(s) and 4GB of RAM and 240GB of hard disk.
Any help will be appreciated.
Thanks in advance.
Bruno


text:
Q: how can we write large DataFrame into excel file quickly in pandas? import pandas as pd
df=pd.read_csv("C:/Users/Admin/Desktop/10lakhhhhh.csv")
writer = pd.ExcelWriter('C:/Users/Admin/Desktop/df/media/pandasEx.xlsx',engine ='xlsxwriter')
df.to_excel(writer, sheet_name ='10lakhhhhh')
writer.save()

A: There is a new module called modin. It can be used as below to read huge data quickly:
Install:
pip install modin

Code:
import modin.pandas as pd
df = pd.read_csv('C:/Users/Admin/Desktop/10lakhhhhh.csv')


text:
Q: Is it possible to knit an R Markdown file only to a preview window/pane in RStudio without saving an html file? I would like to keep the base folder of my R Markdown project tree as uncluttered as possible and still use the Knit button in RStudio to see some results as an HTML output in the RStudio's preview window. However, every time I knit, an HTML file is created to the base folder along my .Rmd files.
My folder structure might look like this:

If I've understood correctly - and do please correct me if I'm wrong - it is not very straightforward to output the HTML files to an upstream folder (here:"results" folder) from an R Markdown file by pressing the Knit button, so I would be willing to:

*

*prevent the creation of HTML files altogether,

*still see the results in an HTML format in RStudio's preview window, and

*only when I'm really willing to save an HTML file, save (export) such a file and (manually) transfer it to the results folder.

So, if there is no easy way of directing the HTML files to the "results" folder, can I prevent the creation of HTML files altogether and only preview the results in the preview window?

A: I don't know of a way to attach this to the knit button, but you could write a function that does this:

*

*get the current file open in the edit pane.  This answer gives details on that.

*run rmarkdown::render() with the output_dir argument set the way you want.

You can attach this function to a keyboard shortcut in RStudio using these instructions.
Here's a simple version of the function:
  knit2 <- function(filename = rstudioapi::getSourceEditorContext()$path,
                    output_dir = tempdir()) {
    result <- rmarkdown::render(filename, output_dir = output_dir)
    getOption("viewer")(result)
  }

Simply call knit2(), and the output will be written to tempdir(), which means the preview will appear in the Viewer pane.  If you want it to write to "results", call it as
knit2(output_dir = "results")

If that's not a subdirectory of tempdir(), the preview will appear in an external browser.


text:
Q: How to lock a text box to a specific amount of characters I'm making a little password generator and I want it to lock the output text box to 10 characters, so that when the user clicks the password genenerate button it does not just continue with an endless line of randomly generated passwords.
How can I do this?

A: There's a control on the text box in Visual Studio.
If you click the button and they go into properties there should be something called "max length".  Set that to however long you want it.

A: You can use Substring() function to cut the extra characters in your generated password.
For an instance
string GeneratedPassword = "1234567891345678";

textBox1.Text = GeneratedPassword.Substring(0,10);

Also the textBox1.MaxLength = 10 will not give you the desired result. It will only limit input of the character manually in the textbox. It will not limit input of characters programmatically.


text:
Q: regex matching outer braces in python I have some f5 config data string formatted with nested braces as follows:
profiles {
    /Common/http { }
    /Common/serverssl {
        context serverside
    }
    /Common/tcp { }
    SOME_CRED_MGMT.DOMAIN_some_date {
        context clientside
    }
}
rules {
    /Common/X-FORWARDED-FOR
}
snat {
    pool SOME_SNAT.POOL
    type snat
}

I want get from the above group a list something like:

some_list = ["profiles{..}", "rules{..}", "snat{..}"]

After searching I found something like (in JS):
profiles {([\s\S]*?)^}

And also similar (in PCRE):
({((?(?={)(?R)|[^}])*)})

But they don't work for Python. How to do a similar thing in Python?

A: You can use the JS regex. You just need to edit it a little bit.
.+ {[\s\S]*?^}

I replaced profile with .* so that it does not only match profile { ... }. I also, made the group non-capturing, since you don't care about what's inside the curly braces. You just want the whole thing.
And then you can call findall to get the list you want:
matches = re.findall(r".+ {(?:[\s\S]*?)^}", test_str, re.MULTILINE)


text:
Q: How to set root password on mysql server on aws? I've been struggling with this for some time. I have Mysql 5.7.20 in my EC2 instance and want to set / change root password. So I do:

*

*sudo /etc/init.d/mysql stop

*sudo mysqld_safe --skip-grant-tables &
which gives the follow error:
mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.
so I do:

*mkdir -p /var/run/mysqld

which gives:
mkdir: cannot create directory '/var/run/mysqld': Permission denied
Any idea how to solve this?

A: Is this what you are looking for?
MySQL 5.7 Reference Manual:
B.5.3.2 How to Reset the Root Password


text:
Q: PHP variable to Xcode variable how can i get an integer variable from PHP page and save it to the integer variable in my program...
USInteger *number =  an integer variable from PHP page...

A: You're talking about IPC I think ... InterProcess Communication ... The PHP "page" is itself a program ... you'll need to setup a way to communicate with your "program" on both the "page" side and the "program" side ... one option of course is to output the variable in the "page" and parse it through the "program"
Of course IPC is more commonly related to pipes, sockets, and shared memory.
Of course this is assuming you are actually attempting to get the value of a variable in a PHP page and assign it to the value of the variable in your "program" ... Its very possible I'm wrong in that understanding of your question.


text:
Q: Extending a pulse from a DTMF Decoder I have built a DTMF decoder which offers relay closures corresponding to the digits received. Everything works great, except the equipment I am interfacing to is slow.
The office telephone system gives a pulse of tone whenever a digit on the telephone is held down. From what I've read, the pulse lasts 300ms. The equipment my DTMF decoder is interfacing to cannot detect a pulse that quick.
I am working on getting the tone pulses extended to 1s, but need a plan B. Can anyone think of a way to take a 300ms pulse and extend it to 1s?
I've tried using a 74LS123 (retriggerable multivibrator) but I dont think the IC is designed to go that long.
I've thought of using a JK Flip Flop to latch in the signal that eventually closes the relay contacts, but haven't worked it out yet. I have a limit on the amount of real estate I can use.
I'm looking at some kind of RC charge/discharge circuit to hold the relays on. But I cant figure out a way to have the capacitor charge in 300ms and discharge over 750ms - 1second.
Any input would be appreciated.
Very simplified schematic attached.

A: Do you want the relay to latch on or just stay energized for the length of the tone?
If (a) then just use any of different latches: could use a toggle F/F if you want it to toggle on and off with tones, or capture the rising edge from the decoder and use it to clock an LS74 flip flop.
For (b) you didn't say what problem you ran into the the LS123. I find it hard to believe that it won't configure as a 1-second one-shot, but if that's really the case, you can make very long one-shots using an NE555.
Also, do you really need two levels of isolation from the phone line? You have  both an optocoupler and a relay in your circuit. Better yet, back off and take a 30,000 foot view: what exactly are you trying to build?


text:
Q: Problems Build React Native Using EAS Expo Cannot (Compressing Project Files) in Windows 10 enter image description here
Why do you want the new Build React Native Can't Compressing Project Files?
What is wrong ?
Is the EAS EXPO still the development stage?
if you use it

*

*Expo Build: Android -t APK

*Expo Build: Android -t App-Bundle

can be good but if you use it

*

*EAS Build - Android Platform

*EAS Build - Platform iOS

*EAS Build -P Android - Prevrofile Preview
can't,
why ?


text:
Q: Constructing a loop to check if the sum of digits of a number is divisible by 3 I need to make a program in which between a given span of numbers, the program needs to find the numbers whose sum of digits is divisible by 3. After that, it needs to check if the sum is larger than 0 and if it's divisible by 4, and print the numbers which fulfill the aforementioned conditions.
This is what I tried:
include <stdio.h>
int main()
{
int a, b, sum, c, i, total, d;
scanf("%d %d", &a, &b);
for (i=a; i<b; i++)
{
  sum = 0;
  c = i;
  while (c != 0)
  {
   d=c%10;
    if ((d%10)%3 == 0)
    {
      sum = sum + d;
    }
      c = c /10;
    if (sum%4==0 && sum>0)
    {
      printf("%d\n", i);
      total++;
    }
   }
  }
  printf("%d", total);
 return 0;
}

I get a wrong output and I can't find the mistake. Any ideas?

A: It should be broken into 2 parts:-
int DigitSum(int num)
{
    int sum = 0;
    while(num){
       sum += num%10;
       num/=10;
    }
    return sum;
}

Follow the D-R-Y principle. Do not repeat yourself. If you are doing that you can be sure that you are missing the chance of reusability.
Separate the independent reusable logic from the core functionality that is helpful once you get into big project.
Now you get into logic:
for(int i=a;i<=b;i++)
{
     int digSum = DigitSum(i);
     if( digSum > 0 && digSum%3 == 0 && digSum%4 == 0 ){
         printf("%d\n", i);
         total++;
     }
}
printf("%d",total);

Where did you go wrong?

*

*In case a digit d is not divisble by 3 you are not considering it in the sum which is wrong.

*For a number like 6666 there will be 2 times when you increase total which is again wrong.


text:
Q: Bean validation for Springboot request param I have a use case wherein we are having multiple parameters being passed in the REST controller, and the parameters have to be validated for not empty, and some custom validations. Also, for some of the parameters the filter options are supported with startswith, endswith. I am able to validate parameters for first filter level, but could not make it work for next filter level. For example: the query string is filter.firstname and it is supported with optional of startswith and endswith.
Can someone help by providing some suggestions on how can I validate the parameter when someone is passing filter.firstname or filter.firstname.startswith for non-empty values?
This is the sample code for Controller.
 @GetMapping()
    public CustomerResponseData findCustomers(@Valid FilterCustomer filter, HttpServletRequest request)

public class FilterCustomer {

    @Valid
    private FilterCustomerCriteria filter;

}

public class FilterCustomerCriteria {

    @NotBlank
    private String firstname;

    @NotBlank
    private String lastname;
}

public class FilterCustomerFinerCriteria {

    @NotBlank
    private String startswith;

    @NotBlank
    private String endswith;
}```

A: If I understand you correctly, you say that the validation framework doesn't have annotations for your custom validation logic on some fields (@NotBlank is not enough).
In this case, you can always create your own custom validators that will implement the validation logic.
Here is a link to example of how to do this,
but to recap:

*

*You have to implement a class that implements javax.validation.ConstraintValidator and add validation logic in its public boolean isValid method

*Then create a custom annotation (like @NotBlank but your own one) and set among other things a meta-annotation@Constraint(validatedBy = { YourValidator.class })`
Then use this annotation just like any other validation annotation


text:
Q: Hashing algorithm and HashMap There are several topics on this in stackoverflow as well as in web, I could not understand them clearly. I found this answer in stackoverflow by Nicklas and his representation which gave me some meaningful insight over the topic.
Some ASCII art
key.hashCode()
     |
     | 32-bit value
     |                          hash table
     V                        +------------+    +----------------------+
HashMap.hash() ----+          | reference  | -> | key1 | value1 | null |
                   |          |------------|    +----------------------+
                   |          | null       |
                   | offset   |------------|    +---------------------+
                   +--------> | reference  | -> | key1 | value1 | ref |
                              |------------|    +---------------------+
                              |    ....    |                       |
                                                  +----------------+
                                                  V
                                                +----------------------+
                                                | key2 | value2 | null |
                                                +----------------------+

What hashing function does Java use to implement Hashtable class?
Map aMap = new HashMap();
aMap.put(key,value);

*

*Can anyone explain me `what is an offset and its value?. Where is
the offset value getting mapped?.

*what's that hash-table?. Is it an Array of Objects?, If so does each
object have an key, value1 and a reference propery?.

Can anyone re-explain the above diagram step-by-step. I am not able to understand the Hashing mechanism behind HashMap.

A: First, lets I explain idea of hash search:

*

*Lets you have some key for search. For example,key is just text string, like "hello".

*Lets we compute some "checksum" for this string - for simple example, just by
adding together ASCII codes of symbols. Lets (for example, I did not counted actually)
this sum is 1009.

*Lets we have array of fixed size, for example, SZ=10. Name this array as "hash_table".
Each array element contains BUCKET -- this is set of possible keys.

*So, we can compute OFFSET - index in the array, i.e. hash-table, by:
offset = sum % SZ = 1009 % 10 = 9;

*Lets we deposit our word "hello" into busker #9 by:
hash_table[9].add_to_list("hello");
There, we have just single key "hello", stored in the cell hash_table[9];

*

*Imagine, need insert 2nd key, for example, "world". Lets we compute sum, and it
will be 37. Again, compute offset = 37 % 10 = 7. So, by this algorithm, we deposit
key "world" into hashtable[7].

*Collision. Imagine, you decided add 3rd word-key, "collision" Lets sum for this word will be 3007. When you compute offset, it would be 7. So, word "collision" must be deposited into the bucket, where is already exist word "world". This is OK. You just add element with world "collision" into linklist (head or tail). So:
hashtable[7] -> "world" -> "collistion" -> NULL;
hashtable[9] -> "hello" ->NULL;

*When you need search for a key "hello", you again compute checksum, and it again would be 1009. Thereafter, you compute offset = 9, and go directly to bucket #9. And, iterate linklist, and there you will found your word "hello". Analogous situation with "world" or "collision".
When you search for word, omitted in the table, you go to empty bucket, or to bucket, which does not contains your key. So, search unsuccessful.
if you make hash table too wide (for example, size as same as your dictionary), average bucket size would be ~1 element (if hash function has good spreading). So, search for a key wil be quick - just compute hashsum, go to bucket, and iterate 1-2 elements in the bucket.
Second - I will answer to your questions:

*

*Offset - just index in the array. Array is a "hash table". Each array element contains pointer to linked list, contains keys, stored in the same bucket.

*hashtable in the bucket scheme - just array, contains pointers to heads of buckets. With another hashing scheme (for example, multiple hashing, etc) - it can contains objects theyself, without linklists.


text:
Q: Microsoft Certified Master on Microsoft SharePoint Server 2010 Has anyone here tried to take this certification (or the 2007 one)?
http://www.microsoft.com/learning/en/us/certification/master-sharepoint.aspx
I understand that the competency required to take this is very high.
But does anyone have a structured plan of how to prepare for this certification?

A: In answer to your first question, yes, and it is very tough. On the two SharePoint 2010 rotations completed at the time of writing, as far as I know, nobody passed on the first time through.
I have written a short article about my experiences at http://www.spdoctor.net/Pages/article.aspx?name=SharePoint-2010-MCM. Many others have also blogged about it. But you will not find much detail in any of the blogs because we are all under NDA.
First you need to get through the interview, which is a challenge in itself, in order to get on the programme. And you will need the four SharePoint 2010 MCP exams.
The preparation is basically to work through the comprehensive pre-reading list, which is available at http://www.dynamicevents.com/upload/MCM-MCA/MCM/SharePoint/MCMSharePointPre-Reads.pdf. This contains scores of links to articles which themselves usually expand into numerous sub-pages. It took me weeks to work through all this. If you can get some practice setting up the more complex SharePoint environments this will help you prepare for the hands-on labs.

A: From what I know, read the TechNet documentation on SharePoint 2010 in it's entirety in the first instance, that's required reading (according to a Tweet a while ago from @harbars).
In other (slightly related) news: MS have substantially reduced the requirements to do the MCM SQL Server, making it far more accessible. There's been no official word yet on MS doing the same on other MCM areas, but we can only hope this will extend to SharePoint at some point in the future.


text:
Q: $(\Delta u_n)_n$ bounded in $L^\infty(\Omega) \Rightarrow (\nabla u_n)_n$ locally bounded in some space? Consider a regular bounded open set $\Omega\subset\mathbb{R}^3$, and a set of regular scalar functions $(u_n)_n\in\mathscr{C}^\infty(\Omega)$ such as $\|\Delta u_n\|_{L^\infty(\Omega)} \leq C$. Is it possible to show that $\|\nabla u_n\|_{L^p_{\text{loc}}(\Omega)}$ is also bounded for some $p\in ]1,\infty[ $ ? Or the values on the boundary are too important ?

A: We can work with harmonic function (which obviously satisfy the bounded Laplacian condition but with unbounded gradient). For example $u_n(x)=nx_1$ is such that $\Delta u_n=0$ but $\int_K|u_n|^p=n^p\int_K|x_1|^p$ so for a compact set with non-empty interior, the sequence $\{\lVert u_n\rVert_{p,K}\}$ is not bounded for any $p$.

A: Sorry for the silly question. Obviously wrong, even in dimension 1 : the sequence $f_n:x\mapsto x^2+nx$ have bounded second derivative though $(f'_n)_n$ is not bounded in $L^1_{\text{loc}}(\mathbb{R})$...


text:
Q: Unity New Input System Touch Menu - Error I'm making a Game with Touch, Controller and Keyboard Input with the NEW InputSystem 1.0.2
If the game is currently running and the StartButton will be pressed, then the TouchUI should disappear and PauseMenu should appear. Currently it shows me the error messages. This only happens in the TouchUICanvas environment. Works perfectly fine with gamepad and keyboard.
Everything works.
ErrorWarnings: by pressing with Touch on the StartButton(TouchUICanvas)

-Assertionfailed UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType,NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType,IntPtr)(at/Users/builduser/buildslave/unity/build/Modules/Input/Private/Input.cs:120)
-ArgumentOutOfRangeExceptionduringeventprocessingofDynamicupdate;resettingeventbuffer
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType,NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType,IntPtr)(at/Users/builduser/buildslave/unity/build/Modules/Input/Private/Input.cs:120)
-ArgumentOutOfRangeException:Specifiedargumentwasoutoftherangeofvalidvalues.
Parametername:index
UnityEngine.InputSystem.Utilities.InlinedArray`1[TValue].get_Item(System.Int32index)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/Utilities/InlinedArray.cs:68)
UnityEngine.InputSystem.DynamicBitfield.ClearBit(System.Int32bitIndex)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/Utilities/DynamicBitfield.cs:51)
UnityEngine.InputSystem.InputManager.FireStateChangeNotifications(System.Int32deviceIndex,System.DoubleinternalTime,UnityEngine.InputSystem.LowLevel.InputEventeventPtr)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/InputManager.cs:2924)
UnityEngine.InputSystem.InputManager.UpdateState(UnityEngine.InputSystem.InputDevicedevice,UnityEngine.InputSystem.LowLevel.InputUpdateTypeupdateType,System.VoidstatePtr,System.UInt32stateOffsetInDevice,System.UInt32stateSize,System.DoubleinternalTime,UnityEngine.InputSystem.LowLevel.InputEventPtreventPtr)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/InputManager.cs:3101)
UnityEngine.InputSystem.InputManager.UpdateState(UnityEngine.InputSystem.InputDevicedevice,UnityEngine.InputSystem.LowLevel.InputEventeventPtr,UnityEngine.InputSystem.LowLevel.InputUpdateTypeupdateType)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/InputManager.cs:3017)
UnityEngine.InputSystem.InputManager.OnUpdate(UnityEngine.InputSystem.LowLevel.InputUpdateTypeupdateType,UnityEngine.InputSystem.LowLevel.InputEventBuffer&eventBuffer)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/InputManager.cs:2707)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime+<>c__DisplayClass7_0.<set_onUpdate>b__0(UnityEngineInternal.Input.NativeInputUpdateTypeupdateType,UnityEngineInternal.Input.NativeInputEventBuffereventBufferPtr)(atLibrary/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/NativeInputRuntime.cs:64)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType,NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType,IntPtr)(at/Users/builduser/buildslave/unity/build/Modules/Input/Private/Input.cs:120)

These 2 Error-Codes Appeared after I pressed with Touch - on the ResumeButton(pauseScreen) with the function PauseUnpause().
-Action has been triggered but apparently not from an interaction yet there's interactions on the binding that got triggered?!?

UnityEngine.GameObject:SetActive(Boolean)
OverworldPauseMenu:PauseUnpause() (at Assets/OverworldPauseMenu.cs:47)
UnityEngine.EventSystems.EventSystem:Update() (at
/Applications/Unity/Hub/Editor/2019.3.15f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:377)
-Control index out of range UnityEngine.GameObject:SetActive(Boolean) OverworldPauseMenu:PauseUnpause() (at Assets/OverworldPauseMenu.cs:47)
UnityEngine.EventSystems.EventSystem:Update() (at
/Applications/Unity/Hub/Editor/2019.3.15f1/Unity.app/Contents/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:377)

The code for the PauseMenu:

public class OverworldPauseMenu : MonoBehaviour
{
    public GameObject pauseScreen;
    public GameObject TouchUICanvas;
    public string mainMenu;
    public bool isPaused;
    ControlsSetup controls;
    public void Awake()
    {
        controls = new ControlsSetup();

        controls.SwitchPro.ButtonStart.performed += ctx => PauseUnpause();
    }
    void Start()
    {

    }
    void Update()
    {

    }
    public void PauseUnpause()
    {
        if (isPaused)
        {
            isPaused = false;
            TouchUICanvas.SetActive(true);
            pauseScreen.SetActive(false);

            Time.timeScale = 1f;
        }
        else
        {
            isPaused = true;
            TouchUICanvas.SetActive(false);
            pauseScreen.SetActive(true);

            Time.timeScale = 0f;
        }
    }
    public void MainMenu()
    {
        SceneManager.LoadScene(mainMenu);
        Time.timeScale = 1f;
    }
    void OnEnable()
    {
        controls.SwitchPro.Enable();
    }
    void OnDisable()
    {
        controls.SwitchPro.Disable();
    }
}

See relevant images below.
StartButton:

Controls Setup:

Console ERROR:

A: I "solved" this issue by delaying for one frame buttons gameobject disabling. A little bit hacky, but at least works for me.


text:
Q: Find duplicate letters in an anagram Im writing a program that is very similar to the show Countdown. There is a bunch of letters and you make words from it.
I have the basics done, where the word submitted by the user is checked against the base word, if the chars match, then it is checked against a dictionary which is an online API. The scores are then added to a top 10 leaderboard. I have all of this implemented but I am now facing my final issue and I can't seem to solve.
// convert the users guess to a char array
char [] chars = word.toCharArray();

for(char c : chars){
    int charIndex = baseWord.indexOf(c);

    if(charIndex != -1){
        continue;
    } else {
        System.out.println("The letter " + c + " is not in " + baseWord);
        return false;
    }
}

I convert the users guess to a char array and then compare each element of the char array to the element of the base word. This works fine until I have duplicate records. For example if I have the base word set to areallylongword and the user guess is set to adder, this returns true while it should return false.
I understand the concept that the int charIndex = baseWord.indexOf(c) will return the same value when char d is looked up.
How do I go about avoiding this issue?

A: You could remove the letters from the baseWord once they are matched

A: Just blank the letters in the baseWord when you find a match:
// convert the users guess to a char array
char [] chars = word.toCharArray();

for(char c : chars){
    int charIndex = baseWord.indexOf(c);

    if(charIndex != -1){
        char[] baseWordChars = baseWord.toCharArray();
        baseWordChars[charIndex] = '#';  // char wiped
        baseWord = new String(baseWordChars);
        continue;
    } else {
        System.out.println("The letter " + c + " is not in " + baseWord);
        return 0;
    }
}

A: Count the Char occurrences into an array or a hash, then decrease the count of the guessed word.
For instance if you assume that baseWords should contains letters ASCI-128, you can create an array with 128 position and use the charcode as the index of your letter.
char [] chars = word.toCharArray();
int[] charCount = int[128]; // By default every position is 0
for (c : chars) {
   charCount[c] += 1; // Increments the count of char
}

Then you go through the user's guess word, and decrease from this charCount, to verify if the user guessed right you should never have a negative number on charCount.
char[] c = guess.toCharArray();
for (c : chars) {
   charCount[c] -= 1;
   if (charCount[c] < 0) {
     return 0;
   }
}


text:
Q: Using Do-Loops in Include Files In my fortran code, I'm attempting to include a DO loop, but I'm ending up with a "DO loop or BLOCK IF not closed." It appears if any other DO loops after the INCLUDE statement are opened it treats them as nested loops, indicating to me the included opening DO line is interpreted correctly, but not the END DO statement. I've reduced the included code to bare-bones to make sure it's the loop and not the statements in the loop giving a problem. The control variable is declared before the DO loop.
DO A = 1,3
END DO

Does Fortran77 not allow for DO loops in INCLUDE files?
I'm using gfortran for my compiler if it changes much.
Edit: grammar
Edit2:
I'm using GCC 4.6.2. Now to note, if this makes a difference, gfortran is being run from a makefile made by PSCAD. I can provide info on that if it's pertinent.
Here's code that is experiencing this issue:
TEST.F:
SUBROUTINE TESTFX()
INTEGER A
INCLUDE '../HDR.INC'
END

HDR.INC:
DO A = 1,3
END DO

Edit3: Edited typos in code and removed RETURN from subroutine.

A: Fortran 77 doesn't have INCLUDE at all. That first made its appearance in a Fortran standard in Fortran 90. That said, INCLUDE was available as an extension in pretty much all Fortran 77 compilers and the behavior was the same - it is essentially the same as inserting the included file in the source file where the INCLUDE appears. There are no restrictions on what can be there, though I have seen compilers struggle with issues related to block constructs that straddle an include file boundary.
Perhaps if you included both the source file and the include file text and told us exactly which version of gfortran you're using, a more definitive response could be provided.

A: Your INCLUDE must be placed on a new line, it is not part of the statement declaring A. Why do you have apostrophes at your ENDs? They cannot be there. The RETURN statement before the END is totally superfluous also. Try:
TEST.F:
SUBROUTINE TESTFX()

INTEGER A

INCLUDE '../HDR.INC'

END SUBROUTINE

HDR.INC:
DO A = 1,3
END DO