text:
Q: In jQuery, is selecting by class or id faster than selecting by some other attribute? Basically, is
$("#someid")

or
$(".someclass")

faster than
$("[someattr='value']")

I would imagine that it is (that is, selection by id is fastest, then class, then attribute), but does anyone know for sure?

A: ID is absolutely the fastest.  Part of the reason is that ID is supposed to be unique, so the API stops searching after the ID is found in the DOM.
If you must use a class or attribute selector, you can improve performance by specifying the optional context parameter.
For example...
$(".someclass", "#somecontainer")

Where somecontainer is something like a div, surrounding an element with class someclass.  This can offer a huge performance benefit in the cases where somecontainer comprises a small fraction of the DOM.

UPDATE:
I did some tests a couple years ago around the context parameter.  After reading the comments below I was curious if anything has changed.  Indeed, it seems the scene has changed somewhat with today's browsers.  Maybe it also has to do with improvements in jQuery?  I don't know.
Here are my results with 10,000 iterations (code is below):
IE9
$(".someclass") - 2793 ms
$(".someclass", "#somecontainer") - 1481 ms
Chrome 12
$(".someclass") - 75 ms
$(".someclass", "#somecontainer") - 104 ms
Firefox 3.6
$(".someclass") - 308 ms
$(".someclass", "#somecontainer") - 357 ms
So among these big 3 modern browsers, the context parameter only seems to help IE9.  Older browsers will also benefit from the context parameter.  But considering the prevalence of each of these browsers and averaging everything out, the net gain is somewhat of a wash now.
And here's the code in case anyone wants to try it themselves...

jQuery Selector Performance: Context vs No Context

$(".someclass")

        --- ms

$(".someclass", "#somecontainer")

        --- ms

a

b

c

a

b

c

a

b

c

a

b

c

a

b

c

a

b

c

someclass

a

b

c

a

b

c

a

b

c

a

b

c

a

b

c

A: ID and class selectors, at least when used by themselves, tend to be faster, whether for jQuery or for CSS. This is due largely to the fact that browsers have optimized algorithms for IDs and classes in their DOM/CSS engines.
In modern browsers with recent versions of jQuery, any selector strings that are understood as supported CSS selectors by a browser will be handled by document.querySelectorAll(), offering maximum performance as long as standard CSS selectors are used. Non-standard selectors or older browsers are taken care of by jQuery and/or the Sizzle library, which do their best to make use of the DOM's get-element(s) methods to traverse the DOM.
The most important thing to remember is that performance will vary from browser (version) to browser (version) because of differing DOM implementations. At least, that's how I believe things are.

A: ID is unique and if you only want to select one/first element here the equivalent

$("#someid") => 75,695 ops/sec, fastest
$(.unique_class') => 45,257 ops/sec, 40% slower : only one class on page
$(".someclass").first() => 42,217 ops/sec, 46% slower : multiple class on page, select first element
$(".someclass:eq(0)") => 18,324 ops/sec, 76% slower : multiple class on page, select element at selected index

Test url: http://jsperf.com/jquery-selector-speed-tests/98

A: The id will always be fastest as it it unique on the page.  The class "may" be faster than an attribute but it depends.
The real kicker here is selection of a class within and ID may NOT be faster than just selection of the class.  It will depend on the page and browser.  In my testing, selection of a complex page with a limited number of elements with a "class" where the parent of the class element had an id such as:

stuff

stuff

a selector such as $('.iamin','#iamout') was not always as fast as $('.iamin')
Not all browsers support select by classname (natively), but modern/newer ones do and thus it might offer better performance depending upon which browser you have.
If you need to have optimum performance you will need to test your exact page.

A: Selecting by ID is the fastest, because it maps directly to getElementByID, the other 2 has to check each element to determine the selected elements.
If you must select using class or attribute, then try enclosing the search in a ID.
ex.
$("#someid .someclass")

A: Id is fastest, because it is the only element that can have that identifier.  Many objects could possibly have the same class name.  Someone could verify this, but it would seem like the document would not need to be traversed any further once the id was found. For classes this may not be the case??  HTH


text:
Q: belong to vs originate from Which of the following sentences sound natural?
I think the second sentence sounds a lot more natural and I suppose the first sentence would be a bit odd. Am I correct?
Which country does pasta belong to?
What country does paste originate from /come from?
Thanks for reading.

A: When I see "belong to" I think about money. "This money belongs to me because I earned it". Food (pasta) on the other hand belongs to the one who made it in their own kitchen or wherever. But the idea can originate from some country. So you are right, the second sentence sounds more natural.

A: 'Belong to' means being owned by. So if you made the pasta in your kitchen, it belongs to you.
'Originate from' means to happen for the first time ever. So wherever pasta was made the first time, that's where it originated from. So this is more natural.
Side note- You can belong to any person. You originated from your parents. It's as simple as that for pasta too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: altering the clustered index in sql How do I alter the clustered index on PK to change the index column or include extra column?
Do I drop and create using the create index?
CREATE CLUSTERED INDEX dateQ ON dbo.devTable(DateCreated, Id)

Clicking drop and create on SSMS spit the following. I have no idea what's going on inside the with parameters. I want to include the datecreated to my index.
USE [devDb]
GO

ALTER TABLE [dbo].[devTable] DROP CONSTRAINT
[PK__devTab__3214EC07339391EF] WITH ( ONLINE = OFF )
GO

SET ANSI_PADDING ON
GO

ALTER TABLE [dbo].[devTable] ADD PRIMARY KEY CLUSTERED
(
 [DateCreated] ASC, //I want to add date created to the index
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS =
ON) ON [PRIMARY]
GO

A: Ok, the below sample script should help you out.
USE Sandbox;
GO
--Very simple sample table
CREATE TABLE IndexSample (ID int IDENTITY(1,1),
                          DateCreated date,
                          CONSTRAINT PK_ID PRIMARY KEY CLUSTERED (ID ASC));
GO

--You can only have one CLUSTERED INDEX on a table. As you've declared the ID as CLUSTERED PRIMARY KEY you'll need to drop it
--Note that if this key is referenced anywhere eklse, you'll need to drop those keys as well.
ALTER TABLE IndexSample DROP CONSTRAINT PK_ID;

GO
--Now, we need to recreate the PRIMARY KEY, but not CLUSTER it.
ALTER TABLE IndexSample ADD CONSTRAINT PK_ID PRIMARY KEY NONCLUSTERED (ID ASC);
--Then create your other Foreign keys and constraints again
GO
--Now create your Clsutered index
CREATE CLUSTERED INDEX DateCreated_ID ON IndexSample (DateCreated ASC, ID ASC);

GO
--Clean up
DROP TABLE IndexSample;

As I note in my comments, you'll need to DROP your existing constraint, as you can't "uncluster" an INDEX. Once you've dropped it, you can then create a new NONCLUSTERED PRIMARY KEY. Finally, you then add your new CLUSTERED index.


text:
Q: Record the sound and play the same sound at same time in iphone I want to record the sound and play the same sound through my application at same time.
Had recorded the sound :-
 NSString *soundFilePath = [docsDir
                               stringByAppendingPathComponent:@"sound.caf"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    NSDictionary *recordSettings = [NSDictionary
                                    dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithInt:AVAudioQualityMin],
                                    AVEncoderAudioQualityKey,
                                    [NSNumber numberWithInt:16],
                                    AVEncoderBitRateKey,
                                    [NSNumber numberWithInt: 2],
                                    AVNumberOfChannelsKey,
                                    [NSNumber numberWithFloat:44100.0],
                                    AVSampleRateKey,
                                    nil];

    NSError *error = nil;

    audioRecorder = [[AVAudioRecorder alloc]
                     initWithURL:soundFileURL
                     settings:recordSettings
                     error:&error];

    if (error)
    {
        NSLog(@"error: %@", [error localizedDescription]);
    } else {
        [audioRecorder prepareToRecord];
        [audioRecorder record];
    }

-(void)StopRecord{
[audioRecorder stop];
 NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];

    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer *newPlayer =
    [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error: nil];
    if([soundFileURL isFileURL]){
        printf("isFileURL\n");
    }
    [newPlayer prepareToPlay];
    [newPlayer setDelegate: self];
       [newPlayer play];

}

Now by this..i record the sound and when i click some method the recording get stop and start playing..What should i do..that it play the sound the same moment i start recording..

A: I got the solution by using SC_listner.
[[SCListener sharedListener] listen];

   if ([SCListener sharedListener] != nil)
    {
        Float32 percentage = [[SCListener sharedListener] peakPower];
        }

By doing this..i get the detect the pitch of the real time


text:
Q: I am new to vue & just starting with the basics and getting the following error [plugin:vite:import-analysis] Failed to resolve import "./HeaderComponent.vue" from "src\main.js". Does the file exist?
I want to print the message "hello world"
Instead of this, getting error!!
Help!
App.vue
<template>
<header-component />
</template>
<script>
import HeaderComponent from './HeaderComponent.vue'
export default{
name:'App',
components:{
HeaderComponent,
}
};
</script>

HeaderComponent.vue
<script >
import HeaderComponent from './HeaderComponent.vue'
export default{
data() {
return{
message:'hello world',
}
},
components:{
HeaderComponent,
}
};
</script>

<template>
<h1> {{message}} </h1>
</template>

main.js
import { createApp } from "vue";
import App from "./App.vue";
import HeaderComponent from "./HeaderComponent.vue";
createApp(App).mount("#app");
export default {
components: {
HeaderComponent,
},
};

Please help and guide me.
What i am doing wrong here?:)


