Q: javascript find matching variables between two nested arrays I have two nested arrays.
arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
arr2 = [["image1","blue"],["image2","red"]]

The desired output is : If the image names (image) match, I want to return the color from the second array to a variable.
I have tried using two for loops:
var color = for (var i = 0; i < arr1.length; i++ ) {
for (var j = 0; j < arr2.length; j++ ) {
if (arr1[i][0] === arr2[j][0]) {
return arr2[j][1]
}
}

Since this is a larger part of a program, The first loop gets executed much before the second loop...however both are nested into each other in the order that I have specified.....I am trying to using the variable to color some html elements, but my entire program gets halted.  I am not sure if my approach is right.

A: Feels like you're trying to use the second array as a lookup into the first. Here's a way to do this by transforming it into an object:
 function toLookupTable(shirtColors) {

     //keys will be image names, values will be colors
     const lookupTable = {};

     shirtColors.forEach(shirtColor => {
         //use array destructuring
         const [ image, color ] = shirtColor;
         lookupTable[image] = color;
     });
     return lookupTable;
 }

 const colorLookup = toLookupTable( [["image1","blue"],["image2","red"]] );

 console.log(colorLookup["image2"]); //outputs "red"

A: Use Array#reduce and Array#findIndex

I want to return the color from the second array to a variable.

const arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
const arr2 = [["image1", "blue"],["image2","red"]]

const res = arr2.reduce((a,[image,color])=>{
   if(arr1.findIndex(([n])=>n===image) > -1) a.push(color);
   return a;
}, []);

console.log(res);

A: You can use reduce

let arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]];
let arr2 = [["image1","blue"],["image2","red"]];

let op = arr1.reduce((out,inp,index)=>{
  if(arr2[index].includes(inp[0])){
    out.push(arr2[index][1])
  }
  return out
},[] )

console.log(op)


Q: Windows screensaver from HTML/JS I've an html page without any external includes with some inline CSS3 animations and JS timers.
Is it possible to convert a simple html file to a screensaver file, which can be further used as a screensaver on my windows and mac desktops?
I mean a real screensaver, which boots once desktop goes to a sleep mode, not the one that  works in the browser.
I know there're some tools available to export swf as a screensaver file, are there any tools available for exporting the HTML? At least, for Windows 8.
Any ideas are respected.


Q: Well-definedness of rational exponents? I am a little bit confused witht the definition of rational exponents. I believe that the definition of $a^{\frac pq}$ is $\sqrt[q]{a}^p.$ However, $\dfrac 26 = \dfrac 13$, yet $-1^{2/6}$ is undefined (or imaginary?), while $-1^{1/3}=-1.$ How do we resolve this situation?


Q: Checkboxes not working in WiX generated windows installer I've used WiXEdit in conjunction with Wix to reverse engineer an MSI installation in order to move my main solution up to VS2013 from VS2010.
The error Im getting is that when the MSI is run, the checkboxes and text box I've placed in a dialog act as if they're disabled. I need the checkboxes as in my main application they allow the user to select a feature set.
I've generated a simple solution that demonstrates the same error.
The solution has 2(3) projects, windowsformsapplication12 will always be installed, windowsformsapplication1 will only be installed if conditional CHECKBOX1A=1 (SetupProject2 is the wix project and the wix script is found here as setup1.wxs)
(Wix toolkit is necessary to be installed into visual studio to compile the Wix setup project if necessary, but if somebody with installer expertise checks the script setup1.wxs they may see what's wrong with it.)
NB
On attempting to compile the reverse engineered file, I received error message "Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes." on lines 491,492,493,494. So I added Property="CHECKBOXA1" (or as appropriate) to the end of the control descriptor xml as can be seen if you unrar the source.
I assume I'm missing adding extra code elsewhere or I assume it would work.
This is the first time I've ever encountered a Wix script and the source code doesn't really resemble Wix tutorial code I've seen so I've not been able to debug it.

A: Converting VS2010 setup project to a Wix script
Please find instructions for anybody else who'd find it useful
1) Install WixToolkit and WixEdit
2) Build VS2010 setup project
3) Create new Wix project within the solution.
4) Remove the default product.wxs file from the Wix project
5) Copy the setup MSI file to the root directory of the Wix project
6) Run WixEdit application
7) Open the setup MSI file in WixEdit
(This should generate files and directories)
7) Add directories and files generated by WixEdit to the Wix project
8) Compile Wix Setup Project and fix errors
9) Delete the original msi file from the wix project
Re Check boxes not working
"Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes"
Go to the error line in the script
<Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no"/>

Change it so it reads (or appropriate changes)
<Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no" Property="CHECKBOXA1" CheckBoxValue="1" />

CheckBoxValue="1" was the missing attribute that caused my checkboxes to be disabled


Q: Android Annotations @AfterViews called 3 times I'm using Android Annotations and my method annotated with @AfterViews is called 3 times. I debugged the generated class and i figure that these 3 methods are invoked but i dont know why.
@Override
public void setContentView(int layoutResID) {
    super.setContentView(layoutResID);
    afterSetContentView_();
}

@Override
public void setContentView(View view, LayoutParams params) {
    super.setContentView(view, params);
    afterSetContentView_();
}

@Override
public void setContentView(View view) {
    super.setContentView(view);
    afterSetContentView_();
}

-- edit 1 --
My activity declaration is the only place where I set a layout:
@EActivity(R.layout.real_estate_customer_leads_list)
public class RealEstateCustomerLeadsListActivity extends
    SlidingFragmentActivity implements FilterResponseHandler {

}

A: that's probably because one super is calling the other. Something like this:
 // super.setContentView(layoutResID); code is:
 View v = LayoutInflater.from(getContext()).inflate(layoutResId);
 setContentView(v);

// then super.setContentView(view); code is:
setContentView(view, null);

// then super.setContentView(view, params);
this one now actually do real work. Hence, 3 calls!


Q: Create FTPS server without giving out my IP address? I am creating an FTPS server with FileZilla, and I want to have some other people access it from wherever they are. The issue is, I don't want to give them my IP address. Is there a way I can do this without giving out my IP address?
P.S: Sorry, my English is not very good. And I'm very new to this

A: No, you can't. They need the IP address to connect. Even if you just give them a domain name address, like ftp.example.com, they can use tools such as nslookup to find the IP address.

A: You can run the server via a Tor hidden service, and give them just the .onion address.


Q: Homeomorphism theorem I need to show that if $f: X \rightarrow Y$ is 1-1 and $X$ and $Y$ are metric spaces,  then if $\forall  A\subset X, f(\overline{A})=\overline{f(A)} $ then $f$ is homeomorphism.
1) Assume $f$ is 1-1 and $\forall  A\subset X, f(\overline{A})=\overline{f(A)} $. I need to show that f is a homeomorphism.
It is sufficient to show that f is continuous and $f^{-1}$ as well is continuous. I cannot show these steps unless f is onto since I need to use $f(f^{-1}(A))=A $ often.
Please help me with this.
Thank you.

A: Suppose that $f:X\to Y$ is bijective. Then there are a few useful things to note/prove:

(1) $f$ is continuous if and only if $f\left(\overline{A}\right)\subseteq\overline{f(A)}$ for all $A\subseteq X$. In the same way, $f^{-1}:Y\to X$ is continuous if and only if $f^{-1}\left(\overline{A}\right)\subseteq\overline{f^{-1}(A)}$ for all $A\subseteq Y$.
(2) $f$ is an open map if and only if $f^{-1}:Y\to X$ is continuous.
(3) Given $A\subseteq X,B\subseteq Y$, we have $f(A)\subseteq B$ if and only if $A\subseteq f^{-1}(B)$.

Is that enough to get you started?

Now, let's suppose that $f:X\to Y$ is 1-to-1, but not necessarily onto. Putting $Z=f(X)$, we have $f:X\to Z$ is a bijection, and $f^{-1}:Z\to X$ is perfectly well-defined. Now, I'm going to give slightly altered versions of the above hints (and add another one) to fit your change to the question. First, though, I'm going to define the following notation to avoid confusion:

Given a subset $S$ of a topological space $T$, we will now denote the closure of $S$ in $T$ by $\text{cl}_T(S)$. (Since we're dealing with several different spaces, it's a good idea to keep track of where things are.)

