text:
Q: Binding Json data to Kendo treeview MVC4 My Kendo Tree-view has many child nodes and sub nodes .Problem with getting sub child's nodes with redundant code
Here is my code .
 nodes = rep.GetTreeViewData(CompanyId);

        var productTreeData = nodes.Select(p => new
        {
            Text = p.CategoryName,
            Url = p.ActionLink,
            hasChildren = p.SubCategories.Any(),
            // Expanded = true,
            EntityType = p.EntityType,
            Selected = currurl.ToLower() == p.ActionLink.ToLower() ? true : false,
            ImageUrl = p.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif",

            Children = p.SubCategories.Select(c => new
            {
                Text = c.SubCategoryName,
                Url = c.ActionLink,
                // Expanded = true,
                hasChildren = c.SubCategories.Any(),
                EntityType = c.EntityType,
                Selected = currurl.ToLower() == c.ActionLink.ToLower() ? true : false,
                ImageUrl = c.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif",

                Children = c.SubCategories.Select(d => new
                {
                    Text = d.SubCategoryName,
                    Url = d.ActionLink,
                    // Expanded = true,
                    hasChildren = d.SubCategories.Any(),
                    EntityType = d.EntityType,
                    Selected = currurl.ToLower() == d.ActionLink.ToLower() ? true : false,
                    ImageUrl = d.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif",

                    Children = d.SubCategories.Select(f => new
                    {
                        Text = f.SubCategoryName,
                        Url = f.ActionLink,
                        //Expanded = true,
                        hasChildren = f.SubCategories.Any(),
                        EntityType = f.EntityType,
                        Selected = currurl.ToLower() == f.ActionLink.ToLower() ? true : false,
                        ImageUrl = f.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif",

                        Children = f.SubCategories.Select(g => new
                        {
                            Text = g.SubCategoryName,
                            Url = g.ActionLink,
                            // Expanded = true,
                            hasChildren = g.SubCategories.Any(),
                            EntityType = g.EntityType,
                            Selected = currurl.ToLower() == g.ActionLink.ToLower() ? true : false,
                            ImageUrl = g.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif",

                        })

                    })

                })

            })

        });

This is my view
 @(Html.Kendo().TreeView()
                                      .Name("treeview-right")
                                      .ExpandAll(true)
                                      //.LoadOnDemand(false)
                                      //.Events(events=>events.DataBound("DataBound"))
                                      .DataSource(d => d
                                      .Model(m => m
                                      .HasChildren("hasChildren")
                                      .Children("Children"))
                                      .Read(r => r.Action("_ProductTree", "Home")))
                                      .DataTextField("Text")
                                      .DataUrlField("Url")
                                      .DataImageUrlField("ImageUrl")
                                      )

By this process am getting all child's and sub child's of individual parent up to four level hierarchy ..if i need another level i need to write one more children code.
Am struggling from 2 days to simplify this process .
Thanks

A: This looks like it could be solved with recursion.  This should be pretty close.
 var productTreeData = new ListofYourTreeViewModelHere();

 foreach (var node in rep.GetTreeViewData(CompanyId))
 {
    productTreeData.Add(FillTree(node));
 }
...
}

private YourTreeViewModelHere FillTree(p)
{
    var tv = new YourTreeViewModelHere();

    tv.Text = p.CategoryName,
    tv.Url = p.ActionLink,
    tv.hasChildren = p.SubCategories.Any(),
    tv.EntityType = p.EntityType,
    tv. Selected = currurl.ToLower() == p.ActionLink.ToLower() ? true : false,
    tv.ImageUrl = p.EntityType == "Company" ? "/Content/Images/company.gif" : "/Content/Images/geolocation1.gif";

     foreach(var sub in p.SubCategories)
     {
         tv.Children.Add(FillTree(x));
     }
  }


text:
Q: ajax call not getting called inside alfresco displayprompt we have written custom doclib action in document library.we are using alfresco 5.x;when the custom link is clicked then "onManifestAsset" action is getting called when it failed then it should prompt popup window with ok and cancel buttons.when i click ok button then another ajax call is not getting called.
YAHOO.Bubbling.fire("registerAction",
            {
                actionName: "onManifestAsset",
                fn: function onManifestAsset(file) {
                    this.modules.actions.genericAction(
                    {
                        success:
                        {
                            message: this.msg("success")
                        },
                        failure:
                        {
                            callback :
                            {
                                scope: this,
                                fn: function(object)
                                {

                                      Alfresco.util.PopupManager.displayPrompt(
                                              {
                                                 text: "Your zip file does not include a metadata spreadsheet;",
                                                 buttons: [
                                                    {
                                                       text: "Ok",
                                                       handler: function()
                                                       {
                                                          this.destroy();
                                                          console.log("...start::::::it is normal zip without meta data template:")

                                                          //its coming here but below ajax is not getting called when I click ok button

                                                          Alfresco.util.Ajax.request(
                                                          {
                                                              url: Alfresco.constants.PROXY_URI+"xxxxx/manifestZIP?nodeRef="+file.nodeRef,
                                                              method: "GET",
                                                             successCallback:
                                                             {
                                                                fn: function dlA_onActionDetails_refreshSuccess(response) {

                                                                    Alfresco.util.PopupManager.displayMessage({
                                                                        text: "Success"
                                                                    });
                                                                },
                                                                scope: this
                                                             },
                                                             failureMessage: this.msg("message.delete.failure", ".......")
                                                          });

                                                       }
                                                    },
                                                    {
                                                       text: "Cancel",
                                                       handler: function()
                                                       {
                                                          this.destroy();
                                                       },
                                                       isDefault: true
                                                    }
                                                 ]
                                              });
                                }
                             }
                        },
                        webscript:
                        {
                            name: "xxxx/extractAsset?nodeRef={nodeRef}",
                            stem: Alfresco.constants.PROXY_URI,
                            method: Alfresco.util.Ajax.GET,
                            params:
                            {
                                nodeRef: file.nodeRef
                            }
                        },
                        config:
                        {
                        }
                    });
                }

            })

redpajama_set_name: RedPajamaStackExchange


text:
Q: What pick-ups are shared in co-op? In Borderlands The Pre-Sequel, what pick-ups are shared in co-op?

*

*Ammo?

*Moonstones?

*Grenades?

*Money?

*Oz canisters?

*Customization items?

A: Moonstones and Money pickups are shared with all players in co-op. As for ammo, when you pick up ammo of a type you're full on, it will be transferred to another person, except for rocket ammo and grenades, which cannot be picked up if you're full on them. Everything else is per-player.


text:
Q: dispatch_sync(dispatch_get_main_queue() UI weirdness This is for MacOS not iOS.
If your running code on a GCD queue
dispatch_sync(dispatch_get_main_queue(), ^{
    //do UI stuff
});

is pretty much the way to do UI stuff on the main thread/queue which seems to work well for iOS.
MacOS seems to be a different story.
Try this for a simple example
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // So my app is doing some background stuff
        // and I need a file from the user so

        // code blah blah code

        dispatch_sync(dispatch_get_main_queue(), ^{
            NSOpenPanel *op = [NSOpenPanel openPanel];

            [op runModal];
        });

        // resume code blah blah code
    });
}

