text:
Q: How can I disable Save As in Ms Excel in Vb 2010 Uhm.. How can I disable Save As button, I can open Ms Excel through vb net but the thing is I also want to disable the 'save as' as the Ms Excel Open... Please Help me THANKS! :) But not in Macro..
Here's my code:
  Imports Excel = Microsoft.Office.Interop.Excel

    Dim oXL As Excel.Application
    Dim oWB As Excel.Workbook
    Dim oSheet As Excel.Worksheet

    ' Start Excel and get Application object.
    oXL = CreateObject("Excel.Application")
    oXL.Visible = True
    oXL.WindowState = Excel.XlWindowState.xlMaximized
    ' Get a new workbook.
    oWB = oXL.Workbooks.Add
    oSheet = oWB.ActiveSheet

How about disabling 'save as' ? :)

A: Look into handling the BeforeSave event:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If SaveAsUI Then
        Cancel = True
    End If
End Sub

You can disable the actual button on the ribbon with RibbonX, but workarounds for the user still exist that will allow them to save.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a struct with `variable: [String: Codable]` codable? I got a struct like the following
struct Wrapper {

  var value: [String: Any]
  // type "Any" could be String, Int or [String].
  // i.g. ["a": 1, "b": ["ccc"]]
  // and the keys of this dictionary are not determined
}

I been struggled for quite a while.
Anyone has any idea how to resolve it?

A: You can use some library like AnyCodable
Then you can make your struct Codable by using AnyCodable class instead of Any.
struct Wrapper: Codable {
    var value: [String: AnyCodable]
}

Example
let arrayWrapper: [String: Any] =
["value" :
       [
         "test" : ["1", "2", "3"],
         "parse" : ["4", "5", "6"]]
        ]

let jsonData = try! JSONSerialization.data(withJSONObject: arrayWrapper, options: .prettyPrinted)

do {
   let decoder = JSONDecoder()
   let result = try decoder.decode(Wrapper.self, from: jsonData)
   print("result:", result)
} catch let error {
   print("error:", error)
}

Output
result: Wrapper(value: ["parse": AnyCodable(["4", "5", "6"]), "test": AnyCodable(["1", "2", "3"])])


text:
Q: Does read request in cassandra (with replica 3 and consistency ONE) return the data? I have a cluster with 5 node, replica 3, and consistency ONE.
If no node goes down, write success, and no Update commands!

if i insert a data (consistency ONE) and then immediately select that data (consistency ONE), when data not exist in other replicas.does it always give me the data (no matter if it is out of date)?

A: No it does not.
When you select the data with CL ONE the one replica contacted may not have the data yet and will respond NotFound.
If you use write CL ONE you must use read CL ALL to be consistent. Or you can use write CL QUORUM and read CL QUORUM.


text:
Q: Why creators of Java specifications did not mandated finalizer chaining just like constructors? We have Constructors in Java which are analogous to Constructors in C++ which would create the object by automatically chaining(Consirering default non parameterized constructors) its constructors from base class to object being constructed.
Now we have finalizers in java which would be same as destructors in C++. And C++ chains its destructors from most derived class to the base class automatically.
Why Java specification designers kept the call to base class finalizer responsibility of programmers when the could have easily defined the specification for the same so that we would have less programmer headaque for explicitely calling base class finalizers.

A: "Now we have finalizers in java which would be same as destructors in C++." Uh, no, Java finalizers are nothing at all even remotely the "same as destructors in C++". There's your problem right there.
Finalizers are very special methods really only needed for very limited use cases, like releasing native resources accessed outside normal Java means. They have a devastating effect on garbage collection if used much or wrong. They have special rules.
They're not destructors. Java doesn't have or need destructors.


text:
Q: Get session value in parameterless constructor in ASP .NET Core I have a class with a parameterless constructor and I am wondering how to get a value from the session. I have tried dependency injection but since I am using this class for deserialization, the httpcontextaccessor is always null.
public class Category
{
    public Category()
    {
        _language = "french"; <-- how to get value from session
    }

    private string _Name;
    public string Name {
        get {
                if (!string.IsNullOrEmpty(_language))
                {
                    var dict = new Dictionary<string, string>();
                    this.localization.FirstOrDefault(x => x.TryGetValue(_language, out dict));
                    return dict != null && dict.ContainsKey("name") ? dict["name"] : _Name;
                }
                else
                    return _Name;
        }
        set
        {
            _Name = value;
        }
    }

    public List<Dictionary<string, Dictionary<string, string>>> localization { get; set; }
}

A: You can get session value in custom model like below:
public class Category
{
    private readonly ISession _session;    //add this..
    public Category(ISession session)
    {
        _session = session;
        _language = _session.GetString("language");
    }

    private string? _language;
    private string _Name;
    public string Name {
        get {
                if (!string.IsNullOrEmpty(_language))
                {
                    var dict = new Dictionary<string, string>();
                    this.localization.FirstOrDefault(x => x.TryGetValue(_language, out dict));
                    return dict != null && dict.ContainsKey("name") ? dict["name"] : _Name;
                }
                else
                    return _Name;
        }
        set
        {
            _Name = value;
        }
    }

    public List<Dictionary<string, Dictionary<string, string>>> localization { get; set; }

}

Test it in Controller:
public IActionResult Index()
{
    HttpContext.Session.SetString("language", "en-US");
    var model = new CategoryModel(HttpContext.Session);

    return View();
}

Be sure add AddSession and UseSession middleware in Program.cs or in Startup.cs.
Reference: Configure session state

but since I am using this class for deserialization, the httpcontextaccessor is always null.

A simple demo you could follow:
Model:
public class CategoryModel
{
    private readonly IHttpContextAccessor _contextAccessor;
    public CategoryModel(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
        _language = contextAccessor.HttpContext.Session.GetString("language");
    }
    //........
}

Test in Controller:
public class HomeController : Controller
{
    private readonly IHttpContextAccessor _contextAccessor;

