text:
Q: camel HTTP4 JBoss : unable to find valid certification path to requested target I request a access token from a UAA service. recieve the token. then use the token to upload a file to an AWS environment. now it works with one environment and doesn't work with another.  the only major difference can find is that the one that works uses SSO auth and and one that doesn't work uses UAA auth.  since I request a token from a UAA server/service and use it to POST a data file to an environment I don't have use of a key store.  I am getting the following error.
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I am using JBoss Fuse JBoss Fuse (6.3.0.redhat-310) container running my application bundles
Java 8
Camel-HTTP4 to post
any suggestions or help would be greatly appreciated, is there anything I am missing? does anything special need to be done ?  thank you!
oh yeah, It works when I do it in Postman? not in fuse?
it also works with Curl.
HTTP/1.1 200 Connection Established
Proxy-Agent: Zscaler/6.0

HTTP/1.1 100 Continue
Server: Zscaler/6.0

HTTP/1.1 201 Created
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Corr: ef75916afaf1db34
Date: Tue, 05 Jun 2018 22:58:27 GMT
Expires: 0
Pragma: no-cache
Server: none
X-Application-Context: APMTS:cloud:10
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Vcap-Request-Id: 1b964238-0dbc-4c09-7c6f-0bc429698584
X-Xss-Protection: 1; mode=block

A: found my problem was with certs. I located the certs for those systems, imported to java keystore. problem is gone.
thank you all


text:
Q: Windows 7 cannot boot after Ubuntu install I installed Ubuntu 13.04 on an unassigned partition, but Windows 7 cannot reboot after choosing it, saying Windows Boot Manager error.
Windows Boot Manager
Windows failed to start. A recent hardware or software change might be the cause.
To fix the problem:

  1. Insert your Windows installation disc and restart your computer.
  2. Choose your language settings, and then click "Next."
  3. Click "repair your computer."

If you don't have this disc, contact your system administrator or computer
manufacturer for assistance.

  File: \boot\bcd

  Status: 0xc000000f

  Info: An error occurred while attempting to read the boot configuration data.
When I tried to repair I cannot find Windows disk. Then I went to reinstall, cannot find the partitions at all. I checked in Ubuntu, the filesystem type for C:drive is NTFS.
What should I do to get my Windows back?

A: BCD Repair
Windows have a tool for this purpose, called BCDboot.

If the system partition has been corrupted, you can use BCDboot to replace the system partition files with new copies of these files from the Windows partition.

When you have booted to the Windows disc, then go to the command prompt (see here) and type the following to recreate the BCD on the C drive:

*

*attrib -r -s -h c:\boot\bcd - unhide BCD so it can be deleted

*del c:\boot\bcd - delete the current BCD

*bcdboot C:\windows - create a new BCD on the C drive

Method 2

*

*Put the Windows installation disc in the disc drive, and then start the computer.

*Press a key when the message indicating Press any key to boot from CD or DVD.... appears.

*Select a language, a time, a currency, and a keyboard or another input method, and then click Next.

*Click Repair your computer.

*Click the operating system that you want to repair, and then click Next.

*In the System Recovery Options dialog box, click Command Prompt.

*Try the bootec commands and then run StartUp Repair twice from your Windows Disk.  Enter these commands:

*

*bootrec /fixmbr

*bootrec /fixboot

*bootrec /scanos

*bootrec /rebuildbcd
From here you should be able to boot into Windows again.
If does not work, you can try to solve this problem using Boot Repair (as already mentioned), see here.

A: Can you boot into Ubuntu?
If so try running sudo update-grub2 That has always fixed windows boot problems for me!

A: I just started using ubuntu on a few different PCs, and I've found that the tried-and-true solution in all of them is using the Boot-Repair-disk provided by ubuntu. It has solved nearly every boot problem I've faced so far, and it doesn't require much but a few clicks (ie. no endless terminal/command prompt tinkering).
Try the automatic repair in the boot repair disk, which will scan all installed OS's, re-build the grub and give you startup options for your dual boot system.

A: if u can't get the disk as they mentioned earlier  just try pressing
F8 to go to advanced startup then F7 to disable driver signature  it Will automatically start your windows (xp,vista,7or8)  ran
tanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to display the value of a known sibling within a template call? This is a cut down snippet of XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="WEEK-AYFM.xsl"?>
<MeetingWorkBook>
  <Meeting>
    <LAC CircuitVisit="0">
      <SongEnd Title=""This Is the Way"" StartTime12="8:55" StartTime24="20:55" EndTime12="9:00" EndTime24="21:00">65</SongEnd>
      <PrayerEnd>Brother 8</PrayerEnd>
    </LAC>
  </Meeting>
</MeetingWorkBook>

And this is some calling XSL:
  <xsl:template match="LAC">

      <xsl:apply-templates select="SongEnd">
        <xsl:with-param name="strPrayerEnd">
          <xsl:value-of select="PrayerEnd"/>
        </xsl:with-param>
      </xsl:apply-templates>

  </xsl:template>

  <xsl:template match="SongEnd">
    <xsl:param name="strPrayerEnd" />

        <xsl:value-of select="@EndTime24"/>

          Prayer:

        •
        Song

          <xsl:value-of select="."/>

        <xsl:value-of select="$strPrayerEnd"/>

  </xsl:template>

Is it possible for the SongEnd template to directly get access to the PrayerEnd value without me passing it as a parameter?

A: In the template which matches SongEnd the context node is a SongEnd element. You can then use a simple XPath expression to select the PrayerEnd node in the template with respect to the context node.
For instance if the PrayerEnd is always the following sibling of SongEnd you can write
<xsl:value-of select="following-sibling::PrayerEnd"/>

without using the parameter.

A: As I said in comments, I believe you're making this more complicated than it needs to be. Either one of the following stylesheets will produce the same result as your current one:
1.
<xsl:template match="LAC">

                <xsl:value-of select="SongEnd/@EndTime24"/>

                  Prayer:

                •
                Song

                    <xsl:value-of select="SongEnd"/>

                <xsl:value-of select="PrayerEnd"/>

</xsl:template>

2.
<xsl:template match="LAC">

            <xsl:apply-templates select="SongEnd"/>

                <xsl:value-of select="PrayerEnd"/>

</xsl:template>

<xsl:template match="SongEnd">

        <xsl:value-of select="@EndTime24"/>

          Prayer:

        •
        Song

            <xsl:value-of select="."/>

</xsl:template>

3.
<xsl:template match="LAC">

            <xsl:apply-templates/>

</xsl:template>

<xsl:template match="SongEnd">

        <xsl:value-of select="@EndTime24"/>

          Prayer:

        •
        Song

            <xsl:value-of select="."/>

</xsl:template>

<xsl:template match="PrayerEnd">

        <xsl:value-of select="."/>

</xsl:template>


text:
Q: Regular expression for 3 decimal point I need a regular expression that satisfy these rules:

*

*The maximum number of decimal point is 3 but a number with no decimal point (e.g 12) should be accepted too

*the value must be at least 0

*the value must be less or equal to 99999999999.999

*the radix point is DOT (e.g 2.5, not 2,5)

Sample of valid numbers:
0
2
0.4
78784764.23
45.232

Sample of invalid numbers:
-2
123456789522144
84.2564

I found an example here (http://forums.asp.net/t/1642501.aspx) and have managed to modify it a little bit to make 0 as the minimum value, 99999999999.999 as the maximum value and to accept only DOT as radix point. Here's my modified regex:
^\-?(([0-9]\d?|0\d{1,2})((\.)\d{0,2})?|99999999999.999((\.)0{1,2})?)$

However, I still have problem with the 3 decimal point and it is rather unstable. Can anyone help me on this since I'm basically illiterate when it comes to regex?
Thanks.
EDITED:
I'm using ASP Regular Expression Validator

A: This is not that difficult:
^[0-9]{1,11}(?:\.[0-9]{1,3})?$

Explanation:
^            # Start of string
[0-9]{1,11}  # Match 1-11 digits (i. e. 0-99999999999)
(?:          # Try to match...
 \.          # a decimal point
 [0-9]{1,3}  # followed by one to three digits (i. e. 0-999)
)?           # ...optionally
$            # End of string


text:
Q: Abort trap: 6 (Calculating a long number factorial) I am following the following function to calculate factorials of big numbers link, and I would like to understand a bit more why some things are happening...
#include<stdio.h>
#define MAX 10000
void factorialof(int);
void multiply(int);
int length = 0;
int fact[MAX];

int main(){
    int num;
    int i;

    printf("Enter any integer number : ");
    scanf("%d",&num);

    fact[0]=1;

    factorialof(num);

    printf("Factorial is : ");
    for(i=length;i>=0;i--){
         printf("%d",fact[i]);
    }
    return 0;
}

void factorialof(int num){
    int i;
    for(i=2;i<=num;i++){
         multiply(i);
    }
}
void multiply(int num){
    long i,r=0;
    int arr[MAX];
    for(i=0;i<=length;i++){
                arr[i]=fact[i];
        }

    for(i=0;i<=length;i++){
         fact[i] = (arr[i]*num + r)%10;
         r = (arr[i]*num + r)/10;
         //printf("%d ",r);
    }
    if(r!=0){
         while(r!=0){
             fact[i]=r%10;
             r= r/10;
             i++;
         }
    }
    length = i-1;
}

My questions are:

*

*What is the real meaning of the MAX constant? What does it mean if it's bigger or smaller?

*I have found out that if I have a MAX = 10000 (as in the example), I can calculate up to 3250! If I try with 3251! I get a 'Abort trap: 6' message. Why is that number? Where does it come from?

*Which would be the difference if I compile this code for a 32-bit machine with the flag -m32? Would it run he same as in 64-bit?

Thanks!

A: *

*MAX is the number of elements in fact and arr; trying to access an element with an index >= MAX would be bad.

*Error messages are often specific to the environment you are using, which you have provided no details for.

*They are not the same, but the differences (for example, the size of pointers) should not affect this code in any discernible way.

A: As Scott Hunter points out, MAX is the maximum number of elements in the fact and arr arrays, which means it's the maximum number of digits that can occur in the result before the program runs out of space.
Note that the code only uses MAX in its array declarations. Nowhere does it use MAX to determine whether or not it's trying to read from or write to memory beyond the end of those arrays. This is a Bad Thing™. Your "Abort trap: 6" error is almost certainly occurring because trying to compute 3251! is doing exactly that: using a too-large index with arr and fact.
To see the number of digits required for a given factorial, you can increase MAX (say, to 20,000) and replace the existing printf calls in main with something like this:
printf("Factorial requires %d digits.\n", length + 1);

Note that I use length + 1 because length isn't the number of digits by itself: rather, it's the index of the array position in fact that contains the most-significant digit of the result. If I try to compute 3251!, the output is:
Factorial requires 10008 digits.

This is eight digits more than you have available in fact with the default MAX value of 10,000. Once the program logic goes beyond the allocated space in the array, its behavior is undefined. You happen to be seeing the error "Abort trap: 6."
Interestingly, here's the output when I try to compute 3250!:
Factorial requires 10005 digits.

That's still too many for the program to behave reliably when MAX is set to 10,000, so the fact that your program calculates 3250! successfully might be surprising, but that's the nature of undefined behavior: maybe your program will produce the correct result, maybe it will crash, maybe it will become self-aware and launch its missiles against the targets in Russia (because it knows that the Russian counterattack will eliminate its enemies over here). Coding like this is not a good idea. If your program requires more space than it has available in order to complete the calculation, it should stop and display an appropriate error message rather than trying to continue what it's doing.


text:
Q: PHP Ignore mysql deprecated errors I'm using a web app based on an older PHP so it uses mysql* functions that throws a deprecated function errors all the time and wont let me see the page. This has been asked many times but all the answers were "switch to mysqli/pdo" and "you should not use these functions anymore". Those answers are not really helping me since the app is huge and changing all the mysql functions to mysqli is completely out of the question. Also many of projects I'm working on are based on it.
I would like to ask for a solution that will help me bypass this problem without need to rewrite the whole app and all the projects that use it. On Windows I simply downgraded to php 5.4 but now I transfered to Ubuntu 14.04 and this doesn't seem to be possible in here. Is there any way I can configure PHP to perhaps not show these errors (yes I'm well aware that would not show all the deprecated errors in general).

