text:
Q: Iterating through DataGridViewRow columns How can I iterate through DataGridViewRow columns? I just want to get the number of columns that I have and go through them and get the values.

A: You can use Cells property to get all values row have
foreach(DataGridViewCell cell in row.Cells)
{
    get value by    cell.Value
}

and number of columns is equal to number of cells


text:
Q: add specific constraints to table I would like to make a table called room_admins which is going to include the admins of chat rooms, so to do that I have made two foreign keys in the room_admins table first one will be for the room_id and the second one is going to be for the member_id.
I hope that's clear, but what I really need to add is a constraint to ensure that the member is actually a member in the room. like for example,
if I have passed room_id 1 and member_id 1 the SQL has to ensure that the member of id 1 is really a member in the room with id 1

A: Foreign key constraints can't do what you ask, and check constraints can generally only reference columns in the table. You could enforce it with a trigger, but that gets slow and complicated.
If you want to enforce that members are in a given room, add a table for room memberships and reference that. Rather than being a simple join table, this could contain other information about that member specific to that room, like what their nickname is.
room_memberships:
  id primary key
  nickname
  room_id not null references rooms(id)
  member_id not null references members(id)
  -- one membership per member and room
  unique(room_id, member_id)

At this point you can simply add an admin flag to room_memberships.
If a member can have multiple roles in a room, have a room_roles table which references room_memberships.
room_roles:
  room_membership_id not null references room_memberships(id)
  role not null
  unique(role, room_member_id)

How do we ensure the role is valid? This can be done with a check constraint, but then schema must be modified when you add a role. Again we can solve this with a new table. Add a roles table and reference it.
room_roles:
  room_membership_id not null references room_memberships(id)
  role_id not null references roles(id)
  unique(role_id, room_member_id)

roles:
  id primary key
  name not null
  unique(name)

redpajama_set_name: RedPajamaStackExchange


text:
Q: I cannot install webpack-cli I'm trying the following:
npm i --save-dev webpack-cli

But, got the following error:
npm ERR! code ENOGIT
npm ERR! No git binary found in $PATH
npm ERR!
npm ERR! Failed using git.
npm ERR! Please check if you have git installed and in your PATH.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Goran\AppData\Roaming\npm-cache\_logs\2018-03-03T06_07_52_
323Z-debug.log

How to install webpack-cli?

A: The error is self-explanatory.
You need to install git in your system.
Also ensure it is set in your environment path.
You might need to restart your command prompt/terminal so that git program is found.


text:
Q: what is the difference between django html_message and message in send mail When im trying to send a mail with django send mail only the html message is coming and not the normal message i want to know the difference between both.
  Is there any best way to send mails through template or html files because i want a comming mailing system in my app.
Note:- the difference is of more important.
THIS IS WHAT I DID
msg_html = (' HELLLOOOOO')
msg_plain = 'Normalallalaa
send_mail("titleeeee", msg_plain,"sender@test",["reciever@tese",],html_message=msg_html)
My mail contained only Hello in bold
Where did my message go.

A: The problem is that some (old or specifically configured) email clients won't display HTML messages, therefore you need to make sure all your users can read your emails properly. If you decide to send just text, then users capable of getting HTML messages won't benefit from it.
This is the strategy I follow:
I use django.template.loader.render_to_string to render a template with a given context. The value this function returns is a string with a message in HTML.
html_text = render_to_string(template, context)

Then I create a plain text message based on the HTML message (for instance, by using a package named html2text):
plain_text = html2text(html_text)

And finally I send the email with django.core.mail.send_mail, passing html_text and plain_text as parameters.

A: Message is plain text, while html_message is a message formatted using HTML. If you set both, probably your email client is displaying the HTML version.


text:
Q: NLog pass Configuration values(ConnectionString and configDir) to nlog.config in Main method I'm trying to pass connectionString for PostgreSQL and my Log directory to nlog.config file in Main method, how can I achieve this?
I'm currently doing something like this
in Startup.cs:
NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");

Only problem I have is if I try to log something in Main method, after this DB logging is working fine:
Error when writing to database. Exception: System.ArgumentException: Host can't be null

at Npgsql.NpgsqlConnector.d__145.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.ConnectorPool.d__24.MoveNext()

A: I found the way to load Configuration in Main method, here is a way if anyone ever needs it:
var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json");

        Configuration = builder.Build();

And then I use NLog.ConfigurationManager to setup connectionString and Log directory:
 NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("databaseConnectionString");
 NLog.LogManager.Configuration.Variables["configDir"] = Configuration.GetValue<string>("Logging:LogFilePath");


text:
Q: iOS Upload Photo Upload with Caption I have seen this question asked before but none of the solutions work for me.
I am trying to post a photo to a users wall (as well as it saving to the photo album of the app)
I am using iOS 6 but I can not use the native popover code.
I am able to post a photo just fine, and I can post a normal message just fine (so permissions seem to be fine) but I can not upload a photo WITH a message/caption.
I am using the iOS Facebook SDK.
Here is one (Of MANY ways I have tried)
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   [UIImage imageNamed:@"bla"], @"source",
                                   @"caption desc", @"message",
                                   @"caption", @"caption",
                                   nil];

    FBRequest *request = [FBRequest requestWithGraphPath:@"me/photos" parameters:params HTTPMethod:@"POST"];

FBRequestConnection *connection = [[[FBRequestConnection alloc] init] autorelease];

    [connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error){
        isProcessingFacebookSharing = NO;

        NSLog(@"Facebook Post Result: %@", result);
        if (error != nil)
        {
            NSLog(@"Facebook Posting Error: %@", [error localizedDescription]);
        }

        if (!isProcessingTwitterSharing)
        {
            dispatch_async(dispatch_get_main_queue(), ^(void){
                [self cancelButtonPressed:nil];
            });
        }
    }];

    [connection start];

This posts my photo just fine but does not add a caption/message/description (or whatever you want to call it)
I have seen people who have said to try the following endpoints, which I have tried and get the same result.
me/photo
feed
me/feed

There are others I have tried but those are all that I am remembering right now.
Anyone know what I am doing wrong?

A: Turns out that the issue wasnt with the code above but instead something going wrong with Xcode.
I was having an issue with Xcode where I couldnt do an Cmd-Z (Undo) and my breakpoints were firing in odd places.
Finally closed Xcode, Deleted the app out of the Simulator, and deleted the apps Derived Data.
When I opened Xcode again all of my changes were gone.
File looked like nothing had been touched.
Changed my code back to the above and it worked.
So FYI for anyone in the future, the above does work!


text:
Q: Creating a union of 2 bezier paths I have two bezier paths that i'd like to combine to form a union, so that I can stroke the entire outer shape. In my case, it's a speech bubble with a tail, so although it's not a complex shape it would actually be quite hard to create it using one single path.
There doesn't appear to be a Core Graphics API for creating unions. Am I wrong?
If I'm not, does anyone know of a library that can handle this? I've search GitHub to no avail.

A: UIBezierPath does that if you are working with closed shapes.
UIBezierPath *firstPath = [UIBezierPath bezierPath];
// build your path

UIBezierPath *secondPath = [UIBezierPath bezierPath];
// build your path

[firstPath appendPath:secondPath];

A: If your deployment target is iOS 16 (or macOS 13) or later, you can compute the union of two CGPath objects using the union method, like so:
let path1: CGPath = ...
let path2: CGPath = ...
let combo = path1.union(path2)

A: In Swift 3 Bezier paths can be unified by:
 override func draw(_ rect: CGRect) {
    super.draw(rect)

    UIColor.black.setStroke()
    UIColor.red.setFill()

    let currentContext = UIGraphicsGetCurrentContext()
    currentContext?.saveGState()

    let path = drawTopView()
    path.lineWidth = 5.0
    path.fill()
    path.stroke()

    let middlepath = drawMiddleView()
    middlepath.lineWidth = 2.0
    middlepath.fill()
    middlepath.stroke()

    path.append(middlepath)
    currentContext?.restoreGState()
}

A: SwiftUI
func createView() -> some View {
    let a = Path { path in
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 50, y: 100))
        path.addLine(to: CGPoint(x: 100, y: 0))
    }
    .stroke(Color.white, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))

    let b = RoundedRectangle(cornerRadius: 5, style: .continuous)
        .fill(Color.white)
        .frame(width: 30, height: 30)
        .position(CGPoint.zero)

    return ZStack {
        a
        b
    }
    .compositingGroup()
    .colorMultiply(Color.red)
}