    public HomeController(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public IActionResult Index()
    {
        HttpContext.Session.SetString("language", "en-US");
        var model = new CategoryModel(_contextAccessor);

        return View();
    }
}

Register the service like:
//.....
builder.Services.AddSession();
builder.Services.AddHttpContextAccessor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

A: So I created a static class:
public static class AppContext
{
    public static IHttpContextAccessor HttpContextAccessor { get; set; }
    public static void Configure(IHttpContextAccessor accessor)
    {
        HttpContextAccessor = accessor;
    }
}

And then in the class where I couldn't do dependency injection, I was able to get the session:
    public Category()
    {
        _language = AppContext.HttpContextAccessor.HttpContext.Session.GetString("language");
    }

Had to add this to Configure in Startup:
AppContext.Configure(context);


text:
Q: Viewport meta tag doesn't work, website renders with zoom-out on mobil So, I'm adding some responsive stuff to a website, and usually this is no problem, but for some reason the page renders zoomed (at 0.3) when refreshing. All the CSS-changes are implemented, it's just the initial zoom that's wierd.
I use this in my <head>:
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no" />

and the responsive stuff is within this tag:
    @media screen and (max-device-width: 767px) {
    /*responsive stuff that works*/
    }

The page is if you want to have a look yourself: http://utt.se
Thanks for help!

A: Try delete all commas from <meta> tag:
<meta name="viewport" content="width=device-width initial-scale=1.0 minimum-scale=1.0 user-scalable=no" />

A: From looking at your site I see that .blogContent has a width set on it, as does #mainContent.
Changing these to both be width: 100% seemed to fix it on chrome for me

A: You can also put zoom viewport property  within css
@viewport{
    zoom: 1.0;
    width: extend-to-zoom;
}

click here for more information about viewport zoom

A: You should also replace width values to max-width
Replace this
.contentCon ul li {
  width: 340px;

for this
.contentCon ul li {
  max-width: 340px;


text:
Q: WordPress get user by meta data How can I retrieve all users registered in my WordPress blog having a particular meta data?
For example I have made an option to add a custom meta data for every registering users having meta key as parent_id. If I want to list all users having parent_id as 2 , then how can I do this?

A: Simple way how to get one user by his metadata is:
$user = reset(
 get_users(
  array(
   'meta_key' => $meta_key,
   'meta_value' => $meta_value,
   'number' => 1
  )
 )
);

A: Here is the codex page from Wordpress detailing how to use the get_users($arg); function.
It contains examples how how to build custom functions to fetch various parts of user data. You'll have to naturally build and make some of your own changes to get it how you want.
Additionally here is a link to a function somebody built that will fetch user data based on roles within wordpress. You can configure it in many different ways with some tweeking, but this will allow you to filter your results in a more powerful manner.

A: Here is how you can get users based on a custom role and multiple metadata keys,
$available_drivers = get_users(
            array(
                'role' => 'driver',
                'meta_query' => array(
                    array(
                        'key' => 'approved',
                        'value' => true,
                        'compare' => '=='
                    ),
                    array(
                        'key' => 'available',
                        'value' => true,
                        'compare' => '=='
                    )
                )
            )
        );

Explaining the above query, I want only those users who I assigned the role of driver, and they are approved and available. The approved and available are custom fields created using ACF as True/False fields.
If you have additional metadata to test, add another array element to the meta_query array.
Meanwhile checkout my open source at github.com/patrickingle

A: Since WP v3.1 it's ridiculously easy to search for a user by his/her meta key.
Use the function
get_users($args)

(WP Documentation)
The function takes an array of parameters, in your case you need
get_users(array(
    'meta_key' => 'parent_id',
    'meta_value' => '42'
))


text:
Q: Is it overall more efficient to convert list to set when checking if a value is in the set I was reading up on some best practices for speed in python and found this which says:

Membership testing with sets and dictionaries is much faster, O(1), than searching sequences, O(n).
When testing "a in b", b should be a set or dictionary instead of a list or tuple.

But if say i have a list long_list and I want to find out if item list_item is in long_list like:
list_item in long_list

Would it under any circumstance be faster to do:
list_item in Set(long_list)

Seeing as I think list to set or dict conversion on average should be O(n) in itself. (?)
Or is it always better to just go with whichever data-type I'm already working with?

A: If you are going to be doing multiple lookups on long_list, it is worth it.  Otherwise, it is not.
$ python3 -m timeit -s 'x = list(range(10000))' '1234 in x'
100000 loops, best of 3: 5.71 usec per loop

$ python3 -m timeit -s 'x = list(range(10000))' '1234 in set(x)'
10000 loops, best of 3: 61.4 usec per loop

$ python3 -m timeit -s 'x = set(list(range(10000)))' '1234 in x'
10000000 loops, best of 3: 0.0198 usec per loop

A:
Would it under any circumstance be faster to do: list_item in Set(long_list)

Yes, here's one where it's about 240 times faster:
from timeit import timeit

# Setup the circumstance
b = ['c' * 100000 + chr(i) for i in range(100)]
set(b)
a = b[-1]

# Measure
for _ in range(3):
    print(timeit(lambda: a in b,      number=1000))
    print(timeit(lambda: a in set(b), number=1000))
    print()

Output:
1.3284053
0.005440200000000006

1.3530345000000001
0.005345699999999898

1.3339443000000002
0.0056618999999997754

That first set(b) during setup of the circumstance makes the strings compute and store their hashes. You could do for s in b: hash(s) instead, I was just lazy.
CPython version used: Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Results on repl.it with its current Python version 3.8.1 64-bit (and I think it's CPython on Linux):
1.2134423210000023
0.0042260629998054355

1.268552630999693
0.005732013999931951

1.1268463759997758
0.003574737000235473

Update
Here's a case where the set version is more than a million times faster for a single check, and you can increase the factor as much as you want by slowing down comparisons further:
from timeit import timeit

setup = '''
from time import sleep
class C:
    def __init__(self, value):
        self.value = value
    def __hash__(self):
        return hash(self.value)
    def __eq__(self, other):
        sleep(10)
        return self.value == other.value
b = [C(1), C(2)]
a = b[-1]
'''

for _ in range(3):
    for stmt in 'a in b', 'a in set(b)':
        t = timeit(stmt, setup, number=1)
        print('%10.7f' % t, 'seconds for: ', stmt)
    print()

Output:
10.0001129 seconds for:  a in b
 0.0000056 seconds for:  a in set(b)

10.0008811 seconds for:  a in b
 0.0000071 seconds for:  a in set(b)

10.0005529 seconds for:  a in b
 0.0000062 seconds for:  a in set(b)


text:
Q: TypeError: () missing 1 required positional argument I am working with a json file and I need to create an array with which I can work later on in my Python code.
It needs to look like this [[1*5,1.75],[2*5,1.74],[3*5,1.76]...]
so i can calculate like avgPoints[x][0]+avgPoints[x+1][0]
My current code looks like this:
data = json.loads(json_file)

avgData = data['diameter_measurement'].split(',')
avgStep = float(data['length']) / (len(avgData) - 1)
avgPoints = list(map(lambda index, delta: [index * avgStep, 1.75 + float(delta) / 1000.0], enumerate(avgData)))

But when I run my code it gives me following error:
->TypeError: <lambda>() missing 1 required positional argument: 'delta'

A: When you iterate over enumerate, you get back one item: the tuple (index, element). This is not implicitly unpacked into index, delta when you call the lambda, so you have to unpack it yourself with something like lambda index_delta: "use index_delta[0] and index_delta[1]". Alternatively you could define a function and unpack the function's single argument into index and delta.


text:
Q: Xcode 8.21 (8C1002) stuck processing symbol files for iPhone 6s 10.1.1 (14B100) on VirtualBox So I've been trying to get xcode working on a VM, using VirtualBox to run macOS Sierra, host machine is Win10, development target is my iPhone 6s. Currently my phone firmware is 10.1.1 (14B100).
I have a project set up in xcode, and my device is recognized in the most recent version of iTunes on my VM, and it is also recognized in XCode. When I attempt to press the play button on my project, I get the loading bar

"Processing symbol files. Xcode will continue when iPhone is finished."

It's been multiple hours with no success, tried multiple times and read what feels like every question posted about similar issues to no avail.
I have tried:
-Resetting network settings on device
-Plugging cable out & in
-Using Apple certified cable (two different ones tried, two different ports)
-Deleting iOS Device Support folder
-Running the clean project command
-Restarting XCode
-Restarting my VM
-Restarting my host computer
-Confirmed that my Xcode & iTunes are up to date
-Emptying trash can in attempt to create more space
Suggestions on how to overcome this issue would be appreciated, is there any method I can use to negate this need for symbol files? Thanks.

A: I had the same problem and got the solution from this post. So, here it goes:

*

*Check if you have the latest version of VirtualBox (and upgrade it if you don't)

*Install the VirtualBox Extension Pack (so step 3 can work)

*On Settings->USB select USB 2.0 (VM must be off)

A few notes:

*

*If the machine does not boot try unplugging the iPhone

*If the iPhone is not detected check if the usb you are using is 2.0 or 3.0 (this should match the VirtualBox setting)


text:
Q: Why is Scrapy not crawling or parsing? I am attempting to scrape the Library of Congress/Thomas website. This Python script is intended to access a sample of 40 bills from their site (# 1-40 identifiers in the URLs). I want to parse the body of each piece of legislation, search in the body/content, extract links to potential multiple versions & follow.
Once on the version page(s) I want to parse the body of each piece of legislation, search the body/content & extract links to potential sections & follow.
Once on the section page(s) I want to parse the body of each section of a bill.
I believe there is some issue with the Rules/LinkExtractor segment of my code. The python code is executing, crawling the start urls, but not parsing or any of the subsequent tasks.
Three issues:

*

*Some bills do not have multiple versions (and ergo no links in the body portion of the URL

*Some bills do not have linked sections because they are so short, while some are nothing but links to sections.

*Some section links do not contain just section-specific content, and most of the content is just redundant inclusion of prior or subsequent section content.

My question is again, why is Scrapy not crawling or parsing?
from scrapy.item import Item, Field
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector

class BillItem(Item):
    title = Field()
    body = Field()

class VersionItem(Item):
    title = Field()
    body = Field()

class SectionItem(Item):
    body = Field()

class Lrn2CrawlSpider(CrawlSpider):
    name = "lrn2crawl"
    allowed_domains = ["thomas.loc.gov"]
    start_urls = ["http://thomas.loc.gov/cgi-bin/query/z?c107:H.R.%s:" % bill for bill in xrange(000001,00040,00001) ### Sample of 40 bills; Total range of bills is 1-5767

    ]

rules = (
        # Extract links matching /query/ fragment (restricting tho those inside the content body of the url)
        # and follow links from them (since no callback means follow=True by default).
        # Desired result: scrape all bill text & in the event that there are multiple versions, follow them & parse.
        Rule(SgmlLinkExtractor(allow=(r'/query/'), restrict_xpaths=('//div[@id="content"]')), callback='parse_bills', follow=True),

        # Extract links in the body of a bill-version & follow them.
       #Desired result: scrape all version text & in the event that there are multiple sections, follow them & parse.
        Rule(SgmlLinkExtractor(restrict_xpaths=('//div/a[2]')), callback='parse_versions', follow=True)
    )

def parse_bills(self, response):
    hxs = HtmlXPathSelector(response)
    bills = hxs.select('//div[@id="content"]')
    scraped_bills = []
    for bill in bills:
        scraped_bill = BillItem() ### Bill object defined previously
        scraped_bill['title'] = bill.select('p/text()').extract()
        scraped_bill['body'] = response.body
        scraped_bills.append(scraped_bill)
    return scraped_bills

def parse_versions(self, response):
    hxs = HtmlXPathSelector(response)
    versions = hxs.select('//div[@id="content"]')
    scraped_versions = []
    for version in versions:
        scraped_version = VersionItem() ### Version object defined previously
        scraped_version['title'] = version.select('center/b/text()').extract()
        scraped_version['body'] = response.body
        scraped_versions.append(scraped_version)
    return scraped_versions

def parse_sections(self, response):
    hxs = HtmlXPathSelector(response)
    sections = hxs.select('//div[@id="content"]')
    scraped_sections = []
    for section in sections:
        scraped_section = SectionItem() ## Segment object defined previously
        scraped_section['body'] = response.body
        scraped_sections.append(scraped_section)
    return scraped_sections

spider = Lrn2CrawlSpider()

A: Just for the record, the problem with your script is that the variable rules is not inside the scope of Lrn2CrawlSpider because it doesn't share the same indentation, so when alecxe fixed the indentation the variable rules became now an attribute of the class. Later the inherited method __init__() reads the attribute and compiles the rules and enforces them.
def __init__(self, *a, **kw):
    super(CrawlSpider, self).__init__(*a, **kw)
    self._compile_rules()

Erasing the last line had nothing to do with that.

A: I've just fixed the indentation, removed spider = Lrn2CrawlSpider() line at the end of the script, ran the spider via scrapy runspider lrn2crawl.py and it scrapes, follows links, returns items - your rules work.
Here's what I'm running:
from scrapy.item import Item, Field
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector

class BillItem(Item):
    title = Field()
    body = Field()

class VersionItem(Item):
    title = Field()
    body = Field()

class SectionItem(Item):
    body = Field()

class Lrn2CrawlSpider(CrawlSpider):
    name = "lrn2crawl"
    allowed_domains = ["thomas.loc.gov"]
    start_urls = ["http://thomas.loc.gov/cgi-bin/query/z?c107:H.R.%s:" % bill for bill in xrange(000001,00040,00001) ### Sample of 40 bills; Total range of bills is 1-5767

    ]

    rules = (
            # Extract links matching /query/ fragment (restricting tho those inside the content body of the url)
            # and follow links from them (since no callback means follow=True by default).
            # Desired result: scrape all bill text & in the event that there are multiple versions, follow them & parse.
            Rule(SgmlLinkExtractor(allow=(r'/query/'), restrict_xpaths=('//div[@id="content"]')), callback='parse_bills', follow=True),

            # Extract links in the body of a bill-version & follow them.
           #Desired result: scrape all version text & in the event that there are multiple sections, follow them & parse.
            Rule(SgmlLinkExtractor(restrict_xpaths=('//div/a[2]')), callback='parse_versions', follow=True)
        )

    def parse_bills(self, response):
        hxs = HtmlXPathSelector(response)
        bills = hxs.select('//div[@id="content"]')
        scraped_bills = []
        for bill in bills:
            scraped_bill = BillItem() ### Bill object defined previously
            scraped_bill['title'] = bill.select('p/text()').extract()
            scraped_bill['body'] = response.body
            scraped_bills.append(scraped_bill)
        return scraped_bills

    def parse_versions(self, response):
        hxs = HtmlXPathSelector(response)
        versions = hxs.select('//div[@id="content"]')
        scraped_versions = []
        for version in versions:
            scraped_version = VersionItem() ### Version object defined previously
            scraped_version['title'] = version.select('center/b/text()').extract()
            scraped_version['body'] = response.body
            scraped_versions.append(scraped_version)
        return scraped_versions

    def parse_sections(self, response):
        hxs = HtmlXPathSelector(response)
        sections = hxs.select('//div[@id="content"]')
        scraped_sections = []
        for section in sections:
            scraped_section = SectionItem() ## Segment object defined previously
            scraped_section['body'] = response.body
            scraped_sections.append(scraped_section)
        return scraped_sections

Hope that helps.


text:
Q: Cannot Capture Value From Nested Firebase Database I have a firebase database structured below:

Essentially, I am trying to capture the value of "answer." I am running the below code:
 public void onDataChange(DataSnapshot dataSnapshot) {
                        //should dump all of poll creators items in the following section of the current user
                        Log.v("DataSnap", dataSnapshot.toString());
                        Log.v("DataSnap", dataSnapshot.child(USER_ID_LABEL).getValue().toString());
                        ArrayList<String > mPollAnswers = new ArrayList<>();
                        for (DataSnapshot y : dataSnapshot.child(ANSWERS_LABEL).getChildren()){
                            Log.v("ANSWER", y.getValue().toString());
                        }

And unfortunately it is returning both "vote count" and "answer," when I strictly want the value of answer:

A: If you have access to the top-level keys e.g L3l1..., "answers" and "1", firebase will return the resultant object in the form of a Hashmap<String, Object> where Object can be anything.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    firebaseDatabase.getReference("<top-level-key>")
            .child("L3l1...")
            .child("answers")
            .child("1")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Returns a hashmap with keys of type answer and vote_count
                    Object value = dataSnapshot.getValue(); /
                    Object o = ((HashMap) value).get("answer");
                    String s = "";
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

*A more elegant solution
To Simplify things, create an Answer class and cast it to the datasnapshot.
public class Answer {
    private int vote_count;
    private String answer;

    public Answer() {
    }

    public int getVote_count() {
        return vote_count;
    }

    public void setVote_count(int vote_count) {
        this.vote_count = vote_count;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }
}

In your Activity or wherever you call firebase:
//In your Activity or Fragment or wherever you call Firebase
        firebaseDatabase.getReference("<top-level-key>")
            .child("L13a")
            .child("answers")
            .child("1")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Answer value = dataSnapshot.getValue(Answer.class);
                    //value.getAnswer() = "rstrrs"
                    //value.getVote_Count() = 0
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


text:
Q: CollapsingToolbarLayout & NestedScrollView don't work together I'm trying to make CollapsingToolbarLayout work with NestedScrollView, but it doesn't follow the scrolling of NestedScrollView correctly. It moves a little bit when the NestedScrollView reaches the top or bottom end, but that's clearly not the intended behavior.
Oh, and the contentScrim covers the ImageView immediately as well.
Here's a video of what happens: https://youtu.be/1GlTJq5fd0U
And here's the xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/articleLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.gmail.senokt16.bosphoruschronicle.ArticleActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/articleAppBarLayout"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/articleCollapsingToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primaryColor"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/article_app_bar">

            <ImageView
                android:id="@+id/articleActivityImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <include
                android:id="@+id/article_app_bar"
                layout="@layout/article_app_bar" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"
        android:fitsSystemWindows="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_scrollFlags="scroll|enterAlways">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="24dp">

            <TextView
                android:id="@+id/articleActivityContents"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="30dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingTop="5dp" />
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/articleFAB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_share"
        app:layout_anchor="@id/articleAppBarLayout"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

A: I ended up playing around with a bunch of xml tags and don't know which one fixed the problem, but here's the last version of the xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/articleLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.gmail.senokt16.bosphoruschronicle.ArticleActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/articleAppBarLayout"
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/articleCollapsingToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/primaryColor"
            app:expandedTitleMarginEnd="96dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <View
                android:layout_width="match_parent"
                android:fitsSystemWindows="true"
                android:layout_height="match_parent"
                android:background="@drawable/gradient"
                />
            <ImageView
                android:id="@+id/articleActivityImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax"
                android:scaleType="centerCrop"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/article_app_bar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="24dp">

            <TextView
                android:id="@+id/articleActivityContents"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="30dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingTop="5dp" />
        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/articleFAB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_share"
        app:layout_anchor="@id/articleAppBarLayout"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>


text:
Q: how to hide private key using craco build for react in docker image on beanstalk I am currently using craco and am using env-cmd to pass .env file into craco build as follows:
"build:nightly": "env-cmd -f .env.nightly craco build"

I am running the environment in a docker image.  However, the problem is I have to commit the .env file onto github which I don't want to because one of the variable in the .env file is a private key.  I am trying to figure out how to get craco to build by reading the host environment variables.  I am using Beanstalk and have set the environment variables in the configuration.  But my docker image is not picking that up.  Does anyone have any idea or recommendation on how I might be able to achieve this?
Thanks in advance


text:
Q: Scala collectons filter and sort a sequence with objects containing a map and then iterate over it given an object:
 case class GT(code: String,names: Map[String, Option[String]]) {}

and
a list :
val gText = List(new GT("USB", Map("de" -> Some("a"), "en" -> Some("abc"), "fr" -> Some("ab"))),
                  new GT("Switch", Map("de" -> Some("abcdef"), "en" -> Some("b"), "fr" ->
                          Some("abc"), "es" -> Some("abc"))),
                  new GT("PVC", Map("de" -> Some("abc"), "en" -> Some("bc"), "fr" -> Some("abcd"))))

I want to iterate over the gText List but dependent from the key of map "names" and in descending order of the length of each "names" map value.
First iteration should be in the following oder with the values for "de":
1. code: "Switch" & names.key="de" & names.value = Some("abcdef")
2. code: "PVC" & names.key="de" & names.value = Some("abc")
3. code: "USB" & names.key="de" & names.value = Some("a")

Second iteration should be in the following oder with the values for "en":
1. code: "USB" & names.key="en" & names.value = Some("abc")
2. code: "PVC" & names.key="en" & names.value = Some("bc")
3. code: "Switch" & names.key="en" & names.value = Some("b")

Third iteration should be in the following oder with the values for "fr":
1. code: "PCV" & names.key="fr" & names.value = Some("abcd")
2. code: "Switch" & names.key="fr" & names.value = Some("abc")
3. code: "Switch" & names.key="fr" & names.value = Some("ab")

Last iteration is for names.key="es"
code="Switch" & names.key="es" and names.value = Some("abc")
As mentioned above the main goal is to iterate the values for the same key of the different GT's dependent from the length of each value.
How can I do that. Maybe first of all I have to collect the key in an additional set and then filter and sortyBy. Please any suggestions are welcome.
Thanks in advance.
Ugur

A: val gtEntries = gText.flatMap( gt => gt.names.toList.map(entry => (gt.code, entry._1, entry._2)))
val gtEntriesByLang = gtEntries.groupBy(_._2)

for (lang <- gtEntriesByLang.keys.toList.sorted;
 gtEntry <- gtEntriesByLang(lang).sortBy(entry => -entry._3.map(_.length).getOrElse(0) ))
 {
    println(gtEntry)
 }

The first line 'flattens' the list of GTs into tuples of the form ("USB","en",Some("abc")).
The second line groups it by language i. e. "en" => List( ("USB","en",Some("abc"), ...)
The for comprehension goes through all the languages in descending order and then sorts the entries by the length of the values of the original name map (0 if the option is undefined; make it 1 if you want to be None different to "").

A: It's not quite clear to me exactly what order of iteration you want, but here's another way of skinning the cat.
  val countrySet = gText.flatMap { _.names.keys }.toSet
  for {
    c <- countrySet
    gc = gText.filter(_.names.contains(c))
    g <- gc.sortBy(_.names(c).get.length).reverse
  } println("country " + c + " " + g)

Get the set of countries. Then, iterate through those, filter the list to only those that have an entry for the current country, sort that list by the length of the corresponding value (reversed, to get descending length)


text:
Q: Firefox CSS select OPTION styling From what im seeing, you cannot style  boxes, because it is OS specific and cannot be broken unless you edit with javascript...
My example is here:
http://www.promilitarybusinessnetwork.com/continueSearch.asp?categoryID=1270
I just restyled the page today. HUGE improvement from where it was before.
Looks perfect in Chrome and Safari...Firefox gives me issues.

*

*In Firefox, the text isnt centered.

*I cant use -moz-appearance:none; to get rid of the  box in the right.

*The items turn up white due to my CSS for chrome and safari. This is only for the SELECT text, but the  still stay black in my preferred browsers. In Firefox, it turns the  white...

What can i do to change this...?
.select{
width:361px;
height:44px;
color:#FFF;
font-size:14px;
padding-left:10px;
font-weight:bolder;
font-family:Verdana, Geneva, sans-serif;
background-image:url(images/baseselect_up.png);
display:block;
position:absolute;
-webkit-appearance: none;
-moz-appearance: none;
}
.select:hover{
background-image:url(images/baseselector_down.png);
}

<form method="post" action="newSearch.asp">
<select class="select" name="baseID" >

<% do while not BaseRs.eof %>
<option value="<%=baseRs("baseID")%>"><%=baseRs("base")%></option>
loop %>
</select>

<input type="hidden" name="CategoryID" value="<%=sqlFilter(request("categoryID"))%>">

<input type="submit"     value="Continue >>>">

</form>

Is there any way I can edit Mozilla to get the OPTION text white, and hide the SELECT appearance and center text...?
Or am I screwed because of how each OS runs?
I run a MAC in the office, PC at home, so Ive yet to see my site on a pc with these new changes ive made today.

A: Javascript-based replacements for the SELECT/OPTION are much more reliable and flexible, especially if you want consistency across browsers. You'll find there are things you just can't do using native styling and tags.

A: Actually if you don`t wanna use additional plugins the easiest way is to use code like this :
Attach file
<input style="display: none;" type="file" id="upload" accept="image/*" name="Change">

You can remove inline css ofc, and also style label to look exactly how you want.

A: select{
width:333px;
height:44px;
color:#FFF;

try the below answer for options color
HTML <select> selected option background-color CSS style
http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-multiple-option/


text:
Q: Printer power adapter I bought a power adapter to my printer but the lable on it says output voltage is 32V at 1.56A that means it is going to deliver around 50 Watts to my printer. On the other hand the original adapter used to supply 20 Watts at 32V and 0.625A. my question is would the new adapter, supplying 50 Watts, break down my printer? Thank you

A: For replacing an adapter four conditions are important:

*

*The voltage of the adapters should be the same (or within spec range), mostly around 10%.

*The current that can be delivered by the adapter should be AT LEAST the current from the original adapter. The device will use current and gets it from the adapter. If the adapter is not capable of delivering it, than problems occur (not working, smoke etc).

*The polarity should match (+ and - on the inner/outer pin). Some devices have a protection for this, some do not. So do not take the risk.

*The size (length/diameter) of the plug should be same (trivial), otherwise it does not fit.

The wattage is just the multiplication of the current and voltage. Mostly there is a safety margin, but even than with the above conditions you should be ok.


text:
Q: Installing Scala 2.9.1/Lift 2.4-M4 using sbt 0.11.0 I am learning to do web development in Scala. currently trying to install the newest version of Scala/lift with sbt 0.11 in MAC OSX. I so far have already done the following:
1. Installed Scala 2.9.1 final
2. Downloaded latest sbt 0.11 from https://github.com/harrah/xsbt/wiki/Setup
3. Setup path environment for sbt
What I am trying to do now is getting the latest lift framework (2.4-M4)from http://liftweb.net/download so that I can try running lift_basic project on localhost:8080 using jetty. I have several questions about that;

*

*Since on the sbt 0.11 I will have to do this:
resolvers += "Web plugin repo" at "http://siasia.github.com/maven2"
addSbtPlugin("com.github.siasia" %% "xsbt-web-plugin" % "0.1.2")
instead of doing libraryDependencies += ... where should I put my object resolvers (checkout the following code below) that would enable me to install both the jetty and web plugin? so, under lift_basic folder should they go within Project/build/LiftProject.Scala or just delete LiftProject.scala and create Build.scala under Project/Build.scala?
object Resolvers {
      val webPluginRepo = "Web plugin repo" at "http://siasia.github.com/maven2"
      val jettyRepo = "Jetty Repo" at "http://repo1.maven.org/maven2/org/mortbay/jetty"
    }
object Dependencies {
      // web plugin
      val webPluginDeps = Seq(
        "org.mortbay.jetty" % "jetty" % "6.1.26" % "jetty", // The last part is "jetty" not "test".
        "javax.servlet" % "servlet-api" % "2.5" % "provided->default"
      )

*What should I do with the sbt.jar existing inside the lift_basic folder? It looks like that it has the old version of sbt there (probably 7.4.0 or so)..

*Besides changing the sbt version to 0.11.0 on the Build.properties, what other changes do I need to make to accomodate this new install? Do I have to change the var BuildScalaVersion and var buildVersion on the Build.scala on the full configuration like the example https://github.com/harrah/xsbt/wiki/Full-Configuration-Example here? If yes, what would be the build version?
I am a total newbie to Scala, and there hasnt been a lot of documentations out there for installing new scala/lift version. will appreciate any pointers/references/answers that would enable me to install new version of scala/lift. Thank you for your time.

A: You can try to look at my project template. Maybe It will be helpful. https://github.com/viktortnk/lift-quickstart


text:
Q: Regex hyphen causing issues I'm trying to use python to extract invoice info from a text file. The items always start with a quantity (1 x, 2 x, etc) and end with a part number, for various reasons the descriptions can differ even for the same item. The following regex seems to pull out most of the entries, but fails when there is a hyphen '-' in the description.
Regex:
^([0-9]+\sx) [\w\s\r\n®.,]* [0-9]{3}-\d[A-Z]\d+(-AB)?

I'm struggling to work out how to modify the regex to deal with this. I though adding (\s-\s) in would help, but the regex then seems to match parts of different entries rather than the individual ones. I'm sure there are more efficient ways of writing the regex, but I don't use them that often, so getting this far was an achievement. Any pointers gratefully received.
Example entries shown below. With the above regex, the middle one doesn't get matched unless I delete the '-'
1 x Product® 100, Low range items

3,456.00 USD

Cat. No. 012-3A45

1 x Product® 100. Low range items - LRI

123,456.00 USD

Part. no. 201-5G95

2 x Product Mid Range Items

7,654.00 USD

Art. no. 001-8Q147-AB

A: You can add a hyphen and make the pattern non greedy
^([0-9]+\sx) [-\w\s®.,]*? [0-9]{3}-\d[A-Z]\d+(-AB)?

Regex demo
Note that \s also matches a newline.


text:
Q: Legendre Polynomial Orthogonality Integral I want to show that $$\int_{-1}^{1}L_n(x)L_m(x)dx$$ is zero for $m<n$ and $\frac{2}{2n+1}$ for $m=n$. For $m<n$, I want to apply $(x^2-1)^n=(x-1)^n(x+1)^n$ and integration by parts. For $m=n$ it should be possible to use the substitution $y=\sqrt{x}$. Some relevant formulae: $$\text{Rodrigues' formula:}\hspace{.4cm} L_n(x)=\frac{1}{2^nn!}\frac{d^n}{dx^n}[(x^2-1)^n]$$ $$\text{Beta Integral:}\hspace{.4cm}\int_{0}^{1}x^{\alpha-1}(1-x)^{\beta-1}dx=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}$$ $$\text{Gamma identities:}\hspace{.4cm}\Gamma(x+1)=x\Gamma(x),\hspace{.2cm}\Gamma(n+1)=n!$$
For $m=n$, $$I_n=\int_{-1}^{1}L_n^2dx=(\frac{1}{2^{n}n!})^2\int_{-1}^{1}\Big(\frac{d^n}{dx^n}\big[(x^2-1)^n\big]\Big)^2dx= \big(\frac{1}{2^{n}n!}\big)^2\Big[\frac{d^{n-1}}{dx^{n-1}}[(x-1)^n(x+1)^n]\frac{d^n}{dx^n}[(x-1)^n(x+1)^n]\Big\rvert_{-1}^{\hspace{.2cm}1}-\int_{-1}^{1}\frac{d^{n-1}}{dx^{n-1}}[(x-1)^n(x+1)^n]\frac{d^{n+1}}{dx^{n+1}}[(x-1)^n(x+1)^n]\Big]$$
I'm not sure where to where to go from here. Is there something that should cancel? Is there a way to do iterative integration by parts here? How do I get to $\frac{2}{2n+1}$?
--------------------------EDIT-------------------------
I finally got it. Here is the proof.
We want to prove the orthogonality relation $I$ defined by
\begin{equation}
I = \int_{-1}^{1}L_n(x)L_m(x)dx
\end{equation}
is zero for $m\neq n$ and $\dfrac{2}{2n+1}$ for $m=n$. In $I$, we can use Rodrigues' formula to express $L_n$ as
\begin{equation}
L_n(x)= \frac{1}{2^nn!}\frac{d^n}{dx^n}\big[(x^2-1)^n\big]
\end{equation}
and apply integration by parts, $\int u'v=uv-\int uv'$.
\begin{equation}
\begin{split}
I= \frac{1}{2^nn!}\int_{-1}^{1}\Big(\frac{d^n}{dx^n}\big[(x^2-1)^n\big]L_m(x)\Big)dx \\ =\frac{1}{2^nn!} \Bigg(\frac{d^{n-1}}{dx^{n-1}}\big[(x^2-1)^n\big]L_m(x) \biggr\rvert_{-1}^{1} - \int_{-1}^{1}\frac{d^{n-1}}{dx^{n-1}}\big[(x^2-1)^n\big]L_m^{(1)}(x)dx  \Bigg) \\
= -\frac{1}{2^nn!} \int_{-1}^{1}\frac{d^{n-1}}{dx^{n-1}}\big[(x^2-1)^n\big]L_m^{(1)}(x)dx
        \end{split}
\end{equation}
Repeated integration by parts $n$ times leaves only
\begin{equation}
\begin{split}
I= (-1)^n\frac{1}{2^nn!}\int_{-1}^{1}(x^2-1)^nL_m^{(n)}(x)dx
        \end{split}
\end{equation}
As $L_m$ has polynomial degree $m$, it will become a constant upon differentiation $m$ times. Since $m<n$, $L_m^{(n)}=0$, so $I=0$ for $m<n$. Since the same argument can be made for $L_n$ when $n<m$, $I$ is always zero for $m\neq n$.
For the case $m=n$,
\begin{equation}
\begin{split}
I= (-1)^n\frac{1}{2^nn!}\int_{-1}^{1}(x^2-1)^nL_n^{(n)}(x)dx \\
= (-1)^n\frac{1}{2^n n!}\int_{-1}^{1}(x^2-1)^n  \frac{d^{2n}}{dx^{2n}}\big[(x^2-1)^n\big] dx \\ =(-1)^n\frac{1}{2^{2n} (n!)^2}\int_{-1}^{1}(x^2-1)^n (2n)!dx \\
=\frac{(2n)!}{2^{2n} (n!)^2}\int_{-1}^{1}(1-x^2)^ndx
    \end{split}
\end{equation}
Considering only the integral $J=\int_{-1}^{1}(x^2-1)^ndx$, use the substitution $x=\sqrt{y}$.
\begin{equation}
\begin{split}
J=2\int_{0}^{1}(1-y)^n \cdot \frac{1}{2\sqrt{y}}dx
    \end{split}
\end{equation}
Letting $\beta=n+1, \alpha=\frac{1}{2}$ and applying the Beta integral,
\begin{equation}
\begin{split}
J=\frac{\Gamma(\frac{1}{2})\Gamma(n+1)}{\Gamma(n+\frac{3}{2})}
    \end{split}
\end{equation}
Using the given Gamma identity for integers,
\begin{equation}
\begin{split}
\Gamma(n+\frac{3}{2})=(n+\frac{1}{2})\Gamma(n+\frac{1}{2}) \\
= (n+\frac{1}{2})(n-\frac{1}{2})(n-\frac{3}{2})\cdot\cdot\cdot\frac{1}{2}\Gamma(\frac{1}{2})
    \end{split}
\end{equation}
and since $\Gamma(n+1)=n!$ we get
\begin{equation}
\begin{split}
J=\frac{n!}{(n+\frac{1}{2})(n-\frac{1}{2})(n-\frac{3}{2})\cdot\cdot\cdot\frac{1}{2}}
    \end{split}
\end{equation}
Then
\begin{equation}
\begin{split}
I=\frac{(2n)!}{2^{2n} (n!)^2}\cdot\frac{n!}{(n+\frac{1}{2})(n-\frac{1}{2})(n-\frac{3}{2})\cdot\cdot\cdot\frac{1}{2}} \\
=\frac{1}{(n+\frac{1}{2})}\frac{(2n)!}{2^{2n}n!(n-\frac{1}{2})(n-\frac{3}{2})\cdot\cdot\cdot\frac{1}{2}} = \frac{1}{\frac{2n+1}{2}}= \frac{2}{2n+1}
    \end{split}
\end{equation}
So
\begin{equation}
I = \int_{-1}^{1}L_n(x)L_n(x)dx = \frac{2}{2n+1}
\end{equation}

A: Here is one approach to prove the orthogonality relation for the Legendre polynomials $P_n (x)$.
We wish to prove
\begin{align*}
\int^1_{-1} P_m (x) P_n (x) \, dx = \begin{cases}
0, & m \neq n\\[1ex]
\displaystyle{\frac{2}{2n + 1}}, & m = n
\end{cases}
\end{align*}
The case $m \neq n$
As $P_m (x)$ and $P_n (x)$ satisfy the Legendre differential equation, namely
$$(1 - x^2) \frac{d^2 P_m}{dx^2} - 2x \frac{dP_m}{dx} + m(m + 1) P_m =
0,$$
and
$$(1 - x^2) \frac{d^2 P_n}{dx^2} - 2x \frac{dP_n}{dx} + n(n + 1) P_n =
0,$$
each of these equations may be rewritten as
\begin{align}
\frac{d}{dx} \left [(1 - x^2) \frac{dP_m}{dx} \right ] + m(m + 1)
P_m &= 0, \qquad (1)
\end{align}
and
\begin{equation}
\frac{d}{dx} \left [(1 - x^2) \frac{dP_n}{dx} \right ] + n(n + 1)
P_n = 0. \qquad (2)
\end{equation}
Multiplying Eq. (1) by $P_n (x)$ and
Eq. (2) by $P_m(x)$ and subtracting we have
$$P_n \frac{d}{dx} \left [(1 - x^2) \frac{dP_m}{dx} \right ] -
P_m \frac{d}{dx} \left [(1 - x^2) \frac{dP_n}{dx} \right ]  + [m(m +
1) - n(n + 1)]P_m P_n = 0. \,\, (*)$$
Now recognising
$$\frac{d}{dx} \left [P_n (1 - x^2) \frac{dP_m}{dx} \right ]
= \frac{dP_n}{dx} (1 - x^2) \frac{dP_m}{dx} + P_n \frac{d}{dx} \left
[(1 - x^2) \frac{dP_m}{dx} \right ],$$
Eq. ($*$) may be rewritten as
$$\frac{d}{dx} \left [P_n(1 - x^2) \frac{dP_m}{dx} \right ]
- \frac{dP_n}{dx} (1 - x^2) \frac{dP_m}{dx} - \frac{d}{dx} \left
  [P_m(1 - x^2) \frac{dP_n}{dx} \right ] + \frac{dP_m}{dx} (1 -
  x^2) \frac{dP_n}{dx} + (m^2 + m - n^2 - n) P_m P_n = 0,$$
which reduces to
$$\frac{d}{dx} \left [P_n(1 - x^2) \frac{dP_m}{dx} \right ]
- \frac{d}{dx} \left [P_m(1 - x^2) \frac{dP_n}{dx} \right ] + (m^2 + m -
  n^2 - n) P_m P_n = 0.$$
On integrating up the above equation with respect to $x$ from $-1$ to 1 we have
\begin{align*}
\int^1_{-1} \left \{\frac{d}{dx} \left [P_n(1 -
x^2) \frac{dP_m}{dx} \right ]
- \frac{d}{dx} \left [P_m(1 - x^2) \frac{dP_n}{dx} \right ] \right \} dx\\
\hspace{-8.0cm}+ (m^2 + m - n^2 - n) \int^1_{-1} P_m P_n \, dx &= 0\\
\left [P_n(1 - x^2) \frac{dP_m}{dx} - P_m(1 -
  x^2) \frac{dP_n}{dx} \right ]^1_{-1} + (m - n)(m + n +
  1) \int^1_{-1} P_m P_n \, dx &= 0\\
(m - n)(m + n + 1) \int^1_{-1} P_m P_n \, dx &= 0.
\end{align*}
Note the term appearing in the square brackets vanishes at both the upper and lower limits due to the presence of the factor $(1 - x^2)$ .
So when $m \neq n$, the factor out the front of the integral cancels
and we obtain
$$\int^1_{-1} P_m (x) P_n (x) \, dx = 0,$$
as required to prove.
The case $m = n$
To prove the $m = n$ case let us define
$$A_n = \int^1_{-1} [P_n (x)]^2 \, dx.$$
From Bonnet's recurrence relation for the Legendre polynomials, namely
$$(n + 1) P_{n + 1} (x) - (2n + 1)x P_n (x) + n P_{n - 1} (x) = 0,$$
if we replace $n$ with $n - 1$, after rearranging we have
$$P_n (x) = \frac{2n - 1}{n} x P_{n - 1} (x) - \frac{n - 1}{n} P_{n -
2} (x).$$
Using this result, substituting for one of the $P_n(x)$ terms in the
integral for $A_n$ we have
\begin{align*}
A_n &= \int^1_{-1} P_n (x) P_n (x) \, dx\\
&= \int^1_{-1} P_n (x) \left [\frac{2n - 1}{n} x P_{n - 1} (x) - \frac{n - 1}{n} P_{n -
2} (x) \right ] \, dx\\
&= \frac{2n - 1}{n} \int^1_{-1} x P_n (x) P_{n - 1} (x) \, dx
- \frac{n - 1}{n} \int^1_{-1} P_n (x) P_{n - 2} (x) \, dx
\end{align*}
But by the orthogonality property, as
$$\int^1_{-1} P_n (x) P_{n - 2} (x) \, dx = 0,$$
this yields
$$A_n (x) = \frac{2n - 1}{n} \int^1_{-1} x P_n (x) P_{n - 1} (x) \, dx.$$
Now from Bonnet's recurrence relation, by making the term $x P_n (x)$ the
subject we have
$$x P_n (x) = \frac{1}{2n + 1} \left [(n + 1) P_{n + 1} (x) + n P_{n -
1} (x) \right ],$$
which on substituting into the integral for $A_n$ one obtains
\begin{align*}
A_n &= \frac{2n - 1}{n} \cdot \frac{n + 1}{2n +
1} \int^1_{-1} \!\! P_{n +
1} (x) P_{n -1} (x) dx + \frac{2n - 1}{2n + 1} \int^1_{-1} [P_{n -
1} (x)]^2 dx\\
&= \frac{2n - 1}{2n + 1} A_{n - 1}, \quad n = 1,2,3,\ldots
\end{align*}
where we have again made use of the orthogonality property.
As $P_0 (x) = 1$, a value for $A_0$ can be found. It is
$$A_0 = \int^1_{-1} [P_0 (x)]^2 \, dx = \int^1_{-1} dx = 2.$$
So we have
\begin{align*}
A_n &= \frac{2n - 1}{2n + 1} A_{n - 1}\\
&= \frac{2n - 1}{2n + 1} \cdot \frac{2n - 3}{2n - 1} A_{n -
2}\\
& \hspace{1.0cm} \vdots\\
&= \frac{2n - 1}{2n + 1} \cdot \frac{2n - 3}{2n -
1} \cdots \frac{3}{5} \cdot \frac{1}{3} A_0\\
&= \frac{2n - 1}{2n + 1} \cdot \frac{2n - 3}{2n -
1} \cdots \frac{3}{5} \cdot \frac{1}{3} \cdot 2\\
&= \frac{2}{2n + 1}
\end{align*}
Hence
$$\int^1_{-1} [P_n (x)]^2 \, dx = \frac{2}{2n + 1},$$
and completes the proof.


text:
Q: Designing signal conditioner to convert current source to voltage output I've seen a lot of signal conditioners online for converting a 4-20 mA current loop signal to a 0-10 voltage output. However, they seem extremely expensive for the task they are achieving. Are the high costs due to protection against spikes in the input/other extreme events?

A:
Are the high costs due to protection against spikes in the input/other extreme events?

Yes, this would be a standard expectation in industrial control systems. Many also include isolation between the input and output signals and this will push the cost up significantly. This eliminates ground loops and allows, for example, the PLC to be electrically isolated from the sensor loop.

simulate this circuit – Schematic created using CircuitLab
Figure 1. Conversion doesn't have to be expensive.
If you can tolerate 2 - 10 V from the conversion then a 500 Ω precision resistor will do the job. These are available in 0.1% tolerance from the big suppliers such as RS.
Just as the 4 mA gives a "live zero" (which means that you can tell the difference between a sensor giving a zero indication as opposed to a sensor that has become disconnected) the 2 - 10 V can be used in the same way if you can set the scale and span of the input you are feeding.


text:
Q: SSJS is not executed on xPage I met some strange problem. A page button does not execute SSJS when it's clicked first time after page load. But does work when you click it again. I found it especially when you clear browser cache.

*

*Try to clear Chrome cache (Ctrl+Shift+Del. Clear everything).

*Restart Chrome.

*Try to load this page TEST.xsp. First pass server login page.

*Click 'My Button'. It doesn't do anything. It's supposed to e.g. redirect to same page with a new parameter e.g. param1=true (sure it should do nothing, but just add param1=true to the URL)

*Click it again. It does work

What could cause this behavior? It can be any SSJS not exactly context.redirectToPage. But it works only when you click button second time. Same problem found on FF but it does work in IE.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
    <xp:button id="button1" styleClass="btn btn-primary btn-sm"
        value="My Button" title="My Button">

        <xp:eventHandler event="onclick" submit="true"
            refreshMode="complete" id="eventHandler10">
            <xp:this.action><![CDATA[#{javascript:context.redirectToPage("TEST.xsp?param1=true");}]]></xp:this.action>
        </xp:eventHandler>
    </xp:button>
</xp:view>

Here is my app configuration options:

A: This does help when you put it into afterPageLoad event.
if(!sessionScope.APP_LOADED){
    sessionScope.put("APP_LOADED", true);
    context.reloadPage();
}else if(sessionScope.APP_LOADED==false){
    sessionScope.put("APP_LOADED", true);
    context.reloadPage();
}

A: You have to set the following parameter, then it should work as expected:

A: I think I had a similar problem. I had to add an OnClientLoad action, with nothing in it. Why exactly I don't know.


text:
Q: Doctrine2 Many to Many Multiple Join on Table My schema looks like this:
items - item_id, ...
items_item_types - item_id, item_type_id
item_types - item_type_id, ...

I need a query that will get items with ALL the item types given. For example, let's say item 1 is type 10, and item 2 is types 10, 11, and 12. I'm given 10 and 11, item 1 wouldn't be returned but item 2 would.
To clarify further:
--------------------------
| item_id | item_type_id |
| 1       | 10           |
| 2       | 10           |
| 2       | 11           |
| 2       | 12           |
--------------------------

I can do this easily in SQL, for example
select * from items
    join item_item_types join_table1 on items.item_id = join_table1.item_id and join_table1.item_type_id = 10
    join item_item_types join_table2 on items.item_id = join_table1.item_id and join_table2.item_type_id = 11

Which would return item 2 in this case
The query is already quite complicated and I'm being passed a reference to the QueryBuilder object, so I cannot use native SQL (as far as I know). What my code looks like:
function addItemTypesToQuery(&$qb, $itemTypes) {
    foreach($itemTypes as $key => $value) {
        $qb->join('item.itemTypes', 'item_type' . $key, 'WITH', ???)
    }
}

I'm not sure what the join condition needs to be to mirror the SQL. Doctrine skips over the intermediary step of joining the item_item_types table but I need to set join conditions on THAT, not on the item_types table.

A: Doctrine will handle the joins automatically and search a set of values in the Many-to-Many table using either the ItemType entity ID or entity reference. This is done with the MEMBER OF DQL:
function addItemTypesToQuery(&$qb, $itemTypes) {
    $i = 0;
    foreach($itemTypes as $key => $value) {
        $qb->addWhere('?'.$i.' MEMBER OF item.itemTypes')
            ->setParameter($i++, $key)
        ;
    }
}

Note: I don't know the parent structure of your QueryBuilder, but you could run into problems if you've already set parameters with the numeric identifiers. One alternative is:
function addItemTypesToQuery(&$qb, $itemTypes) {
    $i = 0;
    foreach($itemTypes as $key => $value) {
        $qb->addWhere(':itemWhere'.$i.' MEMBER OF item.itemTypes')
            ->setParameter('itemWhere'.$i++, $key)
        ;
    }
}

Note that $key must be the primary identifier of the ItemType entity. You can also use $value if it's the actual ItemType entity reference.


text:
Q: How to repackage an .ANE extension in Windows I have an conflict in my flash project between my native extensions. Some java libraries are included in both ANES, so I cant publish the game(I receive an error ...library X is added). I search around the google. And I found that I need to remove duplicated libraries, and after that I need to repackage the ANE with adt. I never did that before and I never created an ANE extension. Can someone guide me to a good direction, and how can I repackage my ane?
Thank you!

A: For AIR native extension packaging, take a look on :

*

*Packaging a native extension.

*Building a native extension for iOS and Android – Part 5: Building the ANE file.

*Developing and using Adobe AIR native extensions for Android devices.
Hope that can help.


text:
Q: Partially duplicated history when setting PS1 in .bash_profile When I set PS1 variable in ~/.bash_profile, it worked as configured. However, the history is somehow messed up.
When I press Arrow Up or Ctrl+P to view commands I typed, it starts to duplicate partially at some points. The scenario is displayed below(pay attention to cd /Co which is  the duplicated part):

Although visually duplicated, when press enter I still get the correct result in history commands.
Here's my system information:

*

*OS: Mac OS X 10.9.4

*Terminal: system default terminal, iTerm 2

I set PS1 in my .bash_profile like this:
PS1='${YELLOW}\u${WHITE} in ${GREEN}\w${WHITE}${YELLOW}`__git_ps1 " on
%s"`${WHITE}\r\n${NORMAL}$ '

A: You need to put \[ and \] around all escape sequences so that the line editor knows how long the prompt is.


text:
Q: Find max number in 2d array with thread I want to create one thread for each row of my 2D array. Then each thread should find the max value in given row, but I can't wait for any thread to complete with pthread_join. So what should I do?

A: From what I understand you want to split your 2D array into 1D arrays and pass them to threads, but you don't know what to do when each of these threads finds maximum in its "own" array - and  you don't want to pass this value to pthread_exit() and retrieve it by pthread_join() in the main thread.
You could use global array managed by the main thread for storing these values. Here's the idea (pseudocode):
int* max; // global

thread(...){
int localMax = 0;
...
max[rowIndex] = localMax;
}

// main thread:
max = malloc (rowCount * sizeof(int));
...
free(max);

Each thread finds local maximum localMax in given array (row) and stores it into array max.
But at the end you will have to use pthread_join so that you know that all threads have finished their work.


text:
Q: Zero horizontal space between cells in UICollectionView not working I am new to iOS development and cannot seem to figure out why my collection view is spacing out. It almost seems as though a "margin-right" as in CSS has been applied to each cell. I have set the "Min Spacing" for cells and for lines to zero but the following is still occurring...
Screen shot of issue that is occurring
I have purposely set the collection view's background color to blue, the cell's background color to red and the label's border color to black to try to see what is what. The objective is to not see any of the 'blue' (collection view background), at all. Upon configuring the collection view, I resize the cell's width to fit the label's intrinsic width but it seems that the other cells' x-axis location stays the same... I need all the cells to come together. Any help would be greatly appreciated!
Current CollectionViewController code...
import Foundation
import UIKit

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

var menu = [
    ("NEWS"),
    ("NEIGHBORHOODS"),
    ("CULTURE"),
    ("DEVELOPMENT"),
    ("TRANSPORTATION"),
    ("CITIES")
]

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Testing"
    self.navigationController?.navigationBarHidden = true

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return menu.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UnderMenuCell", forIndexPath: indexPath) as! UnderMenuCollectionViewCell

    cell.underMenuLabel.text = menu[indexPath.row]
    let label_width = cell.underMenuLabel.intrinsicContentSize().width + 23

    cell.underMenuLabel.layer.zPosition = 1000000
    cell.underMenuLabel.layer.borderWidth = 2
    cell.underMenuLabel.layer.borderColor = UIColor.blackColor().CGColor

    cell.frame.size.width = label_width

    return cell

}

}

A: You might need to set up layout attributes for the cells to specify their width:
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)

    attributes.frame = yourFrameHere
    attributes.size = yourSizeHere

    return attributes
}

Also have you tried setting a breakpoint at cell.frame.size.width = label_width to see what width is actually being set?

A: I ended up figuring out a way that worked perfectly:
import Foundation
import UIKit

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var underMenuCollection: UICollectionView!

var menu = [
    ("NEWS"),
    ("NEIGHBORHOODS"),
    ("CULTURE"),
    ("DEVELOPMENT"),
    ("TRANSPORTATION"),
    ("CITIES")
]

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Testing"
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let scrollToIndexPath = NSIndexPath(forItem: 2, inSection: 0)
    self.underMenuCollection.scrollToItemAtIndexPath(scrollToIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
}

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return menu.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UnderMenuCell", forIndexPath: indexPath) as! UnderMenuCollectionViewCell

    cell.underMenuLabel.text = menu[indexPath.row]

    return cell

}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let size: CGSize!
    let testLabel = UILabel()
    let labelText = menu[indexPath.row]

    testLabel.text = labelText
    testLabel.font = UIFont(name: "Avenir Next Condensed", size: 17)
    testLabel.hidden = true

    size = CGSize(width: testLabel.intrinsicContentSize().width + 13, height: self.underMenuCollection.frame.height)

    return size

}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    self.underMenuCollection.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)

}

}