text:
Q: Twilio Name Look-up for SMS For incoming SMS messages I'd like to be able to match the senders cell phone number with the numbers owners name. Is anyone doing this using Twilio? They have an option for voice calls but not one for SMS. Thanks.

A: In the twilio lookup api.
https://www.twilio.com/docs/api/lookups
// Download the Node helper library from twilio.com/docs/node/install
// These are your accountSid and authToken from https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

const client = require('twilio')(accountSid, authToken);

client.lookups.v1
  .phoneNumbers('+16502530000')
  .fetch({type: 'caller-name'})
  .then((number) => console.log(number.carrier.type, number.carrier.name));

You want to retrieve the callername, this depends on whether you are using nodejs or not, but other examples are posted.


text:
Q: System.UnauthorizedAccessException: 'Access is denied location UWP I try to make a simple weather aplication but i get an exception.
I have location activated. I try to run in emulator for phone, not working
the exception
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace TryToMakeWeatherApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var pos = await LocationManage.GetLocation(); //Here i'm geting the error
            var lat = pos.Coordinate.Latitude;
            var lon = pos.Coordinate.Longitude;

            var weather = WeatherMap.GetWeather(lat, lon).ToString();
            WeatherTxt.Text = weather;
        }
    }
}

This is code from MainPage.
And this is the LocationManage class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;

namespace TryToMakeWeatherApp
{
    class LocationManage
    {
        public async static Task<Geoposition> GetLocation()
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            var geolocator = new Geolocator { DesiredAccuracyInMeters = 0 };

            var position = await geolocator.GetGeopositionAsync();

            return position;

        }
    }
}

A: in your package.manifest file have to turn on this capability too


text:
Q: Need to populate value into a row using INNER JOIN I have stored contact in one table and their relationship in one table and child details in another. I need to populate "child name" of each parent using their childid ?
 CREATE TABLE contact_table(
 contactid NUMBER(3)
,contactname VARCHAR2(30)
,contactage NUMBER(2)
);

CREATE TABLE contact_maritalstatus(
statusid NUMBER(3)
,contactid NUMBER(3)
,contactgender VARCHAR2(8)
,contactstatus VARCHAR2(10)
);
CREATE TABLE contact_relation(
relationid NUMBER(3)
,contactid NUMBER(3)
,partnerid NUMBER(3)
,childid NUMBER(3)
);
CREATE TABLE contact_child(
childid NUMBER(3)
,contactid NUMBER(3)
);

SELECT cb.contactname,cm.contactgender,cm.contactstatus,cr.childid
FROM contact_table cb
 inner join contact_maritalstatus cm  on cb.contactid = cm.contactid
 inner join contact_relation cr on cb.contactid = cr.contactid;

A: You haven't provided the foreign keys so we have to infer your data model. However it seems parents and children are both in contact_table, and the contact_relation joins spouses to each other and parents to children. If so, you simply need join to contact_table a second time, using table and column aliases to distinguish the two instances:
SELECT cp.contactname as parent_name
       , cm.contactgender
       , cm.contactstatus
       , cr.childid
       , cc.contactname as child_name
FROM contact_table cp
 inner join contact_maritalstatus cm  on cp.contactid = cm.contactid
 inner join contact_relation cr on cb.contactid = cr.contactid
 inner join contact_table cc on cc.contactid = cr.childid