A: Try this
ini_set('display_errors', 0);


text:
Q: ASP.NET Core 3.1 MVC Views in custom Areas dont have the same design as those in the default one I am new to ASP and I am creating ASP.NET Core 3.1 MVC application. I just learned about areas and created one named Seller.
I added a controller :
[Area("Seller")]
public class SellerController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

and a view :

Hello @User.Identity.Name

Use the menu below or the navigation bar to navigate the site

        ProductManagement

Now my problem is that the view looks like this :

Another issue I have is that this line :
ProductManagement

does not behave like link, but like a text, I mean "ProductManagement" is beeing writen on scree, but if I click it, or hover over it, nothing happens
How can I use the default design that the default pages have, like this one.

Also if it is relevant I call the SellerControler using this line:
SellerHome

Thank you for the help in advance.

A: Styling:
You rather need to add Layout to your template or add the _ViewStart.chtml in the Area folder:
In Template:
Layout = "~/Views/Shared/_Layout.cshtml";
Or _ViewStart.chtml (Areas > Seller > Views):
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

A: To share a common layout for the entire app, move the _ViewStart.cshtml from your Views/Shared/_Layout.cshtml to the application root folder.
Refer to https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-3.1#shared-layout-for-areas-using-the-_viewstartcshtml-file

Another issue I have is that this line :
  ProductManagement
  does not behave like link, but like a text, I mean "ProductManagement" is beeing writen on scree, but if I click it, or hover over it, nothing happens

It is possible that tag helpers do not work as expected, check your /Views/_ViewImports.cshtml to add
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers


text:
Q: Not able to load property file created at runtime I am using Resource Bundle for loading the property file to fetch the contents into that file.
ResourceBundle.getBundle("com.test.Message");

When this Message property file created manually then the app is working perfectly fine but when i create the Properties file at runtime into the same package the it is throwing the  exception .
 java.util.MissingResourceException: Can't find bundle for base name com.test.Message, locale en_IN

I checked that property file exist in the classes folder after it got created, but why it is not working when created at runtime instead manually before compiling
Note : Already checked this post Since I am not using any locale So answer on this post not resolve my problem

A: You could do
ResourceBundle.clearCache();

I hope you are aware that a resource on the class path actually should not be written to as File. It should be read-only, as the classes/resources could be packed in a jar. The clearCache introduces an efficiency too.
Alternatively you could use Properties on the File system.


text:
Q: How can I reference a google map in another script? How can I reference a google map in another script? On my WordPress page, I load javascript (a) that builds my map, and jQuery script (b). I need to figure out some way passing a reference to the map to script (b). The problem is that the map is created inside a function in script (a).
In script (a), I've got:
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);

//code for building map continues
}

In script (b):
jQuery.noConflict();

jQuery(document).ready(function($) {

//say I need the map's bounds
//how can I access map, in order for this to work:
map.getBounds();

}

I saw this stackoverflow solution, but I couldn't get it to work.

A: stick it in the global namespace.
function map_maker_js( args ) {
     window.map = new google.maps.Map(
          document.getElementById( args['id'] ), myOptions);

     //code for building map continues
}

jquery
jQuery.noConflict();

jQuery(document).ready(function($) {
    window.map.getBounds();
}

but make sure map_maker_js finishes running first.


text:
Q: Join strings from for loop into a single line I have a grammar tag producing nltk block which is,
    sent_text = nltk.sent_tokenize(text) # this gives us a list of sentences
    # now loop over each sentence and tokenize it separately
    for sentence in sent_text:
          tokenized_text = nltk.word_tokenize(sentence)
          tagged = nltk.pos_tag(tokenized_text)
          for word, tag in tagged:
               print(tag)

This gives me the following output,
    DT
    JJ
    NN
    NN
    VBD
    IN
    DT
    JJ
    NN

However, I want the output to single lined like
    DT JJ NN NN VBD IN DT JJ NN

How do I do this?

A: If you want not just print, but store the result in a string, you can use str.join() and a single list comprehension:
tags = [tag
        for sentence in sent_text
        for _, tag in nltk.pos_tag(nltk.word_tokenize(sentence))]
result = " ".join(tags)
print(result)

Note that the _ is a common variable name for throwaway variables.

A: Do this
print (tag, end=" ")

That should leave a space and not go to next line.

A: I dont think ultimately you want to print the whole string and keep using print(tag, end = ' ') so assign it to new variable is explained below.
Initialize a variable tag_str on top and use it after print statement like this.
tag_str += ' '

tag_str += tag

A: If you aren't using Python 3, you could write directly to sys.stdout, which would enable you to skip the newline character.

A: If you are using python 2.x
use print(tag,), the , puts output in the same line. so you can use print (tag + ' ',)
If you are using python 3
use print(tag, end="") or print(tag, end=" ") depending on whether you want whitespace or not.


text:
Q: Remove a line if count of delimiter is not equal to header I want to write a utility to remove lines from a DELIMITED file if count of DELIMITER character is not equal to header count.
For example if file is like this
NAME|ADDRESS|PHONE
Jack|SA|123|aaa|aaaa
JOHN|New York|111-222-3333
Jane|New Jer

I want below output
NAME|ADDRESS|PHONE
JOHN|New York|111-222-3333

Can anyone please help me how to achieve this in shell script? It would be great if I could do it using python.

A: Try this:
awk -F\| 'NR==1{n=NF}NF==n' File

Set | as the delimiter. Save the count of fields (NF) present in the first line (NR==1) to variable n, Then print only the lines with number of fields equal to n (NF==n).
Sample:
$ cat File
NAME|ADDRESS|PHONE
Jack|SA|123|aaa|aaaa
JOHN|New York|111-222-3333
Jane|New Jer

$ awk -F\| 'NR==1{n=NF}NF==n' File
NAME|ADDRESS|PHONE
JOHN|New York|111-222-3333

A: Through python3
with open('file') as f:
    c = f.readline().count('|')      # read the first line and count the occurance of | symbol and store the count to the variable c
    f.seek(0)                        # get back to the top
    for line in f:                   # iterate over all the lines present in the file.
        if line.count('|') == c:     # count the occurances of | on that particular line and check the count against the variable c
            print(line, end="")      # if both counts are equal then print the corresponding line.

Output:
NAME|ADDRESS|PHONE
JOHN|New York|111-222-3333

A: Here is an example (did not test it so some syntax errors might remain but you should get the rough idea)
 delimiter='|'
 with open(input,'r') as fr:
   with open(output,'w') as fw:
     headers=fr.readline()
     headersCount=len(headers.split(delimiter))
     fw.write(headers)
     for line in fr.readlines():
       if len(line.split(delimiter))==headersCount:
         fw.write(line)

A: Logic is good, syntax and error checking may need work.  Double check

delimiter = '|'
lines = open(file,"r").readlines()
header = lines.pop(0)
print(header)
headerElements = header.count(delimiter)
for data in lines:
  if data.count(delimiter) == headerElements:
    print(data)


text:
Q: PHP - Reference to Array - how to? I want to do something like this:
$myArray = array(
'1' => array('2' => array('3' => 'Test'))
);

$changeIt = $myArray['1']['2']['3'];
$changeIt = 'Changed Test';

// $myArray['1']['2']['3'] is now "Changed Test"

Are there ways to do this ?

A: You can do like this:
$myArray = array(
'1' => array('2' => array('3' => 'Test'))
);

$myArray['1']['2']['3'] = &$changeIt;//reference
$changeIt = 'Changed Test';
echo  $myArray['1']['2']['3']; //Changed Test

$changeIt = 'Another test';
echo $myArray['1']['2']['3']; //Another test

A: When you write $variable = array[key][key]... you  are passing value of the array to the variable. If you want to change value of array itself you need to do it like this:
$myArray = array(
'1' => array('2' => array('3' => 'Test'))
);

$myArray['1']['2']['3'] = 'Changed Test';

print_r($myArray);


text:
Q: Swift how to resign first responder on all uiTextfield I would like to use resign the first responder on all uitextfield. I'm able to complete this by placing the uitextfields in an array but I wanted to avoid using the array. the resign should happen to all type of uiTextField how can this be done.
This works fine
    class ViewController: UIViewController, UITextFieldDelegate {
        @IBOutlet weak var text: UITextField!
        @IBOutlet weak var textFieldtwo: UITextField!

        var textField = [UITextField]()

        override func viewDidLoad() {
            super.viewDidLoad()
            self.textField = [text,textFieldtwo]

            for item in textField {
                item.delegate = self
            }
        }

        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            print("text")

            for item in textField {
                item.resignFirstResponder()
            }
        }
    }

A: Now In Swift 3, the easiest methods are
Method 1:
 called when 'return' key pressed.
func textFieldShouldReturn(_ textField: UITextField) -> Bool
 {
 textField1.resignFirstResponder()
 textField2.resignFirstResponder()
        return true;
    }

Method 2:  called when 'return' key pressed.
func textFieldShouldReturn(_ textField: UITextField) -> Bool
    {
    self.view.endEditing(true)
        return true;
    }

Method 3: Global Method Write in view did load
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))