So what happens is I create a hidden label that never evens gets added to the superview, populate it with the text to calculate the intrinsic width and then set the CGSize. It works perfectly...
Picture of collection view to the left
Picture of collection view to the right
The most important part in all this was the have equal spacing between all the cells dynamically based on the width of the string.


text:
Q: installing node.js v0.8.1 via nvm fails While installing node 0.8.1 via nvm (newest from git) I get an error, that doesn't make any sense for me;
CXX(target) /home/ubuntu/.nvm/src/node-v0.8.1/out/Release/obj.target/v8_base/deps/v8/src/checks.o
g++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.6/README.Bugs> for instructions.
make[1]: *** [/home/ubuntu/.nvm/src/node-    v0.8.1/out/Release/obj.target/v8_base/deps/v8/src/api.o] Error 4
make[1]: *** Waiting for unfinished jobs....
make[1]: Leaving directory `/home/ubuntu/.nvm/src/node-v0.8.1/out'
make: *** [node] Error 2
nvm: install v0.8.1 failed!

all previous installs with 0.6.18 were successful. Python is forced to python2 and libssl-dev is the newest on a ubuntu11.10. Does anybody have any advice? Thank you

A: I created a swapfile on my ec2 instance and voilà, compilation worked. Thanks Alan Curry for the memory hint. Was surprised that there wasn't any swap to start with..


text:
Q: Queue job with 4 hours delay I have a mission-critical queue in laravel 5.4 which is powerd by Redis and 8 workers on supervisor.
In this queue, I have to make delayed jobs with a delay about 4 hours like this:
        $job = (new VerifyAndOrderJob($books))
            ->onQueue('orders')
            ->delay(\Carbon::now()->addHours(4));

        dispatch($job);

Now since Laravel queues are based on FIFO, If I have thousands of delayed jobs like this in the queue everyday and I wanted to push a same job but without any delay, is it need to wait till other delayed jobs to be processed or this will be fired instantly?


text: Q: Center text on line vertically while increasing line-spacing in Ms-Word Ms-Word place the text on bottom of line whatever line-spacing is so some small high chars cutting off. Increasing line-spacing "exactly" solving that only but paragraph looks emptily. For balancing line-space require centering text on middle of line but how to do it?


text:
Q: Array filter by array of array elements? I have sample data
[{
    "section": "RADIOGRAPHY",
    "sub_type": "ABDOMEN & PELVIS",
    "list": [{
        "item": "Abdomen",
      },
      {
        "item": "Abdomen/Pelvis"
      }
    ]
  },
  {
    "section": "SCANNING",
    "sub_type": "ABDOMEN & PELVIS",
    "list": [{
        "item": "first",
      },
      {
        "item": "second"
      }
    ]
  }
]

I want to filter the deep array like if I search by list item name it should match likely
if I search with fir it should return matched object to that condition but it is not woking
 let temp = this.name.map(function(ele){
    return ele.list.filter(el => {
      return el['item'].includes(`${value}`)
    })
  });
  console.log(temp);

A: You can use filter instead of map, and in the second find uset find
const temp = name.filter(function(ele){
    return ele.list.find(el => {
      return el['item'].includes(`fir`)
    })
  });

A: Are you looking like this?

let arr = [
    {
    "section": "RADIOGRAPHY",
    "sub_type": "ABDOMEN & PELVIS",
    "list": [{
      "item": "Abdomen",
    },
    {
      "item": "Abdomen/Pelvis"
    }
    ]},
    {
    "section": "SCANNING",
    "sub_type": "ABDOMEN & PELVIS",
    "list": [{
      "item": "first",
    },
    {
      "item": "second"
    }
    ]}
]
let toSearch = 'Abd';

let array = arr.map(a=>a.list).flat().filter(o => o.item.includes(toSearch));

console.log(array);

A: You can try this.
let tmp = this.name.map( ele => ele.list.filter(el => el.item.includes(`${value}`)))

A: This will work for you. Try this out.
let input = "fir";
let temp = [];
arr.forEach(item => item.list.forEach( e => e.item.search(input.trim()) > -1 ? temp.push(e) : ""));

console.log(temp);

Output of this will be:
[ { item: 'first' } ]


text:
Q: Value of type java.lang.String cannot be converted to JSONArray in Android(repost) I am repost this coz I dont find the solution for this problem...
here is error
org.json.JSONException:Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

here is JSON output:
[{"name":"Muhaimin","address":"Sylhet","bgroup":"o+"}]

here is class code:
entpackage com.example.blood;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
resultView=(TextView) findViewById(R.id.result);
getData();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void getData()
{
 String result="";
 InputStream isr=null;
 try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost=new HttpPost("http://10.0.2.2/blood/index.php");
    httppost.setHeader("Content-Type", "application/json");
     httppost.setHeader("Accept", "JSON");
    HttpResponse response=httpclient.execute(httppost);
    HttpEntity entity=response.getEntity();
    isr=entity.getContent();
  }catch(Exception e){
    String err=e.toString();
    resultView.setText("Could not connect to database"+err);
    Log.e("error", err);
  }

try{
    BufferedReader reader=new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
    StringBuilder sb=new StringBuilder();
    String line=null;
    while((line = reader.readLine()) != null){
        sb.append(line + "\n");
    }
    isr.close();

    result=sb.toString();
   }catch(Exception e){
    String err2=e.toString();
    resultView.setText("Error coverting result"+err2);
    Log.e("error", err2);
  }
  try{
    String s="";
    JSONArray jArray=new JSONArray(result);

    for(int i=0;i<jArray.length();i++){
        JSONObject json=jArray.getJSONObject(i);
        s= s +
                "Name :"+json.getString("name")+"\n"+
                "Blood Group :"+json.getString("bgroup")+"\n" +
                "Address :"+json.getString("address")+"\n\n";
    }
    resultView.setText(s);
  }catch(Exception e){
    String err1=e.toString();
    resultView.setText("xxx"+err1);
    Log.e("error", err1);
 }
 }

}

here is php code:
  <?php
$con=mysql_connect("localhost","root","","BloodDB");
mysql_select_db("BloodDB",$con);

$result=mysql_query("SELECT name,address,bgroup FROM tbl_blood_donor");

while($row=mysql_fetch_assoc($result))
{
    $output[]=$row;
}
print(json_encode($output));
mysql_close($con);
 ?>

Now how to solve this problem.I am working in localhost.thanks in advance

A: Your problem is not in JSON and not in the JSONArray so if you got this exception then this means the string to JSONArray not as you expected.
Print the string result and the string length before this line "JSONArray jArray=new JSONArray(result);". You can use the below print message for that
Log.d("My String", "string result :[" + result + "] and its length is :" + result.length());
Note that, I used the below code and it working fine
String str = "[{\"name\":\"Muhaimin\",\"address\":\"Sylhet\",\"bgroup\":\"o+\"}]";
    try {
        JSONArray json = new JSONArray(str);
        Log.d(TAG, "Json value :" + json);
        Log.d(TAG, "Json value :" +    json.getJSONObject(0).getString("bgroup"));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

result:
Json value :[{"bgroup":"o+","address":"Sylhet","name":"Muhaimin"}]
Json value :o+


text:
Q: If Statement Not Running When Condition is True In this code, one of my sprites should reduce speed until it meets 0.75. However, once the code does get to 0.75, it keeps reducing for some reason. I have a timer which calls the speed_Control func every 0.2 seconds and the sprite.speed starts at 1.0.
func speed_Control() {
    if boolDecrease == true {
        speed_Decrease()
    }
}

func speed_Decrease() {
    if sprite.speed != 0.75 {
        println(sprite.speed)
        sprite.speed -= 0.05
    } else {
        boolDecrease = false
    }
}

I added println(sprite.speed) to see if my sprite does actually ever return 0.75, which it does, so I don't know how it passes if sprite.speed != 0.75.
Can anybody see what is wrong with this?

A: Floating-point values should not be compared using (in)equality operators. The value 0.05 cannot be exactly represented, so speed will end up being something close to, but not exactly equal to 0.75. A simple solution here would be to change the condition sprite.speed != 0.75 to sprite.speed > 0.76.


text:
Q: Запись в файл содержимого нескольких StringGrid На форме расположено 4 элемента StringGrid. Как записать содержимое всех четырех элементов в файл? И так же потом считать содержимое файла и внести все данные в StringGrid'ы автоматически с сохранением размерности таблиц и последовательностью данных?
A: На этой странице
можно посмотреть вывод данных из StringGrid в файлы Excel (два способа).

A: Пример желаемого действия с просторов гугла:
// Save a TStringGrid to a file

procedure SaveStringGrid(StringGrid: TStringGrid; const FileName: TFileName);
 var
   f:    TextFile;
   i, k: Integer;
 begin
   AssignFile(f, FileName);
   Rewrite(f);
   with StringGrid do
   begin
     // Write number of Columns/Rows
    Writeln(f, ColCount);
     Writeln(f, RowCount);
     // loop through cells
    for i := 0 to ColCount - 1 do
       for k := 0 to RowCount - 1 do
         Writeln(F, Cells[i, k]);
   end;
   CloseFile(F);
 end;

 // Load a TStringGrid from a file

procedure LoadStringGrid(StringGrid: TStringGrid; const FileName: TFileName);
 var
   f:          TextFile;
   iTmp, i, k: Integer;
   strTemp:    String;
 begin
   AssignFile(f, FileName);
   Reset(f);
   with StringGrid do
   begin
     // Get number of columns
    Readln(f, iTmp);
     ColCount := iTmp;
     // Get number of rows
    Readln(f, iTmp);
     RowCount := iTmp;
     // loop through cells & fill in values
    for i := 0 to ColCount - 1 do
       for k := 0 to RowCount - 1 do
       begin
         Readln(f, strTemp);
         Cells[i, k] := strTemp;
       end;
   end;
   CloseFile(f);
 end;

 // Save StringGrid1 to 'c:\temp.txt':

procedure TForm1.Button1Click(Sender: TObject);
 begin
   SaveStringGrid(StringGrid1, 'c:\temp.txt');
 end;

 // Load StringGrid1 from 'c:\temp.txt':

procedure TForm1.Button2Click(Sender: TObject);
 begin
   LoadStringGrid(StringGrid1, 'c:\temp.txt');
 end;


text:
Q: passbook pass not enter newline using "\r\n" I am using passbook, and have some input value, like this:
{
    "key" : "terms",
    "label" : "terms_contions",
    "value" : "1.aaaaaaa
               2.bbbbbbb
               3.ccccccc
               4.ddddddd
}

I use "enter" key, I want to newline to see the value, but the pass show mistake.
so I modify it to:
{
    "key" : "terms",
    "label" : "terms_contions",
    "value" : "1.aaaaaaa 2.bbbbbbb 3.ccccccc 4.ddddddd
}

and all is ok, but I do not want  1. 2. 3. 4. at one line. I want to have 4 lines. How can I accomplish this?

A: Newlines will only work on back fields. Encode the newlines into the JSON like below and you should be OK.
{
    "key" : "terms",
    "label" : "terms_contions",
    "value" : "1.aaaaaaa\r\n2.bbbbbbb\r\n3.ccccccc\r\n4.ddddddd"
}

Example working pass with newlines in the last backfield.

A: {
    "key" : "terms",
    "label" : "terms_contions",
    "value" : "1.aaaaaaa\n 2.bbbbbbb\n 3.ccccccc\n 4.ddddddd
}


text:
Q: c++ call template class specialization member function I am new in C++ and I am trying to implement template class specialization member functions.
Here is the code which I did:
#include <iostream>
#include <map>
using namespace std;
using std::string;

namespace std {
template <> struct number_limits<Second> {
    using val_type = Second::value_type;

    public:
        val_type fmin() {
            return Second::min_val();
        }
        val_type fmax() {
            return Second::max_val();
        }
};
}

class Borders {};
class Second {
public:
    using value_type = short;
private:
    value_type n = min_val();
public:
    Second() = default;
    value_type valeur() const noexcept {
        return n;
    }
    static value_type min_val() noexcept {
        return 0;
    }
    static value_type max_val() noexcept {
        return 59;
    }

    static value_type prochaine(value_type m) {
        return m == max_val() ? m % max_val() : m + 1;
    }

    Second(value_type val) {
        if (val < min_val() || val > max_val()) {
            throw Borders{};
        }
    }

};

int main()
{
    number_limits<Second> test;

    return 0;
}

When I try to compile it, i am getting the list of the errors:

Please give me suggestions how I can make template class "number_limits" correctly and how I could call function fmax() of this class from main() function?

A: I would recommend researching classes in C++ more before coming back to this problem. I also would recommend not messing with namespaces yet as a beginner as they're only really useful when working in large teams of developers and only make the code harder to understand when used correctly. It doesn't seem like you quite understand what classes are and how they work, so here's a quick rundown about the basics of classes to get you started.
Classes
1. Why are they useful?
Classes, similar to structures, help us to organize data and its related functions. Classes and structures share the same basic structure (no pun intended) but classes build on structures in many ways. When making a class you want to put some related data in the class as well as functions that operate on that data. This helps organize your code better, makes sure that only the function in that class can change the data, and helps with debugging, since it narrows down the culprit of a break or bug.
2. Classes in C++
Here's a simple example class to show the syntax:
class myClass {
public:
    myClass(int x, int y, int z) { a = x; b = y; c = z; }
    int add() { return a + b + c; }
    int getA() { return a; }
    int setA(int newA) { a = newA; }
private:
    int a;
    int b;
    int c;
};

Some things to note are that the public and private access modifiers should only be listed once and everything that is public or private should be under that modifier. Doing otherwise is bad practice.
Your Code
I'm not really sure why you're using a structure of templated type class, but regardless that is not the correct syntax. Templates should be defined as follows:
template <typename T>
class myClass{};

The first line is not required to be on a separate line. The syntax is rigid except for T, which can be any identifier you wish to represent the templated type. When you are defining your structure, you're explicitly stating the type as , which undermines the purpose of templates. However, if you want the template to contain a default type, you could do as follows:
template <typename T = Second>

As you're defining whatever it is you're templating, whether or be a class, structure, or function, write the function exactly as you would normally except replace any type declarations of your templated type with the given template identifier, in this case 'T'. I would strongly recommend not going the structure route for this class, however, and you really shouldn't need a template for what you are trying to do here.
There are a lot of other improvements you could make here, but hopefully this should help you get on the right track. If you're confused about anything at all in programming it's better to research and read up. You should be able to explain to even a non-programmer why every line of code you write is there and what it does in order to write great code.


text:
Q: Some clarifications regarding XSS I happen to read about XSS and how to avoid it. From what I have read, I came to know that we need input filtering, proper handling of application code and output encoding to make the web application somewhat XSS safe. After going through several articles, several doubts still persist.

*

*When I tried jQuery.text("untrusted_data") or element.text=untrusted_data, the
browser seems to be encoding the content perfectly, but I have read somewhere else that client-side encoding should not be trusted and you have to "always" encode at the server-side. Why is client-side encoding considered not safe ?

*Whenever I tried to set value using jQuery.val(untrusted_data) or element.value=untrusted_data it seems to be safe enough. So is it really XSS safe or did I miss any case here ?

*
Also, I happen to read somewhere that jQuery.setAttribute(attrName,untrusted_data) and setAttribute(attrName,untrusted_data) are generally considered safe only if the Attribute Names doesn't include URL Context based attributes(src,href etc) or Event Handlers(onClick,onMouseOver etc). If that is the case, how am I supposed to set an href attribute by using setAttribute("href",untrusted_data)? Is encodeForHtmlAttribute(untrusted_data) from server-side the right way of approach ?

*
How should I handle dynamic html creation. Consider the below example

untrusted_data

function copyData()
{
  var divValue = jQuery("#divName1").html();
  jQuery("#divName2").html(divValue);/XSS Here
}

What I want to achieve here is to get the text from divName1 and paste it to divName2's content. The code I wrote above is XSS vulnerable. I can change this to

jQuery("#divName2").text(divValue)

So, this will ensure encoding, but as I understood, we say that client-side encoding is unsafe and only server-side encoding should be used. How should I write this to be XSS safe without using client-side encoding? I am a bit confused here :(.
Please help me out to clear these doubts.

A: This is a lot of questions at once.

Why is client-side encoding considered not safe ?

Client-side encoding is fine as long as it is done properly and consistently.  Client-side encoding often has a lower bar since it does not need to worry about character-encoding level attacks like UTF-7 attacks.

Whenever I tried to set value using jQuery.val(untrusted_data) or element.value=untrusted_data it seems to be safe enough. So is it really XSS safe or did I miss any case here ?

Assuming untrusted_data is a string and the element whose value is being set is a regular text node in a flow or block element then you're fine.  You might run into trouble if the node whose value is being assigned is a text node in a


text:
Q: How do I stop the currently playing ringtone? I'm writing an app that sometime fires reminders that are supposed to play ringtones. I can start the ringtone OK, but can't stop it.
I have a dismiss method in my fragment that should stop the currently playing ringtone and close the activity, but it doesn't work right.
Here's what it does:
    RingtoneManager ringMan = new RingtoneManager(getActivity());
    ringMan.stopPreviousRingtone();
    getActivity().finish();

The method does get executed and the activity closes, but the ringtone just keeps on playing. What am I doing wrong?

A: You have to create a class extending from Service class, the demo code is given below
Please Note this is the code form my College Project, it is for starting up default Alarm using Ringtone from BroadcastReciever extending Activity and Stopping the Ringtone from different normal Android Activity.
Service Class code:
import android.app.Service;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
public class AlarmRing extends Service {
static Ringtone r;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //activating alarm sound
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    r = RingtoneManager.getRingtone(getBaseContext(), notification);
    //playing sound alarm
    r.play();

    return START_NOT_STICKY;
}
@Override
public void onDestroy()
{
    r.stop();
}
}

Code for Activity calling the Service:
Intent i = new Intent(context, AlarmRing.class);
context.startService(i);

Activity ending or closing the Service:
Intent i = new Intent(this, AlarmRing.class);
stopService(i);`