text:
Q: How can I replace the occurrence of a letter within a string with a number I have an input field where I can enter a text and I would like to replace the occurrence of Vowels with numbers.
eg - (A,E,I,O,U - 1,2,3,4,5) and add 'a' to all the other consonants.
eg - The input field takes in 'Victor as an input and what is printed on the page is 'Va3cata4ra'.
So far, I've been able to get the consonants to display an 'a' at the end of it using template literals and passing the variable to a setState. However I'm having issues getting the Vowels to show their numerical values as explained above. I've tried Switch , if else, for some reason, none is working
export default class App extends Component {

state = {
    mytext: ''
}

onChangeHandler = (event) => {
        const newText = event.target.value;
        const splitText = newText.split('');
        let tempArr = []

        for (let onye in splitText) {
            else if (onye === 'e') {
                onye.replace(parseInt('2'))
            } else if (onye === 'i') {
                onye.replace(parseInt('3'))
            } else if (onye === 'o') {
                onye.replace(parseInt('4'))
            } else if (onye === 'u') {
                onye.replace(parseInt('5'))
            } else {
                return onye
            }

            //This got the consonants to display a after each one

            const raCon = `${splitText[onye]}a`
            tempArr.push(raCon)
        }

        this.setState({
            mytext: tempArr
        })

Expected result would have 'a' at the end of each consonant and numerical values for every vowel corresponding with (A,E,I,O,U)- (1,2,3,4,5)

A: You could take a replacement function and take a letter to replace and and object with replacement values.

function replace(string) {
    return string.replace(/[aeiou]/gi, c => ({ a:1, e: 2, i: 3, o: 4, u: 5 }[c.toLowerCase()]));
}

console.log(replace('banana'));

A: I'm assuming your code looks something like this, we can just define a converter function to swap the vowels with numbers and add an "a" to each consonant.
class App extends React.Component {
  state = {
    myText: ""
  };

  onChange = event => {
    this.setState({
      myText: event.target.value
    });
  };

  convertWord = word => {
    let vowels = ["a", "e", "i", "o", "u"];
    let letters = word.toLocaleLowerCase().split("");

    return letters.map(letter =>
      vowels.includes(letter) ? vowels.indexOf(letter) + 1 : letter + "a"
    );
  };

  render() {
    return (
      <div>
        <input onChange={this.onChange} value={this.state.myText} />
        Converted Word: {this.convertWord(this.state.myText)}
      </div>
    );
  }
}

Also see sandbox: https://codesandbox.io/s/priceless-mcnulty-xyhbr

A: You can create an object where the object keys will be the vowel and set the value as required. Then use split to create an array of the characters of the input text. and use reduce to create the new string. In the reduce callback function check if the current character on iteration is key of the object. If so then retrieve the value and concat , else just concat current character &  a and return it

let vowelCrypt = {
  a: 1,
  e: 2,
  i: 3,
  o: 4,
  u: 5
}

function cryptInput(input) {
  if (input.length > 0) {
    return input.split('').reduce(function(acc, curr) {
      if (vowelCrypt[curr]) {
        acc += vowelCrypt[curr];
      } else {
        acc += curr + 'a';
      }
      return acc;
    }, '')

  }
}

console.log(cryptInput('Victor'))

A: You can use reduce to solve this.

const convertVowels = (str) => {
 const vowels = ['a','e','i','o','u'];
 return str.split('').reduce((newStr, char) => {
  if(vowels.includes(char)) {
   return newStr += (vowels.indexOf(char)+1)
  } else {
   return newStr += char+'a';
  }
 }, '');
}

console.log(convertVowels('Victor'))

A: You can try to iterate the letters and replace.
const newText = event.target.value;
const wovels = ['A','E','I','O','U'];
let p = newText.split('').map(e => {
    let idx = wovels.indexOf(e.toUpperCase());
    if(idx !== -1){
        return idx+1;
    } else {
        return e+'a';
    }
})
console.log(p.join(''));

A: You can use a function like this:
function converter(str) {
  charArr = str.split('');
  charArr.forEach(function (c, i) {
    if (c === 'a') {
      charArr[i] = 1;
    } else if (c === 'e') {
      charArr[i] = 2;
    } else if (c === 'i') {
      charArr[i] = 3;
    } else if (c === 'o') {
      charArr[i] = 4;
    } else if (c === 'u') {
      charArr[i] = 5;
    } else {
      charArr[i] += 'a';
    }
  });
  return charArr.join('');
}


text:
Q: create median and average column out of array column in pyspark I have the following spark dataframe:
import pandas as pd
foo = pd.DataFrame({'id': [1,2,3,4], 'col': [[1,2,None, None], [1,1,2,2], [1,1,1,2], [1,None,None,None]]})

foo_dfs = spark.createDataFrame(foo)
foo_dfs.show()

+---+------------+
| id|         col|
+---+------------+
|  1|    [1, 2,,]|
|  2|[1, 1, 2, 2]|
|  3|[1, 1, 1, 2]|
|  4|      [1,,,]|
+---+------------+

I am creating the min_col and max_col by doing the following:
from pyspark.sql import functions as f
foo_dfs = foo_dfs.withColumn('min_col', f.array_min('col'))
foo_dfs = foo_dfs.withColumn('max_col', f.array_max('col'))

which outputs:
+---+------------+-------+-------+
| id|         col|min_col|max_col|
+---+------------+-------+-------+
|  1|    [1, 2,,]|      1|      2|
|  2|[1, 1, 2, 2]|      1|      2|
|  3|[1, 1, 1, 2]|      1|      2|
|  4|      [1,,,]|      1|      1|
+---+------------+-------+-------+

I would like to also add the mean_col and median_col next to the max_col. How can I do that ? As far as I know there is no f.array_mean or f.array_median function
The output dataframe should look like:
+---+------------+-------+-------+--------+----------+
| id|         col|min_col|max_col|mean_col|median_col|
+---+------------+-------+-------+--------+----------+
|  1|    [1, 2,,]|      1|      2|     1.5|       1.5|
|  2|[1, 1, 2, 2]|      1|      2|     1.5|       1.5|
|  3|[1, 1, 1, 2]|      1|      2|    1.25|       1.0|
|  4|      [1,,,]|      1|      1|     1.0|       1.0|
+---+------------+-------+-------+--------+----------+

So the mean_col and median_col calculation should ignore the None values
I tried this:
 import numpy as np
 array_median = f.udf(lambda x: float(np.nanmedian(x)), FloatType())
 array_mean = f.udf(lambda x: float(np.nanmean(x)), FloatType())
 foo_dfs.withColumn('median_col', array_median('col'))
 foo_dfs.withColumn('mean_col', array_mean('col'))

But it didn't work, I am getting the following error:

TypeError: ufunc 'isnan' not supported for the input types, and the
inputs could not be safely coerced to any supported types according to
the casting rule ''safe''

Any ideas?

A: Use aggregate function for the mean_col and when along with array_sort to get the median_col. But first, you need to filter null values from the array using filter function:
from pyspark.sql import functions as F

foo_dfs = (foo_dfs.withColumn('col', F.array_sort(F.expr('filter(col, x -> x is not null)')))
           .withColumn('size', F.size('col'))
           .withColumn('min_col', F.array_min('col'))
           .withColumn('max_col', F.array_max('col'))
           .withColumn('mean_col', F.expr('aggregate(col, 0L, (acc,x) -> acc+x, acc -> acc /size)'))
           .withColumn('median_col', F.when(F.col('size') % 2 == 0,
                                            (F.expr('col[int(size/2)]') + F.expr('col[int(size/2)-1]'))/2
                                            ).otherwise(F.expr('col[int(size/2)]'))
                       )
           ).drop("size")

foo_dfs.show()
#+---+------------+-------+-------+--------+----------+
#| id|         col|min_col|max_col|mean_col|median_col|
#+---+------------+-------+-------+--------+----------+
#|  1|      [1, 2]|      1|      2|     1.5|       1.5|
#|  2|[1, 1, 2, 2]|      1|      2|     1.5|       1.5|
#|  3|[1, 1, 1, 2]|      1|      2|    1.25|       1.0|
#|  4|         [1]|      1|      1|     1.0|       1.0|
#+---+------------+-------+-------+--------+----------+

Some explanations:

*

*mean_col:  aggregate functions sums all the elements of the array then apply a finish lambda function which divides the resulting sum by the size of the array.

*median_col: sort the array and check its size: if size%2 = 0 then addition the elements at indexes size/2 and size/2 -1 and divide by 2. Otherwise (size%2 != 0) the median correspond to element of index size/2.


text:
Q: How to print elements and values from two related associative arrays in PHP I have two associative arrays.  $dpt_total is a list of departments, and the total for those departments. $cl_subtotal is a multidimensional array of department, class and subtotal.
I want to display the department and total, then the classes associated with that department and the subtotal for the class.
For example:
vdump($dpt_total);

array(2) {
'None' → float 132.88
'instore bakery' → float 786.24
}

Sizes: 2

vdump($cl_subtotal);

array(2) {
 'None' → array(1) {
 'None' → float 132.88
 }

'instore bakery' → array(10) {
  'pies' → float 70.94
  'cakes' → float 146.71
  'miscellaneous' → float 25.57
  'cookies' → float 52.38
  'brownies' → float 33.96
  'rolls' → float 143.02
  'danish' → float 90.42
  'bagels & pretzels' → float 85.68
  'breads' → float 55.73
  'dessert case' → float 81.83
 }
}

Should display these :
Department     Class     Total
--------------------------------
None                     132.88
               None      132.88
Instore Bakery           786.24
               pies      70.94
               cakes     146.71
               misc      25.57
               cookies   52.38
              (and so on)

A: a simple nested foreach statement should get you what you want:
foreach($cl_subtotal as $department=>$classes){
    //formatting
    //also note you can use $department as a key for $dpt_total ex:
    //$dpt_total[$department] will give you the total for the department
    foreach($classes as $class=>$price){
        //formatting
    }
}

A: hope this help.
$tbl=array();
foreach($dpt_total as $key=>$val){
    $row=array($key,'',$val);
    $tbl[]=$row;
    $tmp=$cl_subtotal[$key];
    foreach($tmp as $key2=>val2){
        $row=array('',$key,$val);
        $tbl[]=$row;
    }
}

$table='

Department	Class	Total
'
foreach($tbl as $row){
    $table.='
';
    foreach($row as $col){
        $table.=''.$col.'	';
    }
    $table.='/
';
}
$table.='
';


text:
Q: How to find Screen Title from SAP Program Code and Screen Code? Is it possible to find SAP Screen title from SAP databases? I want to use the Program Code and Screen Code as input and would like to get the Screen Title. For example, the TCODE VA01 Initial Screen Screen Code - 0101 has a title Create Sales Order: Initial Screen. So I want to get the title text from the input SAPMV45A 0101.
I tried with table TSTC, Though it returns the TCODE Text in TText column, it not necessarily the page title always. Generally it changes in the subsequent pages.
As I don't have much experience with SAP, any piece of knowledge will be appreciated.

A: If I understood your question correctly, there is no general way to do this for all possible programs. The title is set at runtime using the statements SET TITLEBAR, and you would have to evaluate the control (and as soon as conditional statements appear, also the data) flow of the application in order to determine the actual statement being executed (see Halting Problem) for more information about why this is a hard problem to solve). In many cases, this is even influenced by some settings or permissions.

A: You are looking for a GUI Title.
In SE80 (Sorry, German screenshot):

The text itself is in table RSMPTEXTS:

To detect the right key (in your case A01), you must go to check the Coding.
Actually I can't give you a recipe to get the correct key,
but you may set a breakpoint (form CUA_SETZEN) and check the value/code yourself:


text:
Q: If statements containing and AND followed by an OR operator I am attempting to ask:

*

*If my variable $a is set

*And if my variable $a is not apple or orange

*Then do something

I'm attempting to do this with the following code, but true is returned.
Any ideas what I am doing wrong?
<?php

    $a = 'banana';

    if (isset($a) && ($a !== 'apple' | $a !== 'orange')) {
        echo 'true';
    } else {
        echo 'false';
    }

A: You probably meant && instead off || (not |):

And if my variable $a is not apple or orange

So if you don't want it to be either of those values, you'll need
($a !== 'apple' && $a !== 'orange')

So the script becomes
<?php