text:
Q: Find longest repeated substring with matched parentheses in ruby Consider a set of strings as follows:
aa(bb(c)dd)
aeeff(bb(cd)eee)
(bb(c)dd)(bb(cd(eee

Even though the longest repeated non-overlapping substring is (bb(cd)eee (10 chars), the longest repeated substring with matched parentheses is (bb(c)ee) (9 chars).
I can easily find the longest non-overlapping repeated substring, but how can this be extended to matching parentheses?

A: As I understand you want the longest string within a single line that begins with "(" and ends with ")" and contains "balanced parentheses". In addition, the substring is to be a "repeated" substring, but that has not been defined, so I've disregarded that requirement.
balanced_parens? (below) is from my answer here.
def longest_balanced(str)
  str.lines.map { |s| longest_by_line(s.chomp) }.max_by(&:size)
end

def longest_by_line(str)
  str.size.downto(1).find do |n|
    str.each_char.each_cons(n) do |a|
      s = a.join
      return s if (s =~ /\A\(.*\)\z/)  && balanced_parens?(s)
    end
  end
  nil
end

def balanced_parens?(str)
  pstr = str.gsub(/[^()]/,"")
  while pstr.gsub!("()", "")
  end
  pstr.empty?
end

str =<<_
aa(bb(c)dd)
aeeff(bb(cd)eee)
(bb(c)dd)(bb(cd(eee
_

longest_balanced str
  #=> "(bb(cd)eee)"


text:
Q: Neovim built-in LSP shows No code actions available for Python files When I open a python file, diagnostics seem to be working fine. Then I navigate to a line with a diagnostic error, press the shortcut to invoke code actions ('<space>ca' in my case) and I get a message 'No code actions available'. I have tried running it for different errors, like the following ones:
b =1  #E225 missing whitespace around operator
from jinja2 import StrictUndefined  #'jinja2.StricUndefined' imported but unused
import jjj # import-error: Unable to import 'jjj'

I have tried two LSP servers so far: pyright and pylsp, both gave me the same 'No code actions available'
I've seen a similar question but JavaScript asked here and it suggest installing a plugin but that didn't work for me.

A: Both Pyright and Pyls don't provide any diagnostic solving code actions like jdtls for java unfortunately...
I would recommend checking out their individual repositories on github for further information and development:
pyls,
pyright
For more insight on what your language server is capable of, run the following command in vim:
:lua print(vim.inspect(vim.lsp.buf_get_clients()[1].resolved_capabilities))

It will output the capabilities of the language server you are attached to in the current buffer.
For example this is the output for Pyright with no special configurations:
{
  call_hierarchy = true,
  code_action = {
    codeActionKinds = { "quickfix", "source.organizeImports" },
    workDoneProgress = true
  },
  code_lens = false,
  code_lens_resolve = false,
  completion = true,
  declaration = false,
  document_formatting = false,
  document_highlight = {
    workDoneProgress = true
  },
  document_range_formatting = false,
  document_symbol = {
    workDoneProgress = true
  },
  execute_command = true,
  find_references = {
    workDoneProgress = true
  },
  goto_definition = {
    workDoneProgress = true
  },
  hover = {
    workDoneProgress = true
  },
  implementation = false,
  rename = true,
  signature_help = true,
  signature_help_trigger_characters = { "(", ",", ")" },
  text_document_did_change = 2,
  text_document_open_close = true,
  text_document_save = true,
  text_document_save_include_text = false,
  text_document_will_save = false,
  text_document_will_save_wait_until = false,
  type_definition = false,
  workspace_folder_properties = {
    changeNotifications = false,
    supported = false
  },
  workspace_symbol = {
    workDoneProgress = true
  }
}

Currently Pyright only supports the organize imports code action.
Keep in mind some lsp's don't provide code actions at all, but generally they do provide the basic needs such as go-to definition/declaration, hover info, documentation, signature help, renaming and references.


text:
Q: Displaying comments under specific posts im trying to assign a list of posts with a comment section that is unique to that post. My problem is that instead of displaying specific comments under specific posts, all the comments are displayed on every single post.
Im using 2 database tables: "posts: id, title, subtitle, content"
and "comments: comment_id, post_fk (foreign key attached to the posts id), uid, date, message.
blog.php, where posts are echoed and comments are submitted and then posted through getComments
// fetch data from posts and echo them into a post

$sql = "SELECT * FROM posts ORDER BY id DESC";
$result = mysqli_query($conn,$sql);

while ($row = mysqli_fetch_array($result)) {
    $title = $row['title'];
    $subtitle = $row['subtitle'];
    $content = $row['content'];
?>

<?php echo $title; ?> - <?php echo $subtitle; ?>

<?php echo $content; ?>

// echo the comment field and then get comments from the getComments function echo
echo    "<form method='posts' action='".setComments($conn)."'>
            <input type='hidden' name='uid' value='Anonymous'>
            <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
            <textarea name='message'></textarea>

            <button type='submit' name='commentSubmit'>Comment</button>
    </form>";

        getComments($conn);

comments.php, where the setComments and getComments functions are defined
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {

    $uid = $_POST['uid'];
    $date = $_POST['date'];
    $message = $_POST['message'];

    $sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', '$date', '$message')";
    $result = mysqli_query($conn, $sql);
    }
}

function getComments($conn) {
    $sql = "SELECT
    c.uid,
    c.date,
    c.message
FROM comments AS c
    LEFT JOIN posts AS p ON
    c.post_fk = p.id
    WHERE c.post_fk = p.id
";
    $result = mysqli_query($conn, $sql);
    while ($row = $result->fetch_assoc()) {
        echo $row['uid'];
        echo $row['date']."

";
        echo $row['message']."

";

I have been experimenting with the LEFT JOIN without any promising results. Im very new to PHP, but im suspecting that I have to add some additional values to the comment form that determines which post the comment belongs to. I hope this information is substantial enough and sorry if my code is messy!
Thank you
(edit)
setcomment.php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
    $comment_id = $_POST['comment_id'];
    $uid = $_POST['uid'];
    $date = $_POST['date'];
    $message = $_POST['message'];

    $sql = "INSERT INTO comments (comment_id, uid, date, message) VALUES ($comment_id, $uid, $date, $message)";
    $stmt = mysqli_prepare($sql);
    mysqli_stmt_bind_param($stmt, "iiss", $id, $uid, $date, $message);
    $result = mysqli_stmt_execute($stmt);
    }
}

comments table
posts table

A: getComments() needs a parameter that specifies which post you want the comments from, and then it needs a WHERE clause that only gets comments from that post.
There's no need to join with the posts table in getComments, since it's not using anything from that table.
function getComments($conn, $post) {
    $sql = "SELECT
        c.uid,
        c.date,
        c.message
    FROM comments AS c
    WHERE c.post_id = $post
    ORDER BY c.date
    ";
    $result = mysqli_query($conn, $sql);
    while ($row = $result->fetch_assoc()) {
        echo $row['uid'];
        echo $row['date']."

";
        echo $row['message']."

";
    }
}

Then you call it as:
getComments($conn, $row['id']);

In the form,
action='".setComments($conn)."'>

makes no sense. The action attribute has to contain the URL of a script that processes all the form fields. You're calling the setComments() function when creating the page, and putting its return value (which is empty, since it has no return statement) in the action attribute. That should be something like:
action='setComments.php'>

You can then add a hidden field to the form with the post ID:
<input name='postid' type='hidden' value='{$row['id']}'>

setComments.php can then use $_POST['postid'] to get the proper post_id of the comment being entered. The setComments function should look like this (using a prepared statement to protect against SQL-injection):
function setComments($conn) {
    if (isset($_POST['commentSubmit'])) {
        $id = $_POST['postid'];
        $uid = $_POST['uid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO comments (post_id, uid, date, message) VALUES (?, ?, ?, ?)";
        $stmt = mysqli_prepare($sql);
        mysqli_stmt_bind_param($stmt, "iiss", $id, $uid, $date, $message);
        $result = mysqli_stmt_execute($stmt);
    }
}


text:
Q: 1960's Batman and Superman? Has there ever been a team-up of Batman from the 1960's tv series with a superman of the same period? I don't think it ever happened in the tv series, but say in a comic or cartoon, even if it's a recent comic/cartoon but obviously intended to be the same universe as the original tv series?

A: Superman and Batman "crossed over" almost as soon as they were in print. Superman debuted in 1938 and the first Batman/Superman co-venture was in 1940 albeit in separate stories in the same issue.

The first "shared story" was in 1952 in Superman #76 in a story entitled 'The Mightiest Team in the World' where Superman and Batman are forced to share a cabin on a cruise liner.

There were numerous shared story comics in the 1960s (embodying many of the traits of the TV Batman and Superman) including "The Composite Superman!" in which both characters are literally combined by a freak accident and "The Sons of Superman and Batman" set in an alternate universe in which both characters have children.

You can find a wealth of covers and additional info here.
Per Sumbuddy's comment below, I've investigated the Annuals that were published while the TV series was on the air and found this. It appears to be a crossover between Superman and Batman with batman modelled on the 1966 TV series.


text:
Q: KVO method firing twice on NSManagedObject property As the title says, I'm observing an NSManagedObject property with KVO. The method override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) is firing twice : The first time when assigning  a new value to the property, and the second time when I'm saving the context in CD. I'm doing that immediately after setting the property value. I'm having another problems in the code because of that, my question is why is this happening, and what would be the right way to do it (set the property, saving the context and firing the method once). Maybe I shouldn't save the context immediately after?

A: I believe my above comment (intuition) is actually correct. It seems to be undocumented, but observed on all platforms that mergeChangesFromContextDidSaveNotification (i.e. when your MOC saves) triggers a refresh on all properties.
cf: KVO notifications after mergeChangesFromContextDidSaveNotification
a suggestion for how to handle the behavior: kvo code, in general, should be idempotent and fast, precisely because it could get called often, i.e. when the keypath is set.


text:
Q: jqplot problem with highlighter I'm using the jQuery plugins provided by jqplot for charting.
When I use seriesDefaults : { fill : true }, the highlighter (tooltip) stops working.
Here is the code I'm using.
var line1=[['23-May-08', 578.55], ['20-Jun-08', 566.5], ['25-Jul-08', 480.88], ['22-Aug-08', 509.84],
    ['26-Sep-08', 454.13], ['24-Oct-08', 379.75], ['21-Nov-08', 303], ['26-Dec-08', 308.56],
    ['23-Jan-09', 299.14], ['20-Feb-09', 346.51], ['20-Mar-09', 325.99], ['24-Apr-09', 386.15]];

var plot = $.jqplot('chartarea', [line1],
                   {
                    seriesDefaults : { fill : true },
                    title          : "Area chart with tooltip",
                    axes           : {
                                      xaxis : { renderer : $.jqplot.DateAxisRenderer },
                                      yaxis : { tickOptions : { formatString : '$%.2f'} }
                                     },
                    highlighter    : { show : true, sizeAdjust : 7.5},
                    cursor         : { show : false }
                   });

Is there any way to get the highlighter working in fill : true case.
Thanks..

A: You need to hack intro the jqplot js file to make this work. I managed to get this to work, but the fill area under the line won't change its transparency on hover any more.
You can look in the JS file for switch (s.renderer.constructor) { and in the following case case $.jqplot.LineRenderer: comment the code for the if (s.fill) { and leave just the code for the else.
You'll get an error somewhere in $.jqplot.ShapeRenderer.prototype.draw = function(ctx, points, options) { because points is not defined, but you can use an if here to check if points is set.
This may not be the best solution, but we really needed the tooltips for a filled line, and this was, for now, the best option.


text:
Q: MySQL service won't start, Error 5 The MySQL56 service will not start giving me the error:
Windows could not start the MySQL56 service on Local Computer.

Error 5: Access is denied.

The last time I was able to get into MySQL was the 11th, but the next day the service would not start. I have full write permissions for the directory that it is installed in and it is not a mapped drive.
From the .err file, it looks like the last shutdown never completed. The last entry is:
2014-07-11 16:48:31 2864 [Note] InnoDB: Starting shutdown...

whereas other showdown events give the Shutdown complete log.
Any ideas about how to get it back up and running?
Windows 7 Home Premium,
MySQL 5.6

A: *

*Download Microsoft SysInternals' ProcessMonitor and run it as an administrator.

*Start the MySQL Service

*Once the error happens, stop ProcessMonitor from capturing more events (File Menu -> untick Capture Events)

*Search (Ctrl+F) for ACCESS DENIED - it shows up in the Result column

If you find any denied entries, the information will show you what process was running, and what file or registry key it was trying to access. That's the one you need to sort out.
Double click on a row to open the properties, look at the 'process' tab, that can show you which user account was being used by the process.
How you fix it depends on what's wrong - maybe it's a file in use that can't be opened, maybe it's file or registry permissions you can change, maybe something is running as the wrong account... but this should tell you some details you can work with. What's denied, and where.


text:
Q: How to fix "Authentication plugin 'caching_sha2_password' cannot be loaded" with mysql@5.6 Database creation fails with Authentication plugin 'caching_sha2_password' cannot be loaded error.
Above error occurs when I run following command:
$ RAILS_ENV=test rake db:create
Error message:
Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/Cellar/mysql@5.6/5.6.46/lib/plugin/caching_sha2_password.so, 2): image not found
Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "reconnect"=>true, "pool"=>5, "socket"=>"/tmp/mysql.sock", "username"=>"root", "password"=>nil, "database"=>"ht_test"}, charset: utf8, collation: utf8_unicode_ci
(if you set the charset manually, make sure you have a matching collation)

I know other developers had similar issues with mysql@8.* . Thats why I switched to mysql@5.6 . Still I am facing this issue.
Please suggest possible solutions.
Thanks

A: try using this, it worked for me
ALTER USER 'yourusername'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'youpassword';


text:
Q: Store FileReader base64 as variable? I'm trying to store the base64 value of an uploaded file/resume into a variable but I keep receiving this error:

Uncaught (in promise) TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

Here is the structure of my HTML:

Application form

        <form action="#"  class="applicantForm">

                    Resume
                    <input class="form-control" type="file" name="resume">

            <button class="submit" type="submit">Apply Now</button>
        </form>

Here is the structure of my JavaScript:
$(document).ready(function() {

const ApplyOpeningPayloadBuilder = function() {

let payload = {
    "fields": [],
    "source" : "new fellow"
};

return {
    withFile: function(key, encoded_data, filename) {
        let value = {};
            value.encoded_data = encoded_data;
            value.file_name = filename;
            this.withKeyValue(key, value);
            return this;
            },
             build: function() {
                    return payload;
              }
    }
}

function getBase64(file, onLoadCallback) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

let files = document.getElementById('file').files;

$('.applicantForm').on('submit',async function(e) {

e.preventDefault();
let promise = getBase64(files);
let encoded_file4 = await promise;

apply_for_an_opening_payload_builder.withFile("resume", encoded_file4, this.value);

let payload = apply_for_an_opening_payload_builder.build();
console.log("Log payload:", payload);

       });
    })

I tried using a promise without async and that didn't work either. I do think it's needed.
I can't think of any other approach or any other work around.
Any ideas?

A: You have a couple errors in your example.  First, your input field doesn't have an id attribute so document.getElementById('file').files; won't resolve to an element.  You're passing the files array to getBase64, but getBase64 is expecting one file.  Finally, you need to read the files on form submit, not on page load.  Below is an updated script.

Application form

        <form onsubmit="return false"  class="applicantForm">

                    Resume
                    <input class="form-control" type="file" name="resume" id="file">

            <button class="submit" type="submit">Apply Now</button>
        </form>

$(document).ready(function() {
    const ApplyOpeningPayloadBuilder = function() {

        let payload = {
            "fields": [],
            "source": "new fellow"
        };

        return {
            withFile: function(key, encoded_data, filename) {
                let value = {};
                value.encoded_data = encoded_data;
                value.file_name = filename;
                this.withKeyValue(key, value);
                return this;
            },
            build: function() {
                return payload;
            }
        }
    }

    function getBase64(files, onLoadCallback) {
        return new Promise(function(resolve, reject) {
            var reader = new FileReader();
            reader.onload = function() {
                resolve(reader.result.substr(reader.result.indexOf(',') + 1));
            };
            reader.onerror = reject;
            reader.readAsDataURL(files[0]);
        });
    }

    $('.applicantForm').on('submit', async function(e) {
        e.preventDefault();

        let files = document.getElementById('file').files;

        let promise = getBase64(files);
        let encoded_file4 = await promise;
        alert(encoded_file4)
        apply_for_an_opening_payload_builder.withFile("resume", encoded_file4, files[0].name);

        let payload = apply_for_an_opening_payload_builder.build();
        console.log("Log payload:", payload);

    });
})


text:
Q: Sorting arrays of paired numbers and removing duplicates or overlaps? How can I sort two arrays of coordinates in numerical order by the start coordinates e.g.
my @starts = (100,100,200,300,400,500,525);
my @ends   = (150,125,250,350,450,550,550);

but choose the biggest difference if there are two matching in either the starts or ends list? E.g.
my @uniq_starts = (100,200,300,400,500);
my @unique_ends = (150,250,350,450,550);

Any help greatly appreciated!
Also, how about if the lists are like this?
my @starts = (100,125,200,300,400,500,525);
my @ends   = (150,175,250,350,450,550,550);

This would give me the following for the in between values:
-25, 25, 50, 50, 50, -25

I would need the following output:
my @uniq_starts = (100,200,300,400,500);
my @unique_ends = (175,250,350,450,550);

So my in between values are:
25, 50, 50, 50

I can get around this by just removing and ignoring any negative values, as I can imagine this would make things much more complicated.

A: How about using Set::IntSpan?
use Set::IntSpan;

my @starts = (100,100,200,300,400,500,525);
my @ends = (150,125,250,350,450,550,550);
my @spec = map { "$starts[$_]-$ends[$_]" } 0..$#starts;
my $p = Set::IntSpan->new(@spec);
print "$p\n";

A: Using Set::IntSpan:
use Set::IntSpan;

my @starts = (100,100,200,300,400,500,525);
my @ends   = (150,125,250,350,450,550,550);

my (@uniq_starts, @unique_ends);

for my $s (Set::IntSpan->new([map [$starts[$_], $ends[$_]], 0 .. $#starts])->spans) {
  push @uniq_starts, $s->[0];
  push @uniq_ends, $s->[1];
}

print join(",", @uniq_starts), "\n";
print join(",", @uniq_ends), "\n";

Or poor man's solution:
sub spans {
  my @s = sort {$a->[0] <=> $b->[0] or $a->[1] <=> $b->[1]} @_;
  my @res;
  while (@s > 1) {
    if ($s[0][1] >= $s[1][0]) {
      splice @s, 0, 2, [$s[0][0], $s[1][1]];
    } else {
      push @res, shift @s;
    }
  }
  push @res, @s;
  return @res;
}

my @starts = (100,100,200,300,400,500,525);
my @ends   = (150,125,250,350,450,550,550);

my (@uniq_starts, @unique_ends);

for my $s (spans(map [$starts[$_], $ends[$_]], 0 .. $#starts)) {
  push @uniq_starts, $s->[0];
  push @uniq_ends, $s->[1];
}

print join(",", @uniq_starts), "\n";
print join(",", @uniq_ends), "\n";

You can check that it works flawless.
More functional spans version:
sub spans {
  return spans_(sort {$a->[0] <=> $b->[0] or $a->[1] <=> $b->[1]} @_);
}

sub spans_ {
  if (@_ > 1 and $_[0][1] >= $_[1][0]) {
    splice @_, 0, 2, [$_[0][0], $_[1][1]];
    goto &spans_;
  } elsif (@_) {
    return shift, spans_(@_);
  } else {
    return;
  }
}

P.S.: If somebody thinks that perl is concise language, compare same algorithm spans function in erlang. I don't even know how it would look in APL or J:
spans(L) -> spans_(lists:sort(L)).

spans_([{A, B}, {C, D}|T]) when B >= C ->
  spans_([{A, D}|T]);
spans_([H|T]) -> [H|spans_(T)];
spans_([]) -> [].

A: Use some list transformations:
my @starts = (100,100,200,300,400,500,525);
my @ends   = (150,125,250,350,450,550,550);

my (%starts_seen, %ends_seen);
my @ar = sort { $a->[0] <=> $b->[0] }   # result in ascending sort order of @starts
         grep ! $starts_seen{$_->[0]}++,
         sort { $b->[0] <=> $a->[0] }   # descending sort b -> a
         grep ! $ends_seen{$_->[1]}++,
         sort { $b->[1] <=> $b->[1] }   # descending sort b -> a
         map  [ $starts[$_],$ends[$_] ],
         0 .. $#starts;

print "($_->[0],$_->[1]) " for @ar;

this results in:
(100,150) (200,250) (300,350) (400,450) (500,550)

Regards
rbo
Edit: modified code to reflect sort order of sorts


text:
Q: mix of asp.net and VSTO project I have  a web site using asp.net mvc4, and a VSTO automation (client side) that need to update and get some data from my web site.
Actually I'm trying to use HttpWebRequest object to perform the dialog. between VSTO and web.
For now I'm thinking on return some jSon objects from web to VSTO. But how can I do to send from VSTO to web ?
Is better approach send XML ? if yes what is the current way to do this in c#.

A: You can make a C# object that matches the object sent via JSON, and then use have it deserialize via the .net default serializer or json.NET.  Investigate the DataContract attribute for more information.


text:
Q: Convert a set of unique numbers to another set of unique numbers within range (0 to 25) Lets say I have a set of unique numbers [5, 123, 49176, 30982, 542] now I want to convert the numbers and get another set of unique numbers (integers) which will be in range of 0 to 25
Can any one suggest any algorithm that can help me solve this problem ?

A: You are going to normalize them?
raw =  [5, 123, 49176, 30982, 542]

normalization = [(i-min(raw))/(max(raw)-min(raw))*25 for i in raw]
print(normalization)

It will give you: (all elements are guaranteed to be unique)
[0.0, 0.059994712330438675, 25.0, 15.749628846271177, 0.2730267840800472]

If the elements of result are limited to be integer:
import random
raw =  [5, 1, 23, 49176, 30982, 542]

if len(raw) > 26: #there's no way to get more than 26 unique elements from 0~25 integers
    print("mission impossible")
else:
    print(random.sample(range(26), len(raw)))

It will give you (for example):
[23, 4, 13, 10, 18, 24]

Those are two compromising way for you. But according to you comment, you actually need a injective function whose domain are all integers and codomain are integers in [0,25]. Unfortunately, it's a mission impossible.

A: (Assuming integers)
You can sort the elements, and give each element its index (in the sorted list). Assuming you have less then (or exactly) 26 numbers, you will get the desired range. You can also avoid sorting if you can allow not deterministic result for the same set by just setting the numbers as the current order (iteration order, for example) of the set.
Note that if you want some general case hashing, it cannot be done - if your range is greater then 26 - you will have duplicates. This is coming directly from Pigeonhole principle, where the range is the pigeons, and the range [0,25] is the Pigeonholes.

A: Use each number as a seed for a random function, and then go through and make sure you don't have any duplicates.
This will also break down if you have a set larger than 25, like Amit said.


text:
Q: Can Node.js's clustering feature leverage multiple CPUs? Let's say I buy a dual cpu motherboard that runs two 16 core cpus. Would this return 32?
const os = require('os')
const cpuCount = os.cpus().length // 32

And could I use Node.js Cluster to leverage all 32 cores, or would the extra CPU not be recognized / Node.js be unable to leverage a second processor?


text:
Q: When running a t-test with a Control and Experimental group, are both groups Samples? Or is the Control group a Population? When running a t-test with a Control and Experimental group, are both groups Samples? Or is the Control group a Population? I am pretty confused on this, since I've pretty much only ever worked with Samples, but have no idea when to switch to a population

A: If you use a 2-sample t test, then you're assuming data from Treatment and Control
groups are both samples. In many cases the two samples are of about the same size.
If you're designing an experiment, trying to know how much data to collect in order
to have a reasonable chance of detecting a difference between the two groups, and
you have a given number of subjects available, then it's most efficient to put half of the subjects (at random) into each group.
However, sometimes you have a situation in which huge control group already exists
(say 100,000) and you imagine you can randomly take a smaller random sample (say 100) from the same population to use for a treatment group. Then it might not make much difference whether
you do a two sample t test on the two groups, or you do a one-sample t test comparing
the sample mean from the small control group against the mean of the huge
group--regarded as a population mean.
Examples 1: Two small groups of about the same size.
Generate fake data for illustration:
set.seed(1234)
x.c = rnorm(100, 50, 5)
x.t = rnorm(100, 51, 5)

A boxplot show the treatment values (top) tend to be a little larger.
boxplot(x.c, x.t, col="skyblue2", horizontal=T)

A two-sample t test finds a significant difference (at the 5% level) between the mean $49.22$ of the control group and the mean $51.21$ of the treatment group
because the P-value $0.0064 < 0.05 = 5\%.$
t.test(x.c, x.t)

        Welch Two Sample t-test

data:  x.c and x.t
t = -2.7635, df = 197.85, p-value = 0.006258
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -3.4101030 -0.5699462
sample estimates:
mean of x mean of y
 49.21619  51.20622

Example 2: Huge control group and small treatment group.
set.seed(1235)
x.c = rnorm(100000, 50, 5)
x.t = rnorm(100, 51, 5)

A boxplot shows that the smaller control values (upper boxplot) tend
to be larger. [It is typical for a huge normal sample to show many boxplot 'outliers'.]
 boxplot(x.c, x.t, col="skyblue2", horizontal=T)

A two-sample t test finds a significant difference (at the 5% level) between the mean $59.92$ of the control group and the mean $51.09$ of the treatment group
because the P-value $0.036 < 0.05 = 5\%.$
t.test(x.c, x.t)

       Welch Two Sample t-test

data:  x.c and x.t
t = -2.1268, df = 99.195, p-value = 0.03592
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -2.0685429 -0.0717558
sample estimates:
mean of x mean of y
 50.01799  51.08814

Example 3: Considering the huge control group as a population.
The mean of the control group is taken as $\mu = 50.02$ and we compare the sample mean of the control group to $\mu.$ In the boxplot below, the vertical line indicates
the position of $\mu.$
boxplot(x.t, col="skyblue2", horizontal=T)
 abline(v = 50.02, col="red")

A one-sample t test finds a significant difference (at the 5% level) between the population mean $50.02$ of the control "population" and the sample mean $51.09$ of the smaller treatment group
because the P-value is $0.036 < 0.05.$ Here we are ignoring any variability in the 'control' group, taking $\mu = 50.02$ as an established value. Even with a 'control population'
as large as $100\,000$ this may be risky.
t.test(x.t, mu=50.02)   # Null population mean shown

    One Sample t-test

data:  x.t
t = 2.1238, df = 99, p-value = 0.03618
alternative hypothesis: true mean is not equal to 50.02
95 percent confidence interval:
  50.09021 52.08607
sample estimates:
mean of x
 51.08814


text:
Q: How to generated the below XMlStructure Based on list size? How to generated the below XMl Based on list size?
Hi,
the below list has 3 records. I need to generate the below XML Structure Based on list size.
List<Product_for_Sample_Literature__c>  ProductLineItems =[SELECT id,Sample_Literature_Request__c,Batch_Information__c,Detail__c,Product__r.Name,Quantity__c,Product_APN__c  from Product_for_Sample_Literature__c WHERE Sample_Literature_Request__c ='a0Eb0000001UVLF'];

If list size has one, the XMl should like this.And assign the values of list to below elements
<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

If list size has two, the XMl should like this.
<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

the list size has 3 ,
<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>3</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

etc, how i can acheive this ?can anyone help me on this

A: Try with this
Apex provides classes that enable you to work with XML content using the DOM (Document Object Model).
Execute below code in anonymous window,
List<Product_for_Sample_Literature__c>  ProductLineItems =[SELECT id,Sample_Literature_Request__c,Batch_Information__c,Detail__c,Product__r.Name,Quantity__c,Product_APN__c  from Product_for_Sample_Literature__c WHERE Sample_Literature_Request__c ='a0Eb0000001UVLF'];

    Dom.Document doc = new Dom.Document();
    Dom.Xmlnode rootNode = doc.createRootElement('ProductLineItems', null, null);
    Integer SFDCLineID=0;

    for (Product_for_Sample_Literature__c Product: ProductLineItems ) {
        Dom.Xmlnode ProductNode = rootNode.addChildElement('Items', null, null);
        ProductNode.addChildElement('SFDCLineID', null, null).addTextNode(++SFDCLineID);
        ProductNode.addChildElement('Material', null, null).addTextNode(Product.Batch_Information__c);
        ProductNode.addChildElement('Quantity', null, null).addTextNode(Product.Quantity__c);

    }
    system.debug(doc.toXmlString());

Resulting log, you will be getting the XML String like below
<?xml version="1.0" encoding="UTF-8"?>
<ProductLineItems>
<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>Product 1</Material>
            <Quantity>3</Quantity>

</Items>
<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>Product 2</Material>
            <Quantity>4</Quantity>

</Items>
</ProductLineItems>

A: You can generate XML using the classes in the Dom namespace, but there's an easier way (well, easier for me at least).
You can use Visualforce to generate XML.
<!--
    You'll probably need to create a small controller extension.
    showHeader, standardStyleSheets, sidebar, applyBodyTag, and applyHtmlTag are all set
      to false to prevent the HTML that Salesforce usually generates automatically
      from appearing in the XML

-->
<apex:page standardController="Product_for_Sample_Literature__c" extensions="MyExtension" showHeader="false" standardStyleSheets="false" sidebar="false" contentType="text/xml" applyBodyTag="false" applyHtmlTag="false" cache="false">
<!-- I think there's an issue with printing the xml header tag, so we'll need to take care
  of that elsewhere -->
<apex:repeat value="{!records}" var="lineItem">
    <!--
    There's no problem using non-visualforce, non-html tags here.
    We don't need to do anything special to make up our own tags (XML is just a bunch of
      arbitrarily defined tags, after all).
    With the contentType being text/xml, your browser won't try to render these
      tags as HTML.
    -->
    <Items>
        <!-- There's no standard way to get the current index number of an apex:repeat.
        There are a few different ways you could achieve this, but I'll leave that
          for you to figure out.
        -->
        <material>{!lineItem.Batch_Information__c}</material>
        <quantity><!-- the code/merge syntax statement in here will be similar to the one above --></quantity>
    </Items>
</apex:repeat>

The extension class you would need is really straightforward.
public class MyExtension{
    // Variable to hold the records that we need to query
    List<Product_For_Sample_Literature__c> records{get;set;}

    // The same, basic constructor signature for a controller extension
    public MyExtension(ApexPages.StandardController con){
        // Just like if this were for a regular visualforce page, you'll need to query
        //   for all the fields that you'll be using
        // We need to use ApexPages.currentPage() to get the page parameters that you
        //   pass in.
        records = [SELECT Id, Batch_Information__c, Quantity__c FROM Product_For_Sample_Literature__c WHERE Sample_Literature_Request = :ApexPages.currentPage().getParameters().get('reqNum')];
    }
}

Using these to generate XML in Apex is also pretty simple.
PageReference myXMLGenerator = Page.MyVisualforcePage;
myXMLGenerator.getParameters.put('reqNum', 'a0Eb0000001UVLF');
String xmlResult;

if(!Test.isRunningTest()){
    // As of API v34.0, pageReference.getContent() is considered a callout.
    // That means that we can't run this code in a unit test, which is the primary
    //   drawback to this approach.
    xmlResult = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' + myXMLGenerator.getContent().toString());
}

For very short and simple XML structures, like the one in your example, this approach probably involves more code/typing than just using the classes in the Dom namespace. However, for more complicated XML (especially if you have a few levels of nested tags), this approach stands head and shoulders above trying to generate XML with Apex alone.
The other benefit to this approach is that, being a visualforce page, it's pretty simple to just open a tab in your browser, navigate to /apexPages/MyVisualforcePage?reqNum="a0Eb0000001UVLF", and look at the resulting XML to verify that the XML looks correct (no need for anonymous apex and debug statements).


text:
Q: Reduce space between col-lg in bootstrap in responsive mode I am using bootstrap 4. Below is my html

A

B

This code works fine on the website. However, on mobile or when I resize the browser to be very narrow, the 2 classes col-lg-6 stack on top of each other with quite a lot vertical space between them. I wonder is there any way to reduce that space?

A: space could be caused by either margin or padding... to set:

*

*padding bottom to zero, use class pb-0

*padding top to zero, use class pt-0

*margin bottom to zero, use class mb-0

*margin top to zero, use class mt-0
this is the bootstrap way... more info here


text:
Q: Are there simple expressions for skew Schur polynomials corresponding to hook-shaped diagrams? I am a physicist who has been studying (skew) Schur polynomials recently. I am particularly interested in skew Schur polynomials $s_{\lambda/\mu}$, where $\lambda$ is a representation corresponding to a hook-shaped Young diagram. Such skew Schur polynomials are of course only non-zero in the case where $\mu$ corresponds to a hook-shaped diagram as well.
For general representations $\lambda$ and $\mu$, skew Schur polynomials have rather complicated expressions. I suspect, however, that these expressions simplify in the case of representations corresponding to hook-shaped diagrams, but I have thus far failed to find evidence for this in the literature. I therefore have the following two questions:

*

*Are there simple expressions for skew Schur polynomials $s_{\lambda/\mu}$, where $\lambda$ and $\mu$ correspond to hook-shaped diagrams?

*Consider pairs of hook-shaped diagrams $\lambda,~\mu$ and $\kappa,~\nu$ such that $\lambda \neq \kappa$ or $\mu\neq \nu$ (i.e. $\lambda_i \neq \kappa_i$ for some $i$, where $\lambda_i$ is the length of row $i$ in the diagram of $\lambda$, similarly for $\mu_i$ and $\nu_i $).  Are there such pairs of hook-shaped diagrams which satisfy $s_{\lambda/\mu} = s_{\kappa/\nu}$? It is known that $s_{\lambda/\mu}$ equals $s_{\lambda/\mu}=s_{({\lambda/\mu})^r}$, where $({\lambda/\mu})^r$ is obtained from ${\lambda/\mu}$ by rotating the skew shape by 180 degrees (see e.g. Stanley - Enumerative combinatorics, Exercise 7.56 a), but this does not give non-trivial identities for the case of hook-shaped diagrams.
As stated above I am a physicist by training, so I apologize in advance for any abuse of language or notation. Any help with these questions would be much appreciated.

A: For two hooks $\lambda = (p,1^q)$ and $\mu = (r,1^s)$ the skew Schur polynomial $s_{\lambda/\mu}$ is equal to $e_{q-s}h_{p-r}$, as long as $\mu$ is nonempty. It simple to describe in terms of partitions the resulting expression in terms of Schur polynomials (using the Pieri formula), and all of the coefficients in the expansion are $1$. All partitions involved are hooks.
To see that this holds, note that the skew diagram consists of a column of length $q-s$ and a row of length $p-r$ that are edge disjoint. Using the formula for skew Schur polynomials in terms of semistandard tableaux, a tableau on the column is independent of a tableau on the row, so we end up with the product of the sum over all tableaux on the column with the sum over all tableaux on the row. For the column, we get the elementary symmetric function $e_{q-s}$ and for the row we get the complete symmetric function $h_{p-r}$, so the skew Schur polynomial is their product.
For your second question, given the expression above it is clear that we have equality whenever $q-s=q'-s'$ and $p-r=p'-r'$.


text:
Q: How to submit input type = range in flask While trying to submit input type = range i'm getting "Bad request error".
HTML:
{% extends "base.html" %} {% block content %}
  <link rel="stylesheet" href="css/style.css" />

    <form method="post" action="#">

                0

                100

            <input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
                  this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[1].style.width=value+'%';
                  children[5].style.left=value+'%';
                  children[7].style.left=value+'%';children[11].style.left=value+'%';
                  children[11].childNodes[1].innerHTML=this.value;" />
            <input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
                  this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
                  var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
                  var children = this.parentNode.childNodes[1].childNodes;
                  children[3].style.width=(100-value)+'%';
                  children[5].style.right=(100-value)+'%';
                  children[9].style.left=value+'%';children[13].style.left=value+'%';
                  children[13].childNodes[1].innerHTML=this.value;" />
            <input id="search" type="submit" value="SEARCH" href="#"></input>

    </form>

<form action="/lobbies" method="POST">
  <input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
  <input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
  <input type="submit" value="CREATE" href="#"></input>
</form>

 {% for lobby in data%}

       {% print lobby['GameValue']%}

      Join

{%endfor%}

 {% endblock %}

Flask:
@app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
    if "username" in session:
        coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
            "balance"
        ]
        ProfilePicture = "https://robohash.org/" + str(session["username"])
        color = str(session["color"])
        PlayerID = session["PlayerID"]
        if request.method == "POST":
            LobbyValue = request.form['LobbyValue']
            if "IsVisible" in request.form:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
            else:
                response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
            LobbyID = response['LobbyID']
            return redirect(url_for('lobby',LobbyID=LobbyID))

        data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
        return render_template(
            "lobbies.html",
            coins=coins,
            ProfilePicture=ProfilePicture,
            color=color,
            data=data.json(),
        )
    else:
        return redirect(url_for("login"))

I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:

So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.


text:
Q: Xamarin Sample Apps for iPad and iPhone? I wonder why none of the Xamarin Prebuilt Apps at https://www.xamarin.com/prebuilt support both iPad and iPhone? They all have the same design on each resolution. Especially Apps like 'Acquaint' would be perfect on iPad to have the contact list on the left and the details on the right. But instead it just has the same design like the iPhone Version.....
Are there any reasons why Xamarin does not offer samples with different designs depending on the client resolution? Are there somewhere else some examples?
Many thanks!

A: You might want to take a look at our Creating Mobile Apps with Xamarin.Forms Book First Edition by Charles Petzold.
I work on the same team as Charles and I know it's a topic he's covered in detail. The full book should be available soon too.
BTW, we are looking into creating some detailed, annotated cross-platform app samples that do all the goodies that a typical modern app would be expected to have.

A: I do not know of any of the stock Xamarin examples that use OnIdiom, but it just a matter of time to code them...hahahah, always just a matter of time and code. (I'm sure the Xamarin guys can chime in on this one):
Xamarin.Forms.OnIdiom Class
<OnIdiom.Phone>Vertical</OnIdiom.Phone>
<OnIdiom.Tablet>Horizontal</OnIdiom.Tablet>

In terms of finding examples that use the Xamarin.Forms XAML OnIdiom I would search Github for OnIdiom, there a few OSS examples of phone/tablet switching floating around there as I used at least one as a template to do a quick phone/tablet prototype for a client.


text:
Q: Unable to create pyspark DataFrame from Datastore in azureml-sdk (version 1.12.0) I am trying to read contents from a CSV file into Spark DataFrame using azureml-sdk using following code but an exception is being thrown.
Code throwing exception
import pyspark.sql as spark
from azureml.core import Dataset
dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, file_path)], header = False)
sdf: spark.DataFrame = dataset.to_spark_dataframe()
sdf.show()

Exception
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/data/dataset_error_handling.py in _try_execute(action, operation, dataset_info, **kwargs)
    100         else:
--> 101             return action()
    102     except Exception as e:

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/dataprep/api/_loggerfactory.py in wrapper(*args, **kwargs)
    178                 try:
--> 179                     return func(*args, **kwargs)
    180                 except Exception as e:

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/dataprep/api/dataflow.py in to_spark_dataframe(self)
    763         self._raise_if_missing_secrets()
--> 764         return self._spark_executor.get_dataframe(steps_to_block_datas(self._steps), use_sampling=False)
    765

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/dataprep/api/sparkexecution.py in get_dataframe(self, steps, use_sampling, overrides, use_first_record_schema)
    136                              overrides,
--> 137                              use_first_record_schema)
    138

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/dataprep/api/sparkexecution.py in _execute(self, blocks, export_format, use_sampling, overrides, use_first_record_schema)
    169                                           + lariat_version + '.')
--> 170             raise e
    171

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/dataprep/api/sparkexecution.py in _execute(self, blocks, export_format, use_sampling, overrides, use_first_record_schema)
    160             if export_format == ExportScriptFormat.PYSPARKDATAFRAMELOADER:
--> 161                 return module.LoadData(secrets=secrets, schemaFromFirstRecord=use_first_record_schema)
    162             else:

/tmp/spark-6ce53791-c8e4-4db0-bd37-bedb53a1ef1e/userFiles-dda6cd30-5d1e-48cf-af87-9c7c2a4b8038/loaderb9bc01c2b40c4b7aa86a95d343021e0c.py in LoadData(secrets, schemaFromFirstRecord)
      8 def LoadData(secrets=dict(), schemaFromFirstRecord=False):
----> 9     pex = Executor("S4ddf53ee8d5f4173bd3dcf4b51d78247", "dprep_2.11", "0.116.0", "42315", "39a925e4-9ae9-4588-93c4-5433250b7f73")
     10     jex = pex.jex

/tmp/spark-6ce53791-c8e4-4db0-bd37-bedb53a1ef1e/userFiles-dda6cd30-5d1e-48cf-af87-9c7c2a4b8038/Executor.py in __init__(self, scalaName, dprepMavenPackageName, dprepMavenPackageMatchingVersion, pythonHostChannelPort, pythonHostSecret)
     54             pythonHostChannelPort,
---> 55             pythonHostSecret)
     56

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1568         return_value = get_return_value(
-> 1569             answer, self._gateway_client, None, self._fqn)
   1570

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:

Py4JJavaError: An error occurred while calling None.com.microsoft.dprep.execution.PySparkExecutor.
: java.lang.NoClassDefFoundError: Could not initialize class com.microsoft.dprep.integration.azureml.AmlPySdkInvoker$
    at com.microsoft.dprep.execution.PySparkExecutor.<init>(PySparkExecutor.scala:79)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:238)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

During handling of the above exception, another exception occurred:

AzureMLException                          Traceback (most recent call last)
<ipython-input-30-c546b1aded42> in <module>
      2 from azureml.core import Dataset
      3 dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, file_path)], header = False)