NOTE: please note for context reference.

A: Reason why stopPreviousRingtone() is not stopping the ringtone
I found that it is only possible to stop a ringtone using RingtoneManager.stopPreviousRingtone() only if the Ringtone was created by the same RingtoneManager instance.  An easy way to confirm this is to create an activity with a RingtoneManager and three buttons:

*

*Clicking the first button will use the RingtoneManager to start a ringtone.

*Clicking the second button will call stopPreviousRingtone() on the RingtoneManager.

*Clicking the third button will call stopPreviousRingtone() on the completely different RingtoneManager instance.

After doing this, you should find that the ringtone will only stop if you click the second button.
Stopping a Ringtone if you have access to the original Ringtone instance
If you have access to the original Ringtone instance, you can just call the stop() method:
Ringtone ringtone = RingtoneManager.getRingtone(getActivity());
ringtone.play();
...
ringtone.stop();

Stopping Ringtones when keeping a reference to the original Ringtone is not possible
What you could try is to create a service which will load and play the ringtone when it was started and will stop the ringtone when it was destroyed.  Here is an example:
public class RingtonePlayingService extends Service
{
    private Ringtone ringtone;

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Uri ringtoneUri = Uri.parse(intent.getExtras().getString("ringtone-uri"));

        this.ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
        ringtone.play();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy()
    {
        ringtone.stop();
    }
}