Note: Don't forget to add this. Other wise its not work.
UIGestureRecognizerDelegate, UITextFieldDelegate

I hope it will work for you :)

A: A simpler approach would by to end editing on the UIView containing the UITextFields by saying:
view.endEditing(true)

A: Or just use a more global approach. (Swift 3.0)
UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil);

This will dismiss any active field as it resigns the current first responder.
Good luck coding!

A: You can try this:
for textField in self.view.subviews where textField is UITextField {
    textField.resignFirstResponder()
}

But if you just want to dismiss the Keyboard by pressing the return on the keyboard or tapping anywhere on the screen without using touchesBegan
You can try with this:
// For pressing return on the keyboard to dismiss keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
    for textField in self.view.subviews where textField is UITextField {
        textField.resignFirstResponder()
    }
    return true
}

...
func hideKeyboard() {
    view.endEditing(true)
}

And add this to your viewDidLoad:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)

A: resignFirstResponder with toolbars buttons Swift4 ##
You can try this :
 1. check the Textfield Delegate
class CoursesViewController: UIViewController,UITextFieldDelegate {

*create a TextField var: var currentTextField:UITextField!

*create "done" & "cancel" buttons toolBar in your TextField
func addDoneCancel(_ textField : UITextField) {

    curentTextField = textField

    // ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()

    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(CoursesViewController.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(CoursesViewController.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar
}

4.actions of toolbar buttons
@objc func doneClick(){
    curentTextField.resignFirstResponder()
}

@objc func cancelClick(){
    curentTextField.resignFirstResponder()
}

5.UItextField delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    curentTextField = textField
    addDoneCancel(textField)
    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    //delegate method
}

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    //delegate method
    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    //delegate method
    textField.resignFirstResponder()

    return true
}

A: Swift 4:
In case you have IBOutlets:
_ = [textFiledOne, textFiledTwo, textFiledThree].map() { $0.resignFirstResponder() }


text:
Q: Set dimensions of element to equal responsive image dimensions I'm building out flippable images on my site. I want the "back" of these images to have the same dimensions as the front.
My problem is that I'm using the Bootstrap img-responsive class on my images so the "back" dimensions need to update dynamically to match the "front".
Here's what I hypothetically want to do (I realize the CSS is not possible as written, just illustrating my goal). I'm using ng-animate to animate transitions and reveal the initially hidden "back" and hide the front (that aspect I'm in good shape with).
html:

Info about image

css:
.back {
    height: [current height of .front]
    width: [current width of .front]
}

A: You can get the height and width of image using jQuery and the apply it to your div

Info about image

$(document).ready(function () {
var img = document.getElementById('img');
var width = img.clientWidth;
var height = img.clientHeight;
$("#info").width(width).height(height);
});

DEMO

A: I don't know if this is how you will use it, but v1.3+ added support, and have found it just now...
See plunkr = http://plnkr.co/edit/utsD4RimPB6RSKXnAlLi?p=preview
<!DOCTYPE html>

   <link rel="stylesheet" href="style.css">

   h: {{height}} w: {{width}}

duplicate: http://noypi-linux.blogspot.com/2014/09/angularjs-binding-inside-of-style-tag.html


text:
Q: IllegalStateException when ListView item count changes while scrolling I know there are dozens of posts about IllegalStateExceptions in ListViews, but no solution worked for me. Hopefully someone can help me find out what I am doing wrong.
What's going on?
When a certain property in my SharedPreferences is updated, I update the ArrayList which provides the data for the ListView, and notify the ListView. An IllegalStateException is thrown only on Android 4 (never on Android 2.3), when the number of items in the ListView changes and the user is scrolling when the update happens.
IllegalStateException
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131165193, class android.widget.ListView) with Adapter(class com.example.view.StatusActivity$StatusAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1545)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4082)
[...]

The Code
Here's a minimal version of the Activity concerned. The ListView update is triggered from onSharedPreferenceChanged, where I also made sure that the update is executed on the UI thread (as opposed to what the IllegalStateException suggests).
public class StatusActivity extends Activity implements OnSharedPreferenceChangeListener {

    private ArrayList<Status> stati;
    private ListView listview;
    private SharedPreferences prefs;
    private StatusAdapter adapter;

    private static final int TYPE_STATUS = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_status);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        prefs.registerOnSharedPreferenceChangeListener(this);

        listview = (ListView) findViewById(R.id.list);

        adapter = new StatusAdapter();
    }

    public void onResume(){
        super.onResume();
        updateList();
    }

    public void updateList(){
        StatusDAO.initialize(this);
        stati = (ArrayList<Status>) StatusDAO.readAll();
        adapter.notifyDataSetChanged();

        listview.invalidateViews();
        listview.refreshDrawableState();
    }

    private class StatusAdapter extends BaseAdapter {

        private Status current;

        public int getCount() {
                return stati.size();
        }

        public Object getItem(int position) {
                return stati.get(position);
        }

        public long getItemId(int position) {
                return position;
        }

        public int getItemViewType(int position) {
                return TYPE_STATUS;
        }

        public int getViewTypeCount() {
                return 1;
        }

        public boolean isEnabled(int position) {
            return false;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null) {
                    final LayoutInflater inflater = LayoutInflater.from(StatusActivity.this);
                    final int layout = R.layout.item_status;
                    convertView = inflater.inflate(layout, parent, false);
            }

            // [..]

            return convertView;
        }

    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(key.equals(Configuration.PREF_LOADINGSTATUS)){
            runOnUiThread(new Runnable() {
                public void run() {
                    updateList();
                }
            });
        }
    }

}

I have no idea how to fix this issue, since I have already tried everything that is suggested on the internet (making sure the update to the dataset happens on the UI thread; calling notifyDataSetChanged(); ...).
I would be very grateful for your help and suggestions, any help is appreciated!


text:
Q: What is the difference between remove and unsetChild methods in layout? What is the difference between remove and unsetChild methods in layout?
For example (in poll.xml layout file):
<customer_account_index>
    <reference name="right">
        <action method="unsetChild"><name>catalog_compare_sidebar</name></action>
    </reference>
</customer_account_index>

Why unsetChild and not just remove?

A: Remove nodes will be processed after all layout handles are merged, and are a good way to remove a block regardless of which layout handle loaded the block; you just want to get rid of it entirely for some handles! It also removes recursively, so all you need to specify is the layout handle.
On the other hand, you may only want to remove a block from a reference in a specific layout handle, in which case you should use unsetChild. It is often used to remove a block from a reference, but then re-insert the same block with a different position. This would not have been possible with remove.
In your very specific example, the magento developers used it to give magento some flexibility. Let's say I added a subpage for the account index page, and the following layout handles were loaded:

*

*default

*...

*customer_account_index

*customer_account_index_subpage

And now assume on this subpage I would actually want the 'catalog_compare_sidebar' block. If they had used 'remove', I would not be able to add this block (with this specific name) because 'remove' would be processed -after- I had added the block myself.
This allows you to easily make changes from one single file; local.xml.

A: Taking your code as an example,if you use unsetchild,compare sidebar block removed from right column,but you can use it anywhere like left column,footer etc..,remove removes entirely from the template,and cannot be used anywhere.
Remove the compare sidebar using remove and if you call it somewhere else,error will be thrown.


text:
Q: How can I make NSObject that is created in runtime key value coding-compliant First of all I want to point out that yes there are a lot of questions on this subject on stack overflow but none that was of any help. I also tried asking the owners of these for advice but was unable to get in touch with any of them.
Here is my scenario. I'm receiving data from an API which is an array of objects. These object are all the same structure but they change dynamically from API end point. When I made an NSArray of NSDictionary and tried to set my grid data source with the value of the provided array. It didn't work. When I looked at the documentation IGGridViewDataSourceHelper I found out the following piece of information "As of right now, the data must be of a derivation of NSObject and have at least one property". So I started thinking of a way to create an NSObject at run time. I was able to find some resource on Apple Developers documentation to make that.
Given that the variable dictionary is given in a function
Kindly check the following
- (NSArray *)getRecrodsFromDictionary: (NSDictionary*)dictionary {
    // the following include the array that I want to turn into objects
    NSArray * response = [self parseKey:@"responseDetails" fromDictionary:dictionary];
    NSMutableArray * rows = [[NSMutableArray alloc] init];
    if ([response count] != 0) {
        // 1. get all NSDictionary keys
        NSDictionary * temp = response[0];
        NSArray * keys = [temp allKeys];

        // 2. create a class
        Class ModelClass = objc_allocateClassPair([NSObject class], "WidgetDetailsModel", 0);

        // 3. all class variables with the same name as key retrieved from NSDictionary
        for (NSString * key in keys) {
            NSString * currkey = [key capitalizedString];
            const char * name = [currkey UTF8String];
            class_addIvar(ModelClass, name, sizeof(id), rint(log2(sizeof(id))), @encode(NSString));
        }

        // 4. register a class to be used
        objc_registerClassPair(ModelClass);

        for (NSDictionary * curr in response) {
            // create object
            id MC = [[ModelClass alloc] init];
            for (NSString * key in keys) {
                // set values
                const char * name = [key cStringUsingEncoding:NSASCIIStringEncoding];
                Ivar CurrVar = class_getInstanceVariable(ModelClass, name);
                NSString * newValue = [curr objectForKey: key];
                object_setIvar(MC, CurrVar, newValue);
            }
            // add object to array
            [rows addObject:MC];
        }
    }
    return [rows copy];
}

