text:
Q: Menus not aligning right My register and login buttons won't align to the right. Can you please help me fix this? I will provide any info needed, just ask for it. By the way this is only one part of a bigger menu so it will have extra things in css.
PHP/ HTML:
<a href="<?php echo URL; ?>login">

Login

<a href="<?php echo URL; ?>register">

Register

CSS:
#page {
    min-height: 100%;
    max-width: 1060px;
    min-width: 954px;
    position: relative;
}
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
}
#page {
  margin: 0 auto;
}
.m_hmenu {
    position: relative;
    overflow: hidden;
}
.m_hmenu .floatright {
    float: right;
}
.m_hmenu .content {
    position: relative;
}
.m_hmenu .content span {
    font-size: 60%;
    margin-left: 6px;
    position: relative;
    bottom: 1px;
}
.m_hmenu .left {
    position: absolute;
    top: 0;
    left: 0;
    width: 50.004%;
    height: 100%;
    background-position: left top;
}
.m_hmenu .right {
    position: absolute;
    top: 0;
    right: 0;
    width: 50.004%;
    height: 100%;
    background-position: right top;
}
.m_hmenu .button {
    float: left;
    position: relative;
    cursor: pointer;
    height: 100%;
    margin-bottom: 100px;
}
.m_hmenu a:hover .button,
.m_hmenu a:focus .button {
    text-decoration: none;
}
.m_hmenu .cap {
    float: left;
    height: 100%;
}

.m_hmenu .stretch .button {
    width: 100%;
    text-align: center;
    padding-left: 0px !important;
    padding-right: 0px !important;
}
body {
    background-attachment:fixed;
    background-color:#f0f0f0;
    background-repeat:repeat;
    background-position:center;
    color:#4f4f4f;
    background-image:url("Background.jpg");
}
#page-wrap {
    background-color:transparent;
    margin-right:-5px;
    font-family:Arial;
    color:#4f4f4f;
    margin-left:-5px;
    font-size:13px;
}
a {
    color:#57c11a;text-decoration:none;
}
.m_header {
    padding-bottom:3px;
    border-color:transparent;
    padding-right:4px;
    background-color:transparent;
    padding-left:3px;
    border-width:1px;
    padding-top:3px
}
.m_hmenu {
    height:63px;
}
.m_hmenu .bg.left {
    background-image:url("Menu.png");
}
.m_hmenu .bg.right {
    background-image:url("Menu.png");
}
.m_hmenu .buttons {
padding-right:0px;padding-left:15px;top:2px;
}
.m_hmenu .button {
    background-color:transparent;
    line-height:58px;
    padding-right:15px;
    font-weight:normal;
    height:40px;
    padding-left:15px;
    font-size:15px;
    color:#89e350;
}
.m_hmenu a:hover .button {
    color:#ffffff;
}
.m_hmenu a:focus .button {
    color:#ffffff;
}
.m_hmenu .cap {
    height:40px;
}

Thanks Joshua

A:

    Login

    Register

In CSS :)
#login, #register {position:fixed;top:50px}
#login {right:100px}
#register {right:10px}


text:
Q: deg2km command does not calculate distance between two points in matlab I am trying to calculate distance between two geographical coordinates and I want to convert geographical coordinates to the km. Therefore I used deg2km function. However, I realise that it is not convert points properly.
For instance, I used these two points.
p_x=[5; 10];        %degree
p_y=[8; 16];        %degree
pos_y=deg2km(p_y,6378);
pos_x=deg2km(p_x,6378);

It returns as:
pos_x= [556.58549846099 1113.17099692198]
pos_y= [890.536797537587 1781.07359507517]

When I calculate distance ( sqrt((556.5-1113.2)^2+(890.5368-1781.1)^2) ) between these points I obtained distance as : 1050.2464
However I checked it google map and also other websites it should be 1042 km.
Do you have any suggestion to calculate distance and also points as kilometers properly?
Thanks in advance!
edited as :
I've points(deg)and I need to convert them km and calculate distance between points.
LAT=[41.000173;41.010134]*pi/180;
LON=[28.995882;28.995584]*pi/180;

I used this code to calculate distance.  It calculates properly.
But I can not convert my points to kilometers.
LAT=[41.000173;41.010134]*pi/180;
LON=[28.995882;28.995584]*pi/180;

 R=6378; %km

 for i=1:length(LAT)-1

psi(i,1) = atan2( sin (LON(i+1)-LON(i)) * cos (LAT(i+1)) , cos (LAT(i)) *sin (LAT(i+1)) - sin (LAT(i)) * cos (LAT(i+1)) * cos (LON(i+1)-LON(i)) );

a=(sin((LAT(i+1)-LAT(i))/2))^2+cos(LAT(i))*cos(LAT(i+1))*(sin((LON(i+1)-LON(i))/2))^2;

c=2*atan2(sqrt(a),sqrt(1-a));

d(i,1)=R*c;

end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python3 threading combining .start() doesn't create the join attribute This works fine:
def myfunc():
    print('inside myfunc')

t = threading.Thread(target=myfunc)
t.start()
t.join()
print('done')

However this, while apparently creating and executing the thread properly:
def myfunc():
    print('inside myfunc')

t = threading.Thread(target=myfunc).start()
t.join()
print('done')

Generates the following fatal error when it hits join():

AttributeError: 'NoneType' object has no attribute 'join'

I would have thought that these statements are equivalent.  What is different?

A: t = threading.Thread(target=myfunc).start()

threading.Thread(target=myfunc) returns a thread object, However object.start() returns None. That's why there is an AttributeError.

A: Since Python 3.8 and the introduction of the walrus operator :=  you can use;
(t := threading.Thread(target=myfunc)).start()


text:
Q: Prevent URL access to files on website I am creating a website with my own CMS. My problem is that I can access certain files via a URL in the browser.
I have tried to block it via .htaccess but when I do that, it also stops my functions from working, because they are blocked.
Does anyone know a solution for my problem?

A: Add line at the end of  .htaccess
      Options All -Indexes

or Use
<FilesMatch "*\.(css|js|png)$">
 Order Allow,Deny
 Allow from all
</FilesMatch>

A: Are your functions in a  server side script or a client side script?
If they're server side, you can block HTTP access to the files by putting them in a directory that doesn't need to be accessed through HTTP and then putting a deny from all directive in that directory's htaccess file.
If they're client side, then you can't block access to them and still have the scripts work. The browser is executing the script, and it needs to access those files. You can do hacky things like refusing to serve the file unless a certain referrer URL is present, but I advise against doing that because it can cause problems with usability, caching, and search engines.


text:
Q: How to use the setInterval function to display a factorial calculation with a 500ms interval in between each value appearing on screen? I need to implement the setInterval function within my program in order to create an interval of 500ms between each value appearing on screen. The program code i am currently using takes an input value from the user and writes out, as well as calculates the factorized answer.
function factorizeFunction(number, numberArray = []) { //this is the function that does the factorization calculations
  if (number == 0 || number == 1) numberArray.push(number);
  else {
    numberArray.push(number);
    factorizeFunction(number - 1, numberArray);
  }
  return numberArray.join(' * ') + ' = ' + numberArray.reduce((a, b) => a * b, 1);
}
document.getElementById("factorialTest").innerHTML = factorizeFunction(number);

I need to have the answer, for Eg: 6 * 5 * 4 * 3 * 2 * 1 = 720 display on my webpage, each value at a time, with a 500ms delay in between displays. So, 6 (500ms delay) * (500ms delay) 5 (500ms delay)... and so forth. I am unsure on how i would go about doing this?

A: Basically, everything you want printed on your screen, the operators and numbers, need to appear in a 500ms delay. Which means it's best to first obtain an array of these elements:
function getFactorElements(factor) {
  // get array like [1, 2, 3, 4]
  const factorArray = Array.from({ length: factor }, (_, i) => i + 1);

  // calculate result
  const result = factorArray.reduce((a, b) => a * b, 1);

  // insert math operators
  const parts = factorArray
    .reverse()
    .map((part) => [ part, part > 1 ? '*' : '=' ])
    .reduce((a, b) => a.concat(b));

  parts.push(result);

  return parts;
}

With this being your HTML