when the NSOpenPanel opens all kinds of weirdness is going on. The scroll views scroll very erratically if at all and the directories don't list properly. I'm just using the NSOpenPanel here as an example, this also happens with any view that contains a scroll view (so I've tested so far).
Is this a bug?
Are others seeing this or is it just me and is there another preferred way of doing this?

A: The issue is that you are blocking the main thread as the main_queue is a serial dispatch queue. The main thread cannot run as it's blocked in the runModal method.
Following the discussion here, the solution is to use beginWithCompletionHandler: instead, which I have verified to work:
//[op runModal];
[op beginWithCompletionHandler:^(NSInteger result) {
    NSLog(@"Done: %lu", (unsigned long)result);
}];


text: Q: Presenting a systemd service Hello I need to present some Linux systemd services that I created but in some king of diagrams (I know it s not nice first code and than the design). I was searching but did't find anything. Does anyone have some template that I can be inspired from.


text:
Q: Multiply or divide in C#/.NET
Possible Duplicate:
Should I use multiplication or division?

Poking around in some (C++) 3D library I often see code like this:
float fInvLength = 1.0f / fLength;
rkAxis.x = x * fInvLength;
rkAxis.y = y * fInvLength;
rkAxis.z = z * fInvLength;

Is this really faster than this code:
rkAxis.x = x / fLength;
rkAxis.y = y / fLength;
rkAxis.z = z / fLength;

I'm primarily interested in C#/.NET performance but I don't mind some info about C++ as well.


text:
Q: Play + Ebean: Changes to the model + database I'm currently using Java Play and persisting models through Ebean to MySQL. This is going to be a generic question – what I see is that whenever I make changes to a model – sometimes just adding a property, after applying the evolution script, the existing data in the corresponding table gets truncated.
Since I love play and I'm thinking about deploying my next project using Play, this is an important question for me – is there a workaround to securely make model changes? Or is the behaviour I'm seeing only when running the application in development mode?
I can't find much about this subject elsewhere.

A: That's common approach of Ebean - it doesn't truncate your tables it just drops whole DB and recreates it with new DDL: @see answer to the other question for explanation.
Note: In meantime I found that using standalone approach which is MyBatis Migrations is little bit more comfortable then Play's evolutions, anyway you need still to create the migrations manually (as evolutions).


text:
Q: How to make API post request when using django-countries package I came across this package called django-countries and the the features it provides look nice. Now I'm trying to test it out in a react application but I'm having issues making API post request when trying to post a named country to the database. Instead of CharField I used countryField() provided by the package.
I have tried several format to make post request from postman but I keep having the error:"country_name" is not a valid choice.
One of the ways I have tried out is this:
{
    "country": "country_name"
}

How do I go about it. Since I'm using react, will be better for me to use charField instead of using the django-countries package since I'll be using html select option to get the country of the user?


text:
Q: how to login to multiple website accounts concurrently with Python I am using urllib2 and HTTPCookieProcessor to login to a website. I want to login to multiple accounts concurrently and store the cookies to be reused later.
Can you recommend an approach or library to achieve this?

A: How to achieve this really depends on you needs: what kind of login is it? Digest authentication?  Is it a web form?  Is JavaScript involved (you're pretty much screwed if this is the case)?  A library like mechanize can help you a lot with such stuff: handling of forms, redirection, authentication, cookies... However, you'd have to take care of concurrency yourself by spawning threads/processes.
Another approach that works beautifully for concurrency is using Twisted. With that solution however you'd have to handle redirection and cookies etc. yourself -- although you might be able to reuse parts of e.g. mechanize.

A: The OP clarified that this is not a concurrency issue.  With sequential processing in mind, this is much simpler.  I once used something like the following to update a bunch of SIP phone base stations (they had a web front-end which you could use to upload VCard files for the phone book).  Note that I just cut away some crap and renamed this and that in this hacky script, I did not test it at all.  Its sole purpose is to give the OP an idea on how he could deal with this.
#!/usr/bin/python
# -*- coding:utf-8 -*-

from optparse import OptionParser
import sys
from mechanize import Browser, CookieJar, Request, urlopen

accounts = [
    {'ipaddr': '127.0.0.1', 'user': 'joe', 'pass': 'foobar'},
    ]

class WebsiteAccount(object):

    def __init__(self, ipaddr, username, password, browser):
        self.ipaddr = ipaddr
        self.username = username
        self.password = password
        self.browser = browser
        self.cookiejar = CookieJar()
        self.browser.set_cookiejar(self.cookiejar)

    def login(self):
        self.browser.open('http://'+self.ipaddr+'/login.html')
        self.browser.select_form(name='loginform')
        self.browser.form.set_value(self.username, name='username')
        self.browser.form.set_value(self.password, name='password')
        resp = self.browser.submit()
        print 'Logging into account %s@%s ...' % (self.username, self.ipaddr),
        if resp.geturl().endswith('/login.html'):
            print 'FAILED!'
            sys.exit(1)
        print ' OK'

    def logout(self):
        print ('Logging out from account %s@%s...' % (self.username, self.ipaddr),
        self.browser.open('http://'+self.ipaddr+'/logout.html')
        self.browser.close()
        print 'OK'

def main():
    parser = OptionParser()
    parser.add_option('-d', '--debug', action='store_true', dest='debug', default=False)
    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False)
    (opts, args) = parser.parse_args()
    for account in accounts:
        browser = Browser()
        browser.set_handle_referer(True)
        browser.set_handle_redirect(True)
        browser.set_handle_robots(False)
        bs = WebsiteAccount(account['ipaddr'],
                            account['user'],
                            account['pass'],
                            browser)
        # DEBUG
        if opts.debug == True:
            browser.set_debug_redirects(True)
            browser.set_debug_responses(True)
            browser.set_debug_http(True)
        bs.login()
        try:
            # ... do some stuff
            # save cookies here?
            pass
        finally:
            # you shouldn't use this if you are interested in the login cookies
            bs.logout()

if __name__=='__main__':
    main()


text:
Q: Parse timezone from a human time input I'm having trouble parsing out timezone information from a string that looks like:

8pm PST on sunday

So far, using parsedatetime and dateutils allows me to parse the date out but the timezone usually causes issues.
Anyone know of a library that handles this sort of thing? My fallback is to naively parse out the timezones via a regex or a simple "PST" in datestring.

A: The abbreviations you're using are not unique; you will therefore need to interpret the time zones somehow (e.g. assume United States) and specify what each abbreviation means for your application:
from dateutil import parser

# map time zones to seconds from GMT
zones = {
    'EST': -5 * 3600,
    'PST': -8 * 3600
}

parser.parse('8 PM on Sunday PST', tzinfos=zones)
# datetime.datetime(2016, 4, 24, 20, 0, tzinfo=tzoffset('PST', -28800))

You can install dateutil with pip: pip install python-dateutil.
See this similar question for more information.


text:
Q: How to find usage of c# indexer method in Visual Studio (with Resharper) For example in IDictionary<TKey, TValue>,
TValue this[TKey key] { get; set; }

How to find usage of get or set, or both?

A: You can put the caret on get or set to just get usages of the getter or setter respectively. Or place the caret on this to find either.


text:
Q: rails 3.2 skip paperclip attachment presence validation on edit action I am new to Rails and i'm working on my first rails application that uses paperclip for attachments and i'm validating the presence of attachment using validates_attachment :avatar, presence: true which is working perfectly well on create action, but when a user is editing his account settings and doesn't upload a new avatar, there is  an error for not having avatar uploaded but i want to skip that validation on edit and only validate on edit if user uploads a new one to replace existing one.
i also have
validates_format_of :avatar, :with => %r{\.(jpg|jpeg|gif|png)$}i,:unless => Proc.new {|m| m[:avatar].nil?}, :message => "Please upload files with the following extensions only
to check format only if present but doesn't seem to be working either
your help would be very much appreciated.
thanks

A: Use on option.
validates_format_of :avatar ... , :on => :create

http://guides.rubyonrails.org/v2.3.11/activerecord_validations_callbacks.html#on


text:
Q: Open WPF form Outlook Vsto with parameter I have an Outlook vsto which adds a Button to the preview pane of the selected mail.
For now the vsto only has the purpose of adding the button, but additional functionality is to come.
Additional I have a WPF Window which opens when the Button is clicked.
 private void ArchiveButton_Click(object sender, EventArgs e)
 {
     var mail = (Outlook.MailItem)OutlookItem; // currently selected mail.
     var app = new App();
     app.InitializeComponent();
     app.Run(new MainWindow(mail));
 }

As you can see I can run the App.xaml to get the stylings and pass the parameter mail to the window.
In this MainWindow I edit some metadata and initiate the storing process, so I need that Outlook.MailItem object.
The solution I found was to have two constructors of MainWindow. One called by app.InitializeComponent() which seems to load the styling and is immediately closed and one called by app.Run(new MainWindow(mail)) which I actually use.
 public MainWindow()
 {
     Close();
 }

 public MainWindow(Outlook.MailItem mail)
 {
     InitializeComponent();
     SearchTextBox.Text = mail == null ? "null" : "mail"; // checking if the WPF got the object
     MailItem = mail;
     ...
 }

My question here is:
Is there a cleaner/ better solution to get both, styling and the parameter?

A: As you are manually creating the WPF main window from code, remove the StartupUri definition from App.xaml file.
If it is defined, it will be automatically created by WPF infrastructure, hence the window blinking.


text:
Q: How can i add more than 1mission I have a problem I want to make an app make more than 1 mission but it makes just 1 mission.
Note that Mission is a class and
toManinActivity is an ArrayList. How can I solve it?
   Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Name.getText().toString().isEmpty()) {
                    Name.setError("");
                } else if (Hours.getText().toString().isEmpty()) {
                    Hours.setError("");
                } else if (Minutes.getText().toString().isEmpty()) {
                    Minutes.setError("");
                } else if (AboutMission.getText().toString().isEmpty()) {
                    AboutMission.setError("");
                } else {
                    int h = Integer.parseInt(Hours.getText().toString());//The hours
                    int m = Integer.parseInt(Minutes.getText().toString());//The minutes
                    if (m >= 60) {
                        Minutes.setError("Minutes should be under 60");
                    } else if (h >= 12) {
                        Hours.setError("Hours should be under 12");
                    } else {
                        toMainActivity.add(0, new NewMission("Date" + ":" + Dates, "Name" + ":" + Name.getText().toString(), "TIme" + ":" + Hours.getText().toString() + ":" + Minutes.getText().toString() + AmPm.getSelectedItem().toString(), "About Mission" + ":" + AboutMission.getText().toString(), Integer.parseInt(importance.getSelectedItem().toString())));
                        PreferencesManager.getInstance(Main2Activity.this).putString("Name", new Gson().toJson(toMainActivity));
                        startActivity(new Intent(Main2Activity.this, MainActivity.class));
                    }
                }
            }
        });