Once I get the return value and try to set it to data source data variable I get the following run time error.
[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key AssetsClass.
I can't find any thing on how to make the created in runtime NSObject key value coding-compliant. How can I make it key value coding-compliant?
Edit 1:
I managed to bypass the runtime error by making the fields names capitalized.
Now the table is being populated with empty data (same number of rows as the data but empty text in it) which was the correct thing to happen because the values of the iVar is not retained. How Can I retain it?
Edit 2:
I'm still not able to retain the iVar value so I changed the location of the function to the same UIView class which then it did retain it for the short period of time I had to set the grid data source data value.
I'm curious to know if there is a way to make the iVar retained or set one of its attribute to be strong/retain to mark it for the deallocation process.

A: After long search on Google, StackOverFlow and other iOS related forums and research. Here is the conclusion that I was able to find. Ivar in objective-c will always be weak reference. In other words there is no way (that I can find) that makes the Ivar strong reference. This can only be achieved throw property with setting the attribute of each property made.


text:
Q: Extract all urls in a string with python3 I am trying to find a clean way to extract all urls in a text string.
After an extensive search, i have found many posts suggesting using regular expressions to do the task and they give the regular expressions that suppose to do that. Each of the RegExs have some advantages and some short comings. Also, editing them to change their behaviour is not straight forward. Anyway at this point i am happy with any RegEx that could detect the urls in this text correctly:
Input:

Lorem ipsum dolor sit amet https://www.lorem.com/ipsum.php?q=suas, nusquam tincidunt ex per, ius modus integre no, quando utroque placerat qui no. Mea conclusionemque vituperatoribus et, omnes malorum est id, pri omnes atomorum expetenda ex. Elit pertinacia no eos, nonumy comprehensam id mei. Ei eum maiestatis quaerendum https://www.lorem.org. Pri posse constituam in, sit http://news.bbc.co.uk omnium assentior definitionem ei. Cu duo equidem meliore qualisque.

Output:

['https://www.lorem.com/ipsum.php?q=suas', 'https://www.lorem.org', 'http://news.bbc.co.uk']

But if there is a python3 class/function/library, that finds all urls in a given text and takes parameters to:

*

*select which protocols to detect

*select which TLDs are allowed

*select which domains are allowed

I would be very happy to know about it.

A: Apart from what others mentioned, since you've asked for something that already exists, you might want to try URLExtract.
Apparently it tries to find any occurrence of TLD in given text. If TLD is found, it starts from that position to expand boundaries to both sides searching for a "stop character" (usually white space, comma, single or double quote).
You have a couple of examples here.
from urlextract import URLExtract

extractor = URLExtract()
urls = extractor.find_urls("Let's have URL youfellasleepwhilewritingyourtitle.com as an example.")
print(urls) # prints: ['youfellasleepwhilewritingyourtitle.cz']

It seems that this module also has an update() method which lets you update the TLD list cache file
However, if that doesn't fit you specific requirements, you can manually do some checks after you've processed the urls using the above module (or any other way of parsing the URLs). For example, say you get a list of the URLs:
result = ['https://www.lorem.com/ipsum.php?q=suas', 'https://www.lorem.org', 'http://news.bbc.co.uk']

You can then build another lists which hold the excluded domains / TLDs / etc:
allowed_protocols = ['protocol_1', 'protocol_2']
allowed_tlds = ['tld_1', 'tld_2', 'tld_3']
allowed_domains = ['domain_1']

for each_url in results:
    # here, check each url against your rules

A: import re
import string
text = """
Lorem ipsum dolor sit amet https://www.lore-m.com/ipsum.php?q=suas,
nusquam tincidunt ex per, ftp://link.com ius modus integre no, quando utroque placerat qui no.
Mea conclusionemque vituperatoribus et, omnes malorum est id, pri omnes atomorum expetenda ex.
Elit ftp://link.work.in pertinacia no eos, nonumy comprehensam id mei. Ei eum maiestatis quaerendum https://www.lorem.org.
Pri posse constituam in, sit http://news.bbc.co.uk omnium assentior definitionem ei. Cu duo equidem meliore
qualisque.
"""

URL_REGEX = r"""((?:(?:https|ftp|http)?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|org|uk)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»""''])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|uk|ac)\b/?(?!@)))"""

urls = re.findall(URL_REGEX, text)
print([''.join(x for x in url if x in string.printable) for url in urls])

Now if you want to keep only urls with valid domains you can write it as follow:
VALID_DOMAINS = ['lorem.org', 'bbc.co.uk', 'sample.com', 'link.net']
valid_urls = []
for url in result_url:
    for val_domain in VALID_DOMAINS:
        if val_domain in url:
            valid_urls.append(url)
print(valid_urls)

A: output = [x for x in input().split() if x.startswith('http://') or x.startswith('https://') or x.startswith('ftp://')]
print(output)

your example:
http://ideone.com/wys57x
After all you can also cut last character in elements of list if it is not a letter.
EDIT:
output = [x for x in input().split() if x.startswith('http://') or x.startswith('https://') or x.startswith('ftp://')]
newOutput = []
for link in output:
    copy = link
    while not copy[-1].isalpha():
        copy = copy[:-1]
    newOutput.append(copy)
print(newOutput)

Your example: http://ideone.com/gHRQ8w

A: If you want a regex, you can use this:
import re

string = "Lorem ipsum dolor sit amet https://www.lorem.com/ipsum.php?q=suas, nusquam tincidunt ex per, ius modus integre no, quando utroque placerat qui no. Mea conclusionemque vituperatoribus et, omnes malorum est id, pri omnes atomorum expetenda ex. Elit pertinacia no eos, nonumy comprehensam id mei. Ei eum maiestatis quaerendum https://www.lorem.org. Pri posse constituam in, sit http://news.bbc.co.uk omnium assentior definitionem ei. Cu duo equidem meliore qualisque."

result = re.findall(r"\w+://\w+\.\w+\.\w+/?[\w\.\?=#]*", string)
print(result)

Output:
['https://www.lorem.com/ipsum.php?q=suas',
 'https://www.lorem.org',
 'http://news.bbc.co.uk']

A: Using an existing library is probably the best solution.
But it was too much for my tiny script, and -- inspired by @piotr-wasilewiczs answer-- I came up with:
from string import ascii_letters
links = [x for x in line.split() if x.strip(str(set(x) - set(ascii_letters))).startswith(('http', 'https', 'www'))]

*

*for each word in the line,

*strip (from the beginning and the end) the non ASCII letters found in the word itself)

*and filter by the words starting with one of https, http, www.

A bit too dense for my taste and I have no clue how fast it is, but it should detect most "sane" urls in a string.


text:
Q: Android Camera2 : How to access every single frames while Recording video? My goal is to get access to every single frame while recording a video.
I'm using Camera2 API.
What I want is to take every single frame while recording, and the frames should be exactly equal to each frame of result video, not preview frames.
Of course I can access each frame after recording is over using tools like OpenCV or FFMPEG or something, but right now I need to get them real-time while recording.
Bitmap, Image, ByteBuffer, byte[] or as file, whatever type is OK if I can access each data.
I've searched some tutorials and found this series, especially this video, but that's not exactly what I need.
That tutorial includes how to take a photo while recording a video.
Can anybody help me?

A: Unfortunately, in general the exact video frames are only sent to the video encoder.  You can of course decode the video after each encoded frame is output from a MediaCodec, but that's a bit expensive.
Alternatively, you can try using an ImageReader with usage flags, which is only possible on fairly recent Android versions, and use both the USAGE_CPU_READ_OFTEN and USAGE_VIDEO_ENCODE usage flags, and format YUV_420_888.  That should be as close as you can get to the 'normal' video recording output, but it may not be exactly identical, unfortunately.


text:
Q: Controlling access on fields in F# types I'm writing Domain Logic for one of the application using F#. I want to control access on fields defined for a type in F# so that I can implement builder pattern and control type instantiation.
Want to do something similar with do in builder pattern in C#/Java.
Kindly suggest.
e.g.
let Person = {
    Name:string
    Age:number
    Salary:string
}
So I want to make sure person should always be instantiated with Name and Age. But salary should be optional. Instantiation should happen in a builder pattern.

A: You cannot make individual record fields private or internal, but you can make all fields private or internal. This hides all the fields, so you have to expose those that you want to make accessible as members. You can also add static methods to create new values. For example:
type Person =
  private {
    name : string
    age : int
    salary : int option }
  member x.Name = x.name
  member x.Age = x.age
  member x.Salary = x.salary

  static member Create(name:string, age:int) =
    { name = name; age = age; salary = None }
  member x.WithSalary(s) =
    { x with salary = Some s }

Now you cannot access the fields or create the record directly, but you can use Create and WithSalary:
Person.Create("Joe", 60).WithSalary(10000)

A: As pointed out in a comment, it seems like you are trying to use object oriented patterns without objects, which hardly is a good idea.
If you decide to use F# types, you would do it like this:
type Employee = {
    name: string
    age: int
    salary: int option
}

let person1 = {
    name = "Mike",
    age = 42,
    salary = Some 4200
}
let person2 = {
    name = "Sue",
    age = 37,
    salary = None
}

Omitting name or age would give you a compile time error, as would using person1 or person2 without checking whether salary exists.
To implement something resembling a builder pattern, with private data, do something like this:
type Employee = private {
    name: string
    age: int
    salary: int option
}

let name employee = employee.name
let employee name age = { name = name; age = age; salary = None }
let withSalary salary employee = { employee with salary = Some salary }

let mike = employee "Mike" 42 |> withSalary 4200

mike.name  //return name of this employee

A: You can implement the builder pattern with plain functions. I see no reason to use objects here:
type person =
  private {
    name: string
    age: int
    salary: int option
  }

let name person = person.name
let age person = person.age
let salary person = person.salary

let create name age =
  { name = name; age = age; salary = None }

let withSalary salary person =
   { person with salary = Some salary }

create "Joe" 60
  |> withSalary 10000
  |> name


text:
Q: Gatsby plugin ERROR "UNHANDLED REJECTION Reducers may not dispatch actions." I have a problem with the initialization of Gatsby plugins, in gatsby.config.js. When I use a simple plugin in "string" in the plugin array there is no problem, but when I use a plugin with options in an object it doesn't work anymore.

module.exports = {
  siteMetadata: {
    author: 'Me',
  },
  plugings: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,

      },
    },
  ]
};

When I use "npm run develop" I get this error message:
"UNHANDLED REJECTION Reducers may not dispatch actions."
Anyone have a solution?

A: I had the same problem and it turned out i hadn't specified the SITE_URL variable in my gatsby.config file, setting it to localhost:8888 fixed the problem, you are definetly missing this variable in siteMetadata consider adding it.