Then, you can start the ringtone in the background just by starting the service:
Intent startIntent = new Intent(context, RingtonePlayingService.class);
startIntent.putExtra("ringtone-uri", ringtoneUri);
context.startService(startIntent);

And, to stop the ringtone, just stop the service:
Intent stopIntent = new Intent(context, RingtonePlayingService.class);
context.stopService(stopIntent);

A: Create RingtoneManager object using Application Context like this
RingtoneManager ringMan = new RingtoneManager(getApplicationContext());
    ringMan.stopPreviousRingtone();

and RingTone object also create like this only.
mRingTome = RingtoneManager.getRingtone(getApplicationContext(), notification);
            mRingTome.play();

It is working for me.


text:
Q: Django 1.3 Static Files Like the 1 billionth static file question about Django 1.3. I've been searching and trying so many things but nothing seems to work for me. Any help would be appreciated. Will try and give as much information as possible.
URL FILE
urlpatterns = patterns('',
url(r'^projectm/statictest/$','project_management.views.statictest'),)

VIEW
def statictest(request):
return render_to_response('statictest.html',locals())

TEMPLATE
<title>Static Load Test Page</title>

{% load static %}

SETTINGS
STATIC_ROOT = '/home/baz/framework/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('',)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = (
"/home/baz/framework/mysite/templates"