    $a = 'banana';

    if (isset($a) && $a !== 'apple' && $a !== 'orange') {
        echo 'true';
    } else {
        echo 'false';
    }

Now, false is shown if:

*

*$a is not set

*$a === apple

*$a === orange

Try it online!

A: You're missing a | in your or expression
if (isset($a) && ($a !== 'apple' || $a !== 'orange')) {
  echo 'true';
} else {
  echo 'false';
}

A: You are missing a | OR operation is ||
if (isset($a) && ($a !== 'apple' || $a !== 'orange')) {


text:
Q: EC2 automatically install software Is there a way to automatically install software on all ec2 instances that are created in an account?  This is outside of automation like cloudformation or opsworks.  I know this can be done a number of ways via userdata when launching, etc.
What I want though it to make sure security monitoring agents are always installed on every instance that is launched, even if the instance is just launched through the console.
Is there a way to set a policy like this, or can these be achieved with something like Lambda?

A: There are three main ways I know to do this:

*

*Automation tools such as OpsWorks or CloudFormation, which you've said you don't want to use

*Install via user data script

*Custom a custom AMI. You create an instance, install the required software, then save it as an AMI. All instances are created from this AMI, so you know the required software is installed. I'm not sure if this is setup using IAM or AWS Config.


text:
Q: passing a long value from one intent to another I am trying to pass a long value from intent of one class to another. But Somehow I dont seem to get the syntax or method to do so. This would solve 90% of my problem. Passing it from a method called intentfunction(setid) in the MainActivity.java to a received intent in SelectOptions.java.
/--MainActivity.java---/
private void intentfunction(long setid)
{
     Intent intent = new Intent(this, SelectOptions.class);
     //editText = (EditText) findViewById(R.id.editText1);
     //editText = new EditText(this);
     etGWid.setText("");   //set the edit text to blank
    //String message = "TestHello";

    intent.putExtra(EXTRA_MESSAGE, setid);
    startActivity(intent);

}

SOmething like the above i wish to implement. And here goes the received part of Selectoptions.java
final Intent intent = getIntent();
    //String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    long getid = intent.getLongExtra(MainActivity.EXTRA_MESSAGE, defaultValue)

Something like this.

A: You have passed your intents correctly, now in the receiving activity to get the intent you could use bundles,
Bundle extras = getIntent().getExtras();
if (extras != null) {
    long getid = extras.getString('KEY',default_value);
}


text:
Q: CSS solution for surplus/overflow of tabs The design team for my project created a mockup for a tab component solution.  In the mockup, if there are a surplus of tabs - meaning there are more tabs than can fit in the available horizontal space - any tab(s) that would be truncated is removed and placed in a flyout/drop down menu.  Here is an example where there are 6 tabs, but the last three would be truncated given the screen size:

Here is some sample markup:

            <button type="button">Tab 1</button>

            <button type="button">Tab 2</button>

            <button type="button">Tab 3</button>

Tab 1 Content

Tab 2 Content

Tab 3 Content

I'm currently using the react-tabs library to render my tabs, but the feature described above is not part of that solution.  This feature could be accomplished with plain javascript/jQuery, but that would be non-ideal.
Can this be accomplished with HTML/CSS or even ReactJS?


text:
Q: Searching excel for a specific patterns. Pivots don't work I have a comically large excel spreadsheet and I need to find specific data sets based on a pattern. I have no idea where to start with this.
To simplify, each line is a transaction that lists a Person (P) a date (t) and an Item that can be X, Y, A, B or C.
What I would like to do is search that data for the following.
If person P on Date T(+/- 7 days) Received Items X and Y and at least one of Items A, B and Or C, To display that Person with each date and item underneath them.
A point in a good starting place would be appreciated because I feel like I am over my head here.

A: The easiest method would be to use conditional formatting, assign your criteria to a fill of any color, then to use "Filter" to filter only by that color.
Assuming that each item has it's own column that can be individually checked (sorry, you did not specify so I am not sure if this is your case), then conditional formatting would be pretty simple.
Let's say your columns are as follows:
A.  =P(erson)
B.  =T [Date]
C.  =X [Mandatory item #1]
D.  =Y [Mandatory item #2]
E.  =A [Optional item #1]
F.  =B [Optional item #2]
G.  =C [Optional item #3]

And let's assume that you type in "X" under each of your item's columns for all that the person has for that date...
Your conditional formatting would be:
=AND( $A1=$H$1 , IF($H$1<>"", OR($B1>=$I$1+7, $B1<=$I$1-7), $B1>=TODAY()+7
,$B1<=TODAY()-7 , $C1="X" , $D1="X" , OR($E1="X",$F1="X",$G1="X") )

So you can leave a blank cell that would be used to type in a person's name, let's just say H1 and a cell for the date you'd like, I1. You can then type in anyone's name in H1 and it would automatically highlight all of the rows that meets your criteria you specified.
Once conditional formatting has highlighted your criteria, you can then go to Ribbon > Data > Filter, then Filter By Color, and there is your list.
But again, you were not 100% specific so I am not exactly sure if this is what you were looking for.
So just remember to make H1 your cell with your name, and I1 your cell with the date you want to check +/- 7 days against.


text:
Q: Zend Framework error : Resource Matching "Jquery" not found I'm facing the following error after I deployed my application to my ubuntu server:
PHP Fatal error:  Uncaught exception 'Zend_Application_Bootstrap_Exception' with message
'Resource matching "Jquery" not found' in /home/ZendFramework-1.12.7/library/Zend/Application
/Bootstrap/BootstrapAbstract.php:706

I have tested my code on local and it works fine but it does not on the server. I'm using ZendFramework-1.12.7 and I'm not able to figure out what the problem is.
Any help is deeply appreciated.
Update:
My application.ini has the following configuration related to jquery:
resources.Jquery.enable = true
resources.Jquery.ui_enable = true
resources.Jquery.noconflictmode = false
resources.Jquery.render_mode = 255

A: Try this:
pluginPaths.ZendX_Application_Resource = "ZendX/Application/Resource"
resources.jquery.enable = true
resources.jquery.ui_enable = true
resources.jquery.noconflictmode = false
resources.jquery.render_mode = 255

Note: now Jquery is jquery
Available resource plugins are listed here. Jquery is zend extra
http://framework.zend.com/manual/1.12/en/zend.application.available-resources.html

A: Solved:
I copied the zend library from my system onto the server and changed the include_path to the new library in php.ini file and everything started working. I think there was some compatibility issues when I used another version of zend library.


text:
Q: Rack Awareness on hadoop I was going through Hadoop. I have questions about Rack Awareness :

*

*Is it logical or physical rack?

*And why for every block of data, two copies will exist in one rack, another copy in a different rack?

*For example if I have three racks and the replica factor = 3, why it doesn't place each block copy in each rack?

A: Racks are logical in Hadoop Rack awareness.
Regarding replica placement policy :

The purpose of a rack-aware replica placement policy is to improve data reliability, availability, and network bandwidth utilization.
      Communication between two nodes in different racks has to go through switches. In most cases, network bandwidth between machines in
  the same rack is greater than network bandwidth between machines in
  different racks.

when the replication factor is three, HDFS's placement policy is to put one replica on one node in the local rack, another on a node in a different (remote) rack, and the last on a different node in the same remote rack.
This policy cuts the inter-rack write traffic which generally improves write performance.
The chance of rack failure is  far less than that of node failure; this policy does not impact data reliability and availability guarantees. However, it does reduce the aggregate network bandwidth used when reading data since a block is placed in only two unique racks rather than three.
One third of replicas are on one node, two thirds of replicas are on one rack, and the other third are evenly distributed across the remaining racks. This policy improves write performance without compromising data reliability or read performance.
Please refer the documentation Hadoop Data replication

A: *

*Logical. You are to provide an external script for Hadoop that converts datanodes' hostnames to rack names.

*Inter-rack bandwidth is an expensive resource (more expensive than bandwidth within the same rack). So, this is a tradeoff between reliability and resource usage.

A:
Is it logical or physical rack ?

logical

And why for every block of data, two copies will exist in one rack, another copy in a different rack ?
For example if I have three racks and the replica factor = 3, why it doesn't place each block copy in each rack?

This provides data availability in the event of a network switch failure or partition within the cluster.
At least one replica is stored on different RAC. If one RAC is not accessible, still Hadoop can fetch data block from other RAC.
Due to replication of data blocks on three different nodes across two different RACs, Hadoop read operations provides high availability of data blocks.
Refer to Apache documentation of HdfsUserGuide for more details


text:
Q: I have a problem when web scraping by bs4 I write code to scrape car info like - title, make, model, transmission, year and price data from ebay.com , everything works fine, but very few of 'transmission' part convert to 'options' with the same address as the transmission and this sometimes causes the code not to work.
I want only automatic or manual of transmission, I try some 'if' for this problem but it did not work.
My code :
import requests
from bs4 import BeautifulSoup
import re

url = 'https://www.ebay.com/b/Cars-Trucks/6001?_fsrp=0&_sacat=6001&LH_BIN=1&LH_ItemCondition=3000%7C1000%7C2500&rt=nc&_stpos=95125&Model%2520Year=2020%7C2019%7C2018%7C2017%7C2016%7C2015'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
ebay_cars = soup.find_all('li', class_='s-item')
for car_info in ebay_cars:
    title_div = car_info.find('div', class_='s-item__wrapper clearfix')
    title_sub_div = title_div.find('div', class_='s-item__info clearfix')
    title_p = title_sub_div.find('span', class_='s-item__price')
    title_tag = title_sub_div.find('a', class_='s-item__link')
    title_maker = title_sub_div.find('span', class_='s-item__dynamic s-
 item__dynamicAttributes1')
    title_model = title_sub_div.find('span', class_='s-item__dynamic s-
 item__dynamicAttributes2')
    title_trans = title_sub_div.find('span', class_='s-item__dynamic s-
 item__dynamicAttributes3')

name_of_car = re.sub(r'\d{4}', '', title_tag.text)
maker_of_car = re.sub(r'Make: ','', title_maker.text)
model_of_car = re.sub(r'Model: ', '', title_model.text)
try:
   trans_of_car = re.sub(r'Transmission: ', '', title_trans.text)
except:
   trans_of_car = ''

year_of_car = re.findall(r'\d{4}', title_tag.text)
year_of_car = ''.join(str(x) for x in year_of_car)

price_of_car = title_p.text
print(trans_of_car )

Output:
Automatic
Manual
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Automatic
Options: 4-Wheel Drive

'Options: 4-Wheel Drive' is my problem.

A: Updated your try-except block:
try:
    if title_trans.text.startswith(r'Transmission: '):
        trans_of_car = re.sub(r'Transmission: ', '', title_trans.text)
    else:
        trans_of_car = ''
except AttributeError:
    trans_of_car = ''


text:
Q: Azure App Service startuop command isn't working on a docker container I'm using the Azure AppService version of WordPress. This version uses the wordpress-alpine-php docker image, running nginx version 1.20.2.
I need to run a startup script.  I've followed all the documentation but it's not working.
I added the script as a startup command on the general settings tab of the configuration blade.
UPDATE:
There is no error in the docker logs.

In the log stream, I see it applies this startup command to the docker command (at the end).

2023-01-28T15:47:13.502Z INFO  - docker run -d --expose=80 --name
doublekblog_53_90b5e145 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=true -e
WEBSITE_SITE_NAME=doublekblog -e WEBSITE_AUTH_ENABLED=False -e PORT=80
-e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=doublekblog.azurewebsites.net -e
WEBSITE_INSTANCE_ID=a6aeecea0459d3f037d6e8e066c862b9ee22384acef65d19b8cae7b67921b742
-e HTTP_LOGGING_ENABLED=1 -e WEBSITE_USE_DIAGNOSTIC_SERVER=False mcr.microsoft.com/appsvc/wordpress-alpine-php:stage3
/home/site/repository/movedefaultconf.sh

This script never runs.
The script works when I run it manually.  As a test, I changed the script to create a file and that didn't work.  I even updated the startup command in azure to only touch a file and that didn't seem to be applied.

A: Please check that the environment variables are correctly set, that the image version exists and the ports are reachable and open. Also, you should check the logs of the container and Azure App Service for more information.
This is for your reference:
https://geeksnewslab.com/the-azure-app-service-startup-command-issue-while-using-the-docker-container/


text:
Q: NGINX : How to configure mutual authentication for TCP Upstream? The particular feature I am interested about about SSL termination for TCP Upstream. I am evaluating both NGINX Open Source and NGINX Plus.
We have an application which accepts messages (TCP) over TLS from clients. With NGINX, I want to terminate TLS at NGINX and then NGINX will forward the decrypted packets to the application. Please note my application does NOT receive message over HTTP, but over TCP (Hence HTTP(S) related modules are not valid for my use case).
Client(s) --(TLS)--> NGINX --(Decrypted)--> Application
I have configured NGINX for TCP load balancing following this document (Non-SSL). For that I have to build the source code with the following two modules:

*

*ngx_stream_core_module

*ngx_stream_ssl_module

Now, I want to enable mutual authentication with SSL between NGINX and the clients. I am seeing this documentation which talks about server side authentication (client verifying server's certificate), but I am not able to find out the steps to configure mutual authentication (both client and server verifying each other's certificates). Could you please help me there? In the "ngx_stream_ssl_module" I don't find any option to mention client certificate.
Following is the content of my nginx.conf:
stream {
      server {
        listen *:5222 ssl;
        proxy_pass backend;
        ssl_certificate      /usr/local/nginx/certs/server.crt;
        ssl_certificate_key  /usr/local/nginx/certs/server.key;
        ssl_protocols         SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers           HIGH:!aNULL:!MD5;
        ssl_session_cache     shared:SSL:20m;
        ssl_session_timeout   4h;
        ssl_handshake_timeout 30s;
      }

      upstream backend {
        server 0.0.0.0:5223;
      }
}

Also I want to allow (SSL handshake) only if client has a specific identity (may be based on the client's identifier/unique name). Is there any way to do it using NGINX or NGINX Plus?
Any other suggestion will be appreciated.

A: Looks Like the Module ngx_stream_ssl_module doesn't support these directive ssl_client_certificate,  ssl_verify_client
stream {
          server {
            listen *:5222 ssl;
            proxy_pass backend;
            ssl_certificate      /usr/local/nginx/certs/server.crt; # Can Include the Chain
            ssl_certificate_key  /usr/local/nginx/certs/server.key;
            ssl_protocols         TLSv1 TLSv1.1 TLSv1.2; # Removed SSLv3
            ssl_ciphers           HIGH:!aNULL:!MD5;
            ssl_session_cache     shared:SSL:20m;
            ssl_session_timeout   4h;
            ssl_handshake_timeout 30s;

            ssl_client_certificate  /usr/local/nginx/certs/ca.chain.cert.pem;
            ssl_verify_client on;
            ssl_verify_depth 2;
          }

          upstream backend {
            server 0.0.0.0:5223;
          }
    }

A:  server {
    listen      80;
    server_name www.example.com;
    ...

    location /upstream {
        proxy_pass                    https://backend.example.com;
        proxy_ssl_certificate         /etc/nginx/client.pem;
        proxy_ssl_certificate_key     /etc/nginx/client.key
        proxy_ssl_protocols           TLSv1 TLSv1.1 TLSv1.2;
        proxy_ssl_ciphers             HIGH:!aNULL:!MD5;
        proxy_ssl_trusted_certificate /etc/nginx/trusted_ca_cert.crt;

        proxy_ssl_verify        on;
        proxy_ssl_verify_depth  2;
        proxy_ssl_session_reuse on;
    }
}

If you use a self-signed certificate, you should include the CA file : proxy_ssl_trusted_certificate.


text:
Q: I am no longer in sudoers?
Possible Duplicate:
How do I add myself back as a sudo user?

jiewmeng is not in the sudoers file.  This incident will be reported.

Whats happening? Its a home PC with me as the only user. I noticed this only happended recently. Perhaps after some recent update. I was running sudo add-apt-repository ...

A: It seems unlikely that just adding a repository would have removed you from sudoers (or more likely, the admin group).
Are you still in the admin group?
Simply run groups from a terminal. You should see a list come out. You're looking for the word admin. If that's in there, this isn't your issue.
The easiest way to restore your sudo rights is to reboot in recovery mode (hold left-shift at boot, select a recovery mode kernel, boot to the root prompt). Once in there you might be able to run (swap oli for your username) :
adduser oli admin

But I've seen some thing that suggest this might not work from a recovery console. Try it. If that doesn't work, or you want to check, run nano /etc/group
Look for the admin group and add your username to the end, like so:
admin:x:115:oli

You should then be able to reboot and be in the right group.
Has something melted /etc/sudoers?
Unfortunately you can't read /etc/sudoers unless you're root. So back to recovery mode (as above). Once you're in there run nano /etc/sudoers. You're looking for a pair of lines like this:
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

If that's there, this isn't your problem. If it's commented out or missing, whack it back in there!


text:
Q: whereIn array to string convertion error - Laravel I am wanting to use the WhereIn function on my Eloquent query, and it requires a PHP array:
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

Currently, the data is being passed into the controller in this format -
array(4) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" }

I am wanting the above data to be casted to (1,4,6) format to utilise the function but I'm unsure how.
This is currently being used in the following code (bedrooms and property_type are shown in the above format):
$bedrooms = Input::get('bedrooms');
$property_type = Input::get('property_type');

$locations = Location::whereHas('coordinate', function ($q) use ($minlat, $maxlat,
             $minlng, $maxlng, $bedrooms, $property_type)
            {
                $q->whereBetween('lat', array($minlat, $maxlat))
                ->whereBetween('lng', array($minlng, $maxlng))
                ->whereIn('bedrooms', '=', $bedrooms)
                ->whereIn('type', '=', $property_type);

            })->lists('id');

This returns a Array to string conversion error.
My Laravel version is 4.2.* - dev.
Any help would be hugely appreciated.

A: There is no need to do this. Have you tried it without casting them to ints? If you are not able to do this post what version of laravel you are using so people who come across this later don't do needless work. In laravel 4.2.* the following code will return the proper rows. I have just tested this.
Route::get('/', function(){

    $t = DB::table('users')->whereIn('id', array('1','2','3'))->get();

    dd($t);

});

This also works.
Route::get('/', function(){

    $t = DB::table('users')->whereIn('id', array(1,2,3))->get();

    dd($t);

});

Furthermore this code you have
array(4) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" }

And this code are exactly the same. One has just being displayed using var_dump.
array("1", "4", "6")

Unless you are literally storing unserialized arrays in your database in which case you have a ton of other issues.
EDIT: After controller was posted
I don't believe whereIn takes 3 parameters. You are trying to cast '=' to an array in your whereIn statements remove this and it should work or at least get ride of the Array to string error.
Link to whereIn Laravel function.

A: First: I think Laravel can handle string typed items to be put in a sql where clause where the column is an integers.
Second: if it doesn't work you can always 'cast' those strings to integers with the array_map method.
More information here:
http://php.net/manual/en/function.array-map.php
In your example:
$ids = array('1', '4', '6');

$ids = array_map(function ($value) {
    return (int) $value;
}, $ids);

$users = DB::table('users')->whereIn('id', $ids)->get();

Hope this helps.


text:
Q: Google App code Submit an html form and get response I'm trying to get a meeting with some local French authorities, and believe it or not, they make signing up possible on random occasions!

*

*I'd like to write a macro that clicks a button every 5 about minutes that says "Effectuer une demande de rendezvous" which translated into English is "Make an appointment request".

*Next it checks to make sure that the resulting page does not include the phrase "Il n'existe plus de plage horaire libre" which translated into English means "
There is no longer a free time slot".

*I need to load the page in a google apps script, tick the box, and click the button.

Any help would be great.

A: To make requests to the site and find out if there are slots or not you can use UrlFetchApp. To compare the strings in the response message to your desired string you can make a simple comparison using if. But to tick the checkbox, you will will need the id or specific class attribute of the checkbox element and make a POST request to submit the form which you can also use UrlFetchApp for.


text:
Q: Optimizing in-count searches with neo4j I am building a social network like graph where we periodically would like to find all the nodes with an incoming count of greater than 2. E.g.
A->B
C->B
C->A
D->A
E->A
Should return node A.
I am new to neo4j and am still a bit confused about whether they will search through all the available rows. Is there an index I can use to optimize these queries? My search query is like this
EXPLAIN MATCH ()-[r:F]->(b:Person)
WITH b, count(r) AS count
WHERE count > 1
RETURN collect(b.username)

Thank you

A: Neo4j has a special relationship count store that holds the number of relationships a node has. It allows to get the count of relationships without having to expand them.
You can access relationship count store values using the size() function.
MATCH (b:Person)
WITH b, size((b)<--()) as size
WHERE size > 2
RETURN collect(b.username)


text:
Q: Disk usage (du) displays TB not MB I have an issue while running du that it does not display the usage in units of Megabytes (as expected with -m switch) but TB:
$ du -mhs /mnt/b
2.0T    /mnt/b

How can I get a more granular result?

A: You need to remove the 'h'. That will convert everything to the most close size format, overwriting the other parameter.
So the proper command would be du -ms /mnt/b

A: Use the  -m option by itself to display the disk usage in 1 Megabyte block units. Note that the disk usage will be displayed as an integer, i.e. only a number without a unit size.
The -h switch "overrides" the -m switch and will display the disk usage not in blocks of any size,  but in a human readable format, converting to GB's and TB's as needed. That number will include unit sizes like k, M, G, T


text:
Q: How to call laravel function in Wordpress themes I am currently developing a laravel app which I only managed the blog section with Wordpress. Everything works fine. Is it possible to call laravel function in my Wordpress function.php? If yes, how can I achieve that?

A: It will depend on what function you want to call. Some things can be used independent of the framework simply by including the packages, for example Laravel Collections. However if you need more in depth integration you should take a look at the following files.

*

*public/index.php

*bootstrap/app.php

*bootstrap/autoload.php

It is in these files that the frameworks gets loaded. Meaning that it does all the prerequisites before your application code can run. If you wanted to use Laravel within WordPress you would need to mimic the logic from these files in WordPress. I have never done this before though, so I don't know if you will encounter any namespacing issues or anything else. You might also be concerned about the performance implications of loading WordPress and Laravel on every request. Good luck!


text:
Q: What are some relevant A.I. techniques for programming a flock of entities? Specifically, I am talking about programming for this contest: http://www.nodewar.com/about
The contest involves you facing other teams with a swarm of spaceships in a two dimensional world. The ships are constrained by a boundary (if they exit they die), and they must continually avoid moons (who pull the ships in with their gravity). The goal is to kill the opposing queen.
I have attempted to program a few, relatively basic techniques, but I feel as though I am missing something fundamental.
For example, I implemented some of the boids behaviours (http://www.red3d.com/cwr/boids/), but they seemed to lack a... goal, so to speak.
Are there any common techniques (or, preferably, combinations of techniques) for this sort of game?
EDIT
I would just like to open this up again with a bounty since I feel like I'm still missing critical pieces of information. The following is my NodeWar code:
boundary_field = (o, position) ->
  distance = (o.game.moon_field - o.lib.vec.len(o.lib.vec.diff(position, o.game.center)))
  return distance

moon_field = (o, position) ->
  return o.lib.vec.len(o.lib.vec.diff(position, o.moons[0].pos))

ai.step = (o) ->
  torque = 0;
  thrust = 0;
  label = null;

  fields = [boundary_field, moon_field]

  # Total the potential fields and determine a target.
  target = [0, 0]
  score = -1000000
  step = 1
  square = 1

  for x in [(-square + o.me.pos[0])..(square + o.me.pos[0])] by step
    for y in [(-square + o.me.pos[1])..(square + o.me.pos[1])] by step
      position = [x, y]
      continue if o.lib.vec.len(position) > o.game.moon_field
      value = (fields.map (f) -> f(o, position)).reduce (t, s) -> t + s
      target = position if value > score
      score = value if value > score

  label = target

  { torque, thrust } = o.lib.targeting.simpleTarget(o.me, target)
  return { torque, thrust, label }

I may have implemented potential fields incorrectly, however, since all the examples I could find are about discrete movements (whereas NodeWar is continuous and not exact).
The main problem being my A.I. never stays within the game area for more than 10 seconds without flying off-screen or crashing into a moon.

A: You can easily make the boids algorithm play the game of Nodewar, by just adding additional steering behaviours to your boids and/or modifying the default ones. For example, you would add a steering behaviour to avoid the moon, and a steering behaviour for enemy ships (repulsion or attraction, depending on the position between yours and the enemy ship). The weights of the attraction/repulsion forces should then be tweaked (possibly by genetic algorithms, playing different configurations against each other).
I believe this approach would give you already a relatively strong baseline player, to which you can start adding collaborative strategies etc.

A: You can achieve the best possible flocking behaviour using control theory. We can start by expressing the state of a ship (a vector of positions and velocities) as variable X. We will use x to represent a small deviation from some state X0. For each node, linearize around the state you want the individual ships to be at:
d/dt(X) = f(X - X0)
where X0 is the state you want the ship to be at. f() can be nonlinear (as in the case of your potential field). Close to this point, the  will obey
d/dt(x) = Ax
A is a fixed matrix which you should tweak to achieve stability. Much of the field of control theory tells you how to do this. It's very important to you that A leads to a stable system and that it converges fast. You should now break out MATLAB or GNU Octave. You should also read up on what poles mean in control theory, and Laplace transforms. The poles of the system (eigenvalues of matrix A) will characterize the response of the ship to disturbances of any kind, its stability, and its convergeance speed. It will also tell you whether the ship will move towards X0 or oscillate around X0.
There are several ways of choosing A (You probably don't get full control over A because of the game's limited physics) without having to do much analysis yourself. Two such algorithms are optimal control (You define the cost of controlling the system vs the cost of deviating from X0), and pole placement (You choose where the poles will go).
The state space theory also applies to an entire flock of ships, deviating from the configuration desired by every ship at that point in time. If the system is nonlinear, You might not be able to guarantee that all configurations are stable.
Conclusion:
Use control theory to guarantee individual stability, calculating X0 based on the ships around you, and add a potential field to prevent ships from bumping into eachother and moons.
Disclaimer:
There are several ways of expressing a state space system. This is the simplest but you'll need to express it differently when considering the open loop system (split up A into another 'A' which gives you the physical system and some other matrices which give you the control parameters)


text:
Q: Sublime text regex find/replace not recognising regex I have to find/replace A LOT of inputs in a lot of files that have name and are either required or have minlength/maxlength or ng-pattern attribute.
I made this regex:
<input([^\/\>]*?) name="([\S\_]+?)" ([^\/\>]*?)(required|pattern|minlength|maxlength)([^\/\>]*?)\/\>

I tested this regex on regex101.com (as a js regex though) and it works.
Sublime probably has slightly different regex syntax than javascript, but I've been using regex find/replace a lot recently, and this is the first time it's not working.
I'm pretty sure it's these parts that are problematic:
([^\/\>]*?)

Any help would be appreciated.

A: < and > don't need to be escaped. So don't escape your the last character i.e change \> to >
<input([^\/\>]*?) name="([\S\_]+?)" ([^\/\>]*?)
(required|pattern|minlength|maxlength)([^\/\>]*?)\/>
                                                   ^ Don't escape

instead of
<input([^\/\>]*?) name="([\S\_]+?)" ([^\/\>]*?)
(required|pattern|minlength|maxlength)([^\/\>]*?)\/\>
                                                   ^ Doesn't WORK in sublimetext


text:
Q: NSApplication sendEvent does not return while in live rezise I have a polling main loop in c++ (opengl game), using code in objC for input and to handle mac specifics.
I want to continue doing drawing during a resize operation, but my polling stops in 'sendEvent' for a mouse left down message, and does not exit before the mouse is released and the resize finished, and no redraw is made.
[run once per main loop]
int FsPollDeviceC()
{
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   while(1)
   {
      [pool release];
      pool = [[NSAutoreleasePool alloc] init];
      NSEvent *event;
      event = [NSApp
      nextEventMatchingMask:NSAnyEventMask
      untilDate: [NSDate distantPast]
      inMode: NSDefaultRunLoopMode
      dequeue:YES];
      if(event!=nil)
      {
         [NSApp sendEvent:event];
         [NSApp updateWindows];
      }
      else
      {
         break;
      }
   }
   [pool release];
   return windowclosed==0 ? 1 : 0;
}

Code https://sourceforge.net/p/galaxyv2/code/HEAD/tree/ext_include/mac/fsmacosxwrapper.m [row 1147]
Based on FsSimpleWindow (http://ysflight.in.coocan.jp/programming/fssimplewindow/e.html) but extended.
The entire project source is at https://sourceforge.net/projects/galaxyv2/files/galaxyv2/galaxyv2_1.81/

A: I was able to implement this with a redraw callback back to c-code on
@implementation YsOpenGLView
-(void) drawRect: (NSRect) bounds

This function is called on each change in size during the resize (while the mouse button is pressed, and the normal polling operation is halted).
The entire code can be found in http://sourceforge.net/projects/galaxyv2/files/galaxyv2/galaxyv2_1.82/galaxyv2_1.82_src.zip/download
For the implementation:
    fsmacosxwrapper.m
    fsmacosxwrappercpp.cpp
    fssimplewindow.h
For the usage:
    galaxy.cpp@1202 and @1270


text:
Q: MagicSuggest fail with php file Hi i'm using Magicsuggest library Here's a link. So i encounter with this errors when i try to connect to mysql
Uncaught SyntaxError: Unexpected end of input

The tag table contain two column the id and name of the tag. So how can i fix this error. Thanks for help. Here it's my php file
<?php

$con=mysqli_connect("localhost",'root', '','freelancer');

$query = "SELECT * FROM tag";

$result = mysqli_query($con,$query);

$rows = array();
while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
}
echo json_encode($rows);

?>

Here is my JavaScript:
$(document).ready(function() {
    $('#magicsuggest').magicSuggest({
        placeholder: 'Các kỹ năng yêu cầu',
        allowDuplicates: false,
        maxSelection: 2,
        data: '/valid/tags.php'
    });
});


text:
Q: ChartJs hiding odd index values on x-axes/labels values ["06月10日","06月13日","06月14日","06月15日","06月16日","06月17日","06月20日","06月21日","06月22日","06月23日","06月24日","06月27日","06月28日","06月29日","06月30日","07月01日","07月04日","07月05日","07月06日","07月07日","07月08日","07月11日","07月12日","07月13日","07月14日","07月15日","07月19日","07月20日","07月21日","07月22日","07月25日","07月26日","07月27日","07月28日","07月29日","08月01日","08月02日","08月03日","08月04日","08月05日","08月08日","08月09日","08月10日","08月12日","08月15日","08月16日","08月17日"]

above are all the labels that I want to show on the graph but it hiding all the odd index values from the graph only showing even index values on the graph from the above list.
see the graph it missing some labels.
if you see the order all the even number index values are displayed and odd are hidden..
This is all my chart code...

const data = {
            labels: dates,
            datasets: [{
                type: 'line',
                label: 'Line graph',
                data: line,
                fill: false,
                borderColor: '#ff5252',
                backgroundColor: '#ff5252',
                yAxisID: 'y-axis-a',
                lineTension: 0.1,
                borderCapStyle: 'butt',
                borderDash: [],
                borderDashOffset: 0.0,
                borderJoinStyle: 'miter',
                pointBorderWidth: 1,
                pointHoverRadius: 4,
                pointRadius: 5,
                pointHitRadius: 10,
            },{
                type: 'bar',
                label: 'Bar graph',
                data: diff,
                borderColor: colors,
                backgroundColor: colors,
                borderWidth: 2,
                pointRadius: 5,
                pointBorderWidth: 1,
                pointHoverRadius: 7,
                pointHoverBorderWidth: 2,
                fill: true,
                showLabelBackdrop:true,
            },]
        };
        const config = {
            type:"scatter",
            data: data,
            options: {
                legend: {
                    display: false
                },
                responsive: false,
                scales: {
                    y: {
                        display:false,
                        beginAtZero: true,
                        ticks: {
                            color: "#ffffff",
                            font: {
                                size: 14,
                            },
                        },
                    },
                },
                plugins: {
                    labels: {
                        ticks:{
                            font: {
                            size: 22
                        },
                            color: "#ffffff",
                        }
                    },
                    title: {
                        display: true,
                        text: title,
                        padding: {
                            top: 10,
                            bottom: 30,
                        },
                        font: {
                            size: 22,
                        },
                        color: "#ffffff"
                    }
                }
            }
        };

        const ctx = document.querySelector(`#chart${index+1}`).getContext('2d');

        const myChart = new Chart(ctx, config)

I have also tried..
x:{ticks:{autoSkip:false}}
when I do this it changes my label to numbers..

A: when you are using the type:"scatter",
Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 4 pointslink for charts scatter charts
when you are not defining the values with x and y then used the x-axis and y-axis as linear and then you can manipulate the x-axes for both line and bar..if you will not provide the chart_type in config it will take axes as linear
you can
xAxisID: 'x-axis-bar',
xAxisID: 'x-axis-line',
and then hide the 1 x-axis and autoSkip=False it will show your all values.
I am attaching the all code below..
const data = {
            labels: dates,
            datasets: [{
                type: 'line',
                label: 'Line graph',
                data: line,
                fill: false,
                borderColor: '#ff5252',
                backgroundColor: '#ff5252',
                yAxisID: 'y-axis-a',
                xAxisID: 'x-axis-line',
                lineTension: 0.5,
                order:1,
            },{
                type: 'bar',
                label: 'Bar graph',
                data: diff,
                borderColor: colors,
                backgroundColor: colors,
                borderWidth: 2,
                pointRadius: 5,
                xAxisID: 'x-axis-bar',
                pointBorderWidth: 1,
                pointHoverRadius: 7,
                pointHoverBorderWidth: 2,
                fill: true,
                showLabelBackdrop:true,
                order:2
            },]
        };
        const config = {
            data: data,
            options: {
                responsive: false,
                scales: {
                    y: {
                        display:false,
                        beginAtZero: true,
                        ticks: {
                            color: "#ffffff",
                            font: {
                                size: 14,
                            },
                        },
                    },
                    'x-axis-bar':{
                        ticks:{
                            autoSkip:false,
                            stepSize:1.0,
                        }
                    },
                    'x-axis-line':{
                      display:false
                    }
                },
                plugins: {
                    labels: {
                        ticks:{
                            font: {
                            size: 22
                        },
                            color: "#ffffff",
                        }
                    },
                    title: {
                        display: true,
                        text: title,
                        padding: {
                            top: 10,
                            bottom: 30,
                        },
                        font: {
                            size: 22,
                        },
                        color: "#ffffff"
                    }
                }
            }
        };

        const ctx = document.querySelector(`#chart${index+1}`).getContext('2d');

        const myChart = new Chart(ctx, config)


text:
Q: Unable to programmatically enable and disable matTooltip through custom directive This is the custom directive being used,
    constructor(
      private el: ElementRef,
      private renderer: Renderer
    ) { }

    @HostListener('mouseover') onHover() {
    const offWidth = this.el.nativeElement.offsetWidth;
    const scrollWidth = this.el.nativeElement.scrollWidth;
    if(offWidth < scrollWidth) {
        this.renderer.setElementAttribute(this.el.nativeElement, 'matTooltipDisabled', false);
        console.log("enable tooltip");
    } else {
        this.renderer.setElementAttribute(this.el.nativeElement, 'matTooltipDisabled', true);
        console.log("disable tooltip");
    }
}

this Does not work. The mat tool tip is always enabled. The attribute is correctly getting updated to true and false but the tooltip is always being displayed.
           <input
                appMyCustomDirective
                class="testclass"
                name="testval"
                id="testid"
                [(ngModel)]="testval"
                type="text"
                autocomplete="off"
                [matTooltip] = "testval"
                matTooltipClass = "tooltip"
                matTooltipPosition = "above"
            />

A: Create a directive that implements the condition and export a reference of the same:
@Directive({
  selector: '[isOutOfBound]',
  exportAs: 'outOfBound'
})
export class IsOutOfBoundDirective {
  constructor() { }
  @Input('isOutOfBound') outOfBound = false;
  @HostListener('mouseenter') onEnter() {
    this.outOfBound = !this.outOfBound;
  }
}

Then use the reference to bind the result to [matTooltipDisabled] somewhat like:
<button mat-raised-button
    matTooltip="Info about the action"
    [isOutOfBound]
    #c="outOfBound"
    [matTooltipDisabled]="c.outOfBound"
    >

A quick sample: https://stackblitz.com/edit/angular-mjz2n7


text:
Q: Select2 drop-down for countries, with flags Does somebody have an easy to use example of a country drop-down, with country flags, for Select2? I am about to implement one based on this suggestion, but I would prefer to avoid reinventing the wheel.

A: The way i did it:

    Destination
    <input type="text" name="cdCountry" class="form-control" required />

and using the css library  (css and a sprite)
https://www.flag-sprites.com/
Official DOC

A: Have a look on the following links.
http://www.marghoobsuleman.com/countries-dropdown-flags
http://vincentlamanna.com/BootstrapFormHelpers/country.html

A: I was working on a similar problem and here is how I solve it.
(function($) {
    $(function() {
        var isoCountries = [
            { id: 'AF', text: 'Afghanistan'},
            ...
        ];
        //Assuming you have a select element with name country
        // e.g. <select name="name"></select>

        $("[name='country']").select2({
            placeholder: "Select a country",
            data: isoCountries
        });
    });
})(jQuery);

I also have made a gist about it and following are the demos.

*

*Demo 1

*Demo 2 with flags based on official DOC of select2

A:
    <link href="select2.css" rel="stylesheet"/>

    <select id="e1">
        <option value="1">Albania</option>
        ...
        <option value="2">Germany</option>
    </select>


text:
Q: How to structure models and use Doctrine in Symfony2 I am switching over to Symfony for a project that I am working on but I need a little advice on how to structure the files when it comes to models and using doctrine.
I have a custom framework that I use, which in turns uses the MVC model. Pretty much all of my MYSQL database queries are stored in the models and I access them through the controller.
Now after looking at Symfony2, my interpretation is that "model" files in Symfony are called Servies. Is this correct?
I have also generated a number of Entities that correspond to my MYSQL database. My question here is do I place my custom Doctrine queries inside the Service files or do I create them inside the Entity files?
I'm a little unsure how to structure this.
Thanks

A:
Pretty much all of my MYSQL database queries are stored in the models

That's bad, but I'll mention about it later.

Now after looking at Symfony2, my interpretation is that "model" files in Symfony are called Servies. Is this correct?

Queries should be done in either repositories or in some cases in services.
If your query returns entities, then it should be repository for sure.

My question here is do I place my custom Doctrine queries inside the Service files or do I create them inside the Entity files?

Entities should be plain PHP objects. They shouldn't depend on anything than other entities. Entities actually doesn't even know anything about database. It's pure object oriented business logic.
Again, all DB queries should be in repositories or services.
I would suggest to go through Symfony Book in first place, to get idea of how "the Symfony way" works.

A: Symfony is not MVC framework:

Symfony2 is really about providing the tools for the Controller part, the View part, but not the Model part [...] Symfony2 is an HTTP framework; it is a Request/Response framework.

And it is great. Symfony allows to make your model as you wish without any restrictions. The Doctrine (ORM and/or DBAL) is a separate set of libraries. You can use any other library, or build your own persistence layer abstraction, or work with native SQL through PDO/MySQLi/etc.
Service is just an object that registered in the container and have some dependencies. Services can doing anything. They can represent your model, but it is not a requirement.

*

*Organizing Your Business Logic (The Symfony Best Practices)

*Doctrine ORM Best Practices


text:
Q: Is intersection a stopping time? Let $\tau$ and $\rho$ be stopping times with respect to filtration $(\mathbb{F}_t)_{t\ge0}$ and $A \in \mathbb{F}_\tau$. Show that $$A \cap\{\tau\le\rho\} \in \mathbb{F}_\rho$$
My work so far
Firstly let's consider discrete case, then :
$$\{\tau \le \rho\} = \bigcup_{s \le t}\{\tau=s\}\cap\{\rho\le t-s\}$$
First term of sum is in $\mathbb{F}_\tau$ and second one in $\mathbb{F_{\tau-p}} \subset \mathbb{F}_\tau$.
So the whole sum is in $\mathbb{F}_\tau$ so that $\{\tau \le \rho\}$. Also if $A \in \mathbb{F}_\tau$ then $A \cap\{\tau \le \rho\} \in \mathbb{F}_\tau$. where is my mistake ?


text:
Q: PHP form will not work Can someone explain why the following PHP form will not work. I have tried submitting a form, but the inbox does not receive the email. It is the correct email address.
Moreover, would it be better to use PHP instead of jQuery to alert "Your message has been successfully sent!"? Because at the moment it states the message was sent even though the inbox is not receiving it. If so, how?
HTML:

        <form id="validationForm">

            This is an anti 's'-to-the-'pam' field. Accordingly, do not delete or enter any information here.
            <input name="anti" id="antiInput"/>

            Name:
            <input name="name" id="name" class="input" required/>

            Email:
            <input name="email" id="email" class="input" required/>

            Subject:
            <input name="subject" id="subject" class="input" required/>

            Message:
            <textarea name="message" id="inputMessage" required></textarea>

            <input id="submitButton" type="submit" value="Submit" class="input"/>

        </form>

PHP:
<?php
$ToEmail = 'jono@s.co.uk';
$EmailSubject = 'Site contact form';

$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";

$MESSAGE_BODY = "Name: ".$_POST["name"]."";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."";
$MESSAGE_BODY .= "Subject: ".nl2br($_POST["subject"])."";
$MESSAGE_BODY .= "Message: ".nl2br($_POST["message"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>

jQuery:

A:  <form id="validationForm">

where have you defined the action?
Add method and action please
 <form id="validationForm" action="yourAction.php" method="post" >

If you want to post it there, just add the method='post'

A: If you plan on retrieving your form values with $_POST['myField'], you need to add the proper method attribute to your <form> tag.
Hence, use:
<form id="validationForm" method="post">

Because it is get by default.


text:
Q: Xcode error: unable to create directory '/[PATH_TO_APP]/[APP_NAME].app' (in target '[TARGET]' from project '[PROJECT]') The project is Objective-C based. The project was building previously building successfully, but now when I try to build, I'm getting the above error. I've seen some posts here with similar issues, but those errors specify permissions errors or give messages like 'no such directory', whereas mine does not, and their solutions do not resolve my problem. In fact, the error message I receive has almost no detail at all:
MkDir /[PATH_TO_APP]/[APP_NAME].app (in target '[TARGET]' from project '[PROJECT]')
cd /[PATH_TO_APP]/
/bin/mkdir -p /[PATH_TO_APP]/[APP_NAME].app

error: unable to create directory '/[PATH_TO_APP]/[APP_NAME].app' (in target '[TARGET]' from project '[PROJECT]')

I've also tried the following:

*

*Rename and rebuild the project.

*Restarted machine.

*Moved the project to a new directory.

*Reinstalled Xcode.

*Successfully created, built and ran a blank Objective-C app (which makes me think the error is not related to Xcode itself).

Note also that I recently archived and uploaded to the app store; I thought it might be something configuration related that I had forgotten about but haven't been able to locate anything.
Update: After navigating to the project folder in a terminal window and running ls -l command if can see the following for my .app:
[APP NAME].app -> /Users/[ME]/Library/Developer/Xcode/DerivedData/[APP NAME]-goiubutyqcjhzheixixhbodhavhe/Build/Intermediates.noindex/ArchiveIntermediates/[APP NAME]/InstallationBuildProductsLocation/Applications/[APP NAME].app

Note that that location (following the ->) does not exist.

A: You have a soft link (or symbolic link) where your app folder should be. Delete the soft link.

The following command creates a symbolic link at the command-line interface (shell):
ln -s target_path link_path

target_path is the relative or absolute path to which the symbolic link should point. Usually the target will exist, although symbolic links may be created to non-existent targets. link_path is the path of the symbolic link.
After creating the symbolic link, it may generally be treated as an alias for the target. Any file system management commands (e.g., cp, rm) may be used on the symbolic link. Commands which read or write file contents will access the contents of the target file. The rm (delete file) command, however, removes the link itself, not the target file. Likewise, the mv command moves or renames the link, not the target.
The POSIX directory listing application, ls, denotes symbolic links with an arrow after the name, pointing to the name of the target file (see following example), when the long directory list is requested (-l option). When a directory listing of a symbolic link that points to a directory is requested, only the link itself will be displayed. In order to obtain a listing of the linked directory, the path must include a trailing directory separator character ('/', slash).

— https://en.wikipedia.org/wiki/Symbolic_link


text:
Q: How to Remove the Card from the Google Pay Wallet I was developing an Android App and was able to save my Card in Google wallet using:-
https://pay.google.com/gp/v/save/{jwt_generated}
After, I add the card to the Pay App. How can I remove the card from the Pay App?
Does Google have an API that can help me to remove the added card from the Google App?
Thank you in Advance.

A: Based on the documentation, there is no API to remove the card.

*

*addmessage

*get

*insert

*list

*modifylinkedofferobjects

*patch

*update

The user needs to initiate the delete, this can be done be navigating the user to: https://pay.google.com/gp/v/object/{issuerId}.{identifier}
Once on this page they can use the three vertical dots in the top right corner of the pass to Remove the pass themselves.


text:
Q: Google Play: Does Beta Tester See Alpha Updates? I know how the process works for Alpha testing an app in Google Play and here is my scenario:
Alpha builds are linked to community A.
Beta builds are linked to community B.
A person (P) happens to be in both groups.
If I release alpha build one today, a beta build tomorrow, and another alpha build the next day, will person P see the latest alpha build, or will they be stuck with the latest beta?

A: If a person is in both builds, they will get the Alpha build. From the docs:
Please keep in mind that if a user is eligible for both alpha and beta versions, they'll receive the alpha version.


text:
Q: How to do something when I change a field in Django admin for a model? I have currently a boolean field called is_active on a model. Whenever I set this field manually in the Django admin to True (initially it it's false) I want it to do a certain action.
How can I trigger this field in Django to do this certain action when it is set to True?
I heard about a save_model() method but i don't know how it works.
class Company(models.Model):
    name = models.CharField(max_length=100, unique=True)
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.name

A: You can indeed override the save_model(..) method [Django-doc] in the ModelAdmin. The form parameter contains the Form in the model admin, and you can inspect the .changed_data [Django-doc] to inspect if the value changed:
from app.models import Company
from django.contrib import admin

class CompanyAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        field = 'is_active'
        super().save_model(request, obj, form, change)
        if change and field in form.changed_data and form.cleaned_data.get(field):
            # ... do a certain action
            pass

admin.site.register(Company, CompanyAdmin)


text:
Q: Can I call a method in a superclass in a python class hierarchy without using the name of the current class I understand that the best way to call a method in a superclass in python is to wirte:
class Foo(Bar):
    def foo(self):
        ...
        super(Foo, self).foo()
        ...

However, this means that if I change the name of the class Foo or I cut and paste the code in another class I have to remember to change the line that calls the method in the super class. Is there any way to get around this? At a minimum is annoying, at worst is very error prone.

A: In Python 3 you can write super() and it will fill in the class for you.
In Python 2 you need to write the name of the class. But changing the names of classes isn't exactly a common operation, so I don't really see that as much of a hardship. You just need to remember to search-and-replace for the name of the class if you change it -- but then you'll probably have to do that anyway, because its subclasses will refer to it by name as well.

A: You mean easy, safe and easily understandable way for everyone (as far as super() goes)?
Short answer: no.
Long answer: yes. There are several ways to do it. One of them is using a metaclass to automate super() creation during class initialization.
>>> class AutoSuper(type):
...     def __init__(cls, name, bases, dict):
...         super(AutoSuper, cls).__init__(name, bases, dict)
...         setattr(cls, '_%s__super'%name, super(cls))
...
>>>

So, the super() call to the class being created is assigned to the __super attribute. The name mangling has to be done manually, but the instances and subclasses will hit it accordingly. Now you don't even have to call super, just use the __super attribute.
>>> class A(object):
...     __metaclass__ = AutoSuper
...     def m(self):
...         print 'A'
...
>>>
>>> class B(A):
...     def m(self):
...         print 'B'
...         self.__super.m()
...
>>>
>>> class C(B):
...     def m(self):
...         print 'C'
...         self.__super.m()
...
>>> obj = C()
>>> obj.m()
C
B
A
>>>

Of course, I'm posting this for learning purposes only, I don't recommend using it. This is the kind of thing that borders on the excess of cleverness that some condemn in Python.


text:
Q: Sorting multi-level Perl hash (dynamically based on arithmetic) How do I sort(and print) a multi-level perl hash based on key value ?
%hash = (
  a => { k1 => 51, k2 => 52, k3 => 53 },
  b => { k1 => 61, k2 => 62, k3 => 63 },
  c => { k1 => 71, k2 => 72, k3 => 73 },
)

For example sort the above hash numerically based on the value of k2?
So it should print:
52,62,72

I wanted to know how I can expand sorting single level hashes to multilevel using
sort { $hash{$b} <=> $hash{$a} } keys %hash`

Edit
If I have another hash
my %property = ( a => 7, b => 6, c => 5 )

Can I sort %hash based on numerical value of  $hash{key}{k2} * $property{key}
using
#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
  a => { k1 => 51, k2 => 52, k3 => 53 },
  b => { k1 => 61, k2 => 62, k3 => 63 },
  c => { k1 => 71, k2 => 72, k3 => 73 },
);

my %property = ( a => 7, b => 6, c => 5 );

foreach (sort { ($hash{$a}{'k2'}*$property{$a}) <=>
                ($hash{$b}{'k2'}*$property{$b}) } keys %hash)
{
    printf("[%d][%d][%d]\n",
    $hash{$_}{'k2'},$property{$_},$hash{$_}{'k2'}*$property{$_});
}

result should be
72,52,62    as products are (360(72*5),364(52*7),372(62*6))

A: sort {$hash{$a}{'k2'} <=> $hash{$b}{'k2'}} keys %hash

The spaceship operator numerically compares the left-hand side with the right-hand side. It's most often seen in its simplest case, with
$a <=> $b

but in this case, you want to compare values from a hash and it can do that too.

A: Get a list of all values in the hash:
values %hash;

transform a list of hashrefs to the contents of the k2 entry:
map $_->{k2}, @list

oh, skip it if it's undef/doesn't exist:
map $_->{k2} // (), @list

sort a list numerically:
sort { $a <=> $b } @list

connect the dots:
sort { $a <=> $b } map { $_->{k2} // () } values %hash;

A: print join ",", sort { $a <=> $b } map { $_->{k2} } values %hash;

A: This program does as you ask. It first list the values of the k2 elements sorted by their value, then the same elements sorted by their product with the corresponding element of the %property hash.
Note that your expected output of 52,72,62 is wrong. The products are, as you say, a => 364, b => 372, c => 360 so the values should be sorted in the order c, a, b or 72, 52, 62
use strict;
use warnings;

my %hash = (
  a => { k1 => 51, k2 => 52, k3 => 53 },
  b => { k1 => 61, k2 => 62, k3 => 63 },
  c => { k1 => 71, k2 => 72, k3 => 73 },
);

my %property = ( a => 7, b => 6, c => 5 );

print join ',', map { $hash{$_}{k2} } sort {
  my ($aa, $bb) = map { $hash{$_}{k2} } $a, $b;
  $aa <=> $bb;
} keys %hash;
print "\n";

print join ',', map { $hash{$_}{k2} } sort {
  my ($aa, $bb) = map { $hash{$_}{k2} * $property{$_} } $a, $b;
  $aa <=> $bb;
} keys %hash;
print "\n";

output
52,62,72
72,52,62

A: Go with ysth's answer, but this syntax may make things a bit easier to understand:
sort { $hash{$a}->{k2} <=> $hash{$b}->{k2} } keys %hash;

Remember that $a and $b are hash keys assigned randomly by the sort. You have no idea what key is being assigned to $a or what key is being assigned to $b. At one time $a = "k1" and another time $b = "k1". You don't even know how many times the comparison is being done. All you know is that $a and $b are assigned to values of keys in your hash, and your job is to compare those two keys to get the results you want.
This isn't going to work:
sort { $hash{$a}->{k2} * $property{$a} <=> $hash{$b}->{k2} * $property{$b} } keys %hash;

because $a and $b will be assigned the values k1, k2, or k3. You don't have those keys in your %property hash. You'll probably get a bunch of warnings.
What do you do if your sorting algorithm is more complex than a simple one liner? You can specify a subroutine to do your sorting for you.
For example, instead of sorting on k2, you want to sort on the sum of all the values in your hash. That is $hash{a}->{k1} + $hash{a}->{k2} + $hash->{k3}... vs. $hash{c}->{k1} + $hash{c}->{k2}..., and I have no idea what any of the keys are. This subroutine will find all the keys in %{ hash{$a} } and add them up and compares them vs. all the keys in %{ hash{$b}  }:
sort sort_function keys %hash;

sub sort_function {

    # Sum of all the values in the hash %{ $hash{$a} }
    my $sum_a = 0;
    for my $hash_key ( keys %$hash{$a} ) {
       $sum_a += $hash{$a}->{$hash_key};
    }
    # Sum of all the values in the hash %{ $hash{$b} }
    my $sum_b = 0;
    for my $hash_key ( keys %$hash{$b} ) {
       $sum_b += $hash{$b}->{$hash_key};
    }
    return $sum_a <=> $sum_b;
}


text:
Q: Remove  and  from the_content? I have problem to remove <p> tag from the_content after upgrading to wp 3.6...
I'm used this in my theme function and worked fine, now this filter does not work,
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

A: Change the priority:
remove_filter('the_content', 'wpautop', 99);
remove_filter('the_excerpt', 'wpautop', 99);


text:
Q: In Java why aren't functions by default covariant with the return types and contravariant with the parameter type Take a look at the following code
If Functions were contravariant with the parameter type, this would work, since they are not, the compiler complains:
  // contravariant with the parameter type
  final Function<Object, Number> objToNUmberfoo = (v) -> 2;
  giveMeAFunction(objToNUmberfoo); // THIS GIVES A COMPILER ERROR

  public void giveMeAFunction(Function<Integer, Number> foo)
  {
         // do something
  }

Same goes here for covariance:
   // covariant with the return type
   final Function<Integer, BigDecimal> intToBigDecimal = (v) -> 2;
   giveMeAFunction2(intToBigDecimal); // THIS GIVES A COMPILER ERROR

   public void giveMeAFunction2(Function<Integer, Number> foo)
   {
          // do something
   }

To fix the compiler errors we should declare the methods respectively:
public void giveMeAFunction2(Function<? super Integer, Number> foo)
{
       // do something
}

and
public void giveMeAFunction2(Function<Integer, ? extends Number> foo)
{
       // do something
}

What I really don't get here is why isn't the java compiler allowing it by default ?
I cannot think of any situation where this wouldn't be safe at runtime...maybe I am wrong here ?
And more importantly what would be the consequences of that ?
Why we need to explicitly opt in for that ?


text:
Q: MSP430 - Assembly ISR doesn't get run Trying to write an ISR in assembly for when a button gets pressed on my MSP430.  I've followed some instructions around the web, but I'm having trouble "linking" the ISR to the button press.
Specifically, I'm trying to get a button attached to port P1.1 to run my ISR.
Steps I've done
1) Enable the interrupt for P1.1 P1IE |= BIT1;
2) Selected H->L transition: P1IES |= BIT1;
3) Cleared flag register: P1IFG &= ~BIT1;
4) Enabled global interrupts: __enable_interrupt();
Still though, I think I'm missing something.   I don't understand how to tell the program to run my ISR, and unfortunately I have not found any guidelines on the web that are very clear about this part. Here is my ISR in assembly:
    .cdecls C,LIST,"msp430.h"
    .sect ".text:_isr"

buttonISR:      push R4
                mov.w #1000, R4
loop:           dec.w R4
                jnz loop
                reti

    .sect BUTTON_ISR
    .word buttonISR
    .end

A: Okay I figured it out.  Apparently the interrupt vector table is a hard-coded memory space.  From the datasheet, I found that the interrupt vector for port 1 was 0xFFDE, which translates to INT47, thus I changed the bottom part of my assembly program to:
.sect ".int47"
.word buttonISR
.end

And now it works beautifully!


text:
Q: Populating SELECT with large JSON data set via ColdFusion (Lucee) very slow Please forgive me if I have provided more information than required for this question. :D
I am building an application that pulls large JSON data-sets from a remote machine.  However, I am working within a secure environment that separates application servers with firewalls, etc.  Because of this I have had to do a bit of fudging (using SSH) to get the data I need.  I have requested additional ports to be opened so I could bypass using SSH but was denied.
Here is the physical path to get my data over SSH:  My Application Server -> Secure Server with Curl -> Multiple unique application servers with JSON data.
To abide by the security rules; I wrote the CFML code below on my application server.  (server is running Linux, Lucee 4.5, MySQL and Apache)
<cfset secure_server = "secure_server.my.example.com">
<cftry>
    <cfexecute
    name="/usr/bin/ssh"
    arguments="#secure_server# ./RemoteDirectory/server_list.sh"
    timeout="10"
    variable="server_list">
    </cfexecute>
    <cfcatch type="any">
        <cfoutput>
            #cfcatch.message#
#cfcatch.detail#

        </cfoutput>
    </cfcatch>
</cftry>

The above code simply SSHs to the secure server and runs a script called server_list.sh.  The important bit of the script is below:
curl -s -k -b cookie.jar -c cookie.jar https://unique_application_server/Path/To/Server/list -H "Accept:application/json"

That curl script returns a JSON string that looks similar (but with far more data) to this:
{
  "os" : "Linux ",
  "fqdn" : "server1.my.example.com",
  "disk_status" : "OK",
  "system_model" : "HP",
  "type" : "Server"
},
{
  "os" : "Linux ",
  "fqdn" : "server2.my.example.com",
  "disk_status" : "OK",
  "system_model" : "Dell",
  "type" : "Server"
},

The amount of JSON data sent, at this time, is about 3MB.  However, that data will grow exponentially over time.
Once I get the JSON back to my application server; I use CF's deserializeJSON function then grab just the field I need.  In this case its the FQDN field.  Since the data from the JSON is a full domain, I needed to chomp just the hostname.  The "new_label" code takes care of that.  There is probably a better REGEX or a better method than the one I am using, but this works.
<cfset arrayOfStructs = deserializeJson(server_list)>
<select multiple="multiple" class="searchable" name="searchable[]">
    <cfloop array="#arrayOfStructs#" index="PARENT">
        <cfset new_label = ReReplace(PARENT.fqdn, "(.[^.]*)$", "")>
        <cfset new_label = ReReplace(new_label, "(.[^.]*)$", "")>
        <cfset new_label = ReReplace(new_label, "(.[^.]*)$", "")>
        <cfoutput><option value="#PARENT.fqdn#">#new_label#</option></cfoutput>
    </cfloop>
</select>

The above code populates the field with the hostnames of servers from the JSON.  The OPTION field would look something like this:
<option value="server1.my.example.com">server1</option>

A couple things of note that may (or may not) help.  I am using jQuery and a multi-select.js that turns the SELECT into a side-by-side field.  The multi-slect is from here: http://loudev.com/
Second, all servers in the path are fairly powerful and are all connected over 10gb.  So besides the firewalls between, there should not be any bottle necks.
No matter the browser I use, the code above works, but is rather slow when it populates the hostname field.  Because the JSON data I am pulling updates about every minute, I am not able to store it long term in the database on my application server.
Knowing all that, my question is:  How could I speed up the form field so the user does not have to wait for the page to load 2500+ servernames?
Could I leverage jQuery or the MySQL database to speed things up without running into stale data?  Could it simply be my method of getting the hostname from the FQDN?  Should I scrap this method and try something else?  Have I overlooked something here on Stack that has my answer?  (I spent a lot of time searching Q/A here but found nothing.  Perhaps I was not looking hard enough.)
Any other information you nice folks need?  Thanks! :D
UPDATE --
@Alex.  I do that very test now.  Code is below.  Good suggestion though!
<cfset tickBegin = GetTickCount()>

<cfset tickEnd = GetTickCount()>
<cfset testTime = tickEnd - tickBegin>
<cfoutput>Page(#testTime#ms)</cfoutput>

As far as caching the data, that is part of my question.  How to cache?  What method to use?  How can I cache the JSON without displaying stale data?  Is this an instance where AJAX would be useful?
UPDATE 2 --
Could I be going about this the wrong way?  I know that sometimes you will need to display large amounts of data back to your users.  Would simply adding a BlockUI and a progress bar stating please wait be an OK solution?  I would prefer to figure out a better solution honestly but I am open to suggestions for sure! Thoughts?