----> 4 sdf: spark.DataFrame = dataset.to_spark_dataframe()
      5 sdf.show()
      6

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/data/_loggerfactory.py in wrapper(*args, **kwargs)
    124             with _LoggerFactory.track_activity(logger, func.__name__, activity_type, custom_dimensions) as al:
    125                 try:
--> 126                     return func(*args, **kwargs)
    127                 except Exception as e:
    128                     if hasattr(al, 'activity_info') and hasattr(e, 'error_code'):

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/data/tabular_dataset.py in to_spark_dataframe(self)
    187         return _try_execute(dataflow.to_spark_dataframe,
    188                             'to_spark_dataframe',
--> 189                             None if self.id is None else {'id': self.id, 'name': self.name, 'version': self.version})
    190
    191     @track(_get_logger, custom_dimensions={'app_name': 'TabularDataset'}, activity_type=_PUBLIC_API)

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/data/dataset_error_handling.py in _try_execute(action, operation, dataset_info, **kwargs)
    102     except Exception as e:
    103         message, is_dprep_exception = _construct_message_and_check_exception_type(e, dataset_info, operation)
--> 104         _dataprep_error_handler(e, message, is_dprep_exception)
    105
    106

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/azureml/data/dataset_error_handling.py in _dataprep_error_handler(e, message, is_dprep_exception)
    143         raise AzureMLException(message, inner_exception=e)
    144     else:
--> 145         raise AzureMLException(message, inner_exception=e)
    146
    147

AzureMLException: AzureMLException:
    Message: Execution failed unexpectedly due to: Py4JJavaError
    InnerException An error occurred while calling None.com.microsoft.dprep.execution.PySparkExecutor.
: java.lang.NoClassDefFoundError: Could not initialize class com.microsoft.dprep.integration.azureml.AmlPySdkInvoker$
    at com.microsoft.dprep.execution.PySparkExecutor.<init>(PySparkExecutor.scala:79)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:238)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

    ErrorResponse
{
    "error": {
        "message": "Execution failed unexpectedly due to: Py4JJavaError"
    }
}

However, I can read and print the data with the following code i.e. create as a Panda's DataFrame.
Working code
dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, file_path)], header = False)
#sdf: spark.DataFrame = dataset.to_spark_dataframe()
sdf: pd.DataFrame = dataset.to_pandas_dataframe()
print(sdf.head(3))

A: Dataset doesn't support Scala 2.12 runtime at the moment. The team is working on it and will address the feature gap soon. Stay tuned!


text:
Q: Dynamically altering object types on instantiation I have a MetaClass that, at the moment, simply returns an obj of a class.
From this MetaClass, I derieved two different classes. The difference in the classes is a dictionary that gets passed to __init__ for one of the classes but not for the other one.
If this dict only contains one single entry, I want python to return an instance of the other class instead of the one that was actually called.
class _MetaClass(type):
    def __new__(cls, name, bases, dct):
        return super(_MetaClass, cls).__new__(name, bases, **dct)