FILES
-bash-3.2$ pwd
/home/baz/framework/mysite/templates
statictest.html

-bash-3.2$ pwd
/home/baz/framework/mysite/project_management/static
-bash-3.2$ ls
testimage.jpg

Not too sure if there is any other information that would be helpful. But basically when I go to this test page and check the page source, the url is pointing to

However the image does not load. I have tried this on multiple browsers too. Maybe I am missing an imort statement somewhere?
cheers for the help

A: Are you using the built in runserver command or do you serve the Django app some other way?
If you use runserver then your problem is that you don't tell Django where to find your static assets in the filesystem. You need to set STATIC_ROOT to a filesystem path where your static assets can be found. Try setting it to: /home/baz/framework/mysite/project_management/static/
If you are using a different server (like gunicorn behind Nginx for example) then it is the responsibility of the front-end server to intercept requests for /static/ and serve them for you.

A: Also remember to run the 'collectstatic' management command once you have set 'STATIC_ROOT'.
https://docs.djangoproject.com/en/1.4/howto/static-files/#deploying-static-files-in-a-nutshell


text:
Q: How to stop in "Too big " to count number s In the "Too big" scenario, there should be no counting behavior and the program should end immediately after printing the "Too big" message.
var num1 = prompt("Enter the first number");
var num2 = prompt("Enter the second number");