text:
Q: How to extrapolate the given data to fill NaN values using Python? I wish to fill the NaN values with apt extrapolation. I think curve fit method will not be apt as I have no clue about the equation of curve from the given points. I got these values from MPU. Can anyone suggest me a best way to extrapolate the values to fill NaN positions using Python?
mean_acc  timestamp     x_acc   x_gyro  y_acc   y_gyro  z_acc   z_gyro

  1.00     1143            0.96     -1.22     0.16     2.81  0.24  0.24

  1.17    1646             1.15     -7.26   0.14    4.88    0.18    -0.06

  1.02     2149            1.00     8.36    0.15    11.78   0.12    3.11

   0.98     2652           0.96     -8.30   0.15    2.01    0.11    -2.01

   1.05     3155           0.94     -4.21   0.17    3.42    0.42    -2.93

   1.01     3658           1.00     2.75    0.12    4.64    0.05    5.13

    NaN     4161            NaN     NaN     NaN     NaN     NaN     NaN

    NaN     4664            NaN     NaN     NaN     NaN     NaN     NaN

    NaN     5167             NaN    NaN     NaN     NaN     NaN     NaN

    NaN     5670             NaN    NaN     NaN     NaN     NaN     NaN

A: By reading your question I had confusion about what you really wanted as answer -

*

*Different methods to extrapolate or

*How to fill NA values to the columns with using particular extrapolation methods.

However I'll try to answer both.
mean_acc, x_acc, y_acc, z_acc null values can be filled by their mean values.
For y_gyro convert the existing into Log Transforms and then extrapolate mean of Log values and then invert the Log transformation to get the required.
Try plotting the  remaining fields and try to find a relation that can be used to extrapolate the NULL values in the remaining columns.

*Extrapolating the null values in pandas.
X['mean_acc'].fillna(X['mean_acc'].mean(), inplace=True)


text:
Q: Where are CoreLib.h,Buffer.h, Logger.h..? Where can I find these header files on Windows 7? I just installed VS2010, but seems dont have these header..
CoreLib.h
#include "Buffer.h"
#include "Logger.h"
#include "CoreLibImpl_.h"

A: Why would you expect them to be a part of Windows 7 or VS2010?
Google tells me what you're looking for is a part of Apache ActiveMQ. So go ahead and install the source. If you already have them and you just can't get VS to find the files, add them to the include directories.

A: Those names don't sound familiar. They're not one of the standard C++ headers like <iostream>, or the C headers like <stdlib.h>. Nor do they appear to be MFC headers. Why do you expect VS2010 to ship with these?


text:
Q: Identity pool not being given permissions I specify I have an aws identity pool set up with the following policy attached:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "iam:*",
            "Resource": "*"
        }
    ]
}

However, when I try to call the 'getuser' method, I get the following error:
AccessDenied: User: {/*the identitypool*/} is not authorized to perform: iam:GetUser on resource: user foo