class Class1(object):
    __metaclass__ = _MetaClass

    def __init__(self, someargs):
        pass

class Class2(object):
    __metaclass__ = _MetaClass

    def __init__(self, someargs, kwargs):
        if len(kwargs) == 1:
            return Class1(someargs)
        else:
            pass

TestInstance = Class2("foo", {"bar":"foo"})    #should now be Class1 instance because only one item in dct

If the dict, like in this case, has only len(dct) == 1, then it should create an instance of Class1 with the "foo" passed to its __init__ instead of returning an instance of Class2 as it normally would
I tried to implement the __new__ and __init__ methods for the MetaClass, but I could not figure out how to check the arguments that are actually passes on new class instantiation

A: You could create a handlerMethod to deal with the issue
def handler(yourDict):
    if len(yourDict) == 1:
         return Class2(yourDict)
     else:
         return Class1(yourDict)

and then call the handler instead of the constructor
TestInstance = handler(yourDict)


text:
Q: How I can remove the cursor from below query? + DECLARE @U_CHK   TABLE (
            ACCOUNT_ID NUMERIC
           ,START_NO NUMERIC
           ,END_NO NUMERIC
           ,SEQ_NO NUMERIC
           ,USED INT
        )

DECLARE @ST_NO NUMERIC
       ,@END_NO  NUMERIC
       ,@ACID    NUMERIC
       ,@SEQ_NO  NUMERIC