console.log("The result is");
var result = ((num1 + num2)*2);{console.log(result);}

if (result < 20) {
  console.log("Too small");

  function countPrint(howMany){
    for ( var count = 1; count <= howMany; count++){
      console.log(count);
    }
  }
}

countPrint(result);if (result > 20){
  console.log("Too big");
}

A: var num1 = prompt("Enter the first number");
var num2 = prompt("Enter the second number");

console.log("The result is");
var result = ((num1 + num2)*2);
//             ^! thise may be strings, should be converted to numbers
{ // why block body? There's no `if` or whatever
  console.log(result);
}

if (result < 20) {
  console.log("Too small");

  function countPrint(howMany) {
    for (var count = 1; count <= howMany; count++) {
      console.log(count);
    }
  }
}

countPrint(result);
// ^! Cannot find name 'countPrint'.
// function should be outside if
// function is called no matter what the result is

if (result > 20) {
  console.log("Too big");
}

As countPrint(5) call is not inside if, it does not care about if. As if is not intide function ..(..), thr function does not care about if
function countPrint(howMany) {
  for (var count = 1; count <= howMany; count++) {
    console.log(count);
  }
}
if (result <= 20) {
  countPrint(result)
} else {
  console.log(`${result} is Too big`); // <- template string
}

function countPrint(howMany) {
  if (howMany <= 20) {
    for (var count = 1; count <= howMany; count++) {
      console.log(count);
    }
  } else {
    console.log(`${howMany} is Too big`); // <- template string
  }
}
countPrint(result)