Here's the code:
  var AWS = require('aws-sdk');
    AWS.config.update({ region: 'us-west-2' });
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'my user pool id' });

    var iam = new AWS.IAM({ apiVersion: '2010-05-08' });
    var params = {
      UserName: "foo"
    };
    iam.getUser(params, function (err, data) {
      if (err && err.code === 'NoSuchEntity') {
        console.log("no such entity");
      } else {
        console.log("err, data", err, data);
      }

What am I missing? I'm pretty new to AWS, so any help is appreciated. Thanks in advance!

A: Looks like you're using the Enhanced flow. You must enable the basic authentication flow in your Identity pool. I'm not really sure about the code (not a JS guy), but if you are using the unauth role, this is the reason behind the error.
"For additional security protection, Amazon Cognito applies a scope-down policy to credentials vended by GetCredentialForIdentity to prevent access to majority of services for your unauthenticated users."
Have a look at the doc here: https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies


text:
Q: Multiple instances of jQuery plugin on same page? I've seen a lot of different jQuery plugin boilerplates, and read many different jQuery plugin authoring articles, including the official one. However, I seem to still be missing something, fundamentally!
I'm using a mix of code I've seen elsewhere and jQuery's official authoring guidelines.
As you can see from the code, I'm doing everything inside of return this.each(function() { });. This includes my private functions. I assumed that this meant that for each .pluginName(); called, the code would be run and tied to that instance. For example, I'm adding a randID to the end of each of the element IDs, so that if multiple instances are created, the instance can refer to the correct element.
My problem is that when I have two instances on the same page, the second instance's functions (like displayAvailableItems()) are using the first instances randIDs.
I'm assuming 2 things wrong right off the bat: the functions are in the wrong place, and the randID is a bad method of identifying the elements. If I move displayAvailableItems() to just above the retun this.each(function() { });, then availableItem variable is no longer available to it.
Here is the abbreviated version of my code: (pastebin) http://tny.cz/6d3d52a8
$.pluginName = {
     id: 'PluginName'
    ,version: '1.0'
,defaults: { // default settings
    foo: 'bar'
}
};

(function($) {
    //Attach this new method to jQuery
    $.fn.extend({

            pluginName: function(params) {
            //Merge default and user parameters
                    var params =  $.extend($.pluginName.defaults, params)
            ,otherGeneralVars = 'example'
        ;

        return this.each(function() {
            var $t = $(this);

            //Generate a random ID to attach to the elements, so we can have endless (up to 50k) quantities of the plugin on the page
                            var randID = 1 + Math.floor(Math.random() * 50000);
                            //Make sure the randID hasn't been previously used
                            while ($.inArray(randID, usedRandIDs) > -1)
                            {
                                    randID = 1 + Math.floor(Math.random() * 50000);
                            }
                            usedRandIDs.push(randID);
                            randID = '_PluginName' + randID;

            /*
                                    RUN INITIALIZATION SETTINGS
                            */
                            var availableItemsContainerID = 'availableItemsContainer' + randID
                ,tagSearchContainerID = 'tagSearchContainer' + randID
                ,tagSearchID = 'tagSearch' + randID
                ,availableItemsID = 'availableItems' + randID
                ,selectedItemsContainerID = 'selectedItemsContainer' + randID
                ,selectedItemsID = 'selectedItems' + randID
                ,selectedValuesID = 'selectedValuesInputName' + randID
            ;

            //Build element structure
                            $t.append('
' +
                                                            '
' +
                                                                    '<input id="' + tagSearchID + '" value="' + params.searchDefaultText + '" />' +
                                                            '
' +
                                                            '

' +
                                                    '
' +
                                                    '
' +
                                                            '

' +
                                                            '

' +
                                                    '
');

            //Show the list of available items
                            displayAvailableItems();

            $('#' + availableItemsContainerID).css({
                              'width': params.availableItemsContainerWidth + params.unitOfMeasurement,
                              'height': params.availableItemsContainerHeight + params.unitOfMeasurement
                            });
                            $('#' + selectedItemsContainerID + ', #' + selectedItemsID).css({
                              'width': params.selectedItemsContainerWidth + params.unitOfMeasurement,
                              'height': params.selectedItemsContainerHeight + params.unitOfMeasurement
                            });

            function displayAvailableItems() {
                                    //Clear out the available items
                                    $("#" + availableItemsID).html('');

                                    //Do other stuff
                            }
        });
               }
       })
        })(jQuery);

A: First, you need to move var params into your this.each, however you will then have a variable hoisting (not absolutely sure if that's actually what is happening, but that's what it appears to be) problem due to using the argument name as a variable name causing params to be undefined. To solve that, just rename params inside of this.each to something else. Example:
$.fn.extend({

    pluginName: function (params) {
        //Merge default and user parameters
        var otherGeneralVars = 'example';

        return this.each(function () {
            var $t = $(this), opts = $.extend({},$.pluginName.defaults, params);

            $t.text(opts.foo + uniqueId);
        });
    }
})

http://jsfiddle.net/M99EY/1/


text:
Q: Why isn't node.js shown in chrome developer tools? I'm just learning node.js so forgive me for the naivete. So I create a JavaScript file to put all my node methods in and then link it to an html file. I run the html file and look in the JavaScript console only to get "Uncaught ReferenceError". My code executes completely fine on windows powershell, but not in chrome developer tools. Why is this?

A: Chrome is a browser.  It runs Javascript in a browser context.
Node.js is a stand-alone Javascript environment meant for running Javascript in a server environment or for stand-alone tool development.
node.js does not do HTML display like a browser and does not support the same "host" environment that a browser does with host objects such as window and document.  Similarly node.js adds all sorts of modules to the run-time environment that are not present in a browser such as the fs module for accessing files or the process module for accessing the system.
Both node.js and Chrome use the same V8 Javascript engine internally for parsing and running plain Javascript, but each puts its own environment around that engine that give them different purposes and capabilities.

o I create a JavaScript file to put all my node methods in and then link it to an html file. I run the html file and look in the JavaScript console only to get "Uncaught ReferenceError".

If you have an HTML file with Javascript <script> tags in it, you would have to use that in a browser (such as Chrome), not in node.js.
If you had just a plain Javascript file who's job it was to start a server and listen for incoming connections, you would use that in node.js, not in Chrome.

My code executes completely fine on windows powershell, but not in chrome developer tools. Why is this?

We could advise more completely if you showed your actual code, but it seems likely that you've written your Javascript to use some of the node.js libraries that are only present in node.js and are not present in a browser environment.  As such that is a node.js program (written in Javascript), not a script that can run in a browser environment.

For an analogy, imagine you had two tools that each had the C language built into them.  One included the standard library that many of us have used.  Another did not include that library, but instead included a very different library.  While they both have the C language at their core, the headers and libraries they come with are completely different and thus code written in one tool using its libraries would not run in the other tool that had different libraries.
That's similar to Chrome vs. node.js.  Each as the Javascript language at their core, but each come with a different set of libraries.
If you write some pure Javascript that doesn't use any external libraries such as:
 function square(x) {
     return x * x;
 }

That code will run in either Javascript environment (Chrome or node.js) because it's nothing but pure Javascript and does not rely on any libraries outside the standard Javascript implementation.
But, if you write some code that uses the fs library such as:
 const fs = require('fs');

 function countLines(filename) {
     let data = fs.readFileSync(filename, 'utf8');
     return data.split('/n').length;
 }

That code needs the fs library.  That library exists in node.js, not in Chrome (or any browser) and as such will only work in node.js.
Or, if you write some code that uses objects that are browser-specific such as document:
 function getHeadline() {
     let obj = document.getElementById("headline");
     return obj.textContent;
 }

This code would run in a browser, but not in node.js because it relies on the document external object which is only supplied by a browser implementation, not by node.js.

If what you're really trying to do is to get access (within a web page) so data that a node.js program can supply (such as getting data from a database), then what you would typically do is to make your node.js program into a web server (often using the Express toolkit).  You can then make Ajax requests from the Javascript in the web page to your remote server to fetch data and bring it back into the web page.


text:
Q: SHA-256 same string return different byte[]? I need SHA-256 to be my key for AES-256.
But my example SHA-256 is:
MessageDigest messageDigest;
messageDigest = MessageDigest.getInstance("SHA-256");

String input = new String("ALIBABA");
messageDigest.update(input.getBytes(Charset.forName("UTF-8")));
byte[] hash = messageDigest.digest();
String hash1s = new String(hash,StandardCharsets.UTF_8);
System.out.println("HASH 1 is "+hash1s);
System.out.println("HASH 1 is "+hash);

String input2 = new String("ALIBABA");
messageDigest.update(input2.getBytes(Charset.forName("UTF-8")));
byte[] hash2 = messageDigest.digest();
String hash2s = new String(hash2,StandardCharsets.UTF_8);
System.out.println("HASH 2 is "+hash2s);
System.out.println("HASH 2 is "+hash2);

Return not a same value byte[]:

HASH 1 is V%��%�P�9�P��v�/�/e\BF}�$]
HASH 1 is [B@629f0666
HASH 2 is V%��%�P�9�P��v�/�/e\BF}�$]
HASH 2 is [B@1bc6a36e

How do I get same byte[] to be key for AES-256?

A: The [B@629f0666 and [B@1bc6a36e thingies are not the contents of hash and hash2 respectively, they are their default toString() representations. The [B part is telling you that it is an array of bytes, and the hex number that follows is its identity hash code, which is something akin to an address in memory.  (Not exactly an address, but it is useful to think of it that way.)
And of course, since they are two different arrays, they live in different locations in memory, so their default toString() representations differ.  But that's irrelevant: their contents are identical.
In order to see that they are identical, you don't have to print them, you can simply compare them byte by byte.  But if you insist on printing them, your attempt with new String( hash2, StandardCharsets.UTF_8 ); is mistaken, because it is trying to reinterpret random bytes as unicode characters, which of course gives funny results.  Take a look at this answer: How to convert a byte array to a hex string in Java?
(And in any case, note that the two strings of garbage are identical, so this should be telling you that your byte arrays are identical, too.)

A: You need to call messageDigest.reset() between successive utilizations of the same object to compute hash for different data.
This because MessageDigest is meant to be used with chunks of data that you feed to it not all at once (by calling update(...)). So the behavior is to keep updating the internal hash until you reset the state through reset().
Basically in your code the second digest is for the string "ALIBABAALIBABA"

A: Someone may need a more simple explanation. String contains info not only for chars in it, but also some other info. May be for example about it's position in String pool etc. That info also included in .toByteArray() so results differ for 2 same strings. A piece of advice is to use char[] instead. Here is some code.
byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
          byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;
}

...

bytesToHex(MessageDigest
             .getInstance("SHA-256")
             .digest(toBytes(charArray)));

...

String bytesToHex(byte[] bytes){
  //any way you want to convert byte array to String
  //for example using apache.commons.codec:
  return Hex.encodeHexString(bytes);
}


text:
Q: Angular syntax error New to angular. Having issues finding out whats wrong here. I see there's a syntax error, but I cant figure out how? Please advise, thanks.
Here's my error:
Error: [$parse:syntax] http://errors.angularjs.org/1.6.4/$parse/syntax?p0=Express&p1=is%20unexpected%2C%20expecting%20%5B%7D%5D&p2=47&p3=prefixes%3D%7BVisa%3A%20'4'%2C%20MasterCard%3A'5'%2C%20American%20Express%3A'3'%2C%20Discover%3A'6'%7D&p4=Express%3A'3'%2C%20Discover%3A'6'%7D

Here is the Html:

Javascript:
angular.module('edu_app',[]).controller('edu_ctrl', function($scope) {
        $scope.prefixes = {};
        $scope.ccNumberChnage = function() {
            var ccType = $scope.prefixes.cards ? $scope.prefixes.cards.charAt(0) : '';
            switch(ccType) {
                case '3': $scope.prefixes.type = 'American Express'; break;
                case '4': $scope.prefixes.type = 'Visa'; break;
                case '5': $scope.prefixes.type = 'MasterCard'; break;
                case '6': $scope.prefixes.type = 'Discover'; break;
                default: $scope.prefixes.type = null; break;
            }
        };

    });

A: There's a syntax error declaring the prefixes variable inside ng-init, you have a property name with spaces on it: American Express. Therefore, you need to enclose it with apostrophes so that javascript can recognize it as a property name like so:
ng-init="prefixes={Visa: '4', MasterCard:'5', 'American Express':'3', Discover:'6'}"

Full working example bellow.

angular.module('edu_app', []).controller('edu_ctrl', function($scope) {
  $scope.prefixes = {};
  $scope.ccNumberChnage = function() {
    var ccType = $scope.prefixes.cards ? $scope.prefixes.cards.charAt(0) : '';
    switch (ccType) {
      case '3':
        $scope.prefixes.type = 'American Express';
        break;
      case '4':
        $scope.prefixes.type = 'Visa';
        break;
      case '5':
        $scope.prefixes.type = 'MasterCard';
        break;
      case '6':
        $scope.prefixes.type = 'Discover';
        break;
      default:
        $scope.prefixes.type = null;
        break;
    }
  };

});


text:
Q: IIS_IUSRS cannot access files uploaded and created by Network Service - error 401.3 Let me rephrase my question as I investigated further:
The problem:
I have a php script that is used to upload images on my windows webserver 2008. The files are created in the correct directory. The are created and owned by the user Network Service. Network Service has full access to the uploaded file.
As soon as I try to access the uploaded file (mostly an image) via HTTP, I get an 401.3 not authorized error.
Now, if I right-click on the not accessible image and grant IIS_IUSRS group read permissions via the security tab, the image can be accessed! By default IIS_IUSRS has NO access at all for the uploaded file.
The directory containing the image files has the correct access rights set. But each file that is new uploaded to the directory is permitted for IIS_IUSRS.
The question:
How can I grant IIS_IUSRS by default access to the newly uploaded file? The appPool of the website has its identity set to its default, I also tried setting it to "networkIdentity" or so, but that did not work either.

A: Here is a fine solution: http://sharepointalex.co.uk/index.php/2010/06/fixing-wordpress-image-upload-on-a-windows-server-permissions-problem/
To summarize:
Give your IUSR account Modify permissions for the C:/Windows/Temp/ directory and restart the IIS site. Or you could modify where php writes to using the php.ini by overwriting the upload_tmp_dir value which may be more preferable over letting a web application write to the C:/Windows/ directory.


text:
Q: Does $\sum_{i=1}^n Xi Yi$ for independent $X_i \sim \mathcal{N}(0,1)$ and $Y_i \sim \mathcal{N}(0,1)$ form a Chi-Square distributed Random Variable? We all know that a chi-square distributed random variable: $U \sim \chi_n^2$ results from:
$ U = \sum_{i=1}^n X_i^2 $, where $X_i \sim \mathcal{N}(0,1)$ and all $X_i$ are i.i.d.
So, my question is whether we can obtain a chi-square distribution if instead of squaring each $X_i$, we multiply it times another independent random variable $Y_i$ with similar distribution. That is:
$V = \sum_{i=1}^n Xi Yi$ for $X_i \sim \mathcal{N}(0,1)$ and  $Y_i \sim \mathcal{N}(0,1)$ independent and i.i.d each. Is $V$ a Chi-Square distributed Random Variable: $V \sim \chi_n^2$?
Please, let me know what do you think since, at the end, the long term question I want to answer is: whether the following random variable   is chi-squared distributed as $W \sim \chi_{n-1}^2$:
$W = \sum_{i=1}^{n-1} X_i X_{i+1}$
thanks!


text:
Q: Splitting multiple columns on a delimiter into rows in pandas dataframe I have a pandas dataframe as shown here:
id    pos      value                sent
1     a/b/c    test/test2/test3     21
2     d/a      test/test5           21

I would like to split (=explode)df['pos'] and df['token'] so that the dataframe looks like this:
id      pos          value         sent
1       a            test          21
1       b            test2         21
1       c            test3         21
2       d            test          21
2       a            test5         21

It doesn't work if I split each column and then concat them à la
pos = df.token.str.split('/', expand=True).stack().str.strip().reset_index(level=1, drop=True)
df1 = pd.concat([pos,value], axis=1, keys=['pos','value'])
Any ideas? I'd really appreciate it.
EDIT:
I tried using this solution here : https://stackoverflow.com/a/40449726/4219498
But I get the following error:
TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'
I suppose this is a numpy related issue although I'm not sure how this happens. I'm using Python 2.7.14

A: I tend to avoid the stack magic in favour of building a new dataframe from scratch. This is usually also more efficient. Below is one way.
import numpy as np
from itertools import chain

lens = list(map(len, df['pos'].str.split('/')))

res = pd.DataFrame({'id': np.repeat(df['id'], lens),
                    'pos': list(chain.from_iterable(df['pos'].str.split('/'))),
                    'value': list(chain.from_iterable(df['value'].str.split('/'))),
                    'sent': np.repeat(df['sent'], lens)})

print(res)

   id pos  sent  value
0   1   a    21   test
0   1   b    21  test2
0   1   c    21  test3
1   2   d    21   test
1   2   a    21  test5


text:
Q: Get AzureWebJobsDashboard through KeyVault As I have read, Azure Webjobs SDK requires the value of AzureWebJobsDashboard to be defined in the connection string section of an App Service. If I do that manually by going to the portal, and configuring the values, my webjob works fine.
What I want now is to provide the value of the connectionString in KeyVault and provide a secretURI provided by KeyVault in the ApplicationSettings of the App Service. Thereafter, I want the SDK to parse the secretURI and obtain the secret stored underneath in KeyVault.
I have tried to do this but am not able to get a definite solution for this. Is there any way to do this, or is currently not supported ?

A: Here is working example of what Mike suggested:
var config = new JobHostConfiguration();

if (config.IsDevelopment)
{
    config.UseDevelopmentSettings();
}
else
{
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    var vaultBaseUrl = ConfigurationManager.AppSettings["KeyVaultUri"];
    var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

    config.DashboardConnectionString = client.GetSecretAsync(vaultBaseUrl, "DashboardConnectionString").Result.Value;;
    config.StorageConnectionString = client.GetSecretAsync(vaultBaseUrl, "StorageConnectionString").Result.Value;;
}

config.UseTimers();

var host = new JobHost(config);

References:

*

*https://learn.microsoft.com/en-us/azure/key-vault/service-to-service-authentication

A: WebJobs SDK will not automatically get from KeyVault.
But you could also fetch from keyvault yourself and then programmatically set the result on the JobHostConfiguration.Dashboard property.
You could file a request here to have more direct integration:  https://github.com/Azure/azure-webjobs-sdk


text:
Q: Python script tkinter resolution and screenshot size effected when running pythonw.exe I currently have a python script which launches a tkinter GUI instance, with a button that once clicked takes a screenshot.
When I run this script under python.exe, the tkinter resolution is fine and the screenshot captures the whole screen. However, when using pythonw.exe, the tkinter window resolution changes (button gets bigger for example) and the screenshot only captures a portion of the screen - the top left hand corner normally.
I need to use pythonw.exe in order to prevent the console window appearing.
Does anyone know why the tkinter window resolution and the screenshot capture is being effected? Presumably the effect on the resolution is why the screenshot capture is being reduced as well.
I am fairly new to Python, so any help with this would be greatly appreciated, below is snippet of the code for the tkinter window and the screenshot functionality. To reiterate this functionality runs completely fine under python.exe.
The screenshot functionality using ImageGrab:
    callback1():
         ImageGrab.grab_to_file('test.png')

The tkinter window:
    master = Tk()
    master.wm_attributes("-topmost", 1)
    master.title("Report")
    master.configure(background='white')
    master.iconbitmap(default='icon.ico')
    master.resizable(0, 0)
    frame1 = Frame(master, bg='white')
    frame1.pack(side=BOTTOM, fill=X)
    button1 = Button(frame1, compound=BOTTOM, width=307, height=82,
    image=photo1, bg='white', command=callback1)
    button1.pack(side=TOP, padx=2, pady=8)

A: I have now fixed this. It seems it was related to the compatibility settings for pythonw.exe in Windows. Changing the following fixes the image capture, but also the tkinter window resolution:

*

*Go to your python directory (c:/python27/ for me)

*Right click python.exe and select properties

*Select the compatibility tab

*Press the "Change settings for all users" button

*Check the "Disable display scaling on high DPI settings" box

Credited by this post:
Python Imaging Library fails to grab whole screen
Hopefully this helps someone with the same issues. It does beg the question as to how this can be done automatically, as for users of a python application it is not user-friendly for them to have to change these settings.


text:
Q: Print variable names when looping over a list Consider the list of variables and a Python list:
apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]

How to print the names of variables, instead of its values when lopping over the elements of the list?
for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.

I know that a dictionary would be a better fit in this problem but for the sake of argument, is it possible to do it with a list?

A: You want this:
apple = "green"
banana = "yellow"
orange = "orange"

fruits = [apple, banana, orange]
for fruit in fruits:
    fruit_name = [key for key, value in locals().items() if value == fruit]
    print(fruit_name[0])

A: It is a bit of a cheat, but if you store the names of the variables in the fruits array instead of the variable itself, it is trivial:
>>> apple = 'green'
>>> banana = 'yellow'
>>> orange = 'orange'
>>> fruits = ['apple','banana','orange']
>>> for fruit in fruits:
...     print fruit, vars()[fruit]
...
apple green
banana yellow
orange orange

If you are really wanting to get the variable name, you have a problem as the array is not storing the variable, but the string it is pointing at - for example, you can change the content of apple after the assignment to demonstrate the array holds the original string:
>>> fruity = [ apple, orange, banana ]
>>> apple = 'yikes'
>>> print fruity
['green', 'orange', 'yellow']

The best you can do is build a reverse lookup of the vars() dictionary and attempt to look up the variable...
>>> yy = dict([v,k] for k,v in vars().items() if isinstance(v,str))
>>> for fruit in fruity:
...     print yy.get(fruit,'Unknown'), fruit
...
Unknown green
orange orange
banana yellow

A: use NamedObject, that should work:
apple='green'
banana='yellow'
orange='orange'
fruits = [apple, banana, orange]

apple = NamedObject('apple', apple)
print(apple)
print(apple.name)

this should print:
green
apple

If you dont understand, here is another similar thing: Access the name of a list in a Python print statement


text:
Q: How is canonicity of derivative works determined for Spaceballs? The movie Spaceballs has spawned several pieces of spin-off media including its own animated TV series, an "official" poster-book and a novelisation of the film.
Has there ever been an official word on what canon levels exist within the Spaceballs 'verse?


text:
Q: return matrix on C Here is my code below.
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>

void rot(int angle);
static double R[3][3]={0};

int main(void) {
    int angle = 30;
    rot(angle);
    int i, j = 0;

   for (i = 0; i < 3;i++) {
      for (j = 0; j < 3; j++) {
        printf("%lf\n", R[i][j]);
    }
}
return 0;
}

void rot(int angle) {
    double cang = cos(angle*M_PI / 180);
    double sang = sin(angle*M_PI / 180);

    R[0][0] = cang;
    R[1][1] = cang;
    R[1][0] = -sang;
    R[0][1] = sang;
}

For now, function rot do not return any value itself.
But since R is static double, I was able to print out the R changed by rot function.
I want to change function rot to return R[3][3](two dimension array).
So I want to use rot function on main like
double R1=rot(30);
double R2=rot(60);

is there any way to make it possible?

A: The duplicate isn't necessarily good for this. As these R² matrices need to be easily copyable, the best way to represent them is to put them in a struct:
typedef struct Matrix3x3 {
    double v[3][3];
} Matrix3x3;

Then it is trivial to get them as return values:
Matrix3x3 rot(int angle) {
    Matrix3x3 m = {0};
    double cang = cos(angle*M_PI / 180);
    double sang = sin(angle*M_PI / 180);

    m.v[0][0] = cang;
    m.v[1][1] = cang;
    m.v[1][0] = -sang;
    m.v[0][1] = sang;
    return m;
}

Unlike arrays, a struct that contains an array is easy to copy too:
Matrix3x3 x = y;

A: C does not allow arrays to be returned from functions. An array can be allocated in the calling function, or an array can be dynamically allocated in the function and a pointer to the array returned. Note that an array which is defined in a function is local, and returning a pointer to such an array is useless since local variables cease to exist after the function has returned. Dynamic allocations, on the other hand, continue to exist. A third option is to use the fact that, while arrays can't be returned from functions in C, structs can be returned from functions and assigned.
Define an array in the caller
A simple solution is to define an array in the calling function. This array will be modified in the rot_3x3_a() function. Note that instead of relying on the user of the function remembering to zero-initialize the array, memset() (defined in string.h) is used within the function to zero the array.
Using this method has the advantage of avoiding dynamic allocation, and the need to deallocate later to avoid memory leaks. All of the methods require a variable to be declared in the calling function which will receive the rotation matrix, but this method also requires that the array be passed to the function, so this may not meet OP requirements.
Dynamic allocation
A more involved solution is to use dynamic allocation. The rot_3x3_b() function takes only an int argument, as OP example suggests, but returns a pointer to an array of 3 doubles (this is the type of pointer that a 3x3 array decays to in most expressions). A typedef has been used here, so Matrix_3x3 is a pointer to an array of 3 doubles; this makes it easier to write the function prototype.
Here, memset() could have been used with malloc(), but instead calloc() has been used, which automatically zero-initializes the allocation. Note that, in the rot_3x3_b() function, if the allocation fails nothing else happens, and a null pointer is returned. The caller must check for this and handle the error appropriately.
The advantages of using this approach are that the resulting matrix allocation can simply be indexed as a 2d array, and arguments to the function match OP requirements. The disadvantages are that this is slightly more complex to code than the other solutions, and more error-prone, and the user of this function must remember to free the allocated memory to avoid memory leaks.
Wrapping an array in a structure
While C does not allow an array to be assigned to another array, a struct can be assigned to another struct. Further, a struct is an lvalue which can be returned from a function. So, one solution to the problem is to create a struct containing a 3x3 array within the rot_3x3_c() function. The array member of the struct can be populated before returning the struct from the function. In this case, a designated initializer has been used to zero-initialize the array member of the struct.
The advantage here is simplicity of implementation. There is no dynamic allocation, so no need to worry about memory leaks. The disadvantage is that the array must be accessed as a struct member, so the user of this function must declare struct Mtrx_3x3 R_c to receive the value returned from the function, and must remember to access the array with R_c.mx.
Concerning the constant M_PI
The C Standard not only does not define this constant, but stipulates that a conforming implementation must not define it by default. This means that if a particular implementation does define M_PI, it is an extension which must be explicitly enabled. As a common extension, this constant is defined. For example, if compiling with gcc -std=gnu11, there is no need to explicitly enable M_PI. But if one of the stricter options is used, e.g., gcc -std=c11, M_PI must be explicitly enabled. Here is an SO question that discusses the issue.
Now, _USE_MATH_DEFINES works with Microsoft implementations, but does not work with GCC in Linux (as far as I am aware). For more portability, note that M_PI is defined in POSIX. This can be enabled by using the feature test macro _XOPEN_SOURCE  700. Either add as the very first line in the source file:
#define _XOPEN_SOURCE  700

or enable from the command-line when compiling with:
gcc -std=c11 -D_XOPEN_SOURCE=700

Note that, when using a #define to enable features, it must be at the very beginning of the source file to work. Of course, -std=c99 or -std=c89 could also be used here instead of std=c11.
This will work on Linux systems, which closely conform to POSIX, but I am not sure that it will work on Microsoft systems, which follows POSIX much less closely. For maximum portability, it is best to simply define the constant explicitly, using:
#define M_PI  3.14159265358979323846

An example program
Here is a program that illustrates each of the above approaches:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define M_PI  3.14159265358979323846

typedef double (*Matrix_3x3)[3];
struct Mtrx_3x3 {
    double mx[3][3];
};

void rot_3x3_a(int angle, Matrix_3x3 mtrx);
Matrix_3x3 rot_3x3_b(int angle);
struct Mtrx_3x3 rot_3x3_c(int angle);
void print_3x3_matrix(Matrix_3x3);

int main(void)
{
    int angle = 30;

    /* Allocate for matrix in caller */
    puts("Method a: pass an array");
    double R_a[3][3];
    rot_3x3_a(angle, R_a);
    print_3x3_matrix(R_a);
    putchar('\n');

    /* Use dynamic allocation in function; must remember to free()! */
    puts("Method b: use dynamic allocation");
    Matrix_3x3 R_b = rot_3x3_b(angle);
    if (R_b == NULL) {
        perror("Allocation failure in rot_3x3_b()");
    } else {
        print_3x3_matrix(R_b);
        putchar('\n');
    }

    /* Return the array inside a struct from the function */
    puts("Method c: wrap the array in a struct");
    struct Mtrx_3x3 R_c = rot_3x3_c(angle);
    print_3x3_matrix(R_c.mx);           // remember the array is R_c.mx
    putchar('\n');

    /* Cleanup */
     free(R_b);

    return 0;
}

/* Takes an array as an argument */
void rot_3x3_a(int angle, Matrix_3x3 mtrx)
{
    /* Zero the array first */
    memset(mtrx, 0, sizeof *mtrx * 3);

    double cang = cos(angle * M_PI / 180);
    double sang = sin(angle * M_PI / 180);

    mtrx[0][0] = cang;
    mtrx[1][1] = cang;
    mtrx[1][0] = -sang;
    mtrx[0][1] = sang;
}

/* Returns a pointer to a dynamically allocated array which must be
 * deallocated by the caller with free(), or returns NULL */
Matrix_3x3 rot_3x3_b(int angle)
{
    Matrix_3x3 mtrx = calloc(3, sizeof *mtrx);

    if (mtrx) {
        double cang = cos(angle * M_PI / 180);
        double sang = sin(angle * M_PI / 180);

        mtrx[0][0] = cang;
        mtrx[1][1] = cang;
        mtrx[1][0] = -sang;
        mtrx[0][1] = sang;
    }

    return mtrx;
}

/* Returns a Mtrx_3x3 struct with a 3x3 array in the mx field */
struct Mtrx_3x3 rot_3x3_c(int angle)
{
    struct Mtrx_3x3 mtrx = { .mx = {{ 0 }} };

    double cang = cos(angle * M_PI / 180);
    double sang = sin(angle * M_PI / 180);

    mtrx.mx[0][0] = cang;
    mtrx.mx[1][1] = cang;
    mtrx.mx[1][0] = -sang;
    mtrx.mx[0][1] = sang;

    return mtrx;
}

void print_3x3_matrix(Matrix_3x3 mtrx)
{
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%10.5f", mtrx[i][j]);
        }
        putchar('\n');
    }
}