Now, we want to show that $f$ is a homeomorphism from $X$ to $Z$ (rather than to $Y$) if and only if $$\forall A\subseteq X,\:f\bigl(\text{cl}_X(A)\bigr)=\text{cl}_Y\bigl(f(A)\bigr).\tag{#}$$
Now, let's amend my list of useful notes/results-to-be-proved.

(1) $f:X\to Z$ is continuous if and only if $f\bigl(\text{cl}_X(A)\bigr)\subseteq\text{cl}_Z\bigl(f(A)\bigr)$ for all $A\subseteq X.$ In the same way, $f^{-1}:Z\to X$ is continuous if and only if $f^{-1}\bigl(\text{cl}_Z(A)\bigr)\subseteq\text{cl}_X\bigl(f(A)\bigr)$ for all $A\subseteq Z.$
(2) $f:X\to Z$ is an open map if and only if $f^{-1}:Z\to X$ is continuous.
(3) Given $A\subseteq X,B\subseteq Y$, we have $f(A)\subseteq B$ if and only if $A\subseteq f^{-1}(B)$. (This is also true if we replace $Y$ with $Z.$)
(4) $S\subseteq Z$ is closed in $Z$ if and only if there is some $F\subseteq Y$ such that $S=F\cap Z$ and $F$ is closed in $Y;$ thus, $\text{cl}_Z(S)=Z\cap\text{cl}_Y(S)$ for all $S\subseteq Z.$

Hopefully that will get you where you need to go.


Q: How can I enter 2 commands on Windows command line? In the DOS command line, I used to be able to enter ¶ between commands to put multiple commands on one line.
For example, instead of typing
c:\> cls
c:\> cd

I could enter
c:\> cls¶cd

Has this functionality been removed or has this been replaced by something else?
How can I run multiple commands from one line?

A: &&.  The double ampersand actually performs error checking.  If the commands to the left of the && don't return with the expected result, the commands on the right aren't executed.
cls && cd
If you want to run the commands on both sides of the &&, use a single ampersand.
cls & cd

A: cls & cd
All you need is &
As others have stated, && will only execute the second command if the first was successful.
|| will execute the second command if the first failed.
Have fun!

A: Use &.
From the documentation:

command1 & command2 : Use to separate multiple commands on one command
  line. Cmd.exe runs the first command, and then the second command.
command1 && command2 : Use to run the command following && only if the
  command preceding the symbol is successful. Cmd.exe runs the first
  command, and then runs the second command only if the first command
  completed successfully.
command1 || command2 : Use to run the command following || only if the
  command preceding || fails. Cmd.exe runs the first command, and then
  runs the second command only if the first command did not complete
  successfully (receives an error code greater than zero).
(command1 & command2) : Use to group or nest multiple commands.
command1 parameter1;parameter2: Use to separate command parameters.


Q: sort values a data frame with duplicates values I have a dataframe with a format like this:
d = {'col1': ['PC', 'PO', 'PC', 'XY', 'XY', 'AB', 'AB', 'PC', 'PO'], 'col2':
[1,2,3,4,5,6,7,8,9]}
df = pd.DataFrame(data=d)

df.sort_values(by = 'col1')

This gives me the result like this:

I want to sort the values based on col1 values with desired order, keep the duplicates. The result I expect would be like this:

Any idea?
Thanks in advance!

A: You can create an order beforehand and then sort values as below.
order = ['PO','XY','AB','PC']
df['col1'] = pd.CategoricalIndex(df['col1'], ordered=True, categories=order)

df = df.sort_values(by = 'col1')
df

    col1    col2
1   PO      2
8   PO      9
3   XY      4
4   XY      5
5   AB      6
6   AB      7
0   PC      1
2   PC      3
7   PC      8


Q: arduino yun to parse.com starter project not working I'm trying to run the arduino starter project from parse.com and like other people i have found the object id blank Parse.com Arduino Yun SDK Quickstart tutorial not working
in the serial monitor i get this response
Parse Starter Project
Response for saving a TestObject:
Test object id:
However i've tried everything i can think of, updated the bridge library, tried various different versions of the IDE and of the bridge library. I'm running windows. I've tried 1.6.1, 1.6.3, 1.6.5 and i've tried several versions of the bridge library. I'm at a loss. Anyone else encountered this issue and have an ideas?

A: So i managed to fix it!
The issue was with the embedded SDK. If anyone struggles with the same probelm here are the steps i took:

*

*Download WinSCP.

*Connect to the arduino using SSH in WinSCP (username root)

*copy across the two embedded parse.com arduino files (make sure they are in the correct root folder

*Download PuTTY and use this to open the arduino command line

*call opkg install *.ipk to install the SDK files

That seems to have sorted the problem, they weren't installed properly before


Q: Invoking a controller method without having a route defined for it I have several routes, and do not want to add another due to the difficulty in setting permissions, etc. I have a controller method, which isn't invoked on any route. Is there any way I can do this in my blade template?
My controller method is as follows:
public static function editROA(){
//do stuff
}

and in my blade template, I would like to refer this:
Edit

However, this throws an error, and says that there is no method named editROA. Is there any solution to this problem?

A: Since you cannot have more than five routes, I would suggest you use only one wild-carded route. So you run an if else on the wild card to call the appropriate method.
Route::get('{uri?}',function($uri){
    if($uri == "/edit")
    {
        return app()->call('App\Http\Controllers\HomeController@editROA');
    }else if($uri == "something else"){
        return app()->call('App\Http\Controllers\SomeController@someMethod');
    }
    // add statements for other routes
});

view
Edit


Q: How to prevent a page from resubmitting? in grails 2.2.0 When once form is submitted successfully....
but When I click on "BACK" button and trying submit same form
its gives me an error
Source:
<g:form action="addData" name="addValues" controller="emp" method="Post">
</g:form>

Controller Source:-
def editProfile (Long id,Long version){
        withForm {
        // code
            }.invalidToken {
            response.status = 405

        }
    }

A: Its hard to infer the cause of the error with what you have posted. However, you asked about how to prevent a page from resubmitting in Grails. Take a look at documentation. Grails has a build in support for that.
Basically you define a form with a token and using withForm you will check if the token still is valid or not.
<g:form useToken="true" ...>

/
withForm {
   // good request
}.invalidToken {
   // bad request
}


Q: Backbone Undefined is not a function error I'm learning backbone and I'm trying to execute this sample code to get the feel.

http://backbonetutorials.com/what-is-a-view/

My code:
  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>
    <script type="text/javascript">
Rocky = Backbone.Model.extend({
  initialize: function(){
    console.log('hello world');
  }
});
</script>
  </body>
  </html>

I get this error.
Uncaught type error: Undefined is not a function!
What did I do wrong? I was just trying to print and see if it's printed on my console!
Thanks,
R

A: Your underscore.js version is too old. Try to use the new version (1.7):
<script src="http://underscorejs.org/underscore.js"></script>


Q: Why is infinite loop needed when using threading and a queue in Python I'm trying to understand how to use threading and I came across this nice example at http://www.ibm.com/developerworks/aix/library/au-threadingpython/
      #!/usr/bin/env python
      import Queue
      import threading
      import urllib2
      import time

      hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
      "http://ibm.com", "http://apple.com"]

      queue = Queue.Queue()

      class ThreadUrl(threading.Thread):
      """Threaded Url Grab"""
        def __init__(self, queue):
          threading.Thread.__init__(self)
          self.queue = queue

        def run(self):
          while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and prints first 1024 bytes of page
            url = urllib2.urlopen(host)
            print url.read(1024)

            #signals to queue job is done
            self.queue.task_done()

      start = time.time()
      def main():

        #spawn a pool of threads, and pass them queue instance
        for i in range(5):
          t = ThreadUrl(queue)
          t.setDaemon(True)
          t.start()

       #populate queue with data
          for host in hosts:
            queue.put(host)

       #wait on the queue until everything has been processed
       queue.join()

      main()
      print "Elapsed Time: %s" % (time.time() - start)

The part I don't understand is why the run method has an infinite loop:
        def run(self):
          while True:
            ... etc ...

Just for laughs I ran the program without the loop and it looks like it runs fine!
So can someone explain why this loop is needed?
Also how is the loop exited as there is no break statement?

A: Do you want the thread to perform more than one job?  If not, you don't need the loop.  If so, you need something that's going to make it do that.  A loop is a common solution.  Your sample data contains five job, and the program starts five threads.  So you don't need any thread to do more than one job here.  Try adding one more URL to your workload, though, and see what changes.

A: The loop is required as without it each worker thread terminates as soon as it completes its first task. What you want is to have the worker take another task when it finishes.
In the code above, you create 5 worker threads, which just happens to be sufficient to cover the 5 URL's you are working with. If you had >5 URL's you would find only the first 5 were processed.


Q: Azure Function ignoring https.request I have an azure function with this line of code.

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();

But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up.
Any ideas?
Edit:
Here is my full code

const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};

A: Ideally it should work. You can also try using request module like below
const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Try and see if it helps.

A: Solved by doing await properly. Used this as guide.

var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    /*if (req.query.name || (req.body && req.body.name)) {*/
    var getOptions = {
        contentType: 'application/json',
        headers: {
            'Authorization': <bearer_token>
         },
    };
    var postData = {
        "key": "value"
    };
    var postOptions = {
        method: 'post',
        body: postData,
        json: true,
        url: <post_url>,
        headers: {
            'Authorization': <bearer_token>
         },
    };
    try{
        var httpPost = await HttpPostFunction(context, postOptions);
        var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
        return {
            res: httpPost
        };
    }catch(err){
       //handle errr
       console.log(err);
    };
};

async function HttpPostFunction(context, options) {
    context.log("Starting HTTP Post Call");
    return new Promise((resolve, reject) => {
        var data = '';
        request(options, function (err, res, body) {
            if (err) {
              console.error('error posting json: ', err)
              reject(err)
            }
            var headers = res.headers;
            var statusCode = res.statusCode;
            //context.log('headers: ', headers);
            //context.log('statusCode: ', statusCode);
            //context.log('body: ', body);
            resolve(body);
          })
    });
};

async function HttpGetFunction(context, url, options) {
    context.log("Starting HTTP Get Call");
    return new Promise((resolve, reject) => {
        var data = '';
        https.get(url, options, (resp) => {
            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            })
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(JSON.parse(data));
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
            reject(err.message);
        });
    });
};


Q: How to run regasm.exe from a C++ program (.NET 4) I need to register a .NET COM dll from a C++ program that is using it. For .NET versions older then .NET 4 this is explained in How to run regasm.exe from a C++ program?. Following is the minimal code (no checks) that provides the path to an older version of the CLR.
CComBSTR mscoreeName("mscoree.dll");
HINSTANCE hMscoree = CoLoadLibrary(mscoreeName, FALSE);
typedef HRESULT (WINAPI *LPFNGETCORSYSDIR)(LPWSTR, DWORD, DWORD*);
LPFNGETCORSYSDIR lpfunc = (LPFNGETCORSYSDIR)GetProcAddress(hMscoree,_T("GetCORSystemDirectory"));

DWORD bufferSize = 256;
DWORD bufferUsed;
LPWSTR pwzBuffer = new WCHAR[bufferSize];
(*lpfunc)(pwzBuffer, bufferSize, &bufferUsed);