A: You are adding your mission object to the first (0) index of your list meaning you will overwrite anything that was already at that index (0). Use basic add() method without an index parameter so that each new object is added at the end of the list.
toMainActivity.add(new NewMission...


text:
Q: is there a way of looping pattern action pair in lex program? I was wondering if there is a means of looping in rules section of a lex program, where i can iterate both pattern and action.
something like this:
%{
  char *pattern[] = {a,b,c,d,e}
%}

%%
 for(i=0,i<5,i++){
   (pattern[1]){action[i]}
 }
%%

//Some functions

Is it possible to make such kind of iteration?
I am in looking for a way to write a lex progam that can identify all C language keywords.

A: I'm not sure exactly how looping will help you solve this problem. (F)lex already loops, repeatedly finding a token until some action returns (or EOF is reached and the default EOF action returns).
To identify keywords, just write the keywords out as patterns:
%{
  int keywords = 0;
%}
%option noyywrap
%%
 /* List of keywords taken from http://port70.net/~nsz/c/c11/n1570.html#6.4.1 */
auto                    { ++keywords; }
break                   { ++keywords; }
case                    { ++keywords; }
char                    { ++keywords; }
const                   { ++keywords; }
continue                { ++keywords; }
default                 { ++keywords; }
do                      { ++keywords; }
 /* Etc. */
[[:alpha:]_][[:alnum:]_]*                ; /* Ignore other identifiers */
\.?[[:digit:]]([[:alnum:].]|[EePp][+-])* ; /* And pp-numbers */
 /* The next one matches too much; it will cause keywords inside comments
  * and quoted strings to be accepted. So you still have some work to do. */
[^[:alnum:]]+                            ; /* And everything else */

%%
int main(void) {
  yylex();
  printf("%d keywords found.\n", keywords);
  return 0;
}

If you need to distinguish between the keywords, you'll need to do something more sophisticated. But a good text editor should let you convert the list of keywords into any simple repeated action, such as
auto     { return TOKEN_auto; }


text:
Q: Scaling a graphics leads to an error I have the following problem: I want to attach a photo in my resume on the right top. If I not use a scale argument, the file compiles but the photo is to large. However using a scale argument leads to an error:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% NOTE: If you find that it says                                     %%
%%                                                                    %%
%%                           1 of ??                                  %%
%%                                                                    %%
%% at the bottom of your first page, this means that the AUX file     %%
%% was not available when you ran LaTeX on this source. Simply RERUN  %%
%% LaTeX to get the ``??'' replaced with the number of the last page  %%
%% of the document. The AUX file will be generated on the first run   %%
%% of LaTeX and used on the second run to fill in all of the          %%
%% references.                                                        %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%% Document Setup %%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Don't like 10pt? Try 11pt or 12pt
\documentclass[10pt]{article}

% This is a helpful package that puts math inside length specifications
\usepackage{calc}
\usepackage[utf8]{inputenc}
% Simpler bibsection for CV sections
% (thanks to natbib for inspiration)
\makeatletter
\newlength{\bibhang}
\setlength{\bibhang}{1em}
\newlength{\bibsep}
 {\@listi \global\bibsep\itemsep \global\advance\bibsep by\parsep}
\newenvironment{bibsection}%
        {\begin{list}{}{%
       \setlength{\leftmargin}{\bibhang}%
       \setlength{\itemindent}{-\leftmargin}%
       \setlength{\itemsep}{\bibsep}%
       \setlength{\parsep}{\z@}%
        \setlength{\partopsep}{0pt}%
        \setlength{\topsep}{0pt}}}
        {\end{list}\vspace{-.6\baselineskip}}
\makeatother

% Layout: Puts the section titles on left side of page
\reversemarginpar

%
%         PAPER SIZE, PAGE NUMBER, AND DOCUMENT LAYOUT NOTES:
%
% The next \usepackage line changes the layout for CV style section
% headings as marginal notes. It also sets up the paper size as either
% letter or A4. By default, letter was used. If A4 paper is desired,
% comment out the letterpaper lines and uncomment the a4paper lines.
%
% As you can see, the margin widths and section title widths can be
% easily adjusted.
%
% ALSO: Notice that the includefoot option can be commented OUT in order
% to put the PAGE NUMBER *IN* the bottom margin. This will make the
% effective text area larger.
%
% IF YOU WISH TO REMOVE THE ``of LASTPAGE'' next to each page number,
% see the note about the +LP and -LP lines below. Comment out the +LP
% and uncomment the -LP.
%
% IF YOU WISH TO REMOVE PAGE NUMBERS, be sure that the includefoot line
% is uncommented and ALSO uncomment the \pagestyle{empty} a few lines
% below.
%

%% Use these lines for letter-sized paper
\usepackage[paper=letterpaper,
            %includefoot, % Uncomment to put page number above margin
            marginparwidth=1.2in,     % Length of section titles
            marginparsep=.05in,       % Space between titles and text
            margin=1in,               % 1 inch margins
            includemp]{geometry}

%% Use these lines for A4-sized paper
%\usepackage[paper=a4paper,
%            %includefoot, % Uncomment to put page number above margin
%            marginparwidth=30.5mm,    % Length of section titles
%            marginparsep=1.5mm,       % Space between titles and text
%            margin=25mm,              % 25mm margins
%            includemp]{geometry}

%% More layout: Get rid of indenting throughout entire document
\setlength{\parindent}{0in}

\usepackage[shortlabels]{enumitem}
\usepackage[pdftex]{graphicx}

%% Reference the last page in the page number
%
% NOTE: comment the +LP line and uncomment the -LP line to have page
%       numbers without the ``of ##'' last page reference)
%
% NOTE: uncomment the \pagestyle{empty} line to get rid of all page
%       numbers (make sure includefoot is commented out above)
%
\usepackage{fancyhdr,lastpage}
\pagestyle{fancy}
%\pagestyle{empty}      % Uncomment this to get rid of page numbers
\fancyhf{}\renewcommand{\headrulewidth}{0pt}
\fancyfootoffset{\marginparsep+\marginparwidth}
\newlength{\footpageshift}
\setlength{\footpageshift}
          {0.5\textwidth+0.5\marginparsep+0.5\marginparwidth-2in}
\lfoot{\hspace{\footpageshift}%
       \parbox{4in}{\, \hfill %
                    \arabic{page} of \protect\pageref*{LastPage} % +LP
%                    \arabic{page}                               % -LP
                    \hfill \,}}

% Finally, give us PDF bookmarks
\usepackage[colorlinks, linkcolor = black, citecolor = black, filecolor = black, urlcolor = blue]{hyperref}
%\usepackage{color,hyperref}
%\definecolor{darkblue}{rgb}{0.0,0.0,0.3}
%\hypersetup{colorlinks,breaklinks,
%            linkcolor=darkblue,urlcolor=darkblue,
%            anchorcolor=darkblue,citecolor=darkblue}

%%%%%%%%%%%%%%%%%%%%%%%% End Document Setup %%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%% Helper Commands %%%%%%%%%%%%%%%%%%%%%%%%%%%%

% The title (name) with a horizontal rule under it
% (optional argument typesets an object right-justified across from name
%  as well)
%
% Usage: \makeheading{name}
%        OR
%        \makeheading[right_object]{name}
%
% Place at top of document. It should be the first thing.
% If ``right_object'' is provided in the square-braced optional
% argument, it will be right justified on the same line as ``name'' at
% the top of the CV. For example:
%
%       \makeheading[\emph{Curriculum vitae}]{Your Name}
%
% will put an emphasized ``Curriculum vitae'' at the top of the document
% as a title. Likewise, a picture could be included:
%
%   \makeheading[\includegraphics[height=1.5in]{my_picutre}]{Your Name}
%
% the picture will be flush right across from the name.
\newcommand{\makeheading}[2][]%
        {\hspace*{-\marginparsep minus \marginparwidth}%
         \begin{minipage}[t]{\textwidth+\marginparwidth+\marginparsep}%
             {\large \bfseries #2 \hfill #1}\\[-0.15\baselineskip]%
                 \rule{\columnwidth}{1pt}%
         \end{minipage}}

% The section headings
%
% Usage: \section{section name}
\renewcommand{\section}[1]{\pagebreak[3]%
    \hyphenpenalty=10000%
    \vspace{1.3\baselineskip}%
    \phantomsection\addcontentsline{toc}{section}{#1}%
    \noindent\llap{\scshape\smash{\parbox[t]{\marginparwidth}{\raggedright #1}}}%
    \vspace{-\baselineskip}\par}

% An itemize-style list with lots of space between items
\newenvironment{outerlist}[1][\enskip\textbullet]%
        {\begin{itemize}[#1,leftmargin=*]}{\end{itemize}%
         \vspace{-.6\baselineskip}}

% An environment IDENTICAL to outerlist that has better pre-list spacing
% when used as the first thing in a \section
\newenvironment{lonelist}[1][\enskip\textbullet]%
        {\begin{list}{#1}{%
        \setlength{\partopsep}{0pt}%
        \setlength{\topsep}{0pt}}}
        {\end{list}\vspace{-.6\baselineskip}}

% An itemize-style list with little space between items
\newenvironment{innerlist}[1][\enskip\textbullet]%
        {\begin{itemize}[#1,leftmargin=*,parsep=0pt,itemsep=0pt,topsep=0pt,partopsep=0pt]}
        {\end{itemize}}

% An environment IDENTICAL to innerlist that has better pre-list spacing
% when used as the first thing in a \section
\newenvironment{loneinnerlist}[1][\enskip\textbullet]%
        {\begin{itemize}[#1,leftmargin=*,parsep=0pt,itemsep=0pt,topsep=0pt,partopsep=0pt]}
        {\end{itemize}\vspace{-.6\baselineskip}}

% To add some paragraph space between lines.
% This also tells LaTeX to preferably break a page on one of these gaps
% if there is a needed pagebreak nearby.
\newcommand{\blankline}{\quad\pagebreak[3]}
\newcommand{\halfblankline}{\quad\vspace{-0.5\baselineskip}\pagebreak[3]}

% Uses hyperref to link DOI
\newcommand\doilink[1]{\href{http://dx.doi.org/#1}{#1}}
\newcommand\doi[1]{doi:\doilink{#1}}

% For \url{SOME_URL}, links SOME_URL to the url SOME_URL
\providecommand*\url[1]{\href{#1}{#1}}
% Same as above, but pretty-prints SOME_URL in teletype fixed-width font
\renewcommand*\url[1]{\href{#1}{\texttt{#1}}}

% For \email{ADDRESS}, links ADDRESS to the url mailto:ADDRESS
\providecommand*\email[1]{\href{mailto:#1}{#1}}
% Same as above, but pretty-prints ADDRESS in teletype fixed-width font
%\renewcommand*\email[1]{\href{mailto:#1}{\texttt{#1}}}

%\providecommand\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
%    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
%\providecommand\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
%    \TeX}}
\providecommand\BibTeX{{B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    \TeX}}
\providecommand\Matlab{\textsc{Matlab}}

%%%%%%%%%%%%%%%%%%%%%%%% End Helper Commands %%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%% Begin CV Document %%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\makeheading[\includegraphics[scale=0.1]{pic.jpg}]{My full name}

\section{\textbf{Hi HO}}

% NOTE: Mind where the & separators and \\ breaks are in the following
%       table.
%
% ALSO: \rcollength is the width of the right column of the table
%       (adjust it to your liking; default is 1.85in).
%
\newlength{\rcollength}\setlength{\rcollength}{2.5in}%
%
\begin{tabular}[t]{@{}p{\textwidth-\rcollength}p{\rcollength}}

Randomstr. 21           & \textit{Mobile:} A funny phone number \\
87129 Apple Pie           & \textit{Home:} A funny home number \\
Moon                & \textit{E-mail:} \email{myname@whatever.com}
\end{tabular}

\section{\textbf{I want!!!!!!}}  A position within your firm as a wizard.

\section{\textbf{hello}} {\sl Birthday:} Sorry, I'm to old\\
                            {\sl Born:} Mordor

\section{\textbf{Yeah! done!}} {\sl 2012-2014:} MSc in reading Harry Potter books \\
{\sl University:} Hogwards, \href{http://www.google.com}{hogwards}
 \begin{itemize}
\item Major: Quiditch, \href{http://www.google.com}{lilalu}
\item Master-Thesis: "Another never ending love story"
\end{itemize}
                % \sl will be bold italic in New Century Schoolbook (or
            % any postscript font) and just slanted in
        % Computer Modern (default) font
{\sl 2008-2012:} BSc in playing guitarre\\
{\sl University:} University of Rock, \href{http://www.google.com}{Rock n Roll}
\begin{itemize}
\item Bachelor-Thesis: ``Never ending love story''
\end{itemize}
\section{\textbf{some questions?}} {\sl What?:} horse \\
                    {\sl Where:} sea\\
                    {\sl why:} boring
\section{\textbf{more}}
                       {\sl Who:} Prince \\
                       {\sl really:}
                       \begin{itemize}
                 \item yes
                 \item no
                 \item maybe
                 \item ok
                \end{itemize}

\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%%% End CV Document %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------%
% The following is copyright and licensing information for
% redistribution of this LaTeX source code; it also includes a liability
% statement. If this source code is not being redistributed to others,
% it may be omitted. It has no effect on the function of the above code.
%----------------------------------------------------------------------%
% Copyright (c) 2007, 2008, 2009, 2010, 2011 by Theodore P. Pavlic
%
% Unless otherwise expressly stated, this work is licensed under the
% Creative Commons Attribution-Noncommercial 3.0 United States License. To
% view a copy of this license, visit
% http://creativecommons.org/licenses/by-nc/3.0/us/ or send a letter to
% Creative Commons, 171 Second Street, Suite 300, San Francisco,
% California, 94105, USA.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
% IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
% CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
% TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
% SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%----------------------------------------------------------------------%

So using once the code \makeheading[\includegraphics[scale=0.1]{pic.jpg}]{My full name} produces an error, however using \makeheading[\includegraphics{pic.jpg}]{My full name} it compiles but the picture is to large. I added a picture below. Note, I also tried to use width=/length= producing the same error. How can I use the scale function properly? Just for completeness here is the error message:
! Argument of \Gin@ii has an extra }.
<inserted text>
                \par
l.220 ...\makeheading[\includegraphics[width=3cm]p
                                                  ic.jpg}]{My full name}
I've run across a `}' that doesn't seem to match anything.
For example, `\def\a#1{...}' and `\a}' would produce
this error. If you simply proceed now, the `\par' that
I've just inserted will cause me to report a runaway
argument that might be the root of the problem. But if
your `}' was spurious, just type `2' and it will go away.

Runaway argument?
width=3cm
! Paragraph ended before \Gin@ii was complete.
<to be read again>
                   \par
l.220 ...\makeheading[\includegraphics[width=3cm]p
                                                  ic.jpg}]{My full name}
I suspect you've forgotten a `}', causing me to apply this
control sequence to too much text. How can we recover?
My plan is to forget the whole thing and hope for the best.

! LaTeX Error: There's no line here to end.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.220 ...\makeheading[\includegraphics[width=3cm]p
                                                  ic.jpg}]{My full name}
Your command was ignored.
Type  I <command> <return>  to replace it with another command,
or  <return>  to continue without it.

! Too many }'s.
l.220 ...ading[\includegraphics[width=3cm]pic.jpg}
                                                  ]{My full name}
You've closed more groups than you opened.
Such booboos are generally harmless, so keep going.

Overfull \hbox (40.83345pt too wide) in paragraph at lines 220--221
[]| []\OT1/cmr/m/n/10 ic.jpg]My
 []

LaTeX Font Warning: Font shape `OT1/cmr/bx/sc' undefined
(Font)              using `OT1/cmr/bx/n' instead on input line 222.

\rcollength=\skip60
LaTeX Font Info:    External font `cmex10' loaded for size
(Font)              <7> on input line 232.
LaTeX Font Info:    External font `cmex10' loaded for size
(Font)              <5> on input line 232.

Overfull \hbox (18.0pt too wide) in paragraph at lines 232--238
[][]
 []

LaTeX Font Info:    Try loading font information for OMS+cmr on input line 250.

(/usr/share/texlive/texmf-dist/tex/latex/base/omscmr.fd
File: omscmr.fd 1999/05/25 v2.5h Standard LaTeX font definitions
)
LaTeX Font Info:    Font shape `OMS/cmr/m/n' in size <10> not available
(Font)              Font shape `OMS/cmsy/m/n' tried instead on input line 250.

AED: lastpage setting LastPage [1

{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
Package atveryend Info: Empty hook `BeforeClearDocument' on input line 276.
Package atveryend Info: Empty hook `AfterLastShipout' on input line 276.
 (./test.aux)
Package atveryend Info: Executing hook `AtVeryEndDocument' on input line 276.
Package atveryend Info: Executing hook `AtEndAfterFileList' on input line 276.
Package rerunfilecheck Info: File `test.out' has not changed.
(rerunfilecheck)             Checksum: BCA175A70C2E86A6152D11F00EBA3623;268.

LaTeX Font Warning: Some font shapes were not available, defaults substituted.

Package atveryend Info: Empty hook `AtVeryVeryEnd' on input line 276.
 )
Here is how much of TeX's memory you used:
 6273 strings out of 495031
 91835 string characters out of 6181530
 182597 words of memory out of 5000000
 9418 multiletter control sequences out of 15000+600000
 5553 words of font info for 20 fonts, out of 8000000 for 9000
 14 hyphenation exceptions out of 8191
 29i,13n,43p,223b,322s stack positions out of 5000i,500n,10000p,200000b,80000s
</usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx10.pfb></us
r/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx12.pfb></usr/shar
e/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.pfb></usr/share/texli
ve/texmf-dist/fonts/type1/public/amsfonts/cm/cmsl10.pfb></usr/share/texlive/tex
mf-dist/fonts/type1/public/amsfonts/cm/cmsy10.pfb></usr/share/texlive/texmf-dis
t/fonts/type1/public/amsfonts/cm/cmti10.pfb>
Output written on test.pdf (1 page, 72354 bytes).
PDF statistics:
 68 PDF objects out of 1000 (max. 8388607)
 58 compressed objects within 1 object stream
 8 named destinations out of 1000 (max. 500000)
 49 words of extra memory for PDF output out of 10000 (max. 10000000)


text:
Q: example of beforeSave cloud code in parse.com I am usning the following code in Corona to post a table to parse.com (example data).
message1["x1"] = 1
message1["x2"] = 2
message1["y1"] = 3
message1["y2"] = 4
message1["v"] = 5
params.body = json.encode ( message1 )
network.request( baseUrl .. objectClass, "POST", sendresponse,  params)

and the following is my beforeSave function to prevent it being save as x1=1.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
  if object.equalTo("1", request.params.x1) {
    response.error("x value not valid");
  } else {
    response.success();
  }
});

is this the right way of writing this code? Also does beforeSave run on each object post or I have to call it?
Many thanks

A: You were close... What you would want to do is something like this:
Parse.Cloud.beforeSave("testClass", function(request, response) {
  if (request.object.get("x1") === 1) {
    response.error("email is required for signup");
  } else {
    response.success();
  }
});

So, in Cloud Code, the object that you are saving is always going to be at "request.object". Since it is a JavaScript object of type Parse.Object, all of the functions outlined at https://parse.com/docs/js/ work (hence the .get("x1")). Once we get the value of the "x1" attribute, we can use standard Javascript evaluators to test equality (in this case, == or === depending on your need).
Also note that "beforeSave" is looking for a String when it comes to the ClassName. Parse.User is the name of the Javascript object class for Parse Users. The User class, in string form, is always "_User".
And yes, this will be called on each POST/save.


text:
Q: How do I prove the estimates? Suppose that $u\in H^{1}(U)$ is the unique weak solution of the boundary value problem
$-\sum_{i,j=1}^n(a^{ij}u_{x_i})_{x_j}+2u=f$ in $U$
$u=g$ on $\partial U$, where $g$ be the trace on $\partial U$ of an $H^1(U)$ function $w$.
Prove that i) $\|u\|_{H^1{(U)}}\leq C(\|f\|_{L^2{(U)}}+\|w\|_{H^1{(U)}}$.
ii)$\|u\|_{H^2{(U)}}\leq C(\|f\|_{L^2{(U)}}+\|w\|_{H^2{(U)}}$, where $w,u \in {H^2{(U)}}$.
Can anyone suggest to me some hints for this question?

A: I am going to make some small additional assumptions.
We assume that the problem is elliptic (this requires assumptions on $a^{ij}$).
We fruther assume that $f\in L^2(U)$.
Then we can use the following arguments.
Let $L$ denote the differential operator on the left-hand side,
so that we currently have $Lu=f$ on $U$, $u=g$ on $\partial U$.
Using $w$, this is equivalent to
$$
L(u-w) = f- Lw\text{ in }U,\quad u-w=0\text{ on }\partial U.
$$
This is an elliptic PDE with zero boundary conditions,
and with the right-hand side $f-Lw\in H^{-1}(U)$.
Then one can apply standard estimates for elliptic PDEs,
which leads to
$$
\|{u-w}\|_{H^1(U)} \leq C\|{f-Lw}\|_{H^{-1}(U)}.
$$
Here, we can apply the triangle inequalities,
norm estimates for $L$, and embedding inequalities to obtain
$$
\|{u}\|\leq \|{w}\|+\|{u-w}\|
\leq \|{w}\|+C\|{f-Lw}\|_{H^{-1}(U)}
\leq (C\|{L}\|+1)\|{w}\|+C\|{f}\|_{H^{-1}(U)}
\leq (C\|{L}\|+1)\|{w}\|_{H^1(U)}+C^2\|{f}\|_{L^2(U)},
$$
where $C>0$ is a suitable constant.
Similar, one can obtain estimates for $H^2(U)$.
This time, we have $f-Lw\in L^2(U)$.
Using the standard estimates yields
$$
\|{u-w}\|_{H^2(U)} \leq C\|{f-Lw}\|_{L^2(U)}.
$$
This implies
$$
\|{u}\|_{H^2(U)}\leq \|{w}\|_{H^2(U)}+\|{u-w}\|_{H^2(U)}
\leq \|{w}\|_{H^2(U)}+C\|{f-Lw}\|_{L^2(U)}
\leq (C\|{L}\|+1)\|{w}\|_{H^2(U)}+C\|{f}\|_{L^2(U)}.
$$
Overall, I have used other constants than you.


text:
Q: Mapping whole numbers to constituent numbers I have an array of numbers that represent number of times some processing needs to be done some entities:
array = [20, 30, 10, 7, 8, 5]

and a number that represents the total number of times processing was actually done:
amount_processed = 80

I'd like to build a hash whose keys are the numbers in the array and whose values represent the number of times that was successfully processed of the 80. For instance:
hash = {}
index = 0
until amount_processed <= 0 || index == array.count
  mapped_amount = [array[index],amount_processed].min
  hash[array[index]] = mapped_amount
  amount_processed -= mapped_amount
  index += 1
end

The output in this case would be:
{20 => 20, 30 => 30, 10 => 10, 7 => 7, 8 => 8, 5 => 5}

If the amount_processed = 65, I would get:
{20 => 20, 30 => 30, 10 => 10, 7 => 5}

I want to map the amount_processed such that it always preferences a mapping where all of the given keys are used up. For example, for an amount_processed = 65, the output should be:
{20 => 20, 30 => 30, 10 => 10, 5 => 5} # skipped 7 and 8 entirely

Where there are different possible outputs, either is valid, I'm indifferent. I.e., if amount_processed = 60, EITHER of the 2 below would be valid
{20 => 20, 30 => 30, 10 => 10}
{30 => 30, 10 => 10, 7 => 7, 8 => 8, 5 => 5}

My code to successfully achieve the above outcomes is below
hash = {}
index = 0
size = array.size
until amount_processed <= 0
    if index == size * 2
        hash["notes"] = "attempting to go beyond 2nd iteration, i.e., there is still amount_processed left but nothing more in the array to map it to"
        return hash
    elsif index >= size
    # we've already looped through everything to find something that fully matches, and still have leftover amounts to be mapped, so now start over, and just go in order to fill in whatever's available
    pseudo_index = index - size # allows us to map to original array once index is on second iteration
    # was that particular one skipped or not
    if hash[array[pseudo_index]].present?
        # it wasn't skipped in earlier go around, so skip it NOW
    else
        mapped_amount = [array[pseudo_index],amount_processed].min
        hash[array[pseudo_index]] = mapped_amount
        amount_processed -= mapped_amount
      end
  else
    if amount_processed < array[index]
      # we don't want a partial map, so just don't, unless it's last resort
    else
      mapped_amount = [array[index],amount_processed].min
      hash[array[index]] = mapped_amount
      amount_processed -= mapped_amount
    end
  end
  index += 1
end
return hash

Will my code always work, for any array/amount_processed combo to create a hash that first matches as many arrays that are "fully complete" as and then creates matches that are not fully complete?

A: Simple Answer: Your code will failure on some cases

Take amount_processed = 62 as an example. A proper solution is {20, 30, 7, 5}, but your code will return {20, 30, 10}
The cause is your original code part will pick the array value if it is smaller then the amount_processed variables and results in picking unnecessary array value.

Suggestion: Rethink your logic for the sub-set sum problem instead of reuse the original greedy algorithm

A: As @iGian pointed out in his answer its possible to find a solution by going trough all the combinations, but sometimes its possible to try to guesstimate the size of the resulting optimal array, so I created the following code which tries to do that in a very naive way:
@amount_processed = 62
@iterations = 0

def found_solution given_array
  puts "Found a solution"
  puts given_array.inspect
  puts given_array.sum == @amount_processed ? "Exact solution" : "Aproximate solution"
  puts "After #{@iterations} iterations"
  exit 0
end

hash = {}
solution = []
array = [20, 30, 10, 7, 8, 5]

found_solution(array) if array.sum <= @amount_processed
found_solution([array.min]) if array.min >= @amount_processed

min_size_array = 0
array.size.times do |i|
  @iterations += 1
  min_size_array = i
  sum_of_maxs = array.max(min_size_array).sum
  found_solution(array.max(min_size_array)) if sum_of_maxs == @amount_processed
  break if array.max(min_size_array).sum > @amount_processed
end

max_value_array = array.max
max_size_array = min_size_array
(min_size_array..array.size).each do |i|
  @iterations += 1
  sum_of_mins = array.min(i).sum
  found_solution(array.min(i)) if sum_of_mins == @amount_processed
  break if sum_of_mins > @amount_processed
  max_size_array = i
end

max_value_in_array = array.max
# Run through all the combinations within the given sizes until a solution is found, including iterations for
# non exact solutions, which can at most be as much as 'max_value_in_array' away from the amount_processed
(0..max_value_in_array).each do |difference_to_solution|
  (min_size_array..max_size_array).each do |size|
    array.combination(size).each do |current_combination|
      @iterations += 1
      if current_combination.sum == (@amount_processed - difference_to_solution)
        found_solution(current_combination) unless difference_to_solution > 0
        # There is a difference, so we need to find the min_value that is not in the current_combination
        # and add it to the approximate solution
        duplicate_array = array.dup
        current_combination.each do |x|
          duplicate_array.slice!(duplicate_array.index(x))
        end
        min_value_not_in_current_combination = duplicate_array.min
        found_solution(current_combination + [min_value_not_in_current_combination])
      end
    end
  end
end

A: Your problem has some similarities to a Knapsack problem, and as others have stated it may not have an optimal algorithmic solution. Your "fit" function has some extra requirements that seem to make it even more challenging. Processing the array elements in varying orders may produce more optimal solutions so I think you kind of have to try them all and pick the one that best meets your criteria.
My solution tries all the permutations to brute force the best solution. It takes advantage of Ruby's hash identity (e.g. { 1=>2, 2=>3 } is equal to { 2=>3, 1=>2 }) to remove duplicate candidate solutions. I tried to align the fit function to your requirements.
def solve(*args)
  best_fit(compute_solutions(*args))
end

def best_fit(solutions)
  # prefer unique solutions with no partial values
  preferred_solutions, alternative_solutions =
    solutions.uniq.partition { |solution| solution.all? { |k, v| k == v } }

  if preferred_solutions.empty?
    # prefer unique solutions with "fullest" partial values
    preferred_solutions = alternative_solutions
      .group_by { |solution| solution.detect { |k, v| v < k and break k } }
      .min_by(&:first)
      .last
  end

  # prefer shortest solution matching above criteria
  preferred_solutions
    .group_by(&:length)
    .min_by(&:first)
    .last
    .first
end

def compute_solutions(array, *args)
  return enum_for(__callee__, array, *args).to_a unless block_given?

  array.permutation do |permuted_array|
    yield compute_solution(permuted_array, *args)
  end
end

def compute_solution(array, amount_processed)
  return enum_for(__callee__, array, amount_processed).to_h unless block_given?

  array.each do |amount|
    break if amount_processed.zero?
    value = [amount, amount_processed].min
    yield [amount, value]
    amount_processed -= value
  end
end

p solve([20, 30, 10, 7, 8, 5], 80) == { 20=>20, 30=>30, 10=>10, 7=>7, 8=>8, 5=>5 } # => true
p solve([20, 30, 10, 7, 8, 5], 79) == { 20=>20, 30=>30, 10=>10, 7=>7, 8=>8, 5=>4 } # => true
p solve([20, 30, 10, 7, 8, 5], 65) == { 20=>20, 30=>30, 10=>10, 5=>5 } # => true
p solve([20, 30, 10, 7, 8, 5], 62) == { 20=>20, 30=>30, 7=>7, 5=>5 } # => true
p solve([20, 30, 10, 7, 8, 5], 60) == { 20=>20, 30=>30, 10=>10 } # => true

A: Maybe this is the logic you are looking for?
It goes trough all combinations if there is no match and returns an empty array
array = [20, 30, 10, 7, 8, 5]
amount_processed = 65

go = true
(array.size + 1).times do |n|
    combinations = array.combination(n).to_a
    combinations.each do |combination|
        sum = combination.inject(0){|sum,x| sum + x }
        if sum == amount_processed
            then
                p combination
                go = false
        end
        break if go == false
    end
    break if go == false
end


text:
Q: Find the sum of the infinite Fibonacci sequence Problem

Let $F_0 = 0, F_1 = 1,$ and $F_n = F_{n-1}+F_{n-2}$. Find the value of the infinite sum $$\dfrac{1}{3}+\dfrac{1}{9}+\dfrac{2}{27}+\cdots+\dfrac{F_n}{3^n}+\cdots.$$

This sort of looks like an arithmetico-geometric series but except for the fact that the fiboncci sequence is not arithmetic. I couldn't think of a way to continue.

A: Let $s_n=F_n/3^n$, we have:
$$
s_n={1\over3}s_{n-1}+{1\over9}s_{n-2},
$$
that is:
$$
\sum_{k=3}^\infty s_n={1\over3}\sum_{k=2}^\infty s_{n}+{1\over9}\sum_{k=1}^\infty s_{n}.
$$
If $S=\sum_{k=1}^\infty s_{n}$ is finite (which is true, because $s_n<(2/3)^n$), it follows that:
$$
S-{1\over3}-{1\over9}={1\over3}\left(S-{1\over3}\right)+{1\over9}S,
$$
whence $S=3/5$.


text:
Q: how to read ChannelMessages using ms graph win. service app (in Application permission) using current userPrincipalName We have a daemon app that connects to teams using MS graph.  It's using "Application Permissions" mode and Admin consent is granted for most permissions.  We are able to add channels (private or 'standard'), add/remove members, etc... from this service based on company requirements.  All is well.
For the ChannelMessages, we'd like to be able to retrieve them based on userPrincipalName, from the same tenant that the app is registered in.  (I know there is an ChannelMessage.Read.All with Application Permission and it requires us to submit a form to MS, we are not currently pursuing that route...).
Do we have to create ConfidentialClientApplication object to communicate with MS graph?  If so, how do we create a ClaimsPrincipal or ClaimsIdentity, based only on userPrincipalName?  Or is there a different solution to this problem?
Your help is appreciated.
thanks,
Art


text:
Q: Can get cleaned_data when customyzing LoginView in django Beginner with Django 3.2. I'm trying to add a Recaptcha V3 from Google on my login screen.

*

*I'am using django-recaptcha3 well configured

*The logo is showing on my login page

*When debugging the json response when calling ReCaptchaField.clean is OK !

The problem is that the form is not validated
"'CustomAuthenticationForm' object has no attribute 'cleaned_data'"
Error occured when I do
form.is_valid() # FALSE !!
captcha_score = form.cleaned_data['captcha'].get('score')
print("SCORE" + str(captcha_score))

Here is my code :
In urls.py
from django.urls import path
from .views import CustomLoginView

urlpatterns = [
    path('login', CustomLoginView.as_view(), name='login'),
]

In Forms.py
from django.contrib.auth.forms import AuthenticationForm
from snowpenguin.django.recaptcha3.fields import ReCaptchaField

class CustomAuthenticationForm(AuthenticationForm):
    captcha = ReCaptchaField()

In Views.py
from django.contrib.auth.views import LoginView
from django.views import generic
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomAuthenticationForm
class CustomLoginView(LoginView):

    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            form = CustomAuthenticationForm(request.POST)
            if form.is_valid():
                captcha_score = form.cleaned_data['captcha'].get('score')
                print("SCORE" + str(captcha_score))
        return super().post(self, request, *args, **kwargs)

    form_class = CustomAuthenticationForm
    template_name = 'accounts/login.html'

request.POST gives

<QueryDict: {'csrfmiddlewaretoken':
['TGoQaJTZACp4MbwB3iGVVdL4IHbqWDQaIhE1ldb9M8fkpjSRDHV7l1A1tTb62f3B'],
'g-recaptcha-response':
['03AGdBq270w7Z23MTavtAHLAUNSY9IWKuVpFZe0eueIiXimW6BvhTeWKANQQIFj43m903GA-cUA-dXZm7I6br.......5Z9vdM6RY9v-Kk1ZLX1uwH5nSoc7ksWUQuA00w0T8'],
'username': ['remi@XXXXXe.fr'], 'password': ['vXXXXX']}>

which is normal. form.is_valid() is failing and I suspect form = CustomAuthenticationForm(request.POST) to be the problem but I don't know how to do.
Thanks a lot for your help,
--- EDIT ---

*

*As you can see here in the debugger username / password are strings... Don't know why pycharm convert it in array.

*Same problem after adding

class CustomAuthenticationForm(AuthenticationForm):
    captcha = ReCaptchaField()
    class Meta(AuthenticationForm):
        model = CustomUser

and deleting
class CustomUser(AbstractUser):
    # first_name = models.CharField(max_length=150)
    # last_name = models.CharField(max_length=150)

A: Two moments here:

*

*username and password fields in your form data are arrays, this is wrong - you need to check how you make POST request to Django and send strings, not arrays.

*Since username/pass fields are arrays (not strings) - form.is_valid returns False, and if the form is invalid there will be no cleaned_data attribute cause it appears only when the form is valid and actually has some valid data.

A: The problem is from the package django-recaptcha3

*

*Validation occured after post method, I can use form_valid

def form_valid(self, form):
    if form.is_valid():
        captcha_score = form.cleaned_data['captcha']
        print("SCORE " + str(captcha_score))
    return super().form_valid(form)

*In snowpenguin\django\recaptcha3\fields.py I changed
return values[0] line 63 in return json_response['score']
Thanks for the help


text:
Q: Set gid bit not working I have these permissions on a folder.
drwxr-sr-x  2 root    sharedmaster  4096 2010-09-22 10:36 rantest99

I have user tony which is in the group sharedmaster.  When I try to mkdir from tony it says permission denied. Why is that?
I have set the gid bit on directory so that new directory has group read write permissions.  Where am I wrong.

A: I believe you need to chmod g+w rantest99.
Edit:
chmod g+w dirname makes a directory writable by members of the group. This is what chmod g+s dirname does:
From info coreutils 'Directory Setuid and Setgid'

27.4 Directories and the Set-User-ID and Set-Group-ID Bits
==========================================================
On most systems, if a directory's set-group-ID bit is set, newly
created subfiles inherit the same group as the directory, and newly
created subdirectories inherit the set-group-ID bit of the parent
directory.  On a few systems, a directory's set-user-ID bit has a
similar effect on the ownership of new subfiles and the set-user-ID
bits of new subdirectories.  These mechanisms let users share files
more easily, by lessening the need to use 'chmod' or 'chown' to share
new files.

A: In addition granting write access on the parent directory you almost certainly need to adjust the umask of the user which is probably set to filter away group/other write access.
You probably want to set a umask of 0002.

A: paste error please.
test@u1004s02:/tmp$ ls -ald 1
drwxr-sr-x 2 root test 4096 Sep 22 05:49 1
test@u1004s02:/tmp$ id
uid=1001(test) gid=1001(test) groups=1001(test)
test@u1004s02:/tmp$ cd 1
test@u1004s02:/tmp/1$

About setgid: http://en.wikipedia.org/wiki/Setuid#setuid_and_setgid_on_directories


text:
Q: Data inconsistency when writing to Galera-clustered MariaDB with go-sql-driver/mysql Description
Data inconsistency is observed when two golang program are concurrently writing to the same DB tables through different MariaDB instances. The MariaDB instances are clustered using Galera.
The test database looks like as follows:
CREATE TABLE `Inc` (
  `Id` int(11) NOT NULL,
  `Cnt` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `Role` (
  `Name` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `Inc` (`Id`, `Cnt`) VALUES ('1', 0);

The golang program is running 10 goroutines, each does the following DB operations:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;

SELECT `Cnt` FROM `Inc` WHERE `Id`=1 FOR UPDATE;
INSERT INTO `Role` (`Name`) VALUES(<some string unique to this transaction>);
UPDATE `Inc` SET `Cnt`=<previous select result + 1> WHERE `Id`=1 and `Cnt`=<previous select result>;
COMMIT;

Simply put, the golang program reads Inc.Cnt, inserts a unique row to Role, and then increases Inc.Cnt by one. When the program completes, Inc.Cnt should be identical to the number of rows in Role:
mysql> START TRANSACTION; SELECT `Cnt` FROM `Inc`; SELECT COUNT(*) FROM `Role`; COMMIT;
Query OK, 0 rows affected (0.27 sec)

+------+
| Cnt  |
+------+
|   30 |
+------+
1 row in set (0.27 sec)

+----------+
| count(*) |
+----------+
|       30 |
+----------+
1 row in set (0.27 sec)

Query OK, 0 rows affected (0.27 sec)

But if two programs concurrently run against two different MariaDB instances, Inc.Cnt becomes snaller than the number of rows in Role. Stranger still, sometimes the update statement returns no changed row, as if the current transaction is not isolated from other transaction. Furthermore, even if I make the program rollback when the 0 changed row is returned, the row inserted in the same transaction still remains.
I first suspected that this is because multi-master Galera does not support SERIALIZABLE isolation level. It does supports SNAPSHOT transaction isolation level, which checks transaction conflict at commit time. With this optimistic approach, it's understandable that the concurrent writes lead to many deadlock. But I still think data consistency should not break even at SNAPSHOT isolation level.
Is this an expected behaviour of Galera cluster or some mistake in Galera configuration? Or a miss in using go-sql-driver/mysql or any known limitation/bug? I didn't see the above anomaly when the number of goroutines is one.
Any suggestion will be appreciated.
Environment

*

*Golang version: go1.13.5 linux/amd64

*MySQl library: go-sql-driver/mysql v1.5.0

*MariaDB docker image: mariadb:10.4.13

*Num of goroutines per program: 10 (when set to 1, no inconsistency happens)

MariaDB configuration
[mysqld]
user = mysql
server_id = 11   # unique to this node in the Galera cluster
port = 13306

collation-server = utf8_unicode_ci
character-set-server = utf8
skip-character-set-client-handshake

skip_name_resolve = ON

default_storage_engine          = InnoDB
binlog_format                   = ROW
log_bin = /var/log/mysql/mysql-bin.log
relay_log = /var/log/mysql/mysql-relay-bin.log
log_slave_updates = on

innodb_flush_log_at_trx_commit  = 0
innodb_flush_method             = O_DIRECT
innodb_file_per_table           = 1
innodb_autoinc_lock_mode        = 2
innodb_lock_schedule_algorithm  = FCFS # MariaDB >10.1.19 and >10.2.3 only
innodb_rollback_on_timeout = 1
innodb_print_all_deadlocks = ON
bind-address                    = 0.0.0.0

wsrep_on                        = ON
wsrep_provider                  = /usr/lib/libgalera_smm.so
wsrep_sst_method                = mariabackup
wsrep_gtid_mode                 = ON
wsrep_gtid_domain_id            = 9999
wsrep_cluster_name              = mycluster
wsrep_cluster_address           = gcomm://172.24.50.27:14567,172.24.52.27:14567,172.24.54.27:14567 # all three MariaDB instances that constitute this Galera cluster
wsrep_sst_auth                  = repl:secret
wsrep_node_address              = 172.24.50.27:14567
wsrep_provider_options          = "ist.recv_addr=172.24.50.27:14568;socket.ssl_cert=/etc/mysql/certificates/maria-server-cert.pem;socket.ssl_key=/etc/mysql/certificates/maria-server-key.pem;socket.ssl_ca=/etc/mysql/certificates/maria-ca.pem"
wsrep_sst_receive_address       = 172.24.50.27:14444
wsrep_log_conflicts = ON

gtid_domain_id                  = 9011 # unique to this node in the Galera cluster

ssl_cert                        = /etc/mysql/certificates/maria-server-cert.pem
ssl_key                         = /etc/mysql/certificates/maria-server-key.pem
ssl_ca                          = /etc/mysql/certificates/maria-ca.pem

# File Key Management
plugin_load_add = file_key_management
file_key_management_filename = /etc/mysql/encryption/keyfile.enc
file_key_management_filekey = FILE:/etc/mysql/encryption/keyfile.key
file_key_management_encryption_algorithm = AES_CTR
# Enables table encryption, but allows unencrypted tables to be created
innodb_encrypt_tables = OFF
# Encrypt the Redo Log
innodb_encrypt_log = ON
# Binary Log Encryption
encrypt_binlog=ON

Golang writer
package main

import (
    "context"
    "database/sql"
    "fmt"
    "github.com/go-sql-driver/mysql"
    _ "github.com/go-sql-driver/mysql"
    "os"
    "strconv"
    "sync"
)

func task(ctx context.Context, prefix string, num int, c *sql.Conn) error {
    _, err := c.ExecContext(ctx, "SET SESSION wsrep_sync_wait=15")
    if err != nil {
        return err
    }

    tx, err := c.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
    if err != nil {
        return err
    }

    var count int
    incRes, err := tx.Query("SELECT Cnt FROM Inc WHERE Id=? FOR UPDATE", 1)
    if err != nil {
        tx.Rollback()
        return err
    }
    defer incRes.Close()
    for incRes.Next() {
        err := incRes.Scan(&count)
        if err != nil {
            tx.Rollback()
            return err
        }
    }

    res, err := tx.ExecContext(ctx, "INSERT INTO Role (Name) VALUES (?)", fmt.Sprintf("%s-%03d", prefix, num))
    if err != nil {
        tx.Rollback()
        return err
    }
    affected, err := res.RowsAffected()
    if err != nil {
        tx.Rollback()
        return err
    }
    if affected != 1 {
        tx.Rollback()
        return fmt.Errorf("inconsistency: inserted row is %d", affected)
    }
    res, err = tx.ExecContext(ctx, "UPDATE Inc SET Cnt = ? WHERE Id=? AND Cnt=?", count+1, 1, count)
    if err != nil {
        tx.Rollback()
        return err
    }
    affected, err = res.RowsAffected()
    if err != nil {
        tx.Rollback()
        return err
    }
    if affected != 1 {
        tx.Rollback()
        return fmt.Errorf("inconsistency: inserted row is %d", affected)
    }
    err = tx.Commit()
    if err != nil {
        tx.Rollback()
        return err
    }
    return nil
}

func main() {
    if len(os.Args) != 5 {
        fmt.Println("Usage: %s <db host> <db port> <count>")
        return
    }
    host := os.Args[1]
    port, err := strconv.Atoi(os.Args[2])
    if err != nil {
        panic(err)
    }
    count, err := strconv.Atoi(os.Args[3])
    if err != nil {
        panic(err)
    }
    prefix := os.Args[4]
    db := "test"
    user := "root"
    pwd := "secret"
    parallelism := 10

    driver := "mysql"
    connstr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, pwd, host, port, db)

    dbconn, err := sql.Open(driver, connstr)
    if err != nil {
        panic(err)
    }
    defer dbconn.Close()

    wg := sync.WaitGroup{}
    for thread := 0; thread <parallelism ; thread++ {
        wg.Add(1)
        go func(thread int) {
            ctx := context.Background()
            defer wg.Done()
            for i := 0; i<count; i++ {
                conn, err := dbconn.Conn(ctx)
                if err != nil {
                    fmt.Println(err)
                }
                err = task(ctx, fmt.Sprintf("%s-%d", prefix, thread), i, conn)
                if err != nil {
                    fmt.Printf("error for %s-%d-%d: %s\n",prefix, thread, i, err)
                    _, ok := err.(*mysql.MySQLError)
                    if !ok {
                        break
                    }
                }
                conn.Close()
            }
        }(thread)
    }
    wg.Wait()
}

Run the program
$ go build
$ ./native 172.24.54.27 13306 50 first

EDITED
As suggested, I added session configuration of SET SESSION wsrep_sync_wait=15 before starting transaction. SQL statements are sent as expected when I checked it using wireshark. But that doesn't change the test results.
EDITED 2
After adding option interpolateParams=true from go-sql-driver, now we do not see data inconsistency. That option is necessary to avoid using prepared statement, making each statemet fully specified. We suspect that query interruption of prepared statements is not handled as expected in Galera multi-master situation. The changed code is as follows:
        driver := "mysql"
        connstr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?interpolateParams=true", user, pwd, host, port, db)

It seems that avoiding prepared statement is a work-around. We'd like to know whether it's a limitation of Galera cluster or our misconfiguration/misuse. So this question is not answered yet.


text:
Q: How do I check whether InputField.Text contains two randomly generated letters? using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class LetterRandomiser : MonoBehaviour
{
    public char[] characters;

    public Text textbox;

    public InputField mainInputField;

    void Start() /*when the game starts*/
    {
        char c = characters[Random.Range(0,characters.Length)];
        textbox.text = c.ToString();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.KeypadEnter) && mainInputField.text.Contains(textbox.text) == true)
        {
            char c = characters[Random.Range(0, characters.Length)];
            textbox.text = c.ToString();
            mainInputField.text = "";
        }
        else if (Input.GetKeyDown(KeyCode.KeypadEnter) && mainInputField.text.Contains(textbox.text) == false)
        {
            mainInputField.text = "";
        }
    }
}

Reference to my game
I'm trying to program my game so that the two textboxes (firstChar and secondChar) would choose one randomly generated letter each.
Then when a player types in a word in the input box, the game would check if the word contains the two randomly generated.
If it does, then the program would randomise the two textboxes again and the input field would be blank.
Otherwise the program wouldn't randomise those two textboxes and the player will have to try again.
However the program doesn't work. There are no errors but when I press enter, nothing happens, like shown on the image.

A: Answered by @DerDingens.

You are checking for KeypadEnter. The normal / big Enter ist Return:
docs.unity3d.com/ScriptReference/KeyCode.KeypadEnter.html.


text:
Q: Python - Searching from a multidimensional list and display it on a TKinter Widget This is my list:
contactlist = [
    ['Person1 Lastname1', '123123', 'Random City 1'],
    ['Person2 Lastname2', '246810', 'Random City 2'],
    ['Person3 Lastname3', '13579123', 'Random City 3'],
    ]

I have a TKinter Widget where the user can input a name and where the search result would be displayed.
Label(root,text = 'NAME',font = 'arial 12 bold',bg = 'SlateGray3').place(x=30,y=20)
Entry(root,textvariable = Name).place(x = 100,y = 20)

What i want to do is whenever the user inputs something in the widget (name), and then press the "search" button, it will display the full name in the widget. How do i do this?
Edit: More clarifcation on objective

A: You can try using this program, just a raw interface you can style it yourself.
from tkinter import *

root = Tk()
contactlist = [
    ['Person1 Lastname1', '123123', 'Random City 1'],
    ['Person2 Lastname2', '246810', 'Random City 2'],
    ['Person3 Lastname3', '13579123', 'Random City 3'],
    ]
l1 = Label(root,text = 'Name')
l1.pack()
l2 = Label(root,text = 'Phn')
l2.pack()
l3 = Label(root,text = 'City')
l3.pack()
e = Entry(root)
e.pack()
def upd():
  global l1, l2, l3, e, contactlist
  resarr = [i for i in contactlist if i[0] == e.get()]
  if len(resarr)>0:
    l1.configure(text = resarr[0][0])
    l2.configure(text = resarr[0][1])
    l3.configure(text = resarr[0][2])
btn1 = Button(root, command=upd, text="Search")
btn1.pack()
root.mainloop()

You can also replace
btn1 = Button(root, command=upd, text="Search")
btn1.pack()

with
e.bind("<KeyRelease>", upd)

To update contents automatically


text:
Q: Has Galactus ever been depicted attempting to lift Mjolnir? I was reading this question and it got me to thinking - Galactus is a being driven solely by need, with no moral or ethic quandaries about what he does, and no malice or "evil" is driving his actions. He is also the size of a planet, and could probably push a small moon out of orbit if needed. That said, he would also probably never have a reason to pick up a tiny little weapon like Mjolnir... but perhaps he could if he wanted to, either through sheer strength or by his nature falling within Odin's definition of "worthy".
Has Galactus ever been depicted attempting to lift or move Mjolnir (Thor's hammer)? I'm putting the comics tag, but any continuity or medium will do, as long as Galactus is shown picking up (or trying and failing to pick up) the hammer - not necessarily to wield it as a weapon, but just to move it at the very least.

A: Firstly I'm almost certain that Galactus directly lifting or wielding Mjolnir hasn't yet been depicted. So we'll have to go back to how the hammer was made and how its magic works. The hammer was made from uru metal and enchanted by Odin whose  enchantments would be backed by the Odin force which is one of the most powerful things in the marvel universe. Now in order to wield Mjolnir you must either be found worthy or have the strength to overpower Odin's enchantments which would be a impossible feat for most anyone.
Galactus himself like the OP mentioned isn't exactly evil well this is true but it goes further than that. Galactus as long as he isn't hungry is a rather peaceful entity, even more so he exists for the purpose of recreating the universe when its time comes, like he did the last time he does feel some remorse for the planets he eats in the same way people might about eating cattle. So it could be a toss up if Galactus is actually worthy or not everything he does is to keep the universe alive, and facilitate the creation of the next one. I got this Galactus info from the marvel wiki page
Now the worthiness may not actually matter if Galactus is strong enough to break Odin's enchantment which is another one that could go either way as there are times where Galactus and Odin have rather epic fights without a clear winner. Although I'd say that if Galactus' power cosmic would be able to overpower the Odin force's enchantments on Mjolnir he'd be able to wield it. This would be like the unstoppable force immoveable object debate.
I also want to add that this is Galactus' and he could easily move the hammer about in a number of ways, but to actually wield the hammer in the same way that thor does would take more effort from him and may not be possible. There are also other things Galactus could do instead such as just creating a copy of the hammer with his own power but lacking a worthiness requirement or a different one. So technically Galactus would likely be able to move the hammer but not actually wield it, not that he would ever want or need to.


text:
Q: which image type is equivalent to 5 I wrote the below code to check if the type of the image "RGB,BGR or any other type". when i ran the code i received value equals to 5, and i also checked the docs here but still i do not know which type is equivalent to number 5!
please let me know how to know the equivalent image type to 5.
code:
public class MainClass {

public static void main(String[] args) throws IOException {

    File imgFile = new File("c:\\img.jpg");
    BufferedImage bi = ImageIO.read(imgFile);

    System.out.println(bi.getType());
}

}

A: It's TYPE_3BYTE_BGR:
/**
 * Represents an image with 8-bit RGB color components, corresponding
 * to a Windows-style BGR color model) with the colors Blue, Green,
 * and Red stored in 3 bytes.  There is no alpha.  The image has a
 * ComponentColorModel.
 * When data with non-opaque alpha is stored
 * in an image of this type,
 * the color data must be adjusted to a non-premultiplied form
 * and the alpha discarded,
 * as described in the
 * {@link java.awt.AlphaComposite} documentation.
 */
public static final int TYPE_3BYTE_BGR = 5;

A: Reading the getType() documentation you provided led me to the image type listings in "See Also". That led to the Constant Field Values document. It would seem that 5 is equivalent to "TYPE_3BYTE_BGR".


text:
Q: Visual Studio 2013 - Rename SSIS Solution (Package, object files, everything) I am using Visual Studio 2013 Data Tools and I have an existing built solution that I want to duplicate and rename.
When copying the new solution over, let's call it 'X' and going to Solution Explorer and renaming the solution to 'Y' I am able to rename it but all child elements (the packages, objects) keep the same name 'X'.
I tried renaming the package.dtsx and the solution to 'Y' but then it broke when trying to reload the solution.
How can I rename everything?

A: It works for me.
I rename the solution, the project and a package. Save All and then close the solution.
At this point, I cannot reopen the previous solution because X.sln/X.dtproj no longer exists through the rename. What gets confusing is that the rename does not rename folders (thus the Y.sln is in the X folder and all the SSIS artifacts remain in the X subfolder).


text:
Q: Nagios core monitoring is occasionally not working for directories owned by newly added users in RHEL6.9 In my environment, we have a Nagios server monitoring the incoming files in directories owned by different users, we have some checks already configured and working fine, but it is causing a problem with newly added services while everything is the same, also we can observe that monitoring sometimes continues and other time it stops with error no such file or directory in Nagios web interface.
There is no error in logs also as per my best belief configuration is fine, so if anyone can help, will be great.


text:
Q: Template Strings in GoLang? i've been researching for a while now but could not find anything.
For Example
var name = "tom"
sentence := "My Name is #{name}"

In JS this works with ${var} and in ruby with #{var}
So are there Template Strings in GoLang ?
Thanks for your help

A: The better way is using template. It allows you to specify a name.
sentence := "My Name is {{ .name }}"
templ := template.Must(template.New("myname").Parse(sentence))
templ.Execute(os.Stdout, map[string]interface{}{
    "name": "tom",
})

A: The Solution is
sentence := fmt.Sprintf("My Name is %s", name)


text:
Q: программа работает не до конца написал программу, которая из текста удаляет все символы, не являющиеся буквами, кроме пробелов. Если использовать string  - то всё работает, но если использовать char - то программа работает не полностью, т.е. не выводит буквы, стоящие после цифры/символа (например при вводе строки: edtrfy54 6bhjkj %^u выводит edtrfy, хотя должно: edtrfy bhjkj u).
в чем ошибка?
#include <cstring>

using namespace std;

int main() {
    char s[255]; //Объявляем символьную строку (массив типа char)
    char str[100] = "";
    cout << "Enter a string:\n";
    cin.getline(s, 255, '\n'); //Вводим строку с клавиатуры
    for (int i = 0; i < strlen(s); i++) { //Пробегаем по строке циклом (слева направо)
        if ((s[i] >= 'a' && s[i] <= 'z') ||
            ((s[i] >= 'A' && s[i] <= 'Z') ||
            (s[i] == ' '))) { //Если символ латинская буква
            str[i] += s[i]; //Записываем в новую строку символы, являющиеся буквами
        }
    }
    cout << "Output of the program: " << str << "\n";
    return 0;
}

A: Как сказал @EOF нужно добавить отдельный счетчик для для массива str, иначе он берет значение i-го индекса (комментарий @Stanislav Volodarskiy
) и как добавил @wololo в месте, где находится символ, неподходящий под условие будет стоять '\0', соответственно конец строки. Код:
#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char s[255]; //Объявляем символьную строку (массив типа char)
    char str[100] = "";
    cout << "Enter a string: ";
    cin.getline(s, 255, '\n'); //Вводим строку с клавиатуры
    for (int i = 0, j = 0; i < strlen(s); ++i) { //Пробегаем по строке циклом (слева направо) // добавил "j", как счетчик
        if (isalpha(s[i]) || (s[i]==' ')) { //Если символ латинская буква
            str[j] += s[i]; //Записываем в новую строку символы, являющиеся буквами // ***str[j]
            ++j; // Если условие выполняется - увеличиваем j
        }
    }

    cout << "Output of the program: " << str << endl;

    system("pause");
    return 0;
}


text:
Q: preg match on image I was wondering, I have this project in which a person copies a link into a form. Now this link has to be a image and what most of use guys say is never trust a user input.
I narrowed it down to preg_match() that can check that there is a image on the link which can be displayed on my site.
My question is basically how do you make sure that when checking the form, it is a image and not like a virus with a .jpg at the end of extension.

A: $url = 'http://foo.bar.com/path.jpg?arg=value#anchor';
if (preg_match("/\.(jpg|png)$/",parse_url($url, PHP_URL_PATH)){
    // YOUR CODE HERE
}

This matches a filename that ends with .jpg or .png.... just add in the parentheses the extensions you want to allow (separated by the | symbol)

A: Use finfo_file to get the mime type of the file.
If the mime type is something like image/gif or  image/png ... then the file is an image.


text:
Q: Does adding 1=1 to a WHERE clause a drop in performance? Consider the following SQL:
select * from dbname.tablename
where
    field1 = 'a' and
    field2 = 'b' and
    field3 = 'c' and
    1=1

You may wonder why I would add 1=1 at the end of the WHERE clause.  For ad-hoc querying, I do this so that I can comment out any combination of conditions without having to modify the SQL.  Using this SQL, I can comment out field1 = 'a' and and the SQL will work because of the trailing 1=1 condition.  Consider this SQL without this little trick:
    field1 = 'a' and
    field2 = 'b' and
    field3 = 'c'

Commenting out field3 = 'c' will break the SQL because it will look at field2 = 'b' and as the final condition and it will bark at you with, "and WHAT??"
The reason why I am asking this is because I have been known to forget to remove the 1=1 from the WHERE clause before I paste the SQL into a production query.  I am wondering if this impedes performance.  1=1 is a constant condition, so is there really a strenuous calculation being made here even if the recordset contains 10,000 rows?

A: In sweet and simple words NO.
Please refer the Answer


text:
Q: How Bootstrap modal get 'id' from url I want to get 'id' from url and using in my Bootstrap modal.
How to get this '69'.In my modal i using this '69' with SQL request.

A: I Hope, your JS code is somehow similar to it.

In, ModalPage.php
<?
$id=$_GET['id'];

  // Now, use this 'id'.
?>

A: an easy trick is to make hidden input inside modal code as below

   <form>
     <input type="hidden" value="<?php echo isset($_GET['id']?$_GET['id']:''); ?>" />
     ID = <?php echo isset($_GET['id']?$_GET['id']:''); ?>

   </form>


text:
Q: How to trigger command after build? Is there a way for maven to trigger system command after successful or unsuccessful build?
Right now I'm using external script to run mvn package, but I would like this feature integrated with maven process.

A: Maven supports pre and post scripts. See the accepted answer here. In your case it would be mavenrc_post.bat

You can easily do that by creating a file at /etc/mavenrc or
  ~/.mavenrc (Linux) or %HOME%\mavenrc_pre.bat (Windows) Maven executes
  those on startup if they exist unless you've defined a variable named
  MAVEN_SKIP_RC.


text:
Q: RTTI: Can I Get a Type by Name? Given a text string containing a type name, is there some way to get the appropriate type itself?
I'm looking to do something like this:
type
  TSomeType<T> = class
    // yadda yadda
  end;

procedure DoSomething;
var
  obj : TObject;
begin
  o := TSomeType<GetTypeByName('integer')>.Create;
  // do stuff with obj
end;

I've looked at several RTTI explanations online and looked through the Delphi units and don't see what I'm looking for. Is this possible?

A: No, generics are entirely compiletime.

A: You can always register your types into some sort of registry (managed by a string list or dictionary) and create a factory function to then return the appropriate object.  Unfortunately you would have to know in advance what types you were going to need.  Something similar to the Delphi functions RegisterClass and FindClass (in the classes unit).  My thinking is to put the generic template type into the list directly.
An example of possible usage:
RegisterCustomType('Integer',TSomeType<Integer>);
RegisterCustomType('String',TSomeType<String>);

if FindCustomType('Integer') <> nil then
  O := FindCustomType('Integer').Create;

EDIT: Here is a specific simple implementation using a tDictionary from Generics.Collections to handle the registry storage...I'll leave extracting this into useful methods as a simple exercise for the reader.
var
  o : TObject;
begin
  TypeDict := TDictionary<String,TClass>.Create;
  TypeDict.Add('integer',TList<integer>);
  if TypeDict.ContainsKey('integer') then
    o := TypeDict.Items['integer'].Create;
  if Assigned(o) then
    ShowMessage(o.ClassName);
end;

Another EDIT: I was giving this some thought last night, and discovered another technique that you can merge into this concept.  Interfaces.  Here is a quick do nothing example, but can easily be extended:
TYPE
  ITest = interface
    ['{0DD03794-6713-47A0-BBE5-58F4719F494E}']
  end;

  TIntfList<t> = class(TList<T>,ITest)
  public
    function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;

procedure TForm1.Button7Click(Sender: TObject);
var
  o : TObject;
  fTestIntf : ITest;
begin
  TypeDict := TDictionary<String,TClass>.Create;
  TypeDict.Add('integer',TIntfList<integer>);
  if TypeDict.ContainsKey('integer') then
    o := TypeDict.Items['integer'].Create;
  if Assigned(o) and Supports(o,ITest,fTestIntf) then
    ShowMessage(o.ClassName);
end;

of course you would have to implement the QueryInterface, _AddRef and _Release methods and extend the interface to do something more useful.

A: The new RTTI unit in Delphi 2010 has a way of retrieving types declared in the interface section of units. For any given type, represented by a TRttiType instance, the TRttiType.QualifiedName property returns a name that can be used with TRttiContext.FindType later to retrieve the type. The qualified name is the full unit name (including namespaces, if they exist), followed by a '.', followed by the full type name (including outer types if it nested).
So, you could retrieve a representation of the Integer type (in the form of a TRttiType) with context.FindType('System.Integer').
But this mechanism can't be used to retrieve instantiations of generic types that weren't instantiated at compile time; instantiation at runtime requires runtime code generation.

A: If you forget generics and basic types, the "RegisterClass" function would be helpful.  But it doesn't work for generics or basic types.


text:
Q: How to read array from UITableView and pass to SQLite I have some problem understanding how to read an array of x elements from an UITableView and pass it to the SQLite assigning a name to it.
Like a TODO List assigned to people's name.
I have created the database, I can save (null) fields except for the name of the list, but now I do not know how can I read all the fields and pass to my SQLite. Any hint?
In PHP, I usually use a foreach, but I am new to Obj-C and I a little bit blocked.
UPDATE:
The "+" button add a new row, instead the "Save" button has to save this list to an sqlite database.
But I am blocked on how to read and save all the fields.

A: A UITableView is a view and should not store your data. Usually you will have a ViewController that serves as the DataSource for the table view. This controller usually holds some array of sort that stores the data displayed in the table view.

A: *

*What is the data source of your tableView ? each tableView object ( witch inherits from UITableView) should have a datasource who gives it the data to display in it's view.

*You can use an SQLite wrapper so save/Load easily in/from an SQLite data base. FMDB


text:
Q: How to add empty alternative to dropDownList I am populating a dropdownlist using the following code:
SPList categories = SPContext.Current.Web.Lists["Categories"];
                dropdownlist.DataSource = categories.Items;
                dropdownlist.DataValueField = "ID";
                dropdownlist.DataTextField = "Title";
                dropdownlist.DataBind();

I need to change the code so that if the user do not want to select any value from dropdownlist he will be able to to select an empty option. How can I add an empty alternative to the dropdown so to make a selection not required?

A: SPList categories = SPContext.Current.Web.Lists["Categories"];
                dropdownlist.DataSource = categories.Items;
                dropdownlist.DataValueField = "ID";
                dropdownlist.DataTextField = "Title";
                dropdownlist.DataBind();

// Add this after DataBind()
dropdownlist.items.Insert(0, new ListItem("",""));


text:
Q: Flutter- bind json data in Table Calendar I've found a calendar scheduler example with a dummy data list. How could I bind real data that comes from API? I've to load data in eventLoader: _getEventsForDay.
  List<Event> _getEventsForDay(DateTime day) {
    // Implementation example
    return kEvents[day] ?? [];
  }

final kEvents = LinkedHashMap<DateTime, List<Event>>(
  equals: isSameDay,
  hashCode: getHashCode,
)..addAll(_kEventSource );

final _kEventSource = Map.fromIterable(List.generate(50, (index) => index),
    key: (item) => DateTime.utc(kFirstDay.year, kFirstDay.month, item * 5),
    value: (item) => List.generate(
        item % 4 + 1, (index) => Event('Event $item | ${index + 1}')))
  ..addAll({
    kToday: [
      Event('Today\'s Event 1'),
      Event('Today\'s Event 2'),
    ],
  });

Here, from _kEventSource dummy data are going to the calendar event. How could I display data containing Date, Event Name, and Event Description in this table calendar?

A: The way I've solved this issue are given below. table_calendar version: ^3.0.3
 LinkedHashMap<DateTime, List<AppEvent>> _groupedEvents;
  DateTime _focusedDay = DateTime.now();
  DateTime _selectedDay = DateTime.now();

  @override
  void didChangeDependencies() {
    // context.read(pnProvider).init();
    super.didChangeDependencies();
  }

  int getHashCode(DateTime key) {
    return key.day * 1000000 + key.month * 10000 + key.year;
  }

  _groupEvents(List<AppEvent> events) {
    _groupedEvents = LinkedHashMap(equals: isSameDay, hashCode: getHashCode);
    events.forEach((event) {
      DateTime date = DateTime.utc(
          event.startDate.year, event.startDate.month, event.startDate.day, 12);
      if (_groupedEvents[date] == null) _groupedEvents[date] = [];
      _groupedEvents[date].add(event);
    });
  }

  List<dynamic> _getEventsForDay(DateTime date) {
    return _groupedEvents[date] ?? [];
  }

  final eventList = getEvents();

  static List<AppEvent> getEvents() {
    List<AppEvent> events = [];
    AppEvent appEvent = AppEvent();
    appEvent.id = "12";
    appEvent.userId = "15";
    appEvent.title = "Calendar";
    appEvent.description = "this is the event1";
    appEvent.startDate = DateTime.now();

    events.add(appEvent);

    appEvent = AppEvent();
    appEvent.id = "13";
    appEvent.userId = "16";
    appEvent.title = "Calendar2";
    appEvent.description = "this is the event2";
    appEvent.startDate = DateTime(kNow.year, kNow.month, kNow.day + 1);

    events.add(appEvent);

    appEvent = AppEvent();
    appEvent.id = "13";
    appEvent.userId = "16";
    appEvent.title = "Calendar2";
    appEvent.description = "this is the event2";
    appEvent.startDate = DateTime.now();

    events.add(appEvent);

    return events;
  }

  @override
  void initState() {
    _groupEvents(eventList);
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

TableCalendar(
    focusedDay: _focusedDay,
    selectedDayPredicate: (day) => isSameDay(day, _selectedDay),
    firstDay: kFirstDay,
    lastDay: kLastDay,
    eventLoader: _getEventsForDay,
    onDaySelected: (selectedDay, focusedDay) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
      });
      print(_selectedDay);
      print(_groupedEvents[_selectedDay]);
    },
    weekendDays: [6],
    headerStyle: HeaderStyle(
      decoration: BoxDecoration(
        color: Colors.blueGrey,
      ),
      headerMargin: const EdgeInsets.only(bottom: 8.0),
      titleTextStyle: TextStyle(
        color: Colors.white,
      ),
      formatButtonDecoration: BoxDecoration(
        border: Border.all(color: Colors.white),
        borderRadius: BorderRadius.circular(10),
      ),
      formatButtonTextStyle: TextStyle(color: Colors.white),
      leftChevronIcon: Icon(
        Icons.chevron_left,
        color: Colors.white,
      ),
      rightChevronIcon: Icon(
        Icons.chevron_right,
        color: Colors.white,
      ),
    ),
    calendarStyle: CalendarStyle(
      // Use `CalendarStyle` to customize the UI
      outsideDaysVisible: false,
    ),
    calendarBuilders: CalendarBuilders(),
  )


text:
Q: How do I install LibreOffice on 10.04 Server? I follow @Seth's answer to install LibreOffice4 on the server.
How do I install LibreOffice 4?
I run dpkg -i *.deb without any error (as root). Then I didn't see any desktop-integration folder. Then nothing. There is no libreoffice command.
Basically, I try to use libreoffice to run in server mode, and convert odt file to pdf file (with python subprocess module). I can do that locally, but I cannot figure out how to install libreoffice on the server, where there is no GUI.
Any ideas?

A: My fault. With help of colleague, it turns out the command is libreoffice4.1 instead of libreoffice. So I had successfully installed libreoffice.
But to share about how to call libreoffice on Ubuntu server version, there are some additional library to be installed.
# for X11 support
apt-get install xorg
apt-get install openbox

# for libdbus
aptitude install libc6
aptitude install libdbus-glib-1-2

And to convert to pdf, must specify writer_pdf_Export in my case.
libreoffice4.1 --headless --invisible --convert-to pdf:writer_pdf_Export result.odt --outdir /path/to/outdir


text:
Q: joomla 3 refresh cache using cronjob Please anybody with sufficient technical experience could please verify or suggest an alternate on how to achieve the following:
I am using a specific component for CCK in a Joomla 3 installation. Unfortunately all its listing pages are quite slow since heavy customization has been made. I have activated caching for this specific component in order to speed up specific pages of my website. Cache interval is 2 hours.
I would like to find a way to force refresh cache every 2h 01mins so as to minimize slow page load user experience.
so I am thinking to create a php script which will manually access (http request) these pages! then I am thinking of executing this script using a cronjob (server side) every 2h 01mins to re-create the cached version of these pages.
so my question is simply the following:
a) Could a php script "load" somehow these pages (by URL)? Could I use something like php cURL? If not could you suggest any other options for "loading" these pages using a script on server side?

A: Based on your use case, you could use a simple cURL script to load the page in question.  This would force Joomla to re-render and cache.
<?php
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "http://www.website.com/my-cached-path");
 $contents = curl_exec ($ch);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_close ($ch);
?>

A: This script will clear cache, you can put it in a cron job.
https://github.com/elinw/jshell/blob/master/clearcache.php