Program output:
Method a: pass an array
   0.86603   0.50000   0.00000
  -0.50000   0.86603   0.00000
   0.00000   0.00000   0.00000

Method b: use dynamic allocation
   0.86603   0.50000   0.00000
  -0.50000   0.86603   0.00000
   0.00000   0.00000   0.00000

Method c: wrap the array in a struct
   0.86603   0.50000   0.00000
  -0.50000   0.86603   0.00000
   0.00000   0.00000   0.00000


text:
Q: Wand install: TypeError: bad argument type for built-in operation System: Windows 7 Professional 64-bit
Python 3.5.0 |Anaconda 2.4.0 (64-bit)
ImageMagick-6.9.2-Q16 installed and runs standalone.
pip install wand successful
[1]:import wand  #imports OK
[2]:from wand.image import Image
.
.
.
TypeError: bad argument type for built-in operation
MAGICK_HOME env is set correctly.
I manually added the ImageMagick directories to PATH
Any idea on how to resolve?

A: I'm not around windows, but I would assume you would do could set MAGICK_HOME at the system, user, session, or runtime level.
For runtime, it might be as simple as updating your python script
import os
os.environ["MAGICK_HOME"] = "C:\ImageMagick-X.Y.Z"
from wand.image import Image

For a cmd session, run the following before executing the python script.
setx MAGICK_HOME "C:\ImageMagick-X.Y.Z"