DECLARE cCurChk           Scroll CURSOR
FOR
    SELECT DISTINCT AC_ID
          ,ST_DOC_NO
          ,ST_DOC_NO
          ,END_DOC_NO
    FROM   AC_LVL_INVEN
     GROUP BY
           ST_DOC_NO
          ,END_DOC_NO
          ,AC_ID

OPEN cCurChk
FETCH NEXT FROM  cCurChk INTO @ACID,@ST_NO,@SEQ_NO,@END_NO
WHILE @@Fetch_Status=0
BEGIN
    WHILE (@SEQ_NO<=@END_NO)
    BEGIN
        INSERT INTO @U_CHK
        VALUES
          (
            @ACID
           ,@ST_NO
           ,@END_NO
           ,@SEQ_NO
           ,0
          )
        SET @SEQ_NO = @SEQ_NO+1
END FETCH NEXT FROM cCurChk
INTO @ACID,@ST_NO,@SEQ_NO,@END_NO
END   CLOSE cCurChk  DEALLOCATE cCurChk

UpDate @U_CHK
SET USED = 1 FROM @U_CHK Ch INNER JOIN FA_Trans FA(NOLOCK) ON Fa.
    Account_ID = Ch.Account_ID AND CONVERT(VARCHAR(10) ,Ch.Seq_No) = Fa.Instrument_No
    WHERE FA.Status>4 AND STATUS<>12 AND Ac_Head_Type<>1 AND Trans_type = 'Debit'

A: You can use a merge statement to do the insert / update in place of the cursor.  Here is an example
MERGE dbo.FactBuyingHabits AS Target
USING (SELECT CustomerID, ProductID, PurchaseDate FROM dbo.Purchases) AS Source
ON (Target.ProductID = Source.ProductID AND Target.CustomerID = Source.CustomerID)
WHEN MATCHED THEN
    UPDATE SET Target.LastPurchaseDate = Source.PurchaseDate
WHEN NOT MATCHED BY TARGET THEN
    INSERT (CustomerID, ProductID, LastPurchaseDate)
    VALUES (Source.CustomerID, Source.ProductID, Source.PurchaseDate)

Take a look at Technet - Inserting, Updating, and Deleting Data by Using MERGE


text:
Q: C# Unicode Parts in Console string I have a code:
string command = @"adb -s 127.0.0.1:62001 install \"D:\Рабочий_стол\Facebook.apk\"";
// clear string: adb -s 127.0.0.1:62001 install "D:\Рабочий_стол\Facebook.apk"

Process p = new Process();

p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;

p.Start();

p.StandardInput.WriteLine(command);

p.StandardInput.Flush();
p.StandardInput.Close();
p.WaitForExit();

return p.StandardOutput.ReadToEnd();

In output:
(c) Љ®аЇ®а жЁп Њ ©Єа®б®дв (Microsoft Corporation). 'ᥠЇа ў  § йЁйҐл.
C:>adb -s 127.0.0.1:62001 install "D:\Рабочий_стол\Facebook.apk"
Performing Streamed Install
C:>
But nothing starts :(
if i run manually this line ("D:\Рабочий_стол\Facebook.apk") in the console - works fine
Problem with "Рабочий_стол"
also i tried a simpler command: D:\Рабочий_стол\Task.txt - the same problem
Can be copied the file, for example, to the root of the D drive where there are no Russian characters in path... but its no good :)
I'l tried many options with encodings and StreamWriters, but nothing work fine in my situation


text:
Q: Change the style of a checkbox in a QTreeWidget without affecting the check marks in Maya? I am having trouble stylizing my tristate check boxes with children in my  QtWidgets.QTreeWidget()
I am trying to use:
css ='''
QTreeView {background-color: #1e1e1e;}
QTreeView::indicator {border: 1px solid white;}
'''
self.file_tree.setStyleSheet(css)

The background color changes fine. But, once I add the solid border or try changing the background color of the checkbox the tristate checks are no longer visible. The old styles no longer apply. I do not have access or do not know how to access the QT resources as Maya has their own version with different images. i.e. the check box png.
Adding the parent directories of the tree with:
parent_widget = DirectoryTreeWidgetItem(parent_widget)
parent_widget.setText(0, self.base_name)
parent_widget.setFlags(parent_widget.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)

Adding QTreeWidetItems through:
# add the items
for child_file in self.child_files:
    # child = QtWidgets.QTreeWidgetItem(parent_widget)
    child = AssetTreeWidgetItem(parent_widget)
    child.setFlags(child.flags() | QtCore.Qt.ItemIsUserCheckable)
    child.setText(0, os.path.basename(child_file))
    child.setCheckState(0, QtCore.Qt.Unchecked)
    child.setFilePath(child_file)

I am looking to change the border and/or the background color to make the boxes more visible rather than blending in with the dark background thee tree view.
Edit: I added color style sheet to designer and it also killed my checkbox. My goal is still the same make the checkbox more visible.

A: Since setStyleSheet overrides the current style I was able to achieve the results I am looking for using QtGui.QPalette() instead:
    file_tree_palette = QtGui.QPalette()
    file_tree_palette.setColor(QtGui.QPalette.Window, QtGui.QColor(255, 255, 255))
    file_tree_palette.setColor(QtGui.QPalette.Base, QtGui.QColor(30, 30, 30))
    file_tree_palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(93, 93, 93))
    self.file_tree.setPalette(file_tree_palette)

I hope this can help someone who is working with style sheets.


text:
Q: cakephp pagination query with hasAndBelongsToMany I'm not too great with sql anyway but I'm having trouble getting a particular query to work.
I have archives and images as tables. They are connected by a archives_images table. I have the $id for the archive I want and I'm trying to paginate the Images which have records in the archives_images table beside the archive_id I have.
The code I'm trying (This is the most correct one - I've been trying for a while now)
$this->Paginator->settings = array(
        'conditions' => array(
                            'Image.user_id'=>$this->Auth->user('id'),
                            'ArchivesImage.archive_id'=>$id
                            ),
        'limit' => 48
    );

But obviously that's giving me an error because there's no 'ArchivesImage.archive_id' in 'where clause'
Can anyone help me out?

A: Try this
 $this->Paginator->settings = array(
    'joins'=>array(
          array(
             'table'=>'archives_images',
             'Alias'=>'ArchivesImage',
             'type'=> 'INNER',
             'conditions'=>array(
                  'ArchivesImage.archive_id=Archive.id'
                      )
         ),
          array(
             'table'=>'images',
             'Alias'=>'Image',
             'type'=> 'INNER',
             'conditions'=>array(
                  'Image.id=ArchivesImage.image_id'
                      )
         )
    ),
    'conditions' => array(
                        'Image.user_id'=>$this->Auth->user('id')
                        ),
    'limit' => 48,
    'recursive'=>-1
);