A: soon you enter the for loop, it will log all number from your specified 1 to howMany, so you need to do something inside the loop and not outside as you are trying to do...
in a for loop, you can use break to get out of the loop
    for (var count = 1; count <= howMany; count++) {
      if (count > 20) break;
      console.log(count);
    }

here's an example

const countNumbers = (howMany, maxCount) => {
    console.log('starting counting to', maxCount);
    for (let count = 1; count <= howMany; count++) {
      if (count > maxCount) {
        console.log('the counting %s is higher than the max %s', count, maxCount);
        break; // let's break out of the loop
      }
      console.log('counting ->', count);
    }
}

countNumbers(30, 10);


text:
Q: Returning a hash for each depth level of a matrix I'm working on developing an algorithm where a user can pass in a centre geohash and a depth_value and would get a hash that maps each depth with an array of geohashes at that depth.
For example, take a look at this:
+--------+--------+--------+
 | xn774d | xn774f | xn7754 |
 +--------+--------+--------+
 | xn7749 | xn774c | xn7751 |
 +--------+--------+--------+
 | xn7748 | xn774b | xn7750 |
 +--------+--------+--------+
If the user passes in center_geohash: xn774c and a depth of 1. It would return
{depth_0: [xn774c],
  depth_1: [xn774d, xn774f, xn7754, xn7751, xn7750, xn774b, xn7748, xn7749]
} (if a depth of 2 was passed in, it would return an array of 16 geohashes)
Tools I have already developed:
I have access to a method that returns back a 2D matrix when you pass in the top right most geohash, and bottom left most geohash. A neighbors method is also available where it returns the 8 geohashes surrounding a given geohash, and an adjacent method that takes in a geohash and a direction and returns a single geohash in that direction.
Thanks so much

A: What I ended up doing was creating a NxN matrix and then traversing it in a spiral order. Say I was iterating through the matrix in a clockwise fashion, then at every point where I move from left -> to -> right, would mean that I am at a new depth value. I would then just populate my hash for that new depth_value_key by appending the geo-hashes until the next time I move from the left to right direction again. Hope that helps!


text:
Q: How to identify albums in "Gallery" app ? The UI automator just displays a Relative Layout without identifying the individual albums How to identify albums in "Gallery" app ? The UI automator just displays a Relative Layout without identifying the individual albums.
I am using Appium.
I am using a real device (Motorola X Play)
Exact functionlity : Open Whatsapp - Search a contact - Click on Attachment icon - Navigate to Gallery app (from Whatsapp ) - Select a pic from a specific album and then send to the contact.
Until Navigation to Gallery app is successful. Unable to click on a specific Album.
Any expert advice would really be helpful.