Note: The path should be a absolute system path to the root-directly of your ImageMagick installation.


text:
Q: How do I do basic text processing while running speech recognition continuously in python I am currently using Microsoft Azure to get transcribed text from live speech recognition. With that transcribed text, I put that into a TextRank to extract keywords from that speech stream. However, when I run this I lose a lot of speech recognition while running the TextRank code. Is there a way to run speech recognition continuously while passing the transcribed results to the next process, at the same time processing the TextRank keyword extraction, so that I don't lose any speech and extract keywords?
def from_mic():
    speech_config = speechsdk.SpeechConfig(subscription="", region="")
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)

    # print("Speak into your microphone.")
    result = speech_recognizer.recognize_once_async().get()
    print(result.text)
    return result.text

for i in range(1,10):
    transcript = from_mic()
    summa_keywords = summa_keyword_extractor.keywords(transcript, ratio=1.0)
    print(summa_keywords)

A: You need to setup two parallel processes but interlinked with a task-queue.
This is because you have a dependency of extraction on recorder-process.
Here is an attempt of one way to achieve this (obviously its not polished and can be improved further):
def recorder_process(recorder_queue, extractor_queue):
  speech_config = speechsdk.SpeechConfig(subscription="", region="")
  speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)

  while True:
    request = recorder_queue.get()
    result = speech_recognizer.recognize_once_async().get()
    extractor_queue.put(result.text)

def extractor_process(extractor_queue, results_queue):
  while True:
    transcript = extractor_queue.get()
    summa_keywords = summa_keyword_extractor.keywords(transcript, ratio=1.0)
    results_queue.put({'transcript': transcript, 'keywords': summa_keywords})

if __name__ == "__main__":
    # Connect to remote host over TCP
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((HOST,PORT))

    # Set up a Queue to pass data to the update process, and another one
    # for the two children to communicate
    recorder_queue = Queue()
    extractor_queue = Queue()
    results_queue = Queue()

    # Create two child processes, pass a reference to the Queue to each
    recorder = Process(target=recorder_process, args=(recorder_queue, extractor_queue))
    extractor = Process(target=extractor_process, args=(extractor_queue, results_queue))

    recorder.start()
    extractor.start()

    index = 0
    while True:
      recorder_queue.put(index)
      index += 1
      sleep(1)

    recorder.join()
    extractor.join()


text:
Q: There is no system image on this computer? So I am trying to reformat my hard drive with a system image disk. I use the options on the Recovery's advanced options.
I have 2 DVD-RW's with the system image. Two because one DVD wasn't big enough.
It restarts I get all the way to the point where it asks to insert a System image disk to start up I have my 1st System image disk in my drive.....but it doesn't read it and says no system image found!
Ether my computer being stupid and not reading the disk or I am doing something wrong. But I cant see what that would be.
I need to reformat my computer so I can sell the hard drive for a better one.
This is so annoying. I need help.
Is it because its a DVD-RW?  If so that's so stupid =-="

A: Are you "booting" from the disk or using the Windows Recovery options.
I suspect you need to boot from the recovery disk...purely conjecture.
DVD-RW isn't the compatibility definer. Is it a DVD "+" or "-"? Some old DVD Drives wont read  one or the other.
(I would have posted this as a comment but lack the 50 rep)


text:
Q: Karaf : dynamic bundle restart I am developing a composite feature for Karaf (i.e. a feature that includes other features as nested elements). I want to write out configuration files for the nested features and then from the outer scope (i.e. the feature that I am writing), I want to restart the bundles included in the nested features.

*

*How do I query a feature for all of its bundles at runtime from another bundle.

*How do I dynamically restart a bundle from another bundle ?

A: For all two operations you need instance of org.osgi.framework.BundleContext - you can get one in your bundle activator.
To query features (and their dependent features and their bundles) you need access to Karaf's org.apache.karaf.features.FeaturesService OSGi service - for example using BundleContext's getServiceReference() method.
To get any bundle (to be able to restart it) you can get one knowing it's ID: BundleContext.getBundle("ID")


text:
Q: Which field can be used in django serializers for entering ipaddress with subnet mask Which field can be used in django serializers for entering ipaddress with subnet mask. example: x.x.x.x\x is the input format.

A: If you using marshmallow, you can create own field type
    from marshmallow import fields, validate

class IpField(fields.String):
    def __init__(self, *args, **kwargs):
        kwargs['validate'] = validate.Regexp(r'(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)',
                                             error='Not valid IP')
        super().__init__(*args, **kwargs)

And if you use from rest_framework import serializers
serializers.RegexField(regex='(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)')


text:
Q: Relating/adding data to a django object list I'm having trouble understanding how to relate additional information to an existing Django list and if I should be doing this in my templates or in the view somehow. Please see the below scenario:
class Team(models.Model):
    team_name = models.CharField(max_length=200)

For example in my view I am retrieving a list of all sports games and returning them:
def get_teams(request):

    teams = Team.objects.all()

    context = RequestContext(request, {
            'teams': teams,
        })
        return context

I would like to add some stats to the teams which I can then access in my template in the below fashion:
def get_teams(request):

    teams = Team.objects.all()

    for team in teams:
        team_win_percent(team)
        team_lose_percent(team)

    context = RequestContext(request, {
            'teams': teams,
        })
        return context

def team_win_percent(team)
    team_win_rate = [calculations here]

    return team_win_rate

def team_lose_percent(team)
    team_lose_rate = [calculations here]

    return team_lose_rate

What I am struggling to understand is how to add team_win_percentage and team_lose_percentage to my teams list so I can reference them in my template?
Any guidance much appreciated!

A: You could also for a few number of records append some field to the model query result the will be accessible from the template
class Team(models.Model):
    team_name = models.CharField(max_length=200)

def get_teams(request):
    teams = Team.objects.all()
    for team in teams:
        team.team_win_percent = calculate_team_win(team)
        team.team_lose_percent = calculate_team_loss(team)
    ....

In template
{% for team in teams %}
    team win percentage = {{ team.team_win_percent }}
    team lose percentage = {{ team.team_lose_percent }}

{% endfor %}

A: You have to write this as as a model method;
class Team(models.Model):
    team_name = models.CharField(max_length=200)

    def team_win_percent(self):
        #self = team object
        team_win_rate = [calculations here]

        return team_win_rate

    def team_lose_percent(self):
        #self = team object
        team_lose_rate = [calculations here]

        return team_lose_rate

In template:
{% for team in teams %}
    team win percentage = {{ team.team_win_percent }}
    team lose percentage = {{ team.team_lose_percent }}

{% endfor %}