However since I use .NET 4 the method GetCORSystemDirectory is superseded by the ICLRRuntimeInfo::GetRuntimeDirectory which is not an entry point in mscoree.dll (checked with depends). According the documentation on MSDN the method is included as a resource in MSCorEE.dll.
Question is how to get access to this method from C++?
Besides that I'm wondering if there is no easier way...

A: The problem with the way of working in the question is in finding the correct location of RegAsm. Thanks to the comment of Hans Passant to use RegistrationService.RegisterAssembly I changed the ClassLibrary into a self-registering executable.
static void Main(string[] args)
{
    if (args.Length != 1)
    {
        ShowHelpMessage();
        return;
    }

    if (args[0].CompareTo("/register") == 0)
    {
        Assembly currAssembly = Assembly.GetExecutingAssembly();
        var rs = new RegistrationServices();
        if (rs.RegisterAssembly(currAssembly, AssemblyRegistrationFlags.SetCodeBase))
        {
            Console.WriteLine("Succesfully registered " + currAssembly.GetName());
        } else
        {
            Console.WriteLine("Failed to register " + currAssembly.GetName());
        }
        return;
    }

    if (args[0].CompareTo("/remove") == 0)
    {
        Assembly currAssembly = Assembly.GetExecutingAssembly();
        var rs = new RegistrationServices();
        if (rs.UnregisterAssembly(currAssembly))
        {
            Console.WriteLine("Succesfully removed " + currAssembly.GetName());
        }
        else
        {
            Console.WriteLine("Failed to remove " + currAssembly.GetName());
        }
        return;
    }

    ShowHelpMessage();
}