text:
Q: Implement SSL in a Java chat I am having a tremendous difficulty implementing SSL in a basic java chat. I was able to do the server and the client as well, but when it comes to implementing ssl, it always crashes and I can not continue.
Where should I start to do the implementation next to my code? The code I'm showing here has a very simple graphical interface using swing.
ClientChat
package clientchat;

import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.*;

public class ClientChat {

public static void main(String[] args) {

    String nome = JOptionPane.showInputDialog(null, "Type your name: ", PLAIN_MESSAGE);

    InterfaceChat chat = new InterfaceChat(name);
    chat.setVisible(true);
}

}

Interface Client
package clientchat;

import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.ERROR_MESSAGE;

public class InterfaceChat extends javax.swing.JFrame {

private BufferedReader b;
private InputStreamReader i;
private String nome;
private Socket s;

public InterfaceChat(String nome) {
    this.nome = nome;
    try {
        s = new Socket("127.0.0.1", 5000);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Não se conectou ao servidor",   "", ERROR_MESSAGE);
        System.exit(0);
    }
    initComponents();

    Thread();
}
private void Thread(){
    Thread t = new Thread(new Runnable() {
    String mensagem;
        @Override
        public void run() {
            try{
                i = new InputStreamReader(s.getInputStream());
                b = new BufferedReader(i);

                while((mensagem = b.readLine())!= null){
                    mensagemRecebida.setText(mensagemRecebida.getText() +  mensagem + "\n");
                }

            }catch(IOException e){
                JOptionPane.showMessageDialog(null, "Erro na conexão com o servidor","",ERROR_MESSAGE);
            }
        }
    });
    t.start();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    mensagemRecebida = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    enviarMensagem = new javax.swing.JTextArea();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

    mensagemRecebida.setColumns(20);
    mensagemRecebida.setRows(5);
    jScrollPane1.setViewportView(mensagemRecebida);

    enviarMensagem.setColumns(20);
    enviarMensagem.setRows(5);
    enviarMensagem.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            enviarMensagemKeyPressed(evt);
        }
    });
    jScrollPane2.setViewportView(enviarMensagem);

    jButton1.setText("Enviar");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Sair");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton2))
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    String mensagem = nome + ": ";

    try {
        PrintStream ps = new PrintStream(s.getOutputStream());
        mensagem += enviarMensagem.getText();

        ps.println(mensagem);
        ps.flush();
        enviarMensagem.setText("");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Não conseguiu enviar a mensagem", "", ERROR_MESSAGE);
    }
}

private void enviarMensagemKeyPressed(java.awt.event.KeyEvent evt) {
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        String mensagem = nome + ": ";

        try {
            PrintStream ps = new PrintStream(s.getOutputStream());
            mensagem += enviarMensagem.getText();

            ps.println(mensagem);
            ps.flush();
            enviarMensagem.setText("");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Não conseguiu enviar a mensagem", "", ERROR_MESSAGE);
        }
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        s.close();
        System.exit(0);
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

// Variables declaration - do not modify
private javax.swing.JTextArea enviarMensagem;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea mensagemRecebida;
// End of variables declaration
}

Server
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.util.ArrayList;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

public class ServidorChat {

public static void main(String[] args) {
    ArrayList<PrintStream> clientes = new ArrayList<>();
    try{
        SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        SSLServerSocket server = (SSLServerSocket) factory.createServerSocket(5000);

        while(true){
            SSLSocket sslsocket = (SSLSocket) server.accept();

            //guarda o endereço dos clientes
            clientes.add(new PrintStream(sslsocket.getOutputStream()));
            Mensagem mensagem = new Mensagem(sslsocket, clientes);
        }

    }
    catch(IOException e){
        e.printStackTrace();
    }
}}

Message Server
public class Mensagem {

private SSLSocket s;
private ArrayList<PrintStream> clientes;

public Mensagem(SSLSocket s, ArrayList<PrintStream> clientes) {
    this.s = s;
    this.clientes = clientes;
    Thread();
}

private void Thread() {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            String mensagem = "";
            try {
                InputStreamReader i = new InputStreamReader(s.getInputStream());
                BufferedReader b = new BufferedReader(i);

                while ((mensagem = b.readLine()) != null) {
                    enviarMensagem(mensagem);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    t.start();

}

private void enviarMensagem(String mensagem) {
    for (int i = 0; i < clientes.size(); i++) {
        clientes.get(i).println(mensagem);
        clientes.get(i).flush();

Server Error
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:710)
at sun.security.ssl.InputRecord.read(InputRecord.java:527)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at   sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:928)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at servidorchat.Mensagem$1.run(Mensagem.java:31)
at java.lang.Thread.run(Thread.java:745)

A: s = new Socket("127.0.0.1", 5000);

You created a plaintext connection, just as it says in the error message. You need
s = SSLSocketFactory.getInstance().createSocket("127.0.0.1", 5000);

After that everything should work, provided your server certificate is trusted by the client.

A: You will have to use SSLContext for this purpose. Check out the sample code which I implemented in one of my applications below. Client context means you become the client and call some back end. Server context means you accept the client requests.
public class SSLUtil {
    private static String KEY_STORE_TYPE = "JKS";
    private static String TRUST_STORE_TYPE = "JKS";
    private static String KEY_MANAGER_TYPE = "SunX509";
    private static String TRUST_MANAGER_TYPE = "SunX509";
    private static String PROTOCOL = "TLS";

    private static SSLContext serverSSLCtx = null;
    private static SSLContext clientSSLCtx = null;

    public static SSLContext createServerSSLContext(final String keyStoreLocation,
                                                    final String keyStorePwd)
                                                                             throws KeyStoreException,
                                                                             NoSuchAlgorithmException,
                                                                             CertificateException,
                                                                             FileNotFoundException,
                                                                             IOException,
                                                                             UnrecoverableKeyException,
                                                                             KeyManagementException {
        if (serverSSLCtx == null) {
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
            keyStore.load(new FileInputStream(keyStoreLocation), keyStorePwd.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
            keyManagerFactory.init(keyStore, keyStorePwd.toCharArray());
            serverSSLCtx = SSLContext.getInstance(PROTOCOL);
            serverSSLCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        }

        return serverSSLCtx;
    }

    public static SSLContext createClientSSLContext(final String trustStoreLocation,
                                                    final String trustStorePwd)
                                                                               throws KeyStoreException,
                                                                               NoSuchAlgorithmException,
                                                                               CertificateException,
                                                                               FileNotFoundException,
                                                                               IOException,
                                                                               KeyManagementException {
        if (clientSSLCtx == null) {
            KeyStore trustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
            trustStore.load(new FileInputStream(trustStoreLocation), trustStorePwd.toCharArray());
            TrustManagerFactory trustManagerFactory =
                                                      TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
            trustManagerFactory.init(trustStore);
            clientSSLCtx = SSLContext.getInstance(PROTOCOL);
            clientSSLCtx.init(null, trustManagerFactory.getTrustManagers(), null);
        }

        return clientSSLCtx;

    }

}

Hope this helps. Happy coding !


text:
Q: Python Code store a group of names in a list and count the number of words with an E in it I want to accept a group of names and then store them in a list. Next, I want to count each name that has an "e" or "E" in it.This is what I have written thus far.
main()

A: EDIT: Forgot you asked for user input instead of programmed list of names
This is a simple program that does what you're asking.
names = []
for i in range(16):
    name = input("Enter a name:")
    names.append(name)

def find_e(names):
    i = 0
    for name in names:
        if 'e' in name or 'E' in name:
            i += 1

    return i

print(find_e(names))


text:
Q: 2 independent dropdown buttons I need to achieve 2 things with these dropdown buttons DEMO

*

*They need to work independently from one
another. So basically what I'm trying to achieve is when you click
on the first button the second button doesn't get affected and
vice-versa. On my example when you click on one button the other one
gets that border around and that shouldn't happen, it should be
completely independent.

*When one dropdown is active if the second one is clicked the first
one should close automatically.
I hope my question makes sense.
Thank you all!

A: There is working mate: http://fiddle.jshell.net/2Yp5r/4
Basically 2 things:

*

*Set only the clicked element as active, by using $(this) instead the general $('.clicker')

*Close previous opened tabs, that's all commented below as well.
$('.clicker').click(function(e) {
     //remove previously active style
$(".clicker").removeClass('active');

//check if this tab is not opened
if( $('+ ul', $(this)).css('display') == 'none')
{
    //hide previous opened tab
    $('.dropdown').not(this).hide();

    //add style to clicked element
    $(this).addClass('active');
}

    $('+ ul', $(this)).slideToggle(200);

    if($(e.target).attr('href') == '#') {e.preventDefault();}

    e.stopPropagation();
    e.stopPropagation();
});


text:
Q: Preventing EntityReference Checks from occuring when Creating/Updating an Entity in Dynamics CRM When executing a CreateRequest using the MS CRM OrganizationService, it seems that any attribute of type 'EntityReference' is checked by the internal CRM pipeline using a SQL query against the respective base table looking for the key specified in the EntityReference object. It's basically a foreign key check substitute since CRM doesn't define actual foreign keys when you relate entities.
I'm trying to import some data into the system where I know the specified EntityReference's already exist since I just retrieved them (race conditions aside). Is there any way to bypass that internal check from happening when using the web services? I'd like to avoid having to do any direct SQL updates since it invalidates the auditbase and modifiedby information.
For example, inserting 100,000 entity instances which each have 5 entity reference attributes on them turns into 500,000 selects being issued, often for the same value. Please tell me there is a supported way around this?

A: No. The only supported way to create records inside Dynamics CRM is to use the API.