You can create another function which accepts an element and the factor:
async function showFactorCalculation(element, factor) {
  element.innerHTML = '';

  for (const part of getFactorElements(factor)) {
    element.innerHTML += ' ' + part;
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
}

Which you should call like this:
showFactorCalculation(document.getElementById('factorialTest'), 9);

And I've got a working stack for you here ;):
stack
I'm using setTimeout because using setInterval is mainly discouraged

A: You could envelope your function with setInterval():
function startInterval(number, numberArray){
   setInterval(() => factorizeFunction(number, numberArray), 500);
}

And call startInterval instead of factorizeFuncion when you want the webpage to start showing the numbers.

A: It was a good excercise.

const factorizeFunction = async num => {
    if (num < 1) return;
    let resDiv = document.querySelector('#res_div');
    let numArr = [];
    while (num >= 1)
        numArr.push(num--);
    for (let i = 0; i < numArr.length; i++) {
        resDiv.append(numArr[i]);
        await _delay(500);
        if (i < (numArr.length - 1))
            resDiv.append(' * ');
        else if (i == (numArr.length - 1))
            resDiv.append(' = ');
        await _delay(500);
    }
    resDiv.append(numArr.reduce((a, b) => a * b, 1));
};
let _delay = (ms = 200) => new Promise((accept) => setTimeout(accept, ms));
factorizeFunction(6);

A: Three different approaches.
inSequence constructs a promise chain:

const factorizeFunction = () => '6 * 5 * 4 * 3 * 2 * 1 = 720' // your existing function
const inSequence = async (arr) => arr.reduce((acc, f) => acc.then(f), Promise.resolve())
const delayed = (fn, ms = 500) => (...args) => () => new Promise((res) => setTimeout(() => { res(fn(...args)) }, ms))
const tokenize = (str) => str.match(/[\S]+[\s]?/g)
const print = (str) => document.getElementById("output").innerHTML += str

const printFactorialString = (str) => inSequence(tokenize(str).map((t) => delayed(print)(t)))

printFactorialString(factorizeFunction())

The following approach uses indirect recursion:

const factorizeFunction = () => '6 * 5 * 4 * 3 * 2 * 1 = 720' // your existing function
const delay = (ms = 500) => new Promise((resolve) => setTimeout(resolve, ms))
const slowly = (action) => {
    return async function go ([i, ...remaining]) {
        if(!i) return
        action(i)
        await delay()
        go(remaining)
    }
}
const tokenize = (str) => str.match(/[\S]+[\s]?/g)
const print = (str) => document.getElementById("output").innerHTML += str

const printFactorialString = (str) => slowly(print)(tokenize(str))

printFactorialString(factorizeFunction())

This solution uses an async generator and async...await:

const factorizeFunction = () => '6 * 5 * 4 * 3 * 2 * 1 = 720' // your existing function
const identity = (x) => x
const delayed = (fn, ms = 500) => (...args) => () => new Promise((res) => setTimeout(() => { res(fn(...args)) }, ms))
const asyncIterable  = (arr) => async function* () { for(let i of arr) yield i() }
const tokenize = (str) => str.match(/[\S]+[\s]?/g)
const print = (str) => document.getElementById("output").innerHTML += str

const printFactorialString = async (str) => {
    const generator = asyncIterable(tokenize(str).map((t) => delayed(identity)(t)))()
    for await (let x of generator) { print(x) }
}

printFactorialString(factorizeFunction())


text:
Q: how do i get access to the list in map for ElevatedButton in flutter? enter image description here[enter image description here](https://i.stack.imgur.com/HxY0x.png)
im new to the mobile development can anyone pleased tell me where did i do wrong?
im trying to access to the list inside the map

A: List of map can be accessed as questions[i]["questionText"]

A: Map is a function, not a Widget. But you can fix it by using ListView.builder like it :
ListView.builder(
  itemCount: questions[_questionIndex]["Questionanswers"].length,
  itemBuilder: (context, index) {
    return Answer(_quess, questions[_questionIndex]["Questionanswers"][index]);
  },
);


text:
Q: Adding a button to form prevents WM_KEYDOWN messages from being sent The following code works and will print to Label1 when the user presses the a key on the keyboard:
Public Class Form1

Sub New()

    InitializeComponent()

End Sub

Public Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA" (ByVal HWND As IntPtr, ByVal WMSG As Integer, ByVal WPARAM As Integer, ByVal LPARAM As IntPtr) As IntPtr

Private WM_KEYDOWN As Integer = &H100

Protected Overrides Sub WndProc(ByRef WindowsMessage As Message)

    Select Case WindowsMessage.Msg

        Case WM_KEYDOWN

            Dim VirtualKeyCode As Integer = CType(WindowsMessage.WParam, Integer)

            Select Case (VirtualKeyCode)

                Case Keys.A
                    Label1.Text = "The a key was pressed"

            End Select

    End Select

    MyBase.WndProc(WindowsMessage)

End Sub

End Class
The code stops working after adding (dragging) a button to the form. The WM_KEYDOWN message is no longer sent once the button is on the form. A breakpoint set at Case WM_KEYDOWN never gets hit.
If I remove the button the code starts working again.
Any suggestions?
Thanks.

A: Keyboard message are posted to the window that has the focus.  As long as your Form doesn't have any child controls, the form will get the focus when it is activated.  Even though it isn't very good at dealing with getting the focus, it doesn't have any way to indicate that it has the focus for example and doesn't itself have any use for keystrokes.
That changes as soon as you put a control on the form that does like getting the focus.  Like a Button.  Now that control always gets the focus and you cannot give it back to the form.  Accordingly, the form stops receiving WM_KEYDOWN messages, they go to the Button instead.
There is a way to have the form respond to keystrokes, they can be important if they are short-cut keys.  Like F1 should display help, regardless of what control has the focus.  There's built-in support for that in Winforms, you can override the ProcessCmdKey() method.  Like this:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
    If keyData = Keys.Control Or Keys.A Then
        MessageBox.Show("yada")
        Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Paste this in your form's code and test it by pressing Ctrl+A.


text:
Q: html2canvas text alignment is off I'm using html2canvas to allow users to download a div element to their local files as an image.
What they are saving is an image with dynamic text on top of it that changes based on their user input (this whole div becomes one image).
The saving part works, and users can save the div as an image to their local files. However, the dynamic text moves downward and the image looks off because of it.
I tried to make changes to html2canvas code based on someone's solution on github, but it didn't work and I reset this code to the original.
Is this a common problem that others have faced? How do I solve this problem without hard-coding the solution (moving the dynamic text up on the web application so when it moves downward when saving, it looks how it's supposed to look)?
Thanks!


text:
Q: Typo3: How to read from database to produce UL for view OK, in good old fashioned PHP MVC, I might use a model to hit the DB, send info to my PHP controller that I pass on to the View. In the View, I might take that info (say i ajax'ed my controller for the info) and create a table or ul to display the data returned.
I've had trouble finding any modern (ver 6.1 is what i'm on) tutorial to show me how to preform this action in typo3.
Can anyone just "steer" me in the right direction? Perhaps provide an example via answer, or some links to further information that may compare it down to "old fashioned MVC"?
Extension has been suggested, but I'd like to know the very base process of what I'm asking before I try writing some extension, unless the extension is the only way. Although, my table is now on the SAME DB my typo3 is on, so shouldn't there be some command to just simply call my table and get the rows? Maybe send them to a ###sub-part###?

A: You can use a typoscript cObj content and the select option together with the function render_obj when your table name is like the typo3 nameing convention. The select pulls the record from the table and pass it to the render_obj function. It's a function that can apply to all cObj and iterate over the entire selection. stdWrap works only on the entire cObj. When you need to work through each record you need the render_obj function. For example:
10 = CONTENT
10 {
     select {
       pidInList = 1
       where = colpos=1
       orderBy = sorting
     }
     table = tt_content
     renderObj.stdWrap.wrap =
|

     renderObj.stdWrap.required = 1
 }
 10.stdWrap.wrap =
|

This gives you an unorderd list from the tt_content table with pid=1 and the content from the far left column.


text:
Q: Python package managers and Node.js I am trying to compile python scripts using Node.js. The python scripts include some modules I have installed.
My package manager for python is Anaconda, so I tried to supply the {"shell":"path to anaconda prompt"} option in :
var exec = require('child_process').exec;
exec('python hello.py',{"shell":"path to anaconda prompt"}, ..callback)

However, I get an error:
{ Error: spawn C:\Users\dream\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)\Anaconda Prompt (Anaconda3) ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:232:19)
    at onErrorNT (internal/child_process.js:407:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall:
   'spawn C:\\Users\\dream\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Anaconda3 (64-bit)\\Anaconda Prompt (Anaconda3)',
  path:
   'C:\\Users\\dream\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Anaconda3 (64-bit)\\Anaconda Prompt (Anaconda3)',
  spawnargs: [ '/d', '/s', '/c', '"python hello.py"' ],
  cmd: 'python hello.py' }
stdout:

stderr:

I suspect that this is because the Anaconda Prompt is just some wierd shortcut that sets up some variables for cmd.exe (which is the location the shortcut points to).
So my questions:
Can I call the anaconda prompt directly with Node.js? Does pip also have a shell?
How do the packagers (pip,anaconda) make modules accessible to python?
-> Is this through some environment variables?
Can I prepare cmd.exe for work with python the same way that they do?

A: I don't think you want to call the Anaconda prompt.
Just call python: python print('hello').
What happens on the command line if you call: Anaconda Prompt (Anaconda3) print('hello')?
(This should be a comment, but I cannot comment.)

A:
I suspect that this is because the Anaconda Prompt is just some weird shortcut that sets up some variables for cmd.exe

Yes, that's pretty much it. So, no I don't think you can call it as proposed. There is probably a way to manipulate the cmd.exe manually to get it running like an Anaconda Prompt session, but instead I'd propose to try...
conda run
Not sure if this will work in Windows, but it might be possible to use conda run to execute within the Conda environment. This was introduced (and still remains) as an experimental feature in Conda v4.6, with the express purpose of enabling one to run something inside a Conda environment without interactively having to activate it.
Prerequisite
First, you should probably test that conda run works on Windows. Let's assume your conda.exe is located at
C:\Users\dream\Anaconda3\Scripts\conda.exe

Start a clean cmd.exe session, where conda is undefined (i.e., not Anaconda Prompt). Then try things like
C:\Users\dream\Anaconda3\Scripts\conda.exe run where python

or, if you have another env, say my_env you can also do
C:\Users\dream\Anaconda3\Scripts\conda.exe run -n my_env where python

to verify that the Python interpreter that gets run is the one specified.
(Possible) Solution
If the above works, then you should be able to do something like
var exec = require('child_process').exec;
exec('C:\Users\dream\Anaconda3\Scripts\conda.exe run python hello.py', ..callback)

Not sure if you'll need the shell specified in this case.


text:
Q: Why the Azure Event Hub get events so slow? Event Hub is fast to send but slow to get. I use next code:
    subscribe(cb: (event: any) => Promise<void>) {
        this.consumerClient.subscribe(
            this.config.partitionId,
            {
                processEvents: async (events: any, context: any) => {
                    if (events.length === 0) {
                        return;
                    }

                    for (const event of events) {
                        await cb(event.body);
                    }

                    await context.updateCheckpoint(events[events.length - 1]);
                },

                processError: async (err, context: any) => {
                    console.error(`Event Hub Subscribe Error`, { err, context });
                },
            },
            { startPosition: earliestEventPosition },
        );
    }

It takes about 1 minute to get 100 events. The await cb(event.body); works fast.

A: You can use the "maxBatchSize" and "maxWaitTimeInSeconds" in the subscribe options:
subscribe(cb: (event: any) => Promise<void>) {
    this.consumerClient.subscribe(
        this.config.partitionId,
        {
            processEvents: async (events: any, context: any) => {
                if (events.length === 0) {
                    return;
                }

                for (const event of events) {
                    await cb(event.body);
                }

                await context.updateCheckpoint(events[events.length - 1]);
            },

            processError: async (err, context: any) => {
                console.error(`Event Hub Subscribe Error`, { err, context });
            },
        },
        {
             startPosition: earliestEventPosition,
             maxBatchSize: 50,
             maxWaitTimeInSeconds: 1
        }
    );
}

A: The issue must be from the source side, not in Event Hub since it is sending the data at expected speed.
Here are some recommendations in the light of the performance and throughput results:

*

*If events do not naturally comes in batch of many events:  simply
stream events.  Do not try to batch them unless network IO is
constrained.

*If a latency of 0.1 seconds is a concern:  move the call to Event
Hubs away from your critical performance path.

Refer Performance and scale for Event Hubs and Azure Functions to know more on how the performance can be improved.


text:
Q: Run a cron job as the tomcat user I want to be able to run a cron job as the tomcat6 user.  I tried to su tomcat6 but I don't know the default password for that user.  Should I run them as tomcat6 (if I can find out the password - this is on Ubunbu 9.04) or run them as another user but grant the tomcat6 user access to the necessary files?  If I do the second option, should I create a group and add tomcat6 to that as well as any other users that may need to run the script the cron job kicks off?

A: I'm not sure whether you've got root on this server or not, could you please clarify? It would seem you don't as you've been asked for a password, but on the other hand you mention creating a group, which in principle you could only do with root access of some kind.
If you've got sudo access as expected on Ubuntu you can easily become tomcat6 like this:
sudo su - tomcat6
Or edit tomcat6's crontab directly:
sudo crontab -u tomcat6
You could of course also add the job directly to the system crontab, remembering to use tomcat6 on the sixth column:
sudo vim /etc/crontab
As for the rest, if this cronjob has to write to files belonging to different users I would probably use a dedicated group (say tomcat6 - check whether you have it already). Then, for each file in that set:
sudo chgrp tomcat6 file
chmod g+rw file


text:
Q: AWS assume-role equivalent in Google cloud (GCP)? How to setup multi-account(project) in GCP? It is possible in AWS by using assume-role. Anyone know how to do that in Google Cloud Platform (GCP)?
I tried exploring AWS equivalent in GCP but not able to find any documentation.

A: As documented, AssumeRole in AWS returns a set of temporary security credentials that you can use to access AWS resources that you might not normally have access to.
In AWS you can create one set of long-term credentials in one account. Then you can use temporary security credentials to access all the other accounts by assuming roles in those accounts.
The equivalent of the above in GCP would be creating short-lived credentials for service accounts to impersonate their identities (Documentation link).
Accordingly, in GCP you have the "caller" and the "limited-privilege service account" for whom the credential is created.
To implement this scenario, first, use handy documentation on Service Accounts and Cloud IAM Permission Roles in GCP, as each account is a Service Account with specific role permissions, in order to understand how accounts work in GCP.
The link I posted above, provides detailed information on the flows that allow a caller to create short-lived credentials for a service account and the supported credential types.
Additionally, this link can assist you in visualizing and understanding the resource hierarchy architecture in GCP and give you examples on how to structure your project according to your organization's structure.

A: The basic answer is "Service Roles".   Limited-time service roles are available.
For assigning permissions across projects (but still in the same organization), you can create a custom role.
For letting any user assume the role of a service account, use the Service Account user role.
For limited-time authorization tokens, you have OAuth 2.0 for server-to-server calls, particularly with JWT where available.


text:
Q: Checkmarx SAST scan code with external unaccessible dependencies in pom.xml General:
code to scan are .java files (Java EE), dependencies are provided as separate JARs
Goal:
How can I provide checkmarx with all the required Java dependencies to build the project to get as sound and complete a scan as possible? I'm not interested in detecting issues in the dependencies themselves and don't want these to be included in the checkmarx report.
Why:
The scan without dependencies returns no findings which is slightly unusual for the size and complexity of the code base. I have all the dependencies locally and can build the project in my IDE (idea). I see no way to tell Chekmarx about dependencies (CLI and maven plugin only have options to include or exclude files and directories from the scan) when I zip the folder and upload it via the web interface for a new scan. I haven't used the maven checkmarx plugin as it requires resources which are inaccessible from the Checkmarx scanner machine (including the dependencies).
The approach I'm currently exploring is to explode the dependencies into the project source folder so that imports can be resolved and Checkmarx can build the project. However Some dependency JARs include java source files, others only the class files and it does not look like Checkmarx CxSAST supports scanning class files (nor JARs for that matter).
If I can get the code to scan, I can filter out any issues found within the dependencies by marking them in the web interface and excluding them from the report.

A: You don't need the dependencies for static analysis if they are not code that you maintain.  If you don't see results, chances are there are no sources or sinks recognized in your code.
Download the scan log and near the end look for the number of results for queries named similar to Find_Interactive_Inputs and Find_Interactive_Outputs.  If the count is zero for one or both, the code you are scanning has no recognizable sources/sinks.   This is not uncommon for class library jars or if you're using a framework not recognized by SAST.  The queries can usually be tuned via CxQL to recognize sources/sinks if indeed there is a pattern to finding them.


text:
Q: Property 'delegate' not found on object 'AddEventViewController' With the help of the Developer Library, I am trying to work with the EventKit and EventKitUI Frameworks. I've hit a very early roadblock. I have copied and pasted code from the library found here. I have added a view controller called 'AddEventViewController' a button to the Navigation Bar in my ViewController and I am using this code to invoke it.
- (IBAction)add:(id)sender {
AddEventViewController *addController = [[AddEventViewController alloc]
                                          init];
addController.delegate = self;
UINavigationController *navigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:addController];
[self presentViewController:navigationController animated:YES completion: nil];

}
The error shows on line: addController.delegate = self;
This code is copied straight from the Library. I am using Xcode 4.2 and a Storyboard if that might help.
UPDATE:
This is AddEventViewController.h:
#import <UIKit/UIKit.h>

@interface AddEventViewController : UIViewController

@end

You're going to tell me I created this ViewController incorrectly? Please explain why just not "how" if you'd be so nice?

A: I see how Apple's example here has likely confused you here. First, download the full source for iPhoneCoreDataRecipes (or at least reference it while trying to understand this code).
To really understand what's going on here, you need to read on down to the section called "Dismissing a Presented View Controller" and then follow the link to "Use a Delegation to Communicate With Other Controllers." ("a Delegation?" Very strange....)
So here's what's going on. The presented view has a "delegate" which is the object it's supposed to tell "interesting" things to. In this case, "interesting" things are "hey, I added a recipe!" To achieve this, the delegate implements a protocol, which just means it promises to implement some methods. In this case, the required method is recipeAddViewController:didAddRecipe:.
AddViewController has a delegate property like this:
@property(nonatomic, assign) id <RecipeAddDelegate> delegate;

That just means that the delegate must conform to the named protocol. The delegate itself indicates that it does so in its interface:
@interface RecipeListTableViewController : UITableViewController <RecipeAddDelegate, NSFetchedResultsControllerDelegate> {

Note that this is marked assign for reasons @Yuras explains. But if you're writing new code targeted at iOS 5, you should use weak instead of assign. weak properties are automatically set to nil if their referenced object is deallocated. It's just safer that way. No dangling pointers.

A: In Objective-C any property you are using should be declared somewhere. Any properties, that are declared in parent class (UIViewController in your case) are inherited by all the derived classes (AddEventViewController in your case).
AddEventViewController inherits UIViewController, but the delegate property is not declared neither in the first, nor in the second. That is why compiler is not happy.
You should declare it. Something like the next:
@interface AddEventViewController : UIViewController

@property (nonatomic, assign) id delegate;

@end

@implementation AddEventViewController

@synthesize delegate;

@end

Delegates are usually declared with assign attribute to prevent circle retains (e.g. A retains B and B retains A)


text:
Q: Python Program to Read in a File of Text and then Write its Contents in Another File, with Margins of Different Sizes, Input By User I am writing a new Python code and want to make it read in a file, then re-write the contents of the file to another one, but with added margins. The margins have to be input by the user and the text has to be left aligned.
This is for a Python project, 3.74 version. I already successfully wrote the code for copying the file from the old one, as well as creating the left margins, but I am having a hard time in finding a good way to create the right margins. Also, I need to determine when and where the line needs to be split and go to the next file. Words cannot be split.
#ask user to input file Name
print("\n\nEnter your file's name")

#have a file name ready
file_Name = "I'm a file.txt"

#set the line length in characters
line_Size=80
#get min size
min_Size = 7

#take in user input
#make file_Name be the name input by user
file_Name=input()

#output file
#get name from user
print("Enter the name of the file you want to output to (i.e. output file)")
show = input()

#get margins from User
#set default margins first
left_Margin=0
right_Margin=0

#ask for left margin
print("\nEnter your left margin")
#get left margin
left_Margin=int(input())

#ask for right left_Margin
print("\nEnter your right margin")
#get right margin
right_Margin=int(input())
#print margins testcase
#print(left_Margin, right_Margin)

#create varible to hold the number of characters to withold from line_Size
avoid = right_Margin
num_chars = left_Margin
#open file now

with open (file_Name, "r") as f:
    #get output file ready
  with open(show, "w") as f1:

    for i in f:
      num_chars += len(i)
      string_length=len(i)+left_Margin
      #string_squeeze=len(i)+right_Margin
      i=i.rjust(string_length)
      words = i.split()
      #check if num of characters is enough
      if num_chars-80-avoid-5<min_Size:
        print("Here is the problem")
        f1.write(i)
        i.split()
        f1.write('\n')
        f1.write(i)

      else:
        f1.write(i)
        f1.write("\n")

A: You created words from i.split() and did nothing with it. From there it's hard to say where your mind went but it's what my code looks like when I bamboozle myself. I would handle it like this:
leftmargin = leftmargin - 1 # we will add a space before the first word of each line

outline = " " * leftmargin  # line to write
for inline in file:
    for word in inline.split():
        if len(outline) + len(word) + rightmargin > max:
            # line would be too long, so write what we have and reset the outline variable
            outfile.write(outline)
            outline = " " * leftmargin
        # the above flow nicely prevents the need for more if/elses
        outline += ' ' + word

this could be improved to handle 0 leftmargins and words longer than the max line length, but I think it should hold you for now.


text:
Q: Constructor in class cannot be applied to given types. Hope for assistance I'm fairly new to Java and I'm using BlueJ. I keep getting the error:
constructor ItemNotFound in class ItemNotFound cannot be applied to given types;
required: int
found: no arguments
reason: actual and formal arguments lists differ in length

I'm fairly confused and in turn not sure how to fix the problem. Hopefully someone can help me. Thank you in advance.
Here is my class Catalog:
public class Catalog {
    private Item[] list;
    private int size;

    // Construct an empty catalog with the specified capacity.
    public Catalog(int max) {
        list = new Item[max];
        size = 0;
    }

    // Insert a new item into the catalog.
    // Throw a CatalogFull exception if the catalog is full.
    public void insert(Item obj) throws CatalogFull {
        if (list.length == size) {
            throw new CatalogFull();
        }
        list[size] = obj;
        ++size;
    }

    // Search the catalog for the item whose item number
    // is the parameter id.  Return the matching object
    // if the search succeeds.  Throw an ItemNotFound
    // exception if the search fails.
    public Item find(int id) throws ItemNotFound {
        for (int pos = 0; pos < size; ++pos){
            if (id == list[pos].getItemNumber()){
                return list[pos];
            }
            else {
                throw new ItemNotFound(); //"new ItemNotFound" is the error
            }
        }
    }
}

For reference, here is the code for the class ItemNotFound as well:
// This exception is thrown when searching for an item
// that is not in the catalog.
public class ItemNotFound extends Exception {
    public ItemNotFound(int id) {
        super(String.format("Item %d was not found.", id));
    }
}

A: The ItemNotFound class only has one constructor: one that takes an int parameter:
public ItemNotFound(int id)

You're trying to call that without any arguments:
throw new ItemNotFound();

That's not going to work - you need to pass an argument for that parameter. I suspect you just want:
throw new ItemNotFound(id);

(Given that the id parameter to the find method is the ID you're looking for.)
Additionally, I'd recommend that you rename your exception to include a suffix of Exception to follow Java naming conventions - so ItemNotFoundException.
You'll also need to change your loop - currently you're throwing an exception if the first value doesn't have the right ID, whereas presumably you want to loop through all of them. So your find method should look like this:
public Item find(int id) throws ItemNotFoundException {
    for (int pos = 0; pos < size; ++pos){
        if (id == list[pos].getItemNumber()){
            return list[pos];
        }
    }
    throw new ItemNotFoundException(id);
}

A: You provided a custom constructor to your class  ItemNotFound  and not passing the required arguments  when you are using it.
Try to pass required args here
  throw new ItemNotFound(id);

So your code becomes
public Item find(int id) throws ItemNotFound {
        for (int pos = 0; pos < size; ++pos){
            if (id == list[pos].getItemNumber()){
                return list[pos];
            }
            else {
                throw new ItemNotFound(id); //  Now constructor satisfied
            }
        }
    }

And
throw new ItemNotFound();

That above line is true when your class     ItemNotFound  is like
// This exception is thrown when searching for an item
// that is not in the catalog.
public class ItemNotFound extends Exception {
    public ItemNotFound() {
        super("Sorry !! No item find with that id"); //Now a generic message.
    }
}

A: throw new Item() is not valid as an explicit constructor has been defined Item(int id).

A: You have provided a constructor without any parameters.
public ItemNotFound()

and you are calling new ItemNotFound(id) which while creating instance of class ItemNotFound expects a constructor with one parameter of type int. So you need to have an overloaded constructor
public class ItemNotFound extends Exception {
    public ItemNotFound() {
        super("Sorry !! No item find with that id"); //Now a generic message.
    }

    public ItemNotFound(int if) {
        this(); //Since you are not using any int id in this class
    }
}


text:
Q: GzipReader each_line method missing in Rubinius I am trying to read a gzipped file using Zlib:GzipReader. This works as expected using ruby 1.9.3 but I am getting a method_missing error for each_line when using Rubinius.
Is there any way to read a gzipped file using Rubinius?
require 'zlib'

Zlib::GzipReader.open("lines.txt.gz").each_line { |line|
  puts "#{line}"
}

Kernel(Zlib::GzipReader)#each_line (method_missing) at kernel/delta/kernel.rb:81

A: I believe this is a bug in Rubinius, you should consider opening an issue for it with the project.  However, this workaround should get you going:
require 'zlib'
require 'stringio'

file = File.read("lines.txt.gz")
lines = Zlib::GzipReader.new(StringIO.new(file)).read


text:
Q: Asp.Net ViewState lost with RegisterClientScriptBlock I am validating a zip code using Javascript that is generated server-side, and injected when a LinkButton is clicked. Then, I retrieve the return value by calling a server-side function when the page loads.
This works nicely, but the problem is that the ViewState is completely lost after PostBack. Below is the code, starting with the page_load event, the button click event, and then the callback called from the page_load event.
Is there a way I can somehow save the ViewState, maybe easily in a session variable? Or is there a workaround I can use?
// In Page_Load
if (Request.Form["__EVENTTARGET"] == "CallFunction") {
    GetValidateZipCodeScriptReturnValue(Boolean.Parse(Request.Form["__EVENTARGUMENT"].ToString()));
}

// OnClick for LinkButton
private bool ValidateZipCode(string zip) {
    StringBuilder script = new StringBuilder();
    script.Append("<script language='javascript' type='text/javascript'>");
    script.Append(@"var regex = /^\d{5}$|^\d{5}-\d{4}$/;");
    script.Append("__doPostBack('CallFunction', regex.test(" + zip + "));");
    script.Append("</script>");

    Type t = GetType();

    if (!ClientScript.IsClientScriptBlockRegistered(t, "ValidateZipCodeScript")) {
        ClientScript.RegisterClientScriptBlock(t, "ValidateZipCodeScript", script.ToString());
    }

    return false;
}

// Method called on PostBack to get the return value of the javascript
private void GetValidateZipCodeScriptReturnValue(bool valid) {
    m_ZipCode = uxZip.Text;

    if (valid) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
        SetupPostBackViewState();
        ScrollToZipCode();
    }
}

A: Why not just use the OnClick event of the LinkButton? Or, better yet, look into the CustomValidator control, since it looks like all you're trying to do is validate a zip code and that's exactly what a CustomValidator can do (you'll need to look at the ClientValidationFunction, which is where you want to put your regex test).


text:
Q: MongoDB: how to do $or with $where (it doesn't do logical OR) How can we use $or with such a $where clause?
This query should always be returning all records (because of the date in 2015), but it doesn't return anything.
In parts, it works, but when trying to apply the $or to the Date or $where, it doesn't work as intended.
Thanks to Sammaye to fixing my previous version of this, to the following (still not working though):

db.turnys.find({
       $or:[
            { start:{
               $lte:new Date("2015-03-31T09:52:29.338Z")
            } },
            { $where:"this.users.length == this.seats" }
       ]
});

How can I accomplish the intended $or?
Here is a sample of the turnys collection:
[
  {
    "gId": "5335e4a7b8cf51bcd054b423",
    "seats": 2,
    "start": "2014-03-31T08:47:48.946Z",
    "end": "2014-03-31T08:49:48.946Z",
    "rMin": 800,
    "rMax": 900,
    "users": [],
    "_id": "53392bb42b70450000a834d8"
  },
  {
    "gId": "5335e4a7b8cf51bcd054b423",
    "seats": 2,
    "start": "2014-03-31T08:47:48.946Z",
    "end": "2014-03-31T08:49:48.946Z",
    "rMin": 1000,
    "rMax": 1100,
    "users": [],
    "_id": "53392bb42b70450000a834da"
  },

Thanks!

A: The problem is that $ors do not work that way, in reality what you need is:
db.turnys.find({
   $or:[
        { start:{
           $lte:new Date("2015-03-31T09:52:29.338Z")
        } },
        { $where:"this.users.length == this.seats" }
   ]
});

That will now create an $or query with two clauses. Each element of the $or array is classed as a $anded clause.

A: As I referenced to you on your other question, the use of the $where operator should be avoided as shown in the given reasons there.
So again as shown what you should be doing is "allocating" a total_users value within your document, using the $inc operator on updates. But your "query" should look like this with the use of .aggregate():
db.collection.aggregate([
    { "$project": {
        "gId": 1,
        "start": 1,
        "alloc": { "$eq": [ "$total_users", "$seats" ] }
    }},
    { "$match": {
        "$or": [
           { "alloc": 1, },
           { "start": { "$lte": new Date("2015-03-31T09:52:29.338Z") } }
        ]
    }}
])

Or even possibly use the "array size" form that was mentioned with more recent versions ( still to be released as of writing ) of MongoDB.
But also to "clarify" you need to make sure your "test" operations are actually valid.


text:
Q: Set href of all links  in page javascript without some links Hi guys please I want to set all href of links without the links in " Site_dont_go "
I was ask and get answer
this is answer
$("a").click(function() {
var x = $(this).attr("href");
var Site_dont_go = ["test.com", "youtube.com"];
var validUrl = true;
$.each(Site_dont_go, function(i, item) {
    if (x.indexOf(item) != -1) {
        validUrl = false;
    }
});

if (!validUrl) {
    window.open('goto.php?url=' + x);
    return false;
}

});
EDIT :
**My qustion is : the answer working only when someone click on the link , and I want to set it as a href of link **
thanks and i'm so sorry

A: Looks like you need to use something other than the click event to trigger the function. The each() method runs at load time.
$("a").each(function () { // <---------------- each!
    var x = $(this).attr("href");
    var Site_dont_go = ["test.com", "youtube.com"];
    ...
});

Don't forget to either place your script after your html or wrap it in document.ready.

A: You should iterate all the  tags and change the hreff property. This should be done on document ready. Not tested code but should do the trick
$( document ).ready(function() {
  $("a").each(function(index) {
            var x = $(this).attr("href");
            var Site_dont_go = ["test.com", "youtube.com"];
            var validUrl = true;
            $.each(Site_dont_go, function(i, item) {
                if (x.indexOf(item) != -1) {
                    validUrl = false;
                }
        });

        if (!validUrl) {
            $(this).attr("href",'goto.php?url=' + x);
        }
});


text:
Q: In a ring, $1-ab$ is invertible $\implies$ $1-ba$ is invertible (from scratch) I know the usual trick: let $c=(1-ab)^{-1}$ and notice that:
$$(1-ba)(bca) = bca - babca = b(c-abc)a=bc(1-ab)a=ba$$
Etc.
I was wondering how to discover this fact from scratch, without invoking this magical observation. Any help in that?


text:
Q: MATLAB: Access Data in Nested Structure using For loop Good day,
I have a nested structure in this format.
Data: [1x1 struct]
    a: [1x1 struct]
        a1: [10x1 double]
        a2: [10x1 double]
        a3: [10x1 double]
    b: [1x1 struct]
        b1: [10x1 double]
        b2: [10x1 double]
    c: [1x1 struct]
        c1: [10x1 double]
        c2: [10x1 double]
        c3: [10x1 double]
        c4: [10x1 double]

Each of sub-fields of a, b & c are duration percentage of an event in buckets. The number of elements in each bucket are number of data-sets. I'd like sum the bucket values of each data set and discard the entire data-set if they don't add up to 100%. How may I access each element of the buckets for a, b & c fields of Data using for loop in a simply format.
EDIT: I figured out how to call the sub-fields & it's elements, sum the percentages & now, if the data-sets not adding up to 100 need to fully removed from each sub-field.
field = fieldnames(Data);
for group = 1:length(field)
    for subfield = fieldnames(Data.(field{group}))

        fieldSize = structfun(@(field) length(field),Data.(field{group}));
        nb_datasets = fieldSize(1,1);

        for jj = 1:nb_datasets
            for ii = 1:length(subfield)
                a_dataset_pcts(jj,ii) = Data.(field{group}).(subfield{ii})(jj,1);
            end
            a_pct_total(jj,:) = sum(a_dataset_pcts(jj,:));
        end

    end
end

A: Matlab like matrices Bensa.... You should drop your approach now.
Fixed size datasets
If all a, b, c arrays are 10x1 sized, you should switch immediately to a cell of arrays, being the index the durations, and the arrays columns the datasets for each duration:
a: [1x1 cell]
    a{1}: [10xna double]
    a{2}: [10xnb double]
    a{3}: [10xnc double]

All statistics go easy. You have two for loops, one for the durations, other for the dataset. Matlab vectorizes the functions inside each dataset (most of the time). In here, i am assuming max(.) is your aggregation array function for obtaining statistics:
n=length(a);
for i=1:n
    ni=size(a{i},2);
    for j=1:ni
        max(a{i})
        mean(a{i}')'
        if j==j0 && i==i0
            a{i}(:,j)=[];  % Cleanup j0th event in i0th dataset
        end
    end
end

Do you need to compare a.a1 & b.b1 & c.c1? If that is true, then you forcedly should create the auxiliar array x, and then get your stats:
for i=1:n
    x(:,i)=a{i};
end
max(x')'

Variable size datasets
If the a, b, c arrays are different each time, then you upgrade the last data and switch to a cell of cells:
a{1}: [1xna cell]
    a{1,1}: [la(1)x1 double]
    ...
    a{1,na}: [la(na)x1 double]
a{2}: [1xnb cell]
    ...
a{3}: [1xnc cell]
    ...

In here the max(.')' approach is useless, because every dataset could be of different length. If that is the case, you still can reference the data as usually through columns:
n=length(a);
for i=1:n
    ni(i)=size(a{i},2);
    for j=1:ni(i)
        li=length(a{i,j})   % Length of each dataset
        max(a{i,j})
        % mean(a{i}')'      % This do not work anymore
        if j==j0 && i==i0
            a{i,j}=[];      % Cleanup j0th event in i0th dataset
        end
    end
end

Do this make sense?. Feel free to comment below...


text:
Q: How to draw $(g \circ f)$ is surjective, $f$ is not surjective I'm writing a proof wherein for one part I'm supposed to prove or disprove:

Let $f: X \to Y$ and $g: Y \to Z$ be two functions, with $X = Y = Z = \mathbb{R}$.
  If $f$ is surjective, then $(g \circ f)$ is surjective.

[The domains and codomains of $f(x)$ and $g(f(x))$, respectively, are the real numbers.]
I've already seen a proof by elements showing that this statement is false. However, I want to do a proof by drawing the sets and showing a counterexample where $(g \circ f)$ is surjective but $f$ is not.
We didn't really go over in detail how to do these set drawings, so I think that I figured out a counterexample that disproves the statement, but I'm not confident that I drew it correctly.

I'd really appreciate if someone could let me know if this is logically sound or if I broke a rule I didn't know about, and if so, how I might go about fixing it. Thank you!

A: Your picture is in itself correct, except that $g$ needs to be a full function.
But why not make it formal:
$X= \{1,2,3\}, Y = \{1,2,3\} ,Z = \{1,2\}$ and define
$$f: X \rightarrow Y\text{ by }f(1) = f(2) = 1, f(3) = 2$$
And
$$g: Y \rightarrow Z\text{ by }g(1) =1, g(2)=2,g(3)=2 $$
Then $f$ is not surjective as $3 \in Y$ is not an image of $f$, while
$$(g \circ f)(1) = g(f(1)) = g(1) = 1, (g \circ f)(2) = g(f(2)) = g(1) = 1, (g \circ f)(3) = g(f(3)) = g(2) = 2$$
Which shows that $g \circ f$ is surjective, as $1$ and $2$ are image points.

A: I just offer this as an example to think (hard) about.
Let $X=\{0\}$, $Y=\{0,1\}$, $Z=\{0\}$.
Let $f:X\to Y$ be such that $f:0\mapsto 0$.
Let $g:Y\to Z$ be such that $g:0\mapsto 0$, $g:1\mapsto 0$.
Then $g\circ f:X\to Z$ is such that $g\circ f:0\mapsto 0$.
Now $g\circ f$ is clearly surjective, but $f$ is not; although of course $g$ is.
Also $g\circ f$ is clearly injective, but $g$ is not; although of course $f$ is.
Once you (really ) understand this example you can adapt it to suit most prescriptions on the sets.


text:
Q: Sort datatable not working in C# ASP.NET? I am trying to apply sorting on datatable but it's working.I want to apply sorting by distance column.
Here is my output img
I want sort in ASC order ,from lowest to highest.
CODE:
  SqlConnection cnn = new SqlConnection(connection);
        string query = "SELECT PostCode,Latitude,Longitude FROM [kaykocou_admin].[kaykocou_admin].[Deals]";
        SqlCommand cmd = new SqlCommand(query,cnn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
       DataTable dtnew = new DataTable();
       DataRow _ravi;
        if (dt.Rows.Count>0)
        {

            dtnew.Clear();
            dtnew.Columns.Add("PostCode");
            dtnew.Columns.Add("Lat");
            dtnew.Columns.Add("Long");
            // dtnew.Columns.Add("Lat 1");
            // dtnew.Columns.Add("Long 1");
            dtnew.Columns.Add("distance");
             string str2 = GET("http://api.postcodes.io/postcodes/SW1A 0AA");
             var serializer2 = new JavaScriptSerializer();
             dynamic deserialize_post2 = serializer2.DeserializeObject(str2);

             decimal Longitude1 = deserialize_post2["result"]["longitude"];
             decimal Latitude1 = deserialize_post2["result"]["latitude"];

            foreach (DataRow dr in dt.Rows)
            {

       string postcode = dr["PostCode"].ToString();
       // string str1 = GET("http://api.postcodes.io/postcodes/" + postcode);
       // string final = str1.Replace(@"{", "");
       // string final2 = final.Replace(@"}", "");
       // str1 = str1.Replace('[', ' ');
       // str1 = str1.Replace(']', ' ');
       // string result = "{ " + final2 + " }";
       // var serializer = new JavaScriptSerializer();
       // dynamic deserialize_post = serializer.DeserializeObject(str1);

        decimal Longitude =Convert.ToDecimal( dr["Longitude"].ToString());
        decimal Latitude =Convert.ToDecimal( dr["Latitude"].ToString()) ;

        _ravi = dtnew.NewRow();

        var sCoord = new GeoCoordinate(Convert.ToDouble(Latitude), Convert.ToDouble(Longitude));
        var eCoord = new GeoCoordinate(Convert.ToDouble(Latitude1), Convert.ToDouble(Longitude1));
        var distance=sCoord.GetDistanceTo(eCoord);
        _ravi["PostCode"] = postcode;
        _ravi["Lat"] = dr["Longitude"].ToString();
          _ravi["Long"]= dr["Longitude"].ToString();
          _ravi["distance"] =Convert.ToDouble( Math.Round(((distance / 1000.0) * 0.621371192), 2));

        dtnew.Rows.Add(_ravi);
            }
            DataView view = dtnew.DefaultView;
            view.Sort = "distance ASC";
            DataTable sortedDate = view.ToTable();
            //dtnew.DefaultView.Sort = "distance";
            gr.DataSource = sortedDate;
            gr.DataBind();
        }

    }


text:
Q: Please tell me what the problem is c# regex.split() string temp_constraint = row["Constraint_Name"].ToString();
string split_string = "FK_"+tableName+"_";
string[] words = Regex.Split(temp_constraint, split_string);

I am trying to split a string using another string.
temp_constraint = FK_ss_foo_ss_fee
split_string = FK_ss_foo_

but it returns a single dimension array with the same string as in temp_constraint
Please help

A: You should use String.Split instead
string[] words =
    temp_constraint.Split(new []{split_string}, StringSplitOptions.None);

A: Your split operation works fine for me:
string temp_constraint = "FK_ss_foo_ss_fee";
string split_string = "FK_ss_foo_";
string[] words = Regex.Split(temp_constraint, split_string);
foreach (string word in words)
{
    Console.WriteLine(">{0}<", word);
}

Output:

><
>ss_fee<

I think the problem is that your variables are not set to what you think they are. You will need to debug to find the error elsewhere in your program.
I would also avoid using Split for this (both Regex and String.Split). You aren't really splitting the input - you are removing a string from the start. Split might not always do what you want. Imagine if you have a foreign key like the following:
FK_ss_foo_ss_fee_FK_ss_foo_ss_bee

You want to get ss_fee_FK_ss_foo_ss_bee but split would give you ss_fee_ and ss_bee. This is a contrived example, but it does demonstrate that what you are doing is not a split.

A: string split uses a character array to split text and does the split by each character which is not often ideal.
The following article shows how to split text by an entire word
http://www.bytechaser.com/en/functions/ufgr7wkpwf/split-text-by-words-and-not-character-arrays.aspx


text:
Q: Xamarin iOS black screen I´m very new to Xamarin and currently I want to develop a little iOS app that receives data from a REST-Service.
So I have the following Storyboard:

In the table view there should be some entries that are consumed from the REST-Service. When you click on one row you should be "redirected" to a detail view which should be the right View.
The problem is, that the screen of the right story board is just black:

Well let´s have a look at my code, first the FinishedLaunching method in my AppDelegate.cs:
public override void FinishedLaunching(UIApplication application)
    {
        Window = new UIWindow(UIScreen.MainScreen.Bounds);
        UIStoryboard storyboard;
        UIViewController initialViewController;

        var credential = CredentialController.Instance.FindAccount(CustomStaticLiterals.AppName);
        if (credential == null)
        {
            storyboard = UIStoryboard.FromName("AccountCreationViewController", NSBundle.MainBundle);
            initialViewController = storyboard.InstantiateInitialViewController() as UIViewController;
        }
        else
        {
            storyboard = UIStoryboard.FromName("OverviewViewController", NSBundle.MainBundle);
            initialViewController = storyboard.InstantiateInitialViewController() as UIViewController;
        }

        Window.RootViewController = initialViewController;
        Window.MakeKeyAndVisible();
    }

Here is my ProjectOverviewController:
public partial class ProjectOverviewController : UITableViewController
{
    public List<Project> Projects { get; set; }
    private static readonly NSString callHistoryCellId = new NSString("ProjectCell");

    public ProjectOverviewController(IntPtr handle) : base(handle)
    {
        TableView.RegisterClassForCellReuse(typeof(UITableViewCell), callHistoryCellId);
        ProjectOverviewDataSource source = new ProjectOverviewDataSource(this);
        source.DetailProjectEvent += DetailProjectPage;
        TableView.Source = source;
        Projects = new List<Project>();
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        var credentials = CredentialController.Instance.FindAccount(CustomStaticLiterals.AppName);
        var service = new ServiceInvoker();
        Projects = new List<Project>(service.GetCurrentProjectsOfUserAsync(credentials.UserName).Result);
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {

    }

    void DetailProjectPage(object sender, EventArgs e, int index)
    {
        var currentProject = Projects[index];
        var projectViewController =
            Storyboard.InstantiateViewController("ProjectViewController") as ProjectViewController;

        if (projectViewController != null)
        {

            projectViewController.Initialize(currentProject);
            NavigationController.PushViewController(projectViewController, true);
        }
    }

    class ProjectOverviewDataSource : UITableViewSource
    {
        ProjectOverviewController controller;
        public delegate void DetailProjectHandler(object sender, EventArgs e, int index);
        public event DetailProjectHandler DetailProjectEvent;

        public ProjectOverviewDataSource(ProjectOverviewController controller)
        {
            this.controller = controller;
        }

        // Returns the number of rows in each section of the table
        public override nint RowsInSection(UITableView tableView, nint section)
        {
            return controller.Projects.Count;
        }
        //
        // Returns a table cell for the row indicated by row property of the NSIndexPath
        // This method is called multiple times to populate each row of the table.
        // The method automatically uses cells that have scrolled off the screen or creates new ones as necessary.
        //
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.DequeueReusableCell(ProjectOverviewController.callHistoryCellId);

            int row = indexPath.Row;
            cell.TextLabel.Text = controller.Projects[row].Header;

            return cell;
        }

        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            var index = indexPath.Row;
            if (DetailProjectEvent != null)
            {
                DetailProjectEvent(this, new EventArgs(), index);
            }
            tableView.DeselectRow(indexPath, true);
        }
    }
}

And finally the the ProjectViewController:
public sealed partial class ProjectViewController : UIPageViewController
{
    private Project masterModel;
    public ProjectViewController (IntPtr handle) : base (handle)
    {
    }

    public void Initialize(Project masterModel)
    {
        if (masterModel == null)
        {
            throw new ArgumentNullException(nameof(masterModel));
        }

        this.masterModel = masterModel;

    }

    public override void ViewDidLoad()
    {
        Title = masterModel.Header;
        CustomerField = new UITextField();
        CustomerField.Text = masterModel.Customer;
        ObjectAddressField = new UITextField();
        ObjectAddressField.Text = masterModel.Customer;
    }
}

Well there is an other strange behaviour I realized:
When I wanted to set a text for the CustomerField.Text and ObjectAddress.Text property I got a NullReferenceException that the two objects CustomerField and ObjectAddressField are null which leads me to the conclusion that there must a wrong initialization of the ProjectViewController.
If you have some other recommendations about my code, feel free to tell my, because as I said I´m a rookie with Xamarin and App-Development.


text:
Q: make a instance of a struct by string i am building a app and i want to use a simple mvc model in it
i have a package controllers with in there controller structs like this
type UserController struct {}

func (u *UserController) Index(res http.ResponseWriter, req http.Request) {
  // some code in it
}

what i want to achieve is that i can make instance of that controller by string like
func NewAppController("user") { }

so i can dynamicly create instances of my controllers by my route requests
an other way i think about is to map my controllers like this
var controllerProvider = map[string]interface{} {
   "user": &controllers.UserController{},
   "warehouse": &controllers.WarehouseController{},
 }

and then call it by
appController = mux.Vars(req)["controller"]
c := controllerProvider[appController]

but i rather use the first way any idea how to deal with this?

A: You could try to create a new object that implements reflect.Type interface and then use it through reflect's mechanisms, but it looks like a complete waste of time. Instead, consider these alternatives:

*

*Make a struct with fields like Name string and Methods map[string]ActionFunc. This would work, but it doesn't look very idiomatic to me. (If anything, this reminds of some JavaScript OOP implementations.)

*Use a framework. If you're comfortable with MVC, why don't you use one of MVC frameworks for Go that already exist? Beego and Revel come to mind.

*Rethink your architecture altogether. From what I see now, you are trying to write Go like it's Ruby-on-Rails. Go is different. Start with vanilla net/http and create a minimal implementation of your app. That's your prototype. With that prototype on your hands, you can rewrite it and expand it. Want resourceful routes? Add gorilla/mux or another router of choice. Need a data storage? Add an ORM. Want more testability and flexibility? Interfaces, interfaces everywhere.

A: If you use this:
var controllerProvider = map[string]interface{} {
   "user": &controllers.UserController{},
   "warehouse": &controllers.WarehouseController{},
}

Be careful, these are not new instances for each access. If you use controllerProvider several times, it will always return the pointer to the instances initialized only once there.
You might want to use functions to dynamically generate instances:
var controllerProvider = map[string]func() interface{}{
    "user":      func() interface{} { return &controllers.UserController{} },
    "warehouse": func() interface{} { return &controllers.WarehouseController{} },
}

c := controllerProvider[appController]()


text:
Q: How do I write a string to a 2D array in C? So I am working on a multi-threading program with 4 threads. For thread1 I am grabbing input from stdin and then putting it into buffer1, thread2 then reads from buffer1, modifies it, then puts it in buffer2 for thread3 to read, and so on....
After I have read from buffer1 (in my thread2 function), I have successfully altered the data, now I want to put it in buffer2, but I am getting the error of "expression must be a modifiable lvalue". Does anyone know why??
My thread 2 function is below and the error is appearing in buffer2[write2] = updatedStr;
void *line_separator_thread(void *args)
{
    // Consuming from buffer 1 and producing to buffer 2
    int haveStop = 0;
    while (1)
    {
        // Snag the mutext for a read
        pthread_mutex_lock(&mutex1);

        // Release the mutex and block on the condition
        pthread_cond_wait(&readyBuffer1, &mutex1);

        // Process all unread slots from the buffer1 queue
        while (buffer1[read1][0] != -1) // Look for no sentinal value
        {
            haveStop = haveStopInText(buffer1[read1]);
            if (haveStop)
                break;

            // ***If no break, then read from buffer1, and modify \n to be a space?
            // str_replace(orig, replace, with)
            char *updatedStr = str_replace(buffer1[read1], "\n", " ");
            printf("UPDATED STRING: %s\n", updatedStr);
            read1 = (read1 + 1) % 5;

            // ***Put the updated string in buffer 2?
            pthread_mutex_lock(&mutex2);
            buffer2[write2] = updatedStr; //ERROR IS HERE!!!

            // ***Need to change buffer1[read1][0] So that it doesn't keep looping?
        }

        // ***Unlock the mutex here? Or outside of the while loop?
        pthread_mutex_unlock(&mutex1);
    }
    return NULL;

Buffer variables and read/write variables are below
char buffer1[5][1000]; //inputThread + lineSeparatorThread
char buffer2[5][1000];
char buffer3[5][1000];

// Set up variables to let the threads know where is it safe to read from and write to
int write1 = 0;
int read1 = 0;

int write2 = 0;
int read2 = 0;

int write3 = 0;
int read3 = 0;

And lastly, below is in my main function where I am creating the 4 threads
pthread_create(&outputThread, &attr, output_thread, NULL);
    usleep(100); // Force the program to allow output thread to actually come up and pend on readyBuffer 3 first

    pthread_create(&plusSignThread, &attr, plus_sign_thread, NULL);
    usleep(100); // Force the program to allow plus_sign_thread thread to actually come up first

    pthread_create(&lineSeparatorThread, &attr, line_separator_thread, NULL);
    usleep(100); // Force the program to allow line_separator_thread thread to actually come up first

    pthread_create(&inputThread, &attr, input_thread, NULL);

    pthread_join(inputThread, NULL);
    pthread_join(lineSeparatorThread, NULL);
    pthread_join(plusSignThread, NULL);
    pthread_join(outputThread, NULL);


text:
Q: Por que estou 'chamando' o método da subclasse? public class A {
  public String imprimir() {
  return "A";
       }
}

 public class B extends A {
   public String imprimir() {
  return "B";
        }
 }

public class C extends B {
   public String imprimir() {
  return "C";
        }
 }

public class Executa{

  public static void main (String[] args){

   A v1 = new A();
    System.out.println(v1.imprimir());

   A v2 = new B();
    System.out.println(v2.imprimir());

   A v3 = new C();
    System.out.println(v3.imprimir());

    System.out.println(((A)v3).imprimir());
    System.out.println(((B)v3).imprimir());

  }

}

Aparentemente um código bem didático e de fácil compreensão, porém me confundiu bastante.
Por que nas linhas
System.out.println(((A)v3).imprimir());
System.out.println(((B)v3).imprimir());

está 'chamando' o método da subclasse? Não deveria chamar, respectivamente, os métodos das classe A e classe B?
Acredito que estou errando em algum conceito de orientação a objetos, mas em qual conceito?

A: Como já foi comentado, o casting não muda o objeto - ele passa um "recado" para o compilador de que naquele contexto ele pode considerar aquele objeto como sendo daquela classe.
Mas no tempo de execução, o método chamado é o do próprio objeto - no caso acima, o C.imprimir. Se o método chamado não existisse na superclasse (isso é, se  imprimir só estivesse definido para as classes B e C, o compiladordaria um erro - já que não teria como gerar código para chamar o método imprimir de um objeto da classe A.
Agora, quanto a sua preocupação de "não estar entendendo algum conceito de orientação a objetos": fique tranquilo - você entendeu O.O. -  o "casting" que é algo que a linguagem Java pega por empréstimo do C que não é algo muito "orientado a objetos", e, sim, mais como um mecanismo para permitir que o compilador se ache em alguns casos.
Se fosse em Python por exemplo, outra linguagem orientada a objetos - em Python não existe o "casting" - mas você sempre pode chamar métodos na própria classe passando a instância explicitamente - nesse caso,  que você está tentando fazer funcionaria:
class A:
    def i(self):
        return "A"
class B(A):
    def i(self):
        return "B"
b = B()
print(b.i())
print(A.i(b))

Imprime a saída B e A - isso é, se o método é chamado na instância, como é obrigatório na sintaxe do Java, o parâmetro self, equivalente ao this, é preenchido pela própria linguagem - mas você tem a opção de chamar o método a partir da classe - A.i() - e nesse caso tem que passar o que seria o self explicitamente - então é possível chamar métodos das superclasses em instâncias de subclasses.
O super do Java não pode te dar uma referência direto aos métodos da superclasse se usado de fora das subclasses. Ele existe dentro de um método, sem argumentos, então assume aponta diretamente para o objeto na super-classe, mas se você tentasse usar super de dentro de Executa, ele procuraria o método imprimir em alguma super-classe de Executa, e não de C. (Novamente, o super() de Python permite que se passe explicitamente a classe e a instância da qual se quer acessar os atributos da superclasse. Na continução do exemplo acima, a chamada abaixo imprime A )
print(super(B, b).i())

O ideal seria uma forma de converter seus objetos para a classe desejada, e a única forma limpa de fazer isso é ter um método explícito para conversão, que seja chamado na subclasse e devolva um objeto da classe desejada.
Achei no SOen uma pergunta parecida, onde as respostas, inclusive usando reflection, indicam que realmente não é possível chamar um método de super-classe a partir de uma instância de uma subclasse: https://stackoverflow.com/questions/5411434/how-to-call-a-superclass-method-using-java-reflection

A: O polimorfismo é justamente o oposto do que acha que é. Ele indica que o objeto concreto é que determina o que será executado e não o tipo que está esperando.
Sem o polimorfismo aconteceria o que está esperando, então ele chamaria sempre o tipo determinado para uso naquela operação. No seu exemplo sem o polimorfismo ele iria imprimir o método do tipo, então imprimiria "A" e "B" pois o tipo é que manda.
Se você quer imprimir "A" você tem que criar um objeto do tipo A. Se o objeto é C muitas coisas nele podem ser diferentes do que deveria ser em A, eles não são substituíveis nas duas direções. C substitui A de forma perfeita porque ele tem tudo de A e algo mais. A não pode substituir C porque ele não tem tudo o que C tem.
Se tentar no seu código ele poderia até dar certo porque você está vendo que tem tudo, mas para o compilador é complicado saber disso, ele tem que ir pelo caminho mais seguro e se tem potencial de erro ele não deixa compilar, até porque mesmo que hoje esteja ok, um dia pode mudar e aí quebrar todos os contratos.
Quanto a usar o super ela é uma palavra-chave contextual e só funciona dentro da classe herdada, não é possível usar no consumo do objeto, é algo para indicar ao compilador o que pegar quando há ambiguidade ou falta de informação do que está disponível, no objeto não existe isto. E nem faria sentido pelo que mostrei acima.

A: No Java, todos os métodos são virtuais. Uma vez que você sobrescreva um método, a nova implementação é definitiva.


text:
Q: Is there a way using SQLite and Python to write an insert statement with the columns as parameters? I am trying to clean raw json data by parsing and inserting it into a table of an sqlite db.
I have 22 columns in my table and want to find a way of looping through them so I don't need to write 22 loops which insert the data or a single column.
I have simplified the approach I am trying with the following:
import sqlite3

conn = sqlite3.connect('cdata.sqlite')
cur = conn.cursor()

column = 'name'
value = 'test'

cur.execute('''INSERT INTO COMPANY (?)
            VALUES (?)''',(column,),(value,))

conn.commit()
conn.close()

This doesn't work at the moment and return the error TypeError: function takes at most 2 arguments (3 given).
Does anyone know if it is possible to write an SQLite insert statement using 2 parameters like this or another way I might be able to iterate through the columns?

A: Sample as below:
import sqlite3

conn = sqlite3.connect("cdata.sqlite")
cur = conn.cursor()

column = ("name", "age")
table = f"CREATE TABLE IF NOT EXISTS COMPANY ({column[0]} text, {column[1]} text);"

cur.execute(table)

name = "hello"
age = "1"
sql_stmt = f"INSERT INTO COMPANY({column[0]},{column[1]}) VALUES ('{name}', '{age}')"

cur.execute(sql_stmt)

with conn:
    cur.execute("SELECT * FROM COMPANY")
    print(cur.fetchall())

conn.commit()
conn.close()


text:
Q: Changing the order of $\lim$ and $\inf$ for point-wise converging monotonic sequence of functions Suppose $f_n: X \rightarrow \mathbb{R}$, where $X$ is some arbitrary subset of $\mathbb{R}^N$. Suppose that
$$ \forall n\geq0, \forall x \in X, \; f_n(x) \leq f_{n+1}(x) $$
Let $\{f_n\}$ be such that each $f_n(x)$ is continuous and $\forall x,\; \lim_{n\rightarrow \infty}f_n(x) = f(x)$ exists, but is discontinuous. Hence, $\{f_n\}$ is point-wise convergent but not uniformly-convergent. My question is:

*

*Is there any such sequence for which
$$ \lim_{n\rightarrow \infty} \inf_{x\in X} f_n(x) = \inf_{x\in X} \lim_{n\rightarrow \infty} f_n(x)  $$ (I know this is true for uniform convergence.)

*If so, what is the best approach to prove it for that sequence?
Any solution or reference would be greatly appreciated. There have been similar questions before, like this one, however, I couldn't really relate to the answer. There's another one here.

A: It is not true in general. Let $g : \mathbb R \to \mathbb R$ such that $g(x) = 0$ if $x\leq 0$ and $g(x)=1 $ for $x\geq 1$ and increasing. Let $f_n(x) = g(x+n)$. Then $f_n$ is an increasing sequence converging to $f=1$. So the left hand side of the limit is $0$, while the right hand side is $1$.


text:
Q: Upgrading Laravel To 5.5.0 From 5.4 Actually, when I want to upgrade my version of Laravel I face to this problem, so any body have any answer to help me in this case.
Problem 1
This package requires php >=7.0.0 but your PHP version (5.6.31) does not satisfy that requirement.

Problem 2
- laravel/framework v5.5.9 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.8 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.7 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.6 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.5 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.4 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.32 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.31 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.30 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.3 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.29 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.28 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.27 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.26 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.25 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.24 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.23 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.22 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.21 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.20 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.2 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.19 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.18 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.17 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.16 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.15 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.14 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.13 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.12 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.11 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.10 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.1 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- laravel/framework v5.5.0 requires php >=7.0 -> your PHP version (5.6.31) does not satisfy that requirement.
- Installation request for laravel/framework 5.5.* -> satisfiable by laravel/framework[v5.5.0, v5.5.1, v5.5.10, v5.5.11, v5.5.12, v5.5.13, v5.5.14, v5.5.15, v5.5.16, v5.5.17, v5.5.18, v5.5.19, v5.5.2, v5.5.20, v5.5.21, v5.5.22, v5.5.23, v5.5.24, v5.5.25, v5.5.26, v5.5.27, v5.5.28, v5.5.29, v5.5.3, v5.5.30, v5.5.31, v5.5.32, v5.5.4, v5.5.5, v5.5.6, v5.5.7, v5.5.8, v5.5.9].

When I checked my Php version in wamp server the version is 7.1.9 but I don't know when I want to update my laravel project I face to this problem.

A: You likely have two php installations. Check your filesystem and remove the old version. It's clearly using 5.6.

A: Actually I found the solution. when I was install the Wamp server 3.1.0, so in this directory C:\wamp64\bin\php I found three folder php5.6.31, php7.0.23, php7.1.9 and with one notepad which mentioned don't delete the folder of php5.6.31, so when I want to change the Php version from wamp it show the Php version is php7.1.9, but when I check through the Cmd. it show the version of php is php5.6.31, and I was unable to upgrade my laravel version.
Soultion:
first go to Computer->Properties-> Advance System Settings-> Advance Option-> Environment variable-> system variable ->find Path and edit remove the path of php5.6.31 and add new path of php7.1.9 from C:\wamp64\bin\php just restart wamp server or even it doesn't work uninstall it again install and through wamp serve select Php version you want,and change it the after selecting the version you can check through Cmd and type php -version, the new version of Php will appear, so finally you can upgrade the version of your laravel.
Thanks


text:
Q: Scala Lift: how to get ajaxRadio parameters I have ajaxRadio ineach row of a table.
when this Radio is selected, I want scala function to get two parameters:
1st one is the selected radio, 2nd one is the data key of the row.
my source is as follows:
val radioList = List("wideArea", "oldArea","newArea")
def liftForm(xhtml: NodeSeq): NodeSeq = {
    var areaList = newOrderList.map(values =>{

{values(4)}

{values(5)}

                            {ajaxButton(S.?("delete"), () => doDelete(values(1)), "class" -> "button delete")}

                            {
                            val it = ajaxRadio[String](radioList,Box.legacyNullTest(values(2)),doRadioChange _).toForm.grouped(4)
                            for(i <- it)yield(
{i.flatMap(y =>  {y} 	)}
)
                            }

})

    bind("list",xhtml,"areaList" ->
{areaList}
)

By doRadioChange _, I can only get selected radio. How can I get the the 2nd parameter: data key of the row. ie values(1)?

A: Your functions can close over all of the local state at that point in the function. You should be able to replace doRadioChange _ with:
doRadioChange(_, values(1))

Assuming, of course, that doRadioChange accepts the proper parameters.


text:
Q: How to incude files runtime in PHP I want to include different files, depending on a parameter passed to get method. E.g. if the id passed in the URL is 101 then I want to include file_101.php. Here is what I have so far:
if(cat_id == 101)
{
    $filename="file_101.php";
}

//some code here
include('$filename');

I have also tried:
include('echo $filename;');

but it is giving error

include() [function.include]: Unable to access echo $filename;

A: Get rid of the single quotes. They make PHP parse the $ as a literal dollar sign instead of the beginning of a variable name.
include($filename);

A: Your echo is too many! You can include file with:
include 'file.php';

Or you can use methods that others have written.
Replace with $cat_id cat_id also!
PS. I counsel you to specify the name of the file that you include without variables.


text:
Q: Linq & ASP.NET MVC: how to use "or" and "equals" in join statement How to translate this sql query in a linq query, please?
USE [BiblioDB]
 GO
 SELECT *
   FROM Exemplaire e
    LEFT JOIN location l
    ON e.ExemplaireId = l.ExemplaireId
    INNER JOIN Retour r
    ON l.LocationId is null or l.LocationId = r.LocationId
 Go

I tried this linq query but the fourth line doesn't work.
 BiblioDBContext biblioDBContext = new BiblioDBContext();
 var query = from e in biblioDBContext.Exemplaires
           join l in biblioDBContext.Locations on e.ExemplaireId equals l.LocationId
           join r in biblioDBContext.Retours on l.LocationId == null || l.LocationId equals r.LocationId r.LocationId
 select e;

A: Try this:
 BiblioDBContext biblioDBContext = new BiblioDBContext();
 var query = from e in biblioDBContext.Exemplaires
     join l in biblioDBContext.Locations on e.ExemplaireId equals l.ExemplaireId into el
     from l in el.DefaultIfEmpty()
     from r in biblioDBContext.Retours
     where (l.LocationId == null) || (l.LocationId.Equals(r.LocationId))
 select new {e, l, r};

The issue is the missing DefaultIfEmpty() clause that is needed for Left Joins.


text:
Q: How to update MalwareBytes on user machines that don't have admin rights? I run a Windows 10 shop. All user PCs have MalwareBytes installed and have in the MalwareBytes settings to auto-update every day. However, the users must be admins to install these updates and therefore the updates never get installed.
I've looked at forums on how to configure MalwareBytes to install updates without needing admin rights but there doesn't seem to be a solution. Could someone recommend a solution?
Solution
Use task scheduler to schedule an administrative task to run the update. Command to run the update is mbam.exe /runupdate. Just go to the directory where you have MalwareBytes installed.

A: Make a Task (Task Scheduler) to run Malwarebytes daily.  Use the settings to give this task Elevated Permissions and set to run daily. You (or an administrator) needs to OK the task to save it.
But then it will run daily for standard users.
Most AntiVirus apps can be set to run this way.


text:
Q: Enabling SSI (ServerSide Includes) in JBoss? Any of you guys have enabled SSI (ServerSide Includes) in JBoss? I guess it should be not difficult as it is built on top of a Tomcat instance.

A: Tomcat already includes in catalina.jar the org.apache.catalina.ssi.SSIServlet so just declare the servlet and attach it to a mapping URL, by setting this in the applications web.xml
<servlet>
    <servlet-name>ssi</servlet-name>
    <servlet-class>
        org.apache.catalina.ssi.SSIServlet
    </servlet-class>
    <init-param>
        <param-name>buffered</param-name>
        <param-value>1</param-value>
    </init-param>
    <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
    </init-param>
    <init-param>
        <param-name>expires</param-name>
        <param-value>60</param-value>
    </init-param>
    <init-param>
        <param-name>isVirtualWebappRelative</param-name>
        <param-value>1</param-value>
    </init-param>
    <load-on-startup>4</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>ssi</servlet-name>
    <url-pattern>*.shtml</url-pattern>
</servlet-mapping>

I put all the parameters, you can see their definition in this Tomcat SSI reference.
As the doc says, SSI can bypass security policies so it must be privileged, do this changing the context.xml located in jboss-web.deploy inside the deploy folder. Just add privileged="true" to the root element.
<Context ... privileged="true">

The servlet will just act as a proxy for the files matching the URL of its mapping.


text:
Q: Share DVD drive over wifi (or lan)? I have two laptops win 8 and win 7. Win 8 has no dvd drive. I want to backup the os and drivers of win 8 using the dvd writer of win 7. Both systems are connected to a wifi router over which I have no control. I can also connect them to a lan network. I tried the instructions on a website and it did not work - http://www.howtogeek.com/114254/how-to-share-cd-dvd-drives-over-the-network-on-windows/
I also tried to use paragon netburner software for this and that also did not help. Is there a simple way to get this done ? Win 8 backup menu allows dvds, but not sure if it allows me to use a network dvd drive.

A: It's very likely that it is not possible to share a DVD drive including the burning capabilities. The link you posted refers to a way to share it as a folder, not as a DVD Burning unit.
My suggestion would be to burn ISO images and then burn them on Win 7:

*

*On Win 8, backup the files to an ISO image.

*Copy the image to Win 7 and burn it into a DVD.


text:
Q: Why && and || cannot be used for nullable type?
Possible Duplicate:
AND operation cannot be applied between nullable bools.

I would expect similar behavior like + or *. So if any of the operand is null, it should return null, but the compile complains if it's used in && or ||. Why?
To illustrate the point:
//this compiles
int? x = null;
int? y = null;
var z = x*y;

// this doesn't compile
bool? x = null;
bool? y = null;
if(x && y)
    ....

A: Probably because && and || are short-circuiting operators. You can use & and | with bool? and I believe you get three-valued logic - null is treated as "unknown". So false & null is false, but true & null is null. This is confusing enough to keep track of, without throwing in short-circuiting too! It's possible that short-circuiting wouldn't actually be any use in the face of null values.
EDIT - On consideration, short-circuiting still makes sense for three-value logic. A logical AND with false on the left will always evaluate false, even if it has null on the right. A logical OR with true on the left will always evaluate true, even if it has null on the right. I imagine this is one of those "not worth the effort to implement" features. Sometimes you need short-circuited Boolean logic. Sometimes you need three-valued Boolean logic. But very rarely do the two overlap.

A: If it were to return null, then you invalidate the boolean requirement.
||
&&
Basically, it would allow for a value other than bool (specifically, null) within an if statement which would be undefined behavior since if statements require boolean expressions.
Interestingly, this is one of the areas where Java and C# differ. Java requires boolean values within the if statement as well, but they allow their version of bool? (Nullable<bool>, or just Boolean in Java) to be null. This leads to somewhat unexpected NullPointerExceptions at runtime, which C# is avoiding with this requirement.

A: Even if (x && y) was possible, result would be bool? and not bool.
If () only works with bool.
Try if (((bool)(x ?? false)) && (bool)(y ?? false)) instead.
Or better yet, following weebles' answer:
If (x & y == true).

A: Nullable types are actually objects. When you apply the nullable operator '?' to a value type (such as bool), it becomes a reference to an object that holds either "null", or the value of the underlying value type.
Consider this:
bool? isActive;

This actually becomes:
Nullable<bool> isActive;

The value type actually becomes an object instance, and therefore doesn't participate in boolean expressions as regular value types do.
More info: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx


text:
Q: Distance at which a 300m asteroid is visible Using the best available telescopes, and assuming a typical albedo of 10%, at what distance can a 300m asteroid be seen (well enough to start plotting its course) in 1) visible and 2) infrared wavelengths?

A: This isn't really an answer, but it got a bit involved to put in as a comment. Anyhow, the nasa.gov site is an absolute mine of information for this sort of thing. The best way to search it is using Google with searches like (in this case) "asteroid detection limits site:nasa.gov". For example this search found articles like http://trs-new.jpl.nasa.gov/dspace/bitstream/2014/7935/1/03-2680.pdf and http://trs-new.jpl.nasa.gov/dspace/bitstream/2014/20572/1/98-1576.pdf both of which discuss the detection limits in some detail. As you'd expect, it's quite complicated. For example an important factor is the speed of the asteroid as an apparently stationary asteroid can't be distinguished from a faint star.
According to those articles the limit of detection is about magnitude 20. If you have a look at http://www.physics.sfasu.edu/astro/asteroids/sizemagnitude.html this tells you how to convert magnitude to diameter and even includes a javascript calculator to do the calculation for you.
I feel as though I bang on about the NASA site quite a bit, but for all that NASA gets criticised they do an excellent job of making information public and it's always worth a quick search of their site. Of course, as a Brit it's not my tax paying for NASA; maybe that makes a difference :-)


text:
Q: Initialising Database Master Tables at App Server Startup Jboss AS 7 i'm using Jboss AS 7 and a Webapp that conncts to database from App Server DataSource. there are tables in Database which i might require to frequently query like Master Tables (e.g Country Master) and populate in dropdown. 'What would be the best method to Query and keep the results in Beans or Data Objects and retrive it from memory whenever required.
any frameworks available or App Server's capability can be usilized ?
pls suggest.

A: Hibernate tool can help you solve this issues. There is a secondary cache level which can help you store the values in the cache through out the application lifetime. (of-course you can delete update the cache when you think it needs to be updated)
Link to the topic here. Managing the secondary cache here, and
example code


text:
Q: all products 95 cents decimal woocommerce Hi all I've got a Woocommerce question,
I was wondering if there is a php function that rounds up all the prices to a decimal to .95 cents.
Example:
$5.66 -> $5.95
$13.23 -> $13.95
$2.54 -> $ $2.95
Thank you!

A: there is no built in function for it you need to make your self
`

<?php
echo myPriceFormat(12.94);
echo '
';
echo myPriceFormat(12.95);
echo '
';
echo myPriceFormat(12.96);
function myPriceFormat($no){
    if( $no<(ceil($no)-0.05) ){
     $no=ceil($no) - 0.05;
    }
    return $no;
}
?>

`


text:
Q: Opening a new activity using both spinners and a button I basically have a spinner displaying an three items. I want it so that if Click on one of these three items and then click a button it will open up a new activity.
 String[] count;
Spinner s;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button view = (Button) findViewById(R.id.button);
    s = (Spinner)findViewById(R.id.spinner);
    count = getResources().getStringArray(R.array.country_array);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,count);
    s.setAdapter(adapter);
    view.setEnabled(false); // initially disable the button
    s.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                                   long id) {
            view.setEnabled(true); // enable when user selects any item
        }
        // Listen to button click
        view.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                //start activity
                startActivity();
            }
        }
    });
    public void startActivity() {
        Intent intent = new Intent(YourCurrentActivity.this, NewActivity.class);
        startActivity(intent);
    }

A: view.setEnabled(false); // initially disable the button
s.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
         view.setEnabled(true); // enable when user selects any item
    }

See how to listen to Button click: Android: how to handle button click
// Listen to button click
view.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                //start activity
                startActivity();
            }
        });

public void startActivity() {
    Intent intent = new Intent(YourCurrentActivity.this, NewActivity.class);
    startActivity(intent);
}


text:
Q: How do I update a TextView that stores an average of list values I have an android activity that consists of a List View and a Text View. The Text view displays information about the summed contents of the list view, if the items in the list view are updated then the Text View needs to reflect the change.
Sort of like an observer pattern but with one component reflecting the changes of many rather than the other way round.
The tasks are displayed as items in the list view and the progress can be updated using a seekbar to set the new progress level.
The following method populates the TextView so I need to call this again from inside the SeekBar onStopTrackingProgress Listener.
private void populateOverviewText() {
TextView overview = (TextView) findViewById(R.id.TaskOverview);

if (!taskArrayList.isEmpty()) {

    int completion = 0;
    try {
    completion = taskHandler.getProjectCompletion();
    overview.setText("Project Completion = " + completion);
    } catch (ProjectManagementException e) {
    Log.d("Exception getting Tasks List from project",
        e.getMessage());
    }
}

}

I realise if I want to call the method from the List Adapter then I'll need to make the method accessible but I'm not sure the best approach to do this.

A: Either make this method public
or you can pass activity to adapter through which you can find the button and update text, or can directly pass Button to adapter...

A: Using DataSetObserver
I was looking for a solution that didn't involve altering the adapter code, so the adapter could be reused in other situations.
I acheived this using a DataSetObserver
The code for creating the Observer is incredibly straight forward, I simply add a call to the method which updates the TextView inside the onChanged() method.
Attaching the Observer (Added to Activity displaying list)
    final TaskAdapter taskAdapter = new TaskAdapter(this, R.id.list, taskArrayList);

    /* Observer */
    final DataSetObserver observer = new DataSetObserver() {
        @Override
        public void onChanged() {
            populateOverviewText();
        }
    };

    taskAdapter.registerDataSetObserver(observer);

Firing the OnChanged Method (Added to the SeekBar Listener inside the adapter)
    public void onStopTrackingTouch(SeekBar seekBar) {
    int progress = seekBar.getProgress();
    int task_id = (Integer) seekBar.getTag();

    TaskHandler taskHandler = new TaskHandler(DBAdapter
        .getDBAdapterInstance(getContext()));

    taskHandler.updateTaskProgress(task_id, progress);

    mList.get(position).setProgress(progress);

    //need to fire an update to the activity
    notifyDataSetChanged();

    }


text:
Q: get the address bar url instead of request url I have the page test_page with the url http://domain.sd/test_page which is in the address bar.
I have used the controller with url filter_details in the same page in ajax response. I want to get the address in the address bar.
Now I can get only the ajax request url
 $url=\Request::getRequestUri();
   echo $url; // output: filter_details

How to get the address in the address bar

A: The PHP-Server only knows the context of a request.
If you use another URL for your ajax request, there is no way for PHP to know the current address displayed in the address bar of your browser.
Try to pass the url in the address bar by parameter / data with the ajax request. You can get your current address in the browser on the client side with window.location and pass it as a query or payload data with your request, depending on your ajax method (GET or POST).