Q: Input Packet Drops Currently, my Cisco 2600 router running CIOS 12.1 is experiencing packet drops on the interface that connects to the ISP.
#show int fa0/0
FastEthernet0/0 is up, line protocol is up
MTU 1500 bytes, BW 100000 Kbit, DLY 100 usec,
reliability 255/255, txload 1/255, rxload 23/255
Encapsulation ARPA, loopback not set
Keepalive set (10 sec)
Full-duplex, 100Mb/s, 100BaseTX/FX
ARP type: ARPA, ARP Timeout 04:00:00
Last input 00:00:00, output 00:00:00, output hang never
Last clearing of "show interface" counters 03:45:44
Queueing strategy: fifo
**Output queue 0/40, 0 drops; input queue 0/75, 145 drops**
5 minute input rate 9285000 bits/sec, 872 packets/sec
5 minute output rate 656000 bits/sec, 493 packets/sec
    10523044 packets input, 906814473 bytes
    Received 25631 broadcasts, 0 runts, 0 giants, 0 throttles
    22116 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
    0 watchdog
    0 input packets with dribble condition detected
    6061031 packets output, 1078369785 bytes, 0 underruns
    0 output errors, 0 collisions, 0 interface resets
    0 babbles, 0 late collision, 0 deferred
    0 lost carrier, 0 no carrier
    0 output buffer failures, 0 output buffers swapped out`

After checking Cisco's support pages, they suggested that this may be caused by CEF being disabled and too much traffic to the interface.  However, neither issue would be the case as I've verified CEF to be enabled as well as utilizing only 20% of my bandwidth.  Any idea of what other checks I may have missed that could help determine what is causing this issue?

A: Input queue drops are one of these things that are very difficult to track down the true cause of.  First, I'd look at your input error counter - you have 22116 input errors, but they are not categorized any further.  So we know they're not CRC errors, etc.  What is on the other side of this router?  If the outgoing interface (internal to your network) is overloaded or busy or half-duplex or any one of a number of other things, the packets might get dropped on the incoming side because they can't be handed off to the outgoing side.  I would also take a look at http://www.cisco.com/en/US/products/hw/routers/ps133/products_tech_note09186a0080094791.shtml and read it top to bottom very carefully, the answers you want may be in there.


Q: Unable to understand where argv[1] and arg [2] command are pointing in this program Here is someone's program, which i need for my project to collect data. I'm unable to understand where is the command #define IMAGE argv[1] #define IFS argv[2] pointing to and what are the values being defined in the IMAGE and IFS. These two command are necessary as they are later on required to for reading a file name.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <alloc.h>

#define IMAGE argv[1]
#define IFS argv[2]

get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int
*assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image, char *argv[]);

unsigned int *image;

main(int argc, char *argv[])
{
unsigned char dom[4][4], d1[4][4], ran[8][8], lowest_error, sym, bestsym,         domain_whites,range_whites;
unsigned int assumed_width_of_image, assumed_height_of_image, width_of_image,
    height_of_image;
unsigned long int count, domx, domy, ranx, rany, bestranx;
time_t start_time;
FILE *ifs_file;

start_time = time(NULL);
if (argc != 3) {
    printf("\nUse the following format:\n\ncompress [image_file] [ifs_file]\n\n");
    exit
}
if ((ifs_file = fopen(IFS, "wb")) == NULL) {
    fprintf(stderr, "\nError opening file %s\n", IFS);
    exit(1);
}
get_image(ifs_file, &assumed_width_of_image, &assumed_height_of_image,   &width_of_image, &height_of_image, argv);

    get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int
   *assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image,    char *argv[])
   {
 FILE *image_file;
unsigned int buf[24], *header, size_of_header, extra_height;
unsigned long size_of_file, size_of_image;

if ((image_file = fopen(IMAGE, "rb")) == NULL) {
    fprintf(stderr, "\nCannot open file %s\n", IMAGE);
    exit(1);
}
if (fread(buf, sizeof(unsigned int), 24, image_file) != 24) {
    fprintf(stderr, "\nError reading file %s\n", IMAGE);
    exit(1);
}
if (buf[0] != 19778) {
    printf("%s is not a .BMP file", IMAGE);
    exit(0);
}
if (buf[23] != 2) {
    printf("%s is not a black and white image", IMAGE);
    exit(0);
}

A: argc and argv refer to command line inputs. When the program is run they are specified by the user.
myprogram.exe --input1 fred
See this: What does int argc, char *argv[] mean?


Q: How get list of days in a week that exist in some date range (Javascript) Hello I need to define existing days in some date range.
I don't wont to make loop from start to end dates and use like here http://www.w3schools.com/jsref/jsref_getday.asp
Is it possible to calculate it some how ?

A: function getDays(earlierDate, laterDate) {
  var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
  var elapsedDays = (laterDate - earlierDate) / 1000 / 60 / 60 / 24;
  if (elapsedDays < 7) {
    var dayArray = [];
    for (i = 0; i <= elapsedDays; i++) {
        dayArray.push(dayNames[(earlierDate.getDay()+i) % 7]);
    }
    return dayArray;
  }
  return dayNames;
}

And testing in the js console:
> getDays(new Date("03-01-2012"), new Date("03-01-2012"));
["Thursday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2012"));
["Thursday", "Friday", "Saturday", "Sunday", "Monday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2013"));
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

A:  var sevenDaysInMS = 604800000;
    if (new Date(dTo - dFrom).getTime() >= sevenDaysInMS) {
        $('.day_hid').attr(attrUnaviableDay, "true");
    } else {
        var dt = dFrom;
        do {
            var day = dt.getDay();
            ActivateDaySelector(day);
            dt.setDate(dt.getDate() + 1);
        } while (dt <= dTo);
    }

I think it is ok. What do you think ?


Q: mgwt / gwtphonegap advices, feedback, tips I have to develop an application on Android, iOS and Windows Phone by using Phonegap.
I would like to know if someone has already used mgwt / gwtphonegap and have your feedback / advices on these technologies, if you have encountered some blocking issues for example.
I have already developed a Phonegap application in javascript (jquery / jquery mobile) html / css, but now I would know if I could start another one by using only GWT. However I would like to avoid to begin the development and realize 3 weeks later that I'm blocked because of mgwt / gwtphonegap.
Note that I have never developed with GWT but often in Java
Thanks

A: I've been using mgwt/phonegap only a few months, so I'm definitely not an expert, but so far no major stumbling blocks. I like GWT, as it is well documented, robust and supported, although mgwt is a bit less so. There's an active google forum at https://groups.google.com/forum/?fromgroups#!forum/mgwt. Maybe if you have some more specific question, I or someone on that forum could answer it.


Q: How to pass UserId Dynamically when reading the event information related to user and How to pass userid to RestRequest? I want to get the user related events based on userid I'm trying to retrieve the event details. Here my query is:
List<Event> events = [SELECT Subject,StartDateTime,EndDateTime FROM Event WHERE OwnerId =:userinfo.getUserId()];

I'm trying to expose through REST API. How can I pass the UserId to RestRequest like here
String OwnerId =req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

but how to link those two? For checking I'm using workbench by passing the user id I'm getting the event details related to that user but it won't display anything.

A: You just need to change your query to use the string you parsed out.
String ownerId = req.requestURI.substringAfterLast('/');
List<Event> events = [SELECT ... FROM Event WHERE OwnerId = :ownerId];

Then you would need to make sure you hit an endpoint that does indeed terminate with /<some_user_id>.


Q: If two random numbers generated at exactly same time using Math.random(), would they be same or different? I want to predict the random number generated with Math.random() function.
I studied an article that the algorithm behind random number generator function takes the time in mili seconds an input, and generate a random number.
So, is this possible to predict the next random number?
I am playing a game named as dragon/tiger. Each dragon and tiger has 13 numbers. The numbers for both are both randomly generated after every 15 seconds. The side having higher number wins. Is there any way to predict which side will win(what number would be generated next)?


Q: Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush I'm getting an error when imagemin is run on png : Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush
i'm on a macbook pro 10.6.8
I installed grunt today along with the plugin's
Any help would be wonderful as google is pointing me to IOS development issues.

A: The binary is compiled for a newer version of the OS (you're now 4 major releases behind — upgrade if you can!)


Q: Find the power of the matrix representation of a linear transformation "The matrix representation of $T:R^2 -> R^2$ in the basis {$\begin{pmatrix}
        1  \\
        1  \\
        \end{pmatrix}$,
$\begin{pmatrix}
        -2  \\
        2  \\
        \end{pmatrix}$} is $D =\begin{pmatrix}
        1 & 0  \\
        0 & \frac 1 {2} \\
        \end{pmatrix}$
Decide $T^n ( \begin{pmatrix}
        2  \\
        5  \\
        \end{pmatrix})$ for every integer $n>0$."
Isn't $T(x)$ representation of the linear transformation which means that I have: $\begin{pmatrix}
        1 & 0  \\
        0 & \frac 1 {2} \\
        \end{pmatrix}^n \begin{pmatrix}
        2  \\
        5  \\
        \end{pmatrix}$? Or how do I tackle this problem?
Another guess that I have is that I should use that $ A^n = PD^nP^{-1}$ but I don't know if that's applicable here?

A: It is incorrect to say that
$$
T^n \pmatrix{2\\5} =
\begin{pmatrix}
        1 & 0  \\
        0 & \frac 1 {2} \\
        \end{pmatrix}^n \begin{pmatrix}
        2  \\
        5  \\
        \end{pmatrix}
$$
In particular, note that the diagonal matrix is the matrix with respect to the basis given.  Instead, note that
$$
\pmatrix{2\\5} = 3.5 \pmatrix{1\\1} + .75  \pmatrix{-2\\2}
$$
and proceed from there.


Q: How to use org.apache.logging.log4j.jul.LogManager in an eclipse-rcp application? I am trying to use the log4j2 LogManager in an eclipse rcp application.
I have

-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager

set as start parameter. Starting the rcp application from within my eclipse IDE everything works as expected. But as soon as I start it as a standalone application logging won't work.
A possible hint may be the following stacktrace from the client console:
Could not load Logmanager "org.apache.logging.log4j.jul.LogManager"
java.lang.ClassNotFoundException: org.apache.logging.log4j.jul.LogManager
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.eclipse.core.runtime.internal.adaptor.ContextFinder.loadClass(ContextFinder.java:131)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.util.logging.LogManager$1.run(Unknown Source)
        at java.util.logging.LogManager$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.util.logging.LogManager.<clinit>(Unknown Source)
        at java.util.logging.Logger.demandLogger(Unknown Source)
        at java.util.logging.Logger.getLogger(Unknown Source)
        at org.apache.felix.gogo.runtime.threadio.ThreadIOImpl.<clinit>(ThreadIOImpl.java:30)
        at org.apache.felix.gogo.runtime.activator.Activator.start(Activator.java:75)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
        at org.eclipse.equinox.console.command.adapter.Activator.startBundle(Activator.java:248)
        at org.eclipse.equinox.console.command.adapter.Activator.start(Activator.java:237)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
        at org.eclipse.osgi.framework.internal.core.ConsoleManager.checkForConsoleBundle(ConsoleManager.java:215)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:297)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:176)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1438)

What do I need to do to get logging running in the RCP application without starting it from within my IDE?

A: It sounds like eclipse is aware of your dependency on this class and is able to add it to the classpath for you. What you need is a way to add the dependency to the classpath when you run it outside of eclipse. To fix this, ensure the class org.apache.logging.log4j.jul.LogManager is on the classpath. This can be done with -cp and the path to the jar file. For example if you have a class com.org.Main you are trying to run.
java -cp your.jar:log4j-jul-2.3.jar com.org.Main

your.jar is the jar containing your application and log4j-jul-2.3.jar is the jar containing the missing class.


Q: Creating HK2 modules I'm trying to leverage the Hundred Kilobyte Kernel (HK2) framework, however I can't find any tutorials or working examples of it. I have installed Maven, as it is required, but I can't find the archetypes to work with. I'm working with Eclipse, and I have only found this Netbeans guide but even the example source files are non existent.
Under Eclipse, I managed to install the m2e maven plugin and I have tried to start a new project, however when I try to search for the hk2 archetype to create my customization of it I can't find the required resources. I try to create a new project, and then add an archetype, I specify com.sun.enterprise as the group id, the artifact id as hk2 (and hk2-maven-plugin as per some instructions), the latest version I could find (1.6.9) and the remote location as http://download.java.net/maven/glassfish/, but even when the jar files are there, there is no archetype catalog file that I can find. I have also tried adding this location as a Remote Catalog, but since there is no xml file to point to, it says the catalog is empty.
My question is, does anyone have any updated resources or startup steps to create an hk2 module? or can tell me how to use what I have? Inside the jars there are pom.xml files, however if I import those to Eclipse, it has errors that I don't know how to fix. Development on the project seems almost completely halted (last updates are from jul 2011) but maybe someone already familiar with Glassfish plugin development can point me in the right direction? or maybe could someone recommend an alternative to HK2? If anyone has any good OSGi tutorials that would be nice too, or any other similar framework.
Thanks!

A: Sounds like you're better off with OSGi ... The HK2 (which would surprise me if it was still 100k) was an attempt to not depend on OSGi directly for Glassfish. I do not think it has a well maintained API.
Since OSGi is a well defined and maintained API, that it runs on Glassfish, and that you also get portability to other environments seems to indicate that the choice for OSGi is smarter. The easiest way to get started is http://bndtools.org/

A: If you want to do Glassfish module development I can recommend you following tutorials and one example taken from the Glassfish trunk. Just have a look there how they do it. I tried it once, but since HK2 is not really OSGi as Peter already mentioned, I let it be after some time :) But maybe you can take advantages of these information now ;)

*

*http://kalali.me/glassfish-modularity-system-how-extend-glassfish-cli-and-web-administration-console-part-2-developing-sample-modules/

*http://java.net/projects/glassfish-samples/sources/svn/show/trunk/v3/plugin/adminconsole/console-sample-ip/


Q: Android loadLabel giving very laggy/slow performance, any solutions? I'm trying to create a launcher app in which I fetch all app names with loadLabel, but it's taking almost 3 second to load the names, and is very slow!!! I tried removing that text and now it works very fast! But I want app labels, Can we use any alternative method? Here's the code:
TextView label = (TextView) grid.findViewById(R.id.label);
            Typeface tf_label = Typeface.createFromAsset(getAssets(),
                    "fonts/RobotoC-Regular.ttf");
            label.setTypeface(tf_label);
            label.setText(info.activityInfo.loadLabel(getPackageManager())
                    .toString());

A: similiar problem here. I load the list of all apps and add them to a recyclerview, i had to wait some seconds before it was loaded so i timed the loading time. What i noticed is that loading icons and labels with 70 apps i needed around 2.6 seconds to load the apps, without loading icons and label ... an astonishing 61ms! YEAH milliseconds!
For now i am using a temporary solution, i will probably improve it in the future. What i did is create a model object that loads labels and icons in a background thread.
public class AppModel {
    ComponentName componentName;

    Drawable icon = null;
    String appName = "";

    public AppModel(ComponentName componentName) {
        this.componentName = componentName;
    }

    public void init(ActivityInfo ai, PackageManager pm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                appName = (String) ai.loadLabel(pm);
                icon = ai.loadIcon(pm);
            }
        }).start();

    }
    ...
    ...
}

when i load the apps i do the following:
AppModel appModel = new AppModel(componentName);
appModel.init(ai, pm);
// other stuff

I needed a fast and working hotfix, in this way while the app is added to the recyclerview the labels and icons get loaded in background, cutting down the loading time by a lot!
A future solution i am considering is to load those icons and labels in multithreading.
Hope it helps.


Q: Notification for When External Users Join We have a few sites that require external access at the folder level. The external user has to be in Active Directory before adding to folder permissions so we created a new group 'External Users' and added a few in there. They do not show up in the group until the invite is accepted. Is there a way to be notified when an external user accepts a SharePoint Group invite?

A: Please following steps:
First, you have to create a Microsoft 365 group in Azure Active Directory

Then, sign in Microsoft 365 admin center as a global administrator. Navigation to Groups, and click Active groups, and find the newly created Microsoft 365 group.
Finally, click on the group. Then go to the "Settings" and turn on the "Allow external senders to email this group" option.

So, when you add an external user to the group, the external user will receive an invitation email.

A: There is no OOB way to know when exactly an external user accepts an invitation. However, we can poll an Azure AD Security group every several minutes using a Power Automate flow. We can detect if there are any new members in a group since the last run.
This is a quick unfinished example, but should give you an idea of how to implement it:

I would create a SharePoint list that will store all processed external users. If an AD Security group has a new member that is not yet in the SharePoint list, then, we can send an email alert.


Q: Capturing IR Data using VB.NET Just found an old IR reciever (Microsoft eHome Infared Transceiver) and i'm trying to write an application that can use data it captures...
Any examples or jumping off points for this are appreciated.

A: Looks like it's a USB HID device. As such, you should be able to use Win32 API to talk to it - similar to other USB HID devices.

A: I think the Microsoft eHome Infared Transceiver is a Human Interface Device (HID), so I'd start with The HID Page.
This has a VB.NET sample on it.


Q: PHP displaying arrays having duplicate with color=red I have a array that i want to check if has duplicates using PHP
$i=array('One','Two','Two','Three','Four','Five','Five','Six');

I was able to achieve it by using below function
  function array_not_unique($input) {
       $duplicates=array();
       $processed=array();
       foreach($input as $i) {
           if(in_array($i,$processed)) {
               $duplicates[]=$i;
           } else {
               $processed[]=$i;
           }
       }
       return $duplicates;

   }

I got below output
Array ( [0] => Two [1] => Five )

Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table.
My goal is to display the duplicated values with red font color.

A: Try this piece of code... simplest and shortest :)
$i=array('One','Two','Two','Three','Four','Five','Five','Six');

$arrayValueCounts  = array_count_values($i);

foreach($i as $value){

    if($arrayValueCounts[$value]>1){

        echo ''.$value.'';
    }
    else{

        echo ''.$value.'';
   }
}

A: Here is optimized way that will print exact expected output.
<?php

$i=array('One','Two','Two','Three','Four','Five','Five','Six');

$dups = array_count_values($i);
print_r($dups);

foreach($i as $v)
{
    $colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : '';
    echo "$v";
}

?>

A: Try this,
function array_not_unique($input) {
       $duplicates=array();
       $processed=array();
       foreach($input as $key => $i) {
           if(in_array($i,$processed)) {
               $duplicates[$key]=$i; // fetching only duplicates here and its key and value
           }
       }
       return $duplicates;
}
foreach($processed as $k => $V){
    if(!empty($duplicates[$k])){ // if duplicate found then red
        echo ''.$duplicates[$k].'';
    }else{
        echo ''.$duplicates[$k].''; // normal string
    }
}

A: Like this :
PHP
function array_duplicate_css($input) {

   $output = $processed = array();

   foreach($input as $key => $i) {
       $output[$key]['value'] = $i;
       if(in_array($i, $processed)) {
           $output[$key]['class'] = 'duplicate';
       } else {
           $output[$key]['class'] = '';
           $processed[] = $i;
       }
   }

   return $output;
}

foreach(array_duplicate_css($input) as $row) {
    echo '
' . $row['value'] . '
';
}

CSS
.duplicate {
    color: #ff0000;
}

A: Simple use array_count_values.
$array=array('One','Two','Two','Three','Four','Five','Five','Six');

$new_array= array_count_values($array);

foreach($new_array as $key=>$val){

  if($val>1){

     for($j=0;$j<$val;$j++){

         echo "".$key."";
     }

   }else{

     echo "".$key."";

   }

}

A: It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.


Q: Abbreviating numbers in Android, locale sensitive In my Android project, I am hoping to find a way to abbreviate numbers that is sensitive to various locales. If the number is less than 1000, it is to remain as is; otherwise, I would like the number divided by the largest possible power of 1000 and rounded to two decimal places. So far, I have the below code, which correctly produces the desired results as stated under Output.
public void formatNumbers() {
    //Output:
    //842 => 842
    //24,567 => 24.57k
    //356,915 => 356.92k
    //7,841,234 => 7.84M
    //1,982,452,873 => 1.98B
    int[] i = new int[] {842, 24567, 356915, 7841234, 1982452873};
    String[] abbr = new String[] {"", "k", "M", "B"};
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.HALF_UP);
    for (long i1 : i) {
        int thousands = thousands(i1);
        String result;
        if(thousands == 0) {
            result = String.valueOf(i1);
        } else {
            double d = (double) i1 / Math.pow(1000.0, thousands);
            result = df.format(d)+abbr[thousands];
        }
        System.out.println(i1 + " => " + result);
    }
}
public int thousands(double num) {
    //returns the number of times the number can be divided by 1000
    int n=0;
    double comp=1000.0;
    while(num>comp) {
        n++;
        comp*=1000.0;
    }
    return n;
}

My concern is that I want a way to ensure that the output is sensitive to locale. If I understand correctly, DecimalFormat should take care of conventions such as commas instead of decimals where applicable; this leaves my concern with the suffix. While my output would be generally be understood in the United States for casual purposes (despite the fact that "M" is used to mean "thousands" in some industries, such as finance) and, from my understanding, many areas in Europe which have languages based on Latin, there are many locales that this would not be understood well. Perhaps there is a built-in function that handles this that I have not been able to find. Thank you in advance for your attention to and input on this task.


Q: Play audio when app is not in foreground or app is inactive I do not want any code but want to get reference that how can we play audio in background in multitasking devices when application is running in background not in foreground...
Please help me to solve this question.
Thanks in advance..

A: There is developer documentation available here:

*

*Executing Code in the Background

*Playing Background Audio

*Audio Session Programming Guide

A: I had solved this question by referring iOS Application Background tasks
and make some changes in .plist file of our application..
Happy coding...


Q: Regex: Match string from set of characters, but need to have exactly X count of a specific character I have a very specific regex match and I can't seem to figure it out.
I need to find full strings matches for /^[aple]+$/i but MUST match exactly two "p's" and exactly one of the other characters.
Any other characters are not allowed. Case insensitive.
So, for example, these will successfully match:
Apple
ppleA
APPLE
apple
ppale

These would not match:
foo
appple
aple
bar
test

I've tried to set the explicit count of p using {brackets} but I think I have the syntax completely wrong. Such as: /^([p]{2})([ale]{1}+$)/i -- not working at all. This one ^(([a]{1})([p]{2})([l]{1})([e]{1}))+$ matches "apple" but it doesn't match "pplea"
Assume I can do this in two sets of matches, run it first to get the set of matches that may have any # of p's and then do a second run to test for exactly two, but there has got to be a one-liner?
Thanks for any help.

A: Something like this would work:
/^(?=.*a)(?=.*p.*p)(?=.*l)(?=.*e)[aple]{5}$/i

*

*/^ - start the regex and use a start string anchor

*(?=.*a) - ensure that an a exists anywhere in the string

*(?=.*p.*p) - ensure that two ps exist anywhere in the string

*(?=.*l) - ensure that an l exists anywhere in the string

*(?=.*e) - ensure that an e exists anywhere in the string

*[aple]{5} - get 5 chars of a, p, l, or e

*$ - end string anchor

*/i - case-insensitive modifier

https://regex101.com/r/DJlWAL/1/
You can ignore the /gm in the demo as they are used just for show with all the words at one time.

A: You can assert a single instance of a l and e by using a character class and optionally matching all allowed chars except the one that you want to assert, preventing unnecessary backtracking.
Then match 2 times a p char between optionally matching the other chars  (as they are already asserted for).
^(?=[ple]*a[ple]*$)(?=[ape]*l[ape]*$)(?=[apl]*e[apl]*$)[ale]*p[ale]*p[ale]*$

Explanation

*

*^ Start of string

*(?=[ple]*a[ple]*$) Assert an a

*(?=[ape]*l[ape]*$) Assert an l

*(?=[apl]*e[apl]*$) Assert an e

*[ale]*p[ale]*p[ale]* Match 2 times a p

*$ End of string

Regex demo
Or a shorter version using a quantifier based of the answer of @MonkeyZeus.
^(?=[ple]*a)(?=[ape]*l)(?=[apl]*e)(?=[ale]*p[ale]*p)[aple]{5}$

Regex demo

A: ^(?=^[^a]*a[^a]*$)(?=^[^l]*l[^l]*$)(?=^[^e]*e[^e]*$)[aple]{5}$
This works by restricting the number of a, l, and e characters to exactly 1 of each, and then restricting the overall string to exactly 5 characters to enforce 2 p characters.
You asked about regex, but in case it helps, an algorithmic version would be to sort the characters of APPLE and compare to the upper-cased version of your string sorted as above.


Q: how to disable addressbar without using windows.open in javascript or jquery or other way Hi I want to disable address bar as I don't want that user can edit anything in to the URL or modify the url.
So basically I'm emailing link to them and by clicking they can complete require task and that'why I want to stop them to make any changes.
thanks

A: The scenario you are describing (give someone a link to do something, and only that thing) is typically solved with server-side validation rather than just hiding the URL. Often, you want to make use of a "nonce", that is a one-time secret value for each allowed action that users could not guess.
So for example http://www.example.com/validate-email/?nonce=d389mxfh47c
A user could not simply change the nonce to get a desired effect. The server can look up what the correct, authorized action is for that nonce when the user accesses/submits the page.


Q: Which curves are boundary of pseudoholomorphic curves? I have posted it on Mathstackexchange but nobody replied.
Consider a loop $\gamma:\mathbb{S}^1\to M^{2n}$ in a symplectic manifold $(M^{2n},\omega)$. Let $J$ be an $\omega$-compatible almost complex structure on $M$.
My naive question is: when does $\gamma$ bound a pseudoholomorphic curve?  More precisely,

when there does exists  a Riemann surface with boundary $\Sigma$, and a J-holomorphic map $u:\Sigma\to (M,J)$ such that $u|_{\partial \Sigma} \equiv \gamma$ ?

I do not  know much about pseudoholomorhic curves, I see that some people requires some conditions on the boundary like, contact type or totally real, if you want you can consider these assumptions or deal with these cases.

A: The 'moment conditions' that Ben McKay mentions are simply this:  A closed curve $C$ in $\mathbb{C}^n$ bounds a compact Riemann surface (which might be singular) if and only if the integral around $C$ of any global holomorphic $1$-form on $\mathbb{C}^n$ vanishes.
One direction is just Stokes' Theorem:  If $\omega$ is a holomorphic $1$-form, then $\mathrm{d}\omega$ is a holomorphic $2$-form, and a holomorphic $2$-form vanishes when pulled back to any (possibly singular) complex curve.  Thus, if $C = \partial X$ where $X\subset\mathbb{C}^n$ is a compact Riemann surface (with boundary), then $\int_C\omega = \int_X\mathrm{d}\omega = 0$.
The converse, which (I think) is due to Harvey and Lawson (Boundaries of complex analytic varieties, I., Annals of Mathematics 102 (1975), 223–290), is rather deeper.
I don't remember whether there is a test for when $C$ bounds an actual holomorphic disk (i.e., a Riemann surface of genus $0$).  I believe I remember that when $C$ does bound a compact (singular) holomorphic Riemann surface, it bounds only one.  (I don't have access to the Harvey-Lawson paper I cited just now.  If you want the definitive statment, I suggest that you check that paper.)

A: I want to explain why one should not expect that a given generic loop is ever the boundary of a holomorphic curve (unless $\dim M = 2$).  My claim (or my intuition) depends of course on the definition of "generic", so let me try to justify the statement:
Take your loop $\gamma$, then construct a totally real submanifold $L$ that contains $\gamma$.  (If $\gamma$ is embedded the construction of $L$ does not pose any difficulty; and we are not requiring that $L$ is closed or anything similar.)
Assuming now that $\gamma$ bounds a smooth map $f\colon \Sigma \to (M,J)$ for some Riemannian surface $\Sigma$, you can use the Riemann-Roch formula to compute the "expected" dimension of the space of holomorphic curves that are homotopic to $f$.  Assuming that $\gamma$ is injective, and that $J$ is chosen "generically" (which of course is a bit of a mysterious property), you can assume that the expected dimension corresponds to the genuine dimension of the space of holomorphic curves.
If the expected dimension is negative, then there will not be any holomorphic curve bounded by $\gamma$ in this homotopy class.
(Note that morally the higher the genus of the surface the more negative the dimension! For example, if $S_1,S_2$ are closed Riemann surfaces and the genus of $S_2$ is $\ge 2$, then the expected dimension of a holomorphic curve
in $S_1\times S_2$ that is homotopic to $\{p\}\times S_2$ is negative.  Obviously
if we take the product almost complex structure of $S_1\times S_2$ then the manifold will be foliated by the holomorphic curves $\{p\}\times S_2$, which seems to be a contradiction to what I wrote, but this is because the almost complex structure $j_1\oplus j_2$ is highly non-generic ... as soon as you slightly perturb it, no holomorphic curves in that homotopy class will survive.)
Note that up to here, we have not used that $M$ is symplectic, but only that it is almost complex!
The Riemann-Roch formula is
$$ \operatorname{index \bar \partial_J} = \frac{1}{2}\dim M \cdot \chi(\Sigma) + \mu (f^*TM, f^*TL) , $$
where $\chi(\Sigma)$ is the Euler class of $\Sigma$ and $\mu(f^*TM, f^*TL)$ is the Maslov index of $f$ with respect to $L$ which measures by how much $TL$ "turns" along $\gamma$ with respect to the trivialization of the complex bundle $f^*(TM,J)$.
In order for a generic $J$ to admit any holomorphic curve with boundary $\gamma$ it follows that the Maslov class $\mu(f^*TM, f^*TL)$ of the homotopy class of the potential holomorphic curve has to be large enough so that the Fredholm index is positive.  For a chosen totally real submanifold $L$ there might thus exist certain homotopy classes that can be represented by holomorphic curves with boundary on $L$, but in the initial question you were not at all interested in a specific $L$ only in $\gamma$!
We can instead choose a countable family of totally real submanifolds $L_k$ such that for any smooth $f\colon (\Sigma, \partial \Sigma) \to (M, \gamma)$ we find an $L_k$ in this family such that the index of $f$ with respect to this $L_k$ will be negative (except of course, when $\dim M = 2$, because in this case $L = \gamma$ without choice).
We can then choose an almost complex structure $J$ close to the initial one that is regular for all of the countably many totally real submanifolds $L_k$ simultaneously. For this generic $J$ there is no holomorphic curve with boundary in $L_k$ that has negative index (with respect to this $L_k$).  But this means that there is no holomorphic curve at all bounded by $\gamma$.
This proves that in a certain sense there is never a holomorphic curve with boundary $\gamma$ except for extremely special choices of $\gamma$ and $J$ (this of course is all modulo "genericity" of the almost complex structure, which is not a very user-friendly definition, because you can never check if "your" $J$ is actually "generic". But this is the way that symplectic topology goes...).


Q: smooth scrolling of imageview I have added the images to scrollview dynamically. Following is the code:
-(void)displayimages {
    for (int i=0; i<[featuredarray count]; i++) {
        NSString *image=[[featuredarray objectAtIndex:i]objectForKey:@"img"];

        if (i==0) {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)];
        }
        else {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*290+15, 0, 270, 380)];
        }
        webview.backgroundColor=[UIColor clearColor];
        webview.layer.borderWidth=4;
        webview.layer.cornerRadius=4;
        webview.layer.borderColor=[[UIColor whiteColor]CGColor];
        [webview setTag:i];
        webview.userInteractionEnabled=YES;
        NSURL *url = [NSURL URLWithString:image];
        [webview setImageWithURL:url placeholderImage:[UIImage
           imageNamed:@"placeholder.png"]];
        [scroll addSubview:webview];

        UITapGestureRecognizer *tap1 =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlefirstTap:)];
        tap1.delegate=self;
        tap1.numberOfTapsRequired=1;
        [webview addGestureRecognizer:tap1];
        [tap1 release];
        [webview release];
   }

   pages.defersCurrentPageDisplay=YES;
   scroll.delegate =self;

   scroll.contentSize = CGSizeMake(290*[featuredarray count],300);
   scroll.pagingEnabled = YES;
   pages.numberOfPages = [featuredarray count]-1;
   pages.currentPage =0;
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGRect frame = scroll.frame;
    frame.origin.x = frame.size.width-15*gallerypage;
    NSLog(@"frame.origin.x..%f",frame.origin.x);
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGRect frame = scroll.frame;
    frame.origin.x=gallerypage*290;
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

It is showing the images well when I use pagecontroller action
-(IBAction)pagecontrolaction:(id)sender {
    int page = pages.currentPage;
    CGRect frame = scroll.frame;
    frame.origin.x=page*290;
    frame.origin.y =0;
    [scroll scrollRectToVisible:frame animated:YES];
}

but when I used touch event to imageview then it is not displaying the images smoothly. It gets stuck during scrolling.

These are the preview which shows the current image with the start of second image.

A: The two methods: scrollViewWillBeginDecelerating and scrollViewDidEndDecelerating contains two animation with different x position it is animated to:
frame.origin.x = frame.size.width-15*gallerypage;

and
frame.origin.x=gallerypage*290;

It is better if you could turn off either function: scrollViewWillBeginDecelerating or scrollViewDidEndDecelerating. Otherwise probably you should adjust the x position (must be in sync for both functions) it will be animated to.

A: if (i==0) {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 440)];
        }
        else {
            webview=[[UIImageView alloc]initWithFrame:CGRectMake(i*320, 0, 270, 380)];
        }

A: You need to change your implementation for loading the images from a remote resource, thats where the biggest bottle neck lies.
I don't want to go into details but try to replace this line of code
[webview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

With something more c.p.u friendly. Use a caching mechanism that employs multi-threading, what you want to do is move the heavy lifting (Downloading remote images) to another thread.
SDWebImage does a perfect job at this  https://github.com/rs/SDWebImage
If you are a bit hard core, you can roll your own multi-threaded image downloader using
[NSURLConnection sendAsynchronousRequest:queue: completionHandler:]

And do the image loading in the block, Or even better dispatch_async(queu, block)

A: You should checkout SYPaginator (SYPaginator is a horizontal TableView with lazy loading and view recycling.)

Simple paging scroll view to make complicated tasks easier. We use
  this in several of the Synthetic apps including Hipstamatic, D-Series,
  and IncrediBooth.

If you need more perfomance you should give MSCachedAsyncViewDrawing a try:

Helper class that allows you to draw views (a)synchronously to a
  UIImage with caching for great performance.

A: I think that happens because your images are larger in size (MB) , and you fit them into that CGRect without resizing them that specific size, also it matters how many pictures you have loaded inside the scrollview , if you load many pictures it will take a lot of memory and it will slide slowly.

A: It happens when you are trying to show an image of larger size in that case you have to use cache to get the image there and try to load image from there.For better know how to use it..use SDwebimage thats the nice way to do it and it is fast.
You can read

*

*Lazy Loading
2.paging enabled.
https://github.com/rs/SDWebImage
Need any further help.Happy to help you.

A: I am not sure why are you setting the frame when you start scrolling, but if I were in your place I would do the logic as per below:
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    // do nothing
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    int gallerypage = scrollView.contentOffset.x /scrollView.frame.size.width;
    CGFloat xoffset = 290 * gallerypage;
    [UIView animateWithDuration:0.5
                     animations:^{
                         scrollView.contentOffset = CGPointMake(xoffset, 0);
                     }
                     completion:^(BOOL finished){
                         NSLog(@"Done!");
                     }];
}

Hope it helps.

A: You should definitely resize your image in background prior to loading it into UIImageView. Also you should set UIImageView content mode to the none-resizing one. It gave me significantly scrolling improvement after other ways were already implemented (async cache and others).


Q: Runtime Error 1004 / Error 438 when getting the Text property of a copied button, setting the property works though I've inserted a large number of form controll buttons (with the text "") into an excel worksheet by copy'n'pasting (from another workbook).

These buttons are connected to this macro (which is located in PERSONAL.XLSB):
Option Explicit

Sub ChangeSomething()
    ' The button which called the macro.
    Dim b As Button
    Set b = ActiveSheet.Buttons(Application.Caller)

    ' Do run the code if the button was not already active.
    If b.Text <> "x" Then        ' SEEMS TO BE THE PROBLEM
        ' Do something

        ' Mark the button as activated.
        b.Text = "x"
        b.Font.Bold = True

    ' If the button was already activated, deactivate it.
    Else
        'Mark the button as deactivated.
        b.Text = " "
    End If
End Sub

This set up worked properly before. But since copying, I get Runtime Error 1004 "Unable to set the Text property of the Button class".
When handled, the exception seems to be Error 438 "Object Doesn't Support This Property or Method".

The Debugging marks the line:
If b.Text <> "x" Then

What puzzles me is that getting the text property seems to throw the runtime error, but setting the value runs just fine:
b.Text = "x"

The correct Button in the correct Worksheet of the correct Workbook is changed.

As soon as I change the text of the button manually to something other than "", the macro also seems to work.
Unfortunately, the inserted buttons do not appear to be included in the list returned by ActiveSheet.Buttons, so I can not loop over them to change their values.

I'm not sure if that's appropriate, but I've uploaded here a sample file.

A: I'm not sure your question has the right details. If these buttons are indeed Form Controls - and I think they must be because I believe ActiveX controls don't return a Caller - then their parent object is Shapes, and you would call the Text property from the Shape.TextFrame.Characters object.
I wonder if your original worksheet had aCollection object called Buttons
which contained, perhaps, a list of the buttons in the form of a class object, called Button (hence your error message) and which exposes the properties that are called in your code.
Without that collection and class, the code would be more like this:
Public Sub ChangeSomething()
    Dim btn As Shape

    With Application
        'Check for correct data types.
        If Not TypeOf .ActiveSheet Is Worksheet Then Exit Sub
        If IsObject(.Caller) Then Exit Sub

        'Acquire button
        On Error Resume Next
        Set btn = .ActiveSheet.Shapes(.Caller)
        On Error GoTo 0

        'Check for a found button
        If btn Is Nothing Then Exit Sub
    End With

    'Check for non-actionable button.
    With btn.TextFrame.Characters
        If .Count = 0 Then
            .Text = "x"
            Exit Sub
        End If
    End With

    'If we've reached here, it's an actionable button.
    Debug.Print "Do something."

    'Clear the button text.
    btn.TextFrame.Characters.Text = ""

End Sub

I rather suspect some half-copied code here, and the rest of the project remains elsewhere.


Q: iOS swift pointer CGPoint startPoint1;
CGPoint startPoint2;
CGPoint startPoint3;
CGPoint startPoint4;

- (void)Method {
    CGPoint* startPoint = NULL;

    if (panGesture.view == ...) {
       startPoint = &startPoint1;
    } else if (panGesture.view == ...) {
       startPoint = &startPoint2;
    }

    if (panGesture.state == UIGestureRecognizerStateBegan) {
       *startPoint = [panGesture locationInView:...]
    } else if (panGesture.state == UIGestureRecognizerStateChanged) {
       CGPoint endPoint = [panGesture locationInView:...];
       *startPoint = endPoint;
    }
}

CGPoint* startPoint = NULL;
startPoint = &startPoint1;
*startPoint = endPoint;

This three lines of code in Swift 3.0 is how to express Or how do I write the above code into swift

A: The problem is that Swift doesn't have pointers in the C sense. Well, it does, sort of, but it's not worth invoking them just to do what you're trying to do. The simplest approach is to rewrite the core of your method to call a function that takes an inout parameter.
So let's take the reduction you ask about in your last three lines:
CGPoint* startPoint = NULL;
startPoint = &startPoint1;
*startPoint = endPoint;

To do that, we need a general way to set one CGPoint to another by indirection, expressed as a func (because that is the only way to work with an inout parameter). To make it truly general, we may as well make this a generic, so we're not confined to CGPoint alone:
func setByIndirection<T>(_ thing1 : inout T, to thing2: T) {
    thing1 = thing2
}

And now we can test it, doing exactly what you asked to do:
var startPoint = CGPoint.zero
let endPoint = CGPoint(x:5, y:5)
setByIndirection(&startPoint, to: endPoint)
print(startPoint) // 5,5

So you see, the use of the inout parameter has allowed us to pass into the function a "pointer" to the CGPoint whose value is to be set, which is what your code is trying to accomplish at its heart.
If you're willing to "damage" your original endPoint, you don't even need to write setByIndirection; you can use the built-in swap:
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:5, y:5)
swap(&startPoint, &endPoint)

A: In swift, I would use enums and an array. I simplified the code a litte, but I guess you'll get it:
var points = [CGPoint(), CGPoint()]
enum indexEnum:Int {
    case startPoint = 0
    case endPoint   = 1
}

func method() {
    var inx:indexEnum

    if (1==1) {
        inx = .startPoint
    } else {
        inx = .endPoint
    }

    if (2==2) {
        points[inx.rawValue] = CGPoint(x:10,y:10)
    } else {
        points[inx.rawValue] = CGPoint(x:20,y:20)
    }
}


Q: Laravel 4 NotFoundHttpException [2014-04-28 12:34:46] production.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' in C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php:140
Stack trace:

#0 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(1021): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#1 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(989): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#2 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Routing\Router.php(968): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#3 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(738): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#4 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(708): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#5 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Http\FrameGuard.php(38): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#6 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Session\Middleware.php(72): Illuminate\Http\FrameGuard->handle(Object(Illuminate\Http\Request), 1, true)
#7 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#8 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Cookie\Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#9 C:\wamp\www\ppdb\vendor\stack\builder\src\Stack\StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#10 C:\wamp\www\ppdb\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(606): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#11 C:\wamp\www\ppdb\public\index.php(49): Illuminate\Foundation\Application->run()
#12 C:\wamp\www\ppdb\index.php(19): require_once('C:\wamp\www\ppd...')
#13 {main} [] []

Tried to create a form with laravel , and seems fine when i load the page , the problem is when i try to submit the form this error is getting in log file.
Can anyone please check to solve this issue?
Thanks in advance

A: I missed  to add post routing in routes.php
Route::post('search', 'SearchController@index');

Post routing did the job for me.
Cheers!


Q: Change file system of Eclipse for procedure/support of "New Web dynamic project" I want to change file system of Eclipse for change "support" or "User interface" (UI) of New Dynamic WEB Project.
I have Windows 7 but I am interested also on Linux.
Should be easy change file system in Linux and not in Windows.

*

*What do I would to change?
In Eclipse, I press NEW-> Dynamic Web Project, put the name and press Next.
We have, in default, this window:

Now I have to remove src folder and put new folders src\main\java and src\main\resource.
So I will have a folder "Source Folders" of Maven project because I will convert in it.
So the result is:

- Why not do New Maven Project so I will have these directory
   java resource.
Why I not like the pom.xml of new Maven Project that is in default:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bla</groupId>
  <artifactId>bla</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>asd Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>bla</finalName>
  </build>
</project>

Miss the plugin of maven:
<build>
      <finalName>${project.artifactId}</finalName>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
            <configuration>
              <warSourceDirectory>WebContent</warSourceDirectory>
              <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
          </plugin>
        </plugins>

      </build>

If I do, from project Dynamic WEB project and will convert to Maven Project. I will have this pom.xml that is generated from Eclipse:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateExample</groupId>
  <artifactId>HibernateExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>HibernateExample</name>
  <url>http://maven.apache.org</url>

  <build>
  <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>

  </build>
</project>

For me like too the second pom.xml and not get error of miss plugin maven.
So today I've got an idea:

*

*Why not change the program files (say inside folder Eclipse) and change line of folder " Source
Resource"?
So I will have the new default windows (see second image) in every time when I create Dynamic WEB Project.
I hope the title is correct.


Q: Using Django REST Framework with sessions-based CSRF I am using Django + Django REST Framework in an environment where I cannot use cookie-based CSRF tokens; therefore I must run with CSRF_USE_SESSIONS = True.
The DRF web UI, however, depends on this cookie for all interactions. It appears this is set by reading the csrftoken cookie and settings the X-CSRFToken header on the subsequent request, which is then consumed by django.middleware.csrf.CsrfViewMiddleware.process_view() if the hidden field is not included in the request body. This is set in this code from rest_framework.templates.rest_framework.base.html:
<script>
  window.drf = {
    csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
    csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}"
  };
</script>

DRF forms that do not use POST do contain the CSRF token in the form body, so not having the cookie means the web interface does not have access to the CSRF token at all, causing all PUT, PATCH, and DELETE requests to fail with a 403 response.
I believe this is a bug in DRF, but it is possible this is intended behavior. Can someone explain how DRF is intended to be used with CSRF_USE_SESSIONS = True?

A: This was fixed in https://github.com/encode/django-rest-framework/pull/6207 and released as part of DRF 3.9.2. More complete context can be read at https://github.com/encode/django-rest-framework/issues/6206.


Q: Print vowels from the vector I need to execute the vowels from the LETTERS R build-in vector
"A", "E", etc.

> LETTERS

  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U"
   "V" "W" "X"
  [25] "Y" "Z"

Maybe, someone knows how to do it with if() or other functions. Thank you in advance.

A: Looks like you need extract vowels, does this work:
> vowels <- c('A','E','I','O','U')
> LETTERS[sapply(vowels, function(ch) grep(ch, LETTERS))]
[1] "A" "E" "I" "O" "U"
>


Q: Convert number into amount of space I have a number and want it to generate to a string with corresponding space
For Example:
var NumberOfSpace = 3;

// This will result in a string with 3 empty space
// the result will be "   "
var space = convertToSpace(NumberOfSpace);

A: You can simply use the String.prototype.repeat method:
" ".repeat(3);

A polyfill for older browsers.

A: Here is a convertToSpace function
var convertToSpace = function (spaces) {
  var string = "";
  for (var i = 0; i < spaces; i++) {
    string += " ";
  }
  return string;
}

A: A concise option:
function convertToSpace(n) {
  return new Array(n + 1).join(' ')
}

A: Using Array#fill and Array#reduce

The fill() method fills all the elements of an array from a start index to an end index with a static value.
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

var NumberOfSpace = 3;

function convertToSpace(param) {
  return new Array(param).fill(' ').reduce(function(a, b) {
    return a + b;
  });
}
var space = convertToSpace(NumberOfSpace);
console.log(space);


Q: webkit framework iphone i am not able to add webkit framework in my application. Getting error which says no such framework is available.

A: The WebKit framework is not available on iPhone - it's only for Macs. The nearest you can get is adding a UIWebView to your app, which gives you a WebKit-based HTML window.


Q: SQLite Trigger issue - "No such column" I have a sqlite database with a table named Achievements, it stores whether certain achievements have been met in a simple quiz I am building (iphone project to learn objective-c).  The table structure is:
ID    Name           Completed
=============================
1     FiveInARow     0
2     TenInARow      0
3     AllCorrect     0
4     UnderASecond   0
5     AllCompleted   0

The ID is the primary key, Name is a VARCHAR and Completed is BOOL (0 for false and 1 for true).
I am trying to add a trigger onto the update statements of this table, such that when a Completed column is set to 1 (i.e. achievement completed - this is the only update that will happen on the table) there will be a calculation to see whether all of the other achievements have been completed and if so also update the AllCompleted achievement (ID 5) to 1.
The trigger I created is:
CREATE TRIGGER "checkAllAchievements" AFTER UPDATE ON "Achievements"
WHEN (Select SUM(Completed) from Achievements) = (Select COUNT(Completed) -1 from Achievements)
BEGIN UPDATE Achievements SET Completed = 1 WHERE Name= 'AllCompleted';
So what I am trying to do is take the sum of the completed row and compare it to the total count minus 1, if they match then it means that all achievements apart from the AllCompleted achievement are achieved so we can also set that to true.  The trigger gets created fine.
Now on to the problem - When I attempt to update the table with the following statement
UPDATE Achievements SET Completed = 1 WHERE ID = 1
I receive the error message "No such Column Completed".
Am I trying to do something that is fundamentally wrong?  Is it not possible for me to achieve this using a trigger?  Any advice?
Thanks.

A: Double check that you spelled everything exactly as it is in the database.  In your example, you state the table name is "Achievements" however reference "Achievement" in two places.
Fixing that should solve your issue.  Final SQL is as follows:
CREATE TRIGGER "checkAllAchievements"
AFTER UPDATE ON Achievements
WHEN (SELECT SUM(Completed) FROM Achievements) = (SELECT COUNT(Completed)-1 FROM Achievements)
BEGIN
  UPDATE Achievements SET Completed=1 WHERE Name='AllCompleted';
END;

A: typically this would be a mutation in the table you are updating...
the trigger should just set the value something like
new_rec.completed := 1;

not try to do another update.
(excuse my Oracle syntax)

A: I think you should not update a table from a trigger on updating of that table, could be a infinite recursion. Maybe SQLite doesn't like that, but give a bad diagnositic


Q: Cancel a send if over a threshold Though a strange request, we're not asking the 'why' but the 'how' ...
We have a situation where a marketer is sending an email from Marketing Cloud to a  Salesforce (Salescloud) report, using Marketing Cloud Connect.
During the send configuration process, they marketer isn't informed how many records are on the Salesforce Report they are about to send to.
Ultimately what has happened (due to wider permissions issues in Salesforce) -
 the marketer sends to a 'filtered' report without the correct filters working and therefore sends the email to a much larger audience than they had anticipated.
What we'd like to do is add in a fail-safe, that should the Salesforce Report have greater than 1000 records, then cancel the send (i.e. prevent the send from going to the incorrect audience).
We've thought about adding AMPScript to the Email / Template (below) but we have some caveats with this across the organisation - i.e. marketers could copy an existing email rather than creating from New Template etc
%%[
if _isTestSend == False then
Var @rcount, @finalcount
Set @rcount = __DataSourceName
set @finalcount = DataExtensionRowCount(@rcount)
If @finalcount >=1000
The
RaiseError("Subscriber Count Limited Reached",False)
ENDIF

EndIF
]%%

Do you have any thoughts / suggestions of how we could enable something Business Unit wide that would fail a send if over a threshold?

A: I'd definitely do this with an Exclusion Script on the Send Defintion instead of using RaiseError().  Something like this, perhaps:
_isTestSend == false and DataExtensionRowCount(AttributeValue("_DataSourceName")) > 100
You still get billed for sends even if you stop them with RaiseError().
Your script wouldn't work for sends to lists, if that matters.
(Also, you have an extra underscore in front of _DataSourceName in your example.)


Q: Google Amp Contact form error when submitting Anyone can help me work out in using the AMP Contact form?
I am doing a subscribe form using Mailchimp and SendEngine and I embedded the form to my HTML page.
Here is the screenshot of the error:

A: This happens when you try to submit to a domain different than your AMP site.
You need to whitelist your AMP domain on your server to enable CORS or contact Administrator if it's a shared hosting for your AMP domain to be whitelisted for CORS. Read further about CORS on AMP.
Also check out specs on CORS Whitelisting.


Q: Why are some energies dependent on reference frame, and some are not? And why is transfer between them possible? For example the chemical energy of a kilogram of gasoline is 44-46 MJ/kg. It is only dependent on its chemical structure, which stays the same, whether the gas tank moves or stays still relative to the observer.
But the kinetic energy of a car depends on the reference frame. In a reference frame of a car A of the same speed, the car B in question have no kinetic energy.
But for a bystander, car B has a lot of kinetic energy.
What puzzles me, is:
1 - why are some energies relative to reference frame and some are not?
2 - why the "absolute" energy from gasoline can be changed into kinetic energy of car, and therefore change into "relative" energy?
I wouldn't be surprised if someone answers "the chemical energy is also relative", but I can't understand why.

A:
What puzzles me, is: 1 - why are some energies relative to reference
  frame and some are not? 2 - why the "absolute" energy from gasoline
  can be changed into kinetic energy of car, and therefore change into
  "relative" energy?

The reason is there are two types of energy of an object or substance: Internal Energy and External Energy. The total energy of an object or substance is the sum of the two.
Internal energy, though not directly measurable, is the sum of the microscopic kinetic and potential energies of the atoms and molecules of an object. It is an absolute quantity as it does not depend on an external frame of reference. The chemical potential energy of gasoline is an example of microscopic internal potential energy. The chemical potential energy of the gasoline in the tank of the car does not depend on how fast the car goes, or if it is climbing a hill. The car is made of parts consisting of various materials (metals, plastics, glass, etc). These parts also have internal energy that is independent of the motion or position of the car. One measure of the internal kinetic energy of a part is its temperature.
The external energy of an object or substance is the sum of the external macroscopic kinetic and potential energies of object as a whole is depends on an external frame of reference. The motion and position of your car is an example. Its kinetic energy depends on its velocity relative to a particular external reference frame (the street, another moving car, etc.). Its gravitational potential energy depends on the position in the gravitational field.
Hope this helps

A: Many of the answers are right for the most part, but I think they have too much detail. The simple answer is that velocities are reference frame dependent, while lengths are not. Kinetic energy depends on velocity, so it is reference frame dependent. Potential energies depend on lengths between two objects (or from some reference point), so they are not reference frame dependent.
The transfer of energy between these forms requires work to be done, which relies on the change of lengths (or a velocity over time) through the integral $\int\mathbf F\cdot\text d\mathbf x$. Therefore, we can have transfer between these "absolute" and "relative" types of energy through this "relative" type of energy transfer.

A: Energy is defined as the ability to do work.  Think about yourself floating in space and a high velocity projectile, say a meteor, coming your way.  The only way that meteor can do work on you is via a collision (neglecting the mutual gravitational attraction between you and the meteor for the moment).  The only relevant quantity in the calculation is not, your speed relative to some other frame, or the meteor's speed relative to another frame, but the difference in velocity in a common frame.  In other words the speed of the meteor relative to YOU.  If you and the meteor are moving at the same velocity (relative to some other frame) then that meteor is AT REST relative to you and cannot do work on you.  It is effectively inert.  This does not contradict the fact that some 3rd observer would say you both have a large amount of energy, flying through space at a high speed, since either you or that meteor can do a lot of work on that 3rd observer.
When I observe another object's movement and attribute some K to that body that is a measure of the work I can get out of it.  It makes sense that every other observer would acquire a different answer since K in their frame is a measure of the possible work they can get from the object in a process if interacting with it.  Any observer looking at the interaction of two moving objects should calculate the same internal energy change and momentum transfer between them in a collision process.  Now, what constitutes internal energy?  The total energy can be split into the energy of the center of mass of the system and the relative energy between the internal moving parts.
This is just one example, not meant to address every possible type of E and process but makes the point that these quantities may be frame depended there is something absolute in play here.  You need to attach a process to these measurements and transform all components of that process from one frame to another to see it.

A: Chemical energy ultimately comes from electromagnetic interactions. Microscopically it depends on how the electrons and nuclei are placed relative to each other. As an example take two charged particles. The coulomb potential between them is
$$U(x_1,x_2)=k\frac{q_1q_2}{d_{12}}$$ with
$d_{12}=|x_2-x_1|$. The energy only depends on the difference in positions. This means the energy of this systems doesn't change when you go to a different frame of reference.
If you transform to a frame with a different velocity the positions transform like
$$x_1'=x_1-vt,\quad x_2'=x_2-vt$$
but the difference in position stays the same: $x_2'-x_1'=(x_2-vt)-(x_1-vt)=x_2-x_1$.
The chemical energy of the gasoline in your car depends on many, many of these interactions. However, since this argument holds for every pair of interactions this also holds for the overall chemical energy.
Note that in reality you have to use quantum mechanics to calculate the chemical energy where now every electron is described by a wavefunction which is spread out in space. But for this wavefunction a similar argument like the one above holds.
As a second note I would like to add that for moving particles you can no longer apply Coulomb's law, but applying Coulomb's law in this case will still be pretty accurate (I think!).

A: All energy is more or less frame-dependent. This is obvious in the case of the kinetic energy of a moving car, but less so for a quantity of gasoline. An illustration: let's say the chemical energy of 1 kg gasoline is 45 MJ at rest. If you put this gasoline in motion so it moves at 1000 m/s, the total energy will now be 45.5 MJ, since 1 kg of matter moving at 1000 m/s has a kinetic energy of 0.5 MJ.
This situation becomes more clear when looking at it through special relativity instead of the Newtonian approximation. In special relativity, energy is the time-component of the 4-momentum vector. The temporal and spatial components of this 4-vector are transformed into each other when changing reference frames, while only $m_0c^2$ is guaranteed to stay constant.