text:
Q: Parse SQS message trigger in AWS Lambda - Python I have a notification on an S3 bucket upload to place a message in an SQS queue. The SQS queue triggers a lambda function. I am trying to extract the name of the file that was uploaded from the SQS message which triggers the lambda function. My SQS event record looks like this when printed to the CloudWatch logs:
{
"Records": [
    {
        "eventVersion": "2.1",
        "eventSource": "aws:s3",
        "awsRegion": "eu-west-2",
        "eventTime": "2020-04-05T13:55:30.970Z",
        "eventName": "ObjectCreated:Put",
        "userIdentity": {
            "principalId": "A2RFWU4TTDGK95"
        },
        "requestParameters": {
            "sourceIPAddress": "HIDDEN"
        },
        "responseElements": {
            "x-amz-request-id": "024EF2A2E94BD5CA",
            "x-amz-id-2": "P/5p5mDwfIu29SeZcNo3wjJaGAiM4yqBqp4p3gOfLVPeZhf+w5sRjnxsost3BuYub1FVf7tuMFs9KoC98+fwSI9NrT5WbjYq"
        },
        "s3": {
            "s3SchemaVersion": "1.0",
            "configurationId": "ImageUpload",
            "bucket": {
                "name": "HIDDEN",
                "ownerIdentity": {
                    "principalId": "A2RFWU4TTDGK95"
                },
                "arn": "arn:aws:s3:::HIDDEN"
            },
            "object": {
                "key": "activity1.png",
                "size": 41762,
                "eTag": "9e1645a32c2948139a90e75522deb5ab",
                "sequencer": "005E89E354A986B50D"
            }
        }
    }
]
}

Using this code:
import boto3
rek = boto3.client('rekognition')

def test(event, context):
    for record in event['Records']:
       print ("test")
       payload=record["body"]
       fullpayload=str(payload)
       print(fullpayload)

Using ['s3]['object]['key'] to access the filename 'activity1.png' on the payload string gives me this error:
's3': KeyError
Traceback (most recent call last):

How can i access the file name from the lambda function?

A: If this is what I think it is: the S3 Object Create events --> SQS <-- lambda polls,
I ran into this also. I was using the s3 put example test and also used my poll from sqs message to make another test. When it came from actually reading the queue not in a test, I had issues.
The output of  print(event) is actually json of the entire event like below:
    {   'Records':
        [
            {
            'messageId': '61155c1d-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
            'receiptHandle': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalF5156pb+aSqhRWbEY1XWIAVpingcBgOM8/uv1pIgfVXtfNRwzjtoCcInH6doGo9C38uWG7V48uEzpiAPr6Ao2IkXn5IEQKgxXzgelT5FtW3gpwhsQ3fvsFZdZNkMj2YiBHpdJ9QDgfmjFOWmqEJL+LWHUyksdAHxqVZMFrdaS1Tmno3Xni7DMBg1Ed+HpHkBmAVOWssDfM25lC1RNUivXj8i3iI/gD0yBlCttA4aioAlYNZ0txBrkm8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaML+jK3JcKXiaslbu+JNZaB7hwevHRNsGIQ2MLuRhX+eHD4BN',
            'body':
                '{"Records":
                  [
                    {
                    "eventVersion":"2.1",
                    "eventSource":"aws:s3",
                    "awsRegion":"us-east-1",
                    "eventTime":"2021-02-24T00:30:07.549Z",
                    "eventName":"ObjectCreated:Put",
                    "userIdentity":{"principalId":"AWS:AROAAAAAAAAAA:Rolehere"},
                    "requestParameters":{"sourceIPAddress":"x.x.x.x"},"responseElements":{"x-amz-request-id":"860A2aaaaaaaB19","x-amz-id-2":"J8epzX+FGaLsliSYSiJaaaaaaaaaaaaaETviVcrVCD/FsQjVLNBJgcv8v/PIh37Y9waaaaaaaaaaaaaaaaoUkoqhlr"},
                    "s3":
                        {"s3SchemaVersion":"1.0",
                        "configurationId":"New arrival",
                        "bucket":
                        {"name":"molly-bucketname","ownerIdentity":{"principalId":"A2aaaaaaFMND3"},"arn":"arn:aws:s3:::molly-bucketname"},
                        "object":{"key":"dietcokeofevil.mp3","size":420049,"eTag":"bf153e303affbb6e54feb0a233879d4d","versionId":"B2WJZpLLvpWA4nXP5T5QjVZY09qpnHKa","sequencer":"0060359E131BAA52C0"}
                        }
                    }
                   ]
                 }',
            'attributes': {
                'ApproximateReceiveCount': '1',
                'SentTimestamp': '1614126612305',
                'SenderId': 'AIDAJHaaaaaaaaaaJEBU',
                'ApproximateFirstReceiveTimestamp': '1614126612308'
            },
            'messageAttributes': {},
            'md5OfMessageAttributes': None,
            'md5OfBody': 'c752a7082100075786323ff7e5cdfc26',
            'eventSource': 'aws:sqs',
            'eventSourceARN': 'arn:aws:sqs:us-east-1:#########:queuename',
            'awsRegion': 'us-east-1'
            }
        ]
    }

When an s3 doesn't deliver to lambda, lambda is reading from the queue - it seems like there's a wrapper around the json you actually see in the put examples. If you tried to add the printed event (above) to your test in lambda, it will json error. We need to parse the initial Records json & for the body
then json.load the "body"- then parse our s3 info out of it.
import json
import boto3

def lambda_handler(event, context):

    #Loops through every file uploaded
    for record in event['Records']:
        #pull the body out & json load it
        jsonmaybe=(record["body"])
        jsonmaybe=json.loads(jsonmaybe)

        #now the normal stuff works
        bucket_name = jsonmaybe["Records"][0]["s3"]["bucket"]["name"]
        print(bucket_name)
        key=jsonmaybe["Records"][0]["s3"]["object"]["key"]
        print(key)

A: What is the output from print(fullpayload)? I would expect payload to be None because there is no attribute named body in the record.
From the example record in your question, you should be doing this:
record['s3']['object']['key']

A: this code for Lambda function Python v3.7
import json
import boto3

def lambda_handler(event, context):
    print("Reciving Message from myQueue SQS")
    for record in event["Records"]:
        message = record["s3"]
        print(message)


text:
Q: Power/HDD/LED wire for motherboard - are they standard these days? I'm not sure what it's called - the set of wires that connect the power button, LED, HDD activity indicator lights - to the motherboard. My question is, are they standard these days? Meaning, if I purchase a motherboard and a case, do I have to be careful to make sure that the plug from the case will fit my motherboard?
To add onto the question, I built one system where they did match up. I have another system, but it was a motherboard from HP and a case from Dell, where the adapter did not match. Perhaps OEMs differ?

A: Usually these lights/switches all have separate cables and connectors. The motherboard's manual will tell you where they go.

A: Generic systems are pretty much standard these days. The only thing you have to worry about is which polarity is correct, but that's just a matter of flipping it around.
OEMs have their own custom specifications, sometimes to add features, sometimes to remove interchangeability.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mathematica 12.1: Evaluation result does not show decimals It surprises me that Mathematica does not show decimals after evaluating the following calculations:
500000+5.05

Result: 500005.
Expecting: 500005.05
500000+5.65

Result: 500006.
Expecting: 500005.65
It is possible to use FullForm[] to see the decimals, but this seems redundant when working with smaller numbers and/or a few decimals.


text:
Q: validate unix timstamp in controller by laravel validation is there anyway to validate incoming unixtime's parameter to server and compare that second one is greather that first one by laravel validation?
my code only validate date format
$this->validate($request, [
            'start_date'    => 'required|date',
            'end_date'   => 'required|date|after_or_equal:start_date',

        ]

A: A timestamp is a number and can be anything between 0 and 2147483647. That's all you can validate. (And of course that one is bigger than the other.)
So, you could do the following:
$this->validate($request, [
    'start_date' => 'required|numeric',
    'end_date' => 'required|numeric|gte:start_date',
]);

*

*numeric will make sure the input is a number

*gte checks if the value is greater than or equal to another number.


text:
Q: Keep away vs. Keep aloof What is the difference between these phrasal verbs or both mean the same.
For instance;
Keep away from my brother
Keep aloof from my brother

A: "Aloof" in this sense is now a literary word. I don't think many people would use it in ordinary conversation, except as an adjective meaning " Lacking affection or warmth of feeling, often in a manner suggesting a (disproportionate) sense of one's own superiority;" (from the OED)
So I would expect to hear

He seems very aloof.

much more often than

He kept aloof from ...

A: To keep away has the meaning that there is planning involved in staying away from your brother. For example, you consciously ignore your brother by not answering his phone calls.
To be aloof / stay aloof /keep aloof has more the meaning of being unpredictable in staying away from your brother. For example, you might be ignoring your brother because you are distracted by something else.


text:
Q: Special symbols are missed in name of file uploaded using Google Sites API The goal: I want to upload file to my Google Classic Site programmatically using Google Sites API.
Used approach: To create a file in my Google Classic Site I use this request with
Content-Type: multipart/related; boundary=END_OF_PART

header and request body like this:
--END_OF_PART
Content-Type: application/atom+xml

<entry xmlns="http://www.w3.org/2005/Atom">
  <category scheme="http://schemas.google.com/g/2005#kind"
            term="http://schemas.google.com/sites/2008#attachment" label="attachment" />
  <link rel="http://schemas.google.com/sites/2008#parent" type="application/atom+xml"
            href="https://sites.google.com/feeds/content/domainName/siteName/PARENT_ENTRY_ID"/>
  <title>File Title</title>
  <summary />
  <content type="xhtml">
    <div xmlns="http://www.w3.org/1999/xhtml" />
  </content>
  ...
  <-- Other matadata here -->
</entry>

--END_OF_PART
Content-Type: <file mime type here>

... file contents here ...

--END_OF_PART--

The problem: When File Title starts with symbols like '_' (underscore), '%' (percent sign), '*' (asterisk), '&' (ampersand) request is successfully executed and file on my Google Classic Site in created with right content but with different title - no symbols listed above at the beginning of file name.
Is this known issue in Google Sites API? What I do wrong? How can I handle this problem?


text:
Q: jquery - toggle number of divs I want to have number of URLs that toggle different hidden divs
BTN
BTN

  text here
  CLOSE DIV

here is the script code (just because i need some text in my message...):

    text here
    CLOSE DIV

A: Your code should be like following.

$(".hidenBox").hide();

$(".toggleBtn").click(function () {
     var div = this.id.split('_')[0];
     $('#' + div).toggle();
});

$(".hideBoxBtn").click(function () {
     $(this).closest(".hidenBox").toggle();
});

BTN
BTN

    text here 1
    CLOSE DIV

    text here 2
    CLOSE DIV

A: $( ".hidenBox" ).hide();

$( ".toggleBtn" ).click( function(){
        var div = $(this).attr('id');

        $( "#" + div + "_box" ).toggle();
} );

$( ".hideBoxBtn" ).click( function(){
        $( this ).closest(".hidenBox").toggle();
} );


text:
Q: lost data when i refresh the page react Hi I want to show a page with id which is a form from a list of forms, it works but when I refresh the page I lost data and get an error
this is the code
function FormFinal() {
    const { id } = useParams();

    const forms = useSelector((state) => state.forms.data)

    const specificForm = forms.find((elem) => elem._id === id)

and this is how I'm trying to show data
<div className='title-compagny'> Entreprise: {specificForm.compagnyName </div>

this is the route on my api:

formRouter.get('/:formId', formController.getForm)

and the route on the front:
   <Route exact path="/final-form/:id">
    <FormFinal /></Route>

on refresh I'm getting this message: TypeError: Cannot read property 'compagnyName' of undefined


text:
Q: NetBeans - how to set default startup Maven module in multi-module maven project? I'm looking for the way to configure Netbeans workspace for multi-module maven project to always start some module when pressing CTRL+F5 (Debug main project). Being within maven project this shortcut always starts the project whose source file is currently being open. This is annoying - to start debugger i always have to either switch to some source file from the 'main' module or find that module in project explorer (huge sub-tree) and right click -> Debug (both are regular useless waste of time )
Similar question is about re-running last unit test - i can't find shortcut for this, but i see related bug report is not addressed since Aug 2010: http://netbeans.org/bugzilla/show_bug.cgi?id=189113.

A: You have to put that action specified in the nbactions.xml like:
<action>
    <actionName>debug</actionName>
    <packagings>
        <packaging>jar</packaging>
    </packagings>
    <goals>
        <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
    </goals>
    <properties>
        <jpda.listen>maven</jpda.listen>
        <exec.args>-classpath %classpath com.domain.package.Main start</exec.args>
        <exec.executable>java</exec.executable>
        <exec.workingdir>./content</exec.workingdir>
    </properties>
</action>

So it will excecute the Main file in a module of your proyect.
If you want to excecute a Main java file of a dependency project you must include this plugin entry:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
                    </configuration>
                </execution>
        </plugin>

This will allow your maven project to copy all dependencies you need to your target during packaging phase. Then use this other plugin entry for making the Main class you need accessible:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>com.domain.package.Main</mainClass>
                        <classpathPrefix>dependency-jars/</classpathPrefix>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

You may change the folder where dependency jars will be or even make it a property in the pom.xml of your parent maven project.


text:
Q: If you miss that train then you'll have to get a taxi Some dictionary said, 'If you miss that train then you'll have to get a taxi.' Is it wrong not to use a comma  between an if-clause and a main clause? I'm confused because this is from an Oxford dictionary.

A: If a conditional clause comes before the main clause, a comma is used.
Examples from Cambridge Dictionary (https://dictionary.cambridge.org/us/grammar/british-grammar/conditionals):
If you see Dora, will you give her a message? (conditional clause first; a comma is normally used in writing)
I'll go to Bristol tomorrow if the weather is good. (conditional clause second; a comma is not normally used in writing)


text:
Q: Internet not working after enabling Power on by PCI-E I tried to setup wake on lan for my Ubuntu 19.04 PC. According to the docs I should enable "Power on PCI-E" option in a BIOS. Which i did. Set up ethetool and so on. After some time I started feeling that something is wrong with my internet connection. The first noticed problem was that my internet does not work immediately after power on. So what I saw is I had no connection for 3 minutes and then got back. I was thinking that's ok, maybe its tradeoff of the WOL. But the next day I completelly had no internet connection. I rebooted many times, I tried to play with the settings (reset them all) and the only thing that helped me was turned off "Power on PCI-E" option in BIOS.
My question is how can I setup WOL and do not have problems with my internet connection?
Additional info I set up my wol to the network interface (sorry if the terminology isn't right) named ent0s5 which is responsible for internet connection too as I see.
Update: I'm still having issue with my internet connection. It boots up randomly after restart of PC
Update 2: When i try to go for any website I see "err_proxy_connection_failure" error
Update 3: NAT forwarding from my router.


text:
Q: Object Cannot Be Cast to ArrayList I'm having some trouble with reading an arraylist from file in Java.
I have a "User" class which implements Serializable, so when I go to save an ArrayList of these users it seems to work fine - but when I try read them it's a different story.
ava.lang.ClassCastException: User cannot be cast to java.util.ArrayList
The Code I have for reading in is as follows ..
 private List<User> userList = new ArrayList<User>();

public void readList() throws FileNotFoundException, IOException, ClassNotFoundException
{
    System.out.println("Trying to read list..");
    FileInputStream fis = new FileInputStream("userList.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    System.out.println("Created Streams....");
    userList = ((ArrayList<User>)ois.readObject());
    ois.close();
}

Has anyone has similar problems or know how to help me out?
Thanks.

A: If you want to deserialize an ArrayList out of the stream, then you must be sure to serialize an ArrayList into the stream. The way you've serialized your User objects, you would be required to deserialize them like so:
private List<User> userList;

public void readList() throws FileNotFoundException, IOException, ClassNotFoundException {
    System.out.println("Trying to read list..");
    this.userList = new ArrayList<User>();
    FileInputStream fis = new FileInputStream("userList.txt");
    try {
        ObjectInputStream ois = new ObjectInputStream(fis);
        System.out.println("Created Streams....");

        // you would want to store this number in your object stream as userList.size()
        int numberOfUsersSerialized = 5;
        for (int i = 0; i < numberOfUsersSerialized; i++) {
            userList.add((User) ois.readObject());
        }
    } finally {
        fis.close();
    }
}


text:
Q: Problem with Velocity of efflux I am stuck in this problem-

I need to find the velocity of efflux at the hole of the container. [We can assume that the area of the hole is negligible in comparison with the base area of the container].
Here's my approach
Velocity of liquid at the upper-surface = $v_2$
Velocity of efflux (velocity of water at the hole, right?) = $v_1$
Using Bernoulli's equation for the surface and the hole -
$$
P_{atm} + \rho_2 g (h_1 + h _2) + \frac{1}{2}\rho_2 v_2^2 = P_{atm} + \rho_1 g h_1 + \rho_2 g h_2 + \frac{1}{2}\rho_1 v_1^2 \\
\implies \rho_2 g h_1 + \rho_2 g h_2 - \rho_1 g h_1 - \rho_2 g h_2 = \frac{1}{2}(\rho_1 v_1^2 - \rho_2 v_2^2) \\
\implies \frac{1}{2}(\rho_1 v_1^2 - \rho_2 v_2^2) = g h_1 (\rho_2 - \rho_1)
$$
Now, let area of the base be $A_2$ and that of the hole be $A_1$
then, using equation of continuity,
$$
A_1 v_1 = A_2 v_2 \\
\implies v_2 = \frac{A_1}{A_2} v_1 \\
\implies v_2 \approx 0  (\because {A_1 << A_2})
$$
Using this value in the previous Bernoulli's relation
$$
\frac{1}{2}(\rho_1 v_1^2) = g h_1 (\rho_2 - \rho_1) \\
\implies \frac{1}{2} \rho_1 v_1^2 = g h_1 (\rho_2 - \rho_1) \\
\implies v_1 = \sqrt {\frac {2gh_1(\rho_2 - \rho_1)}{\rho_1}}
$$
Which is not the correct answer.
I did get a correct answer in the chat room, but it was using a different method.
What's wrong with my method?

A: Why do you want to use continuity at all? It is not valid in this case simply because all the fluid in the container is not going to come out of the orifice. Suppose you had a pipe whose diameter was being reduced, you'd be able to apply continuity because all fluid going through section A on the pipe would have to go through section B.
Additionally, Bernoulli's equation fully resolves the problem for you, so there is no need to use equation of continuity.
\begin{align}
\frac{\rho1 * v_{efflux}^2}{2} &= P_{bottom} - P_{atm} = g * (\rho_1 * h_1 + \rho_2 * h_2) \\
v_{efflux} &= \sqrt{\frac{2g * (\rho_1 * h_1 + \rho_2 * h_2)}{\rho_1}}
\end{align}


text:
Q: MDP implementation using python - dimensions I have problem in implementing mdp (markov decision process) by python.
I have these matrices: states: (1 x n) and actions: (1 x m)
.Transition matrix is calculated by this code:
p = np.zeros((n,n))
for t in range(l): # my data is a 1x100 matrix
p[states[t]-1, states[t+1]-1] = p[states[t]-1, states[t+1]-1] + 1
for i in range(n):
p[i,:] = p[i, :] / np.sum(p[i, :])

and Reward matrix by this code:
for i in range(l):
Reward = (states[i+1]-states[i])/(states[i])*100

To have the optimal value, "quantecon package" in python is defined by:
ddp = quantecon.markov.DiscreteDP(R, Q, beta)

where Q : transition matrix should be m x n x m.
Can anyone help me understand how Q can be a (m,n,m) matirx?!
Thank you in advance.

A: If you have n states and m actions, Q will be an array of shape (n, m, n) (not (m, n, m)), where you let Q[s, a, t] store the probability that the state in the next period becomes the t-th state when the current state is the s-th state and the action taken is the a-th action.


text:
Q: Proof that a model has a higher $R^2$ if F > 1 I need to prove that a model has a higher adjusted $R^2$ than another model if the F-statistic is greater than 1. Below is as far as I've gotten, but I'm not even sure if that's correct.
$$R^2_{adj} = 1 - \frac{\frac{SSR}{(n - k)}}{\frac{SST}{(n - 1)}}$$
$$F = \frac{MSR}{MSE} = \frac{\frac{SSR}{1}}{\frac{SSE}{n-2}}$$
Let $F > 1$ so $$\frac{\frac{SSR}{1}}{\frac{SSE}{n-2}} > 1$$ $$SSR > \frac{SSE}{(n-2)}$$ $$SSR > \frac{SSE}{p - (q + 1) - 2}$$ $$SSR > \frac{SSE}{p - q - 3}$$
Where do I go from here to complete the proof, and is the above even correct?


text:
Q: issues when Iterate Map with list as value using groovy def map  = new HashMap<String,List<String>>()
def list = new ArrayList<String>()
def list1 = new ArrayList<String>()
list.add("hello1")
list.add("world1")
list.add("sample1")
list.add("sample1")
list1.add("hello2")
list1.add("world2")
list1.add("sample2")
list1.add("sample2")
map.put("abc",list)
map.put("bcd",list1)
def data = new ArrayList<String>()
for(e in map){
println "key = ${e.key} value=${e.value}"
// data = "${e.value} as String[]"
data = "${e.value}"
println "size ${data.size()} " --(B)

check(data)
}
def check(input)
{
println "${input.size()}" ---(A)
for(item in input){
print "$item  "}
}

I have to pass string[] to another java function from this groovy script. so I am trying to read the array list and then convert it into String array. But the problem is when I assign {e.value} to variable data and try to get the size data.size() (both step (A) and (B) ). and the size is 34. It is counting each character not the word as whole from the list. I want to iterate over each word from the list. Kindly let me know how to resolve this problem.
sample output is
key = abc value=[hello1, world1, sample1, sample1]

size 34

A: Here is the groovified vesion of creating the map and accessing it:
def map = [abc:['hello1', 'world1','sample1', 'sample1'], bcd:['hello2', 'world2','sample2', 'sample2']]
map.collect{ println "key: ${it.key}, list: ${it.value}, and size: ${it.value.size()}" }

Output:
key: abc, list: [hello1, world1, sample1, sample1], and size: 4
key: bcd, list: [hello2, world2, sample2, sample2], and size: 4

If you want to convert a list to an array you can just do it:
def list = ['hello1', 'world1','sample1', 'sample1']
assert list instanceof List
def array = list as String[]
assert array instanceof String[]
assert !(array instanceof List)


text:
Q: How to use Database login and Azure AD Authentication both in a react app at same time? I have created a react app in which I have a login page as the first page and there are two ways to login into it, first one is using Azure AD and second is database login.
I have implemented the Azure ad login part with the help of protected routes and all the stuff.
Now in the same app I want to implement the Database Login but I'm unable to do so.
So how it can be done. If anyone can help me in this?
App.tsx code:-
import './css/App.css';
import { AuthenticatedTemplate, UnauthenticatedTemplate } from '@azure/msal-react';
import { Login } from './auth/Login';
import Routers from './components/Router/Routers';

function App() {
  return (

        <Routers />

  );
}

export default App;

index.tsx code:-
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./auth/authConfig";

const msalInstance = new PublicClientApplication(msalConfig);
const container = document.getElementById("root");
const root = createRoot(container!);

root.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>
);

module.hot?.accept();

Auth.tsx code:-
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import {
    AuthenticatedTemplate,
    UnauthenticatedTemplate,
} from "@azure/msal-react";
import { useIsAuthenticated } from "@azure/msal-react";

export const PrivateRoutes = () => {
    const location = useLocation();
    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? (
            <AuthenticatedTemplate>
                <Outlet />
            </AuthenticatedTemplate>
        )
        : <Navigate to="/Login" replace state={{ from: location }} />;
}

export const AnonymousRoutes = () => {

    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? <Navigate to="/Home" replace />
        : (
            <UnauthenticatedTemplate>
                <Outlet />
            </UnauthenticatedTemplate>
        );
}

Router.tsx code:-
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import { Login } from "./pages/Login";
import { AnonymousRoutes, PrivateRoutes } from '../components/auth';

function Routers() {
  return (

      <BrowserRouter>
        <Routes>
          <Route element={<PrivateRoutes />}>
            <Route path="/" element={<Home />} />
            <Route path="/Home" element={<Home />} />
            <Route path="/About" element={<About />} />
            <Route path="/Contact" element={<Contact />} />
          </Route>
          <Route element={<AnonymousRoutes />}>
            <Route path="/login" element={<Login />} />
          </Route>
        </Routes>
        <Outlet />
      </BrowserRouter>

  );
}

So now with this code I want to implement database login also. Please suggest the possible way.


text:
Q: Authentication AWS Cognito SRP I am writing a console POC to demo AWS cognito authentication - App Pool not federated identity, as our API gateway authentication mechanism (not hosted in AWS). This is being written in C#.
I have successfully created a user, confirmed them; but now I need to authenticate to retrieve a JWT that an I can pass around and validate downstream.
The following code
 using (var client = new AmazonCognitoIdentityProviderClient())
            {
               var initAuthRequest = new InitiateAuthRequest();
                   initAuthRequest.AuthParameters.Add("USERNAME", username);
                   initAuthRequest.AuthParameters.Add("PASSWORD", password);
                   initAuthRequest.ClientId = clientId;
                   initAuthRequest.AuthFlow = AuthFlowType.USER_SRP_AUTH;
                   var response = client.InitiateAuth(initAuthRequest);
                   WriteLine("auth ok");
            }

Yields this exception:

An unhandled exception of type
  'Amazon.CognitoIdentityProvider.Model.InvalidParameterException'
  occurred in AWSSDK.Core.dll
Additional information: Missing required parameter SRP_A

I cannot find a way in the dotnet sdk of generating an SRP header, can anyone help?
Thanks
KH

A: There is actually a new extension class, helping with exactly that. Just search for this NuGet package:
AWSSDK.Extensions.CognitoAuthentication

The GitHub repository can be found here.
Some examples can be found here. The very first code example shows you how to do the SRP-flow.

A: Cognito User Pools does not support SRP authentication from .NET SDK. You will not be able to use AuthFlowType.USER_SRP_AUTH with the InitiateAuth API call.
If you want to sign-in using a USERNAME and PASSWORD directly, you can look at the Admin Authentication flow which uses the AdminInitiateAuth API and ADMIN_NO_SRP_AUTH flow.

A: As already stated by Chetan, SRP authentication is not supported by the .NET SDK. However, it should be possible by using some 3rd party implementation of the SRP procedure which can be found here.
According to some comments on Github, this code should work (but unfortunately the custom SRP authentication implementation did not work for me but maybe it works for you).

A: I want to preface that am not familiar with the AWS .NET SDK; however, the following may provide helpful insight.
AWS provides a Cognito Identity helper library in JavaScript amazon-cognito-identity-js you can review the source code specifically the AuthenticationHelper.js file as it contains logic used to calculate SRP. Furthermore, there is a method to calculate SRP_A which is the parameter required for invoking the "initiateAuth" API method. Hopefully this helps you move forward in the correct direction.
As a side note, you may notice that the amazon-cognito-identity-js library has dependency on a big integer library to handle loss of significance issues intrinsic to the JavaScript Number data type that effects accuracy of precision. Primarily, I mention this as I am not familiar whether or not this arithmetic issue is relevant in the context of .NET as it relates to SRP calculations.


text:
Q: Can't find target runtime in maven project I'm using Eclipse Java EE IDE (Juno).
When I right click my project then click Properties I Can't find target runtime.
What I want to do is to connect my project with Tomcat.
I have other Maven project where I have target runtime, see below:

Any idea how to solve this?
== Update (solution): ==============================
Maven project is not a Java EE project

A: Do you have project facets enabled ?

A: Select Artifact id as a maven-archetype-webapp when you are creating a maven project.


text:
Q: Qt/Embedded: Caps Lock is not working I am developing an application with Qt/Embedded 4.8.4(c++ bindings).I found that enabling caps lock is not putting the characters in capital letter inside the edit-box. Here is a simple program for your reference, which is showing same behavior.
#include <QApplication>
#include <QMainWindow>
#include <QLineEdit>

int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QMainWindow *win = new QMainWindow(0);
    win->move(50,50);
    win->resize(500, 500);
    win->show();

    QLineEdit *edit = new QLineEdit(win);
    edit->move(30, 30);
    edit->resize(100, 30);
    edit->show();

    return a.exec();
}

In the editbox, characters, you are typing, will appear in small case , no matter you have set the caps lock state
Re: For you information I am using LinuxInput as the input driver for both of keyboard and mouse

A: It is possible that the key map used by the Qt Window Server (QWS) is has the wrong setting for the caps Lock key (keycode 58). I had this problem and was able to fix it as follows.
To generate a custom keyboard mapping I followed the method in this post: Qt Embedded for Linux. Keyboard layout switching
However, before running kmap2qmap I edited the kmap file so that keycode 58 used Caps_Lock rather than CtrlL_Lock
I then passed the generated qmap file as an input to the keyboard driver:
export QWS_KEYBOARD="LinuxInput:keymap=/path/to/xx.qmap"
./myApp -qws


text:
Q: Using vapply to assign function to coordinates I'm being threatened with having to hand draw hundreds of circles in PowerPoint with a very short turnaround and so I'm looking to R to do this for me. Forgive me, I've never programmed before, and I'm leaping straight in.
Essentially I'm drawing a scatterplot on a timeline. This I've done easily using ggplot2. Unfortuantely due to the hundreds of dots involved I need to be able to space them out so all can be seen. Jitter is not an option as I don't know my final number of dots. Therefore, I'm trying to build something which will eventually know how many dots are in a quadrant. First of all, I'm trying to assign my co-ordinates a value within a range:
    getxcordinate <- function (x) {
  x <- as.numeric(x)
  runif(1,x-1,x)
}

getycordinate <- function (y) {
    y<- as.numeric(y)
    runif(1,y-1,y)
}

getxcordinate(x = my.data$t_score[1])
getycordinate(y = my.data$Geography[1])

#Precreate the offset as numeric x-y coordinates that so that the points and the text can refer to the same coordinates later
my.data$moved_t_score <- vapply(my.data$t_score,getxcordinate, any)
my.data$moved_Geography <- vapply(my.data$moved_Geography,getycordinate, any)

From the help I can see that vapply needs something called FUN.VALUE in order to work. I tried "any" but that was optimistic - what is it I should be doing?
Thanks!


text:
Q: Angular PayPal Processing, Childcomponent and Lifecycle I am currently working on the PayPal integration in my own shop (Angular Frontend, dotnet core WebApi backend) and apparently I have a problem with the life cycle between the main component (CheckoutProcessComponent) and the child component (PaymentPayPalComponent) and with the use of the necessary PayPal javascript.
Basically the complete PayPal workflow works as long as I use static variables. And this is exactly where my problem starts.
CheckoutProcessComponent.ts
import { Component, OnInit } from '@angular/core';
import { CartService } from 'src/app/_services/shop/cart.service';
import { ISubscriptionCollection } from 'src/app/_models/misc/ISubscriptionCollection';
import { serialUnsubscriber } from 'src/app/shared/utility.module';
import { CheckoutService } from 'src/app/_services/checkout/checkout.service';
import { ICheckoutOrderData } from 'src/app/_models/shop/ICheckoutOrderData';
import { IOrderProcessSummary } from 'src/app/_models/shop/IOrderProcessSummary';

@Component({
  selector: 'app-checkout-process',
  templateUrl: './checkout-process.component.html',
  styleUrls: ['./checkout-process.component.css']
})
export class CheckoutProcessComponent implements OnInit {
  subscriptions: ISubscriptionCollection = {};

  checkoutOrderData = {} as ICheckoutOrderData;
  orderSummaryFromServer: IOrderProcessSummary;
  orderCreated: boolean = false;

  constructor(public checkoutService: CheckoutService, public cartService: CartService) { }

  ngOnInit() {
    this.checkoutOrderData.Order = this.checkoutService.orderData;
    this.checkoutOrderData.Cart = this.cartService.shoppingCart;
    // Create Order
    this.subscriptions['createOrder'] = this.checkoutService.createOrder(this.checkoutOrderData)
      .subscribe((res: IOrderProcessSummary) => {
        this.checkoutService.checkoutSummary = res;
        this.orderSummaryFromServer = res;
        console.log('Order created: ' + res);
      }, error => {
        console.log('Error');
      });
  }

  ngOnDestroy(): void {
    serialUnsubscriber(...Object.values(this.subscriptions));
  }

  nextStep(step: number) {
    this.checkoutService.updateCheckoutStep(step);
  }
 ...
}

CheckoutProcessComponent.html
<app-payment-paypal [orderSummary]="orderSummaryFromServer" *ngIf="checkoutService.orderData.paymentMethod === 'PM_PAYPAL'"></app-payment-paypal>
<app-payment-stripe *ngIf="checkoutService.orderData.paymentMethod === 'PM_STRIPE'"></app-payment-stripe>
<app-payment-moneytransfer *ngIf="checkoutService.orderData.paymentMethod === 'PM_TRANSFER'"></app-payment-moneytransfer>

PaymentPayPalComponent.ts
import { Component, OnInit, AfterViewChecked, Input } from '@angular/core';
import { environment } from 'src/environments/environment';
import { IOrderProcessSummary } from 'src/app/_models/shop/IOrderProcessSummary';
import { CheckoutService } from 'src/app/_services/checkout/checkout.service';

declare let paypal: any;

@Component({
  selector: 'app-payment-paypal',
  templateUrl: './payment-paypal.component.html',
  styleUrls: ['./payment-paypal.component.css']
})
export class PaymentPaypalComponent implements OnInit, AfterViewChecked {
  @Input() orderSummary: IOrderProcessSummary;

  paypalClientId = environment.paymentPayPal.clientId;
  addScript: boolean = false;
  scriptTagElement: HTMLScriptElement;
  constructor(private checkoutService: CheckoutService) { }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    if (this.scriptTagElement) {
      document.body.removeChild(this.scriptTagElement);
    }
  }

  ngAfterViewChecked(): void {
    if (!this.addScript) {
      this.addPayPalScript().then(() => {
        paypal.Buttons({
          createOrder: function() {
            return fetch('https://localhost:5021/api/payments/paypal-create-order', {
              method: 'post',
              headers: {
                'content-type': 'application/json'
              },
              body: JSON.stringify({
                orderId: 1234
              })
            }).then(function(res) {
              return res.json();
            }).then(function(data) {
              return data.id; // Use the same key name for order ID on the client and server
            });
          },
          onApprove: function(data, actions) {
            console.log('onApprove - transaction was approved, but not authorized', data, actions);
            actions.order.get().then(details => {
                    console.log('onApprove - you can get full order details inside onApprove: ', details);
            });

            return fetch('https://localhost:5021/api/payments/paypal-capture-order', {
              method: 'post',
              headers: {
                'content-type': 'application/json'
              },
              body: JSON.stringify({
                token:   data.orderID,
                payerID: data.payerID,
              })
            });
          },
          onClientAuthorization: (data) => {
            console.log('onClientAuthorization - you should probably inform your server about completed transaction at this point', data);
            // this.showSuccess = true;
          },
          onCancel: (data, actions) => {
            console.log('OnCancel', data, actions);
            // this.showCancel = true;
          },
          onError: err => {
            console.log('OnError', err);
            // this.showError = true;
          }
        }).render('#paypal-button-container');
      })
    }
  }

  addPayPalScript() {
    return new Promise((resolve, reject) => {
      this.scriptTagElement = document.createElement('script');
      this.scriptTagElement.src = 'https://www.paypal.com/sdk/js?currency=EUR&client-id=' + this.paypalClientId;
      this.scriptTagElement.onload = resolve;
      document.body.appendChild(this.scriptTagElement);
      this.addScript = true;
    })
  }

}

PaymentPayPalComponent.html

The processing flow is as follows:

*

*CheckoutProcessComponent > creates the order on the server with the cart data and stores the order in the database (general function, non PayPal related)

*The result from 1. is of IOrderProcessSummary which holds the order Id and the total of the order

*Depending on the selected payment method, the corresponding payment-Child Component will be displayed. In this case the PaymentPayPalComponent.

*Then I use the PayPal-feature "CreatePayPalOrderOnServer" which uses the PayPal Api in my backend to create an order on the PayPal server. But for that I need the specific orderId because I need to fill the PayPal-Order data with the specific order data from my system (in the example I have a fixed 1234 order Id).

For step 4. I tried it with Input()-parameter and with injecting the CheckoutService to the PaymentPayPalComponent but I am not able to work with any kind of dynamic variables within the PayPal-Button-Function (JavaScript). In the example I need to change the "orderId: 1234" with a value from the Input() orderSummary or the same value from the CheckoutService, but both of them stay undefined.
The PayPal-Javascript is loaded correctly and the PayPal-Buttons show up and work as intended technically.
How do I bring my dynamic data into the PaymentPayPalComponent and into the PayPal.Buttons-Function?
Thanks for your tips!


text:
Q: How to Convert Vue 2 x to Vue 3 x? We are integrating Vue into an existing ASP.Net MVC Application
Below  code (Vue 2 X)working fine in our .Net Application
new Vue({
  el: '#component1',
  render: h => h(App)
});

To convert Vue 2 X to Vue 3 X used command "vue add vue-next" , after executing command version changed  but  "npm run build" command giving error.

A: You can use the Vue 3 migration build to help with the upgrade. It shims most of the Vue 2 code, while emitting console warnings that help you identify what to migrate.
To enable it in your Vue CLI project (based on installation steps from the migration guide), and to fix the code you mentioned:

*

*Update vue to 3.1, and install @vue/compat of the same version:
npm i -S @vue/compat@^3.1.4
npm i -S vue@^3.1.4

*Setup an alias from vue to @vue/compat:
// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.resolve.alias.set('vue', '@vue/compat')
  }
}

*Update the app entry to the new global mounting API:
// import Vue from 'vue'
// import App from './App.vue'
// new Vue({ el: '#component1', render: h => h(App) });

import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#component1')


text:
Q: Visualising frequency of events from time series I have a series like this:
00:00:08,00:00:24,00:00:27,00:00:36,00:00:36,00:00:37,00:00:42,00:00:43,00:00:44,00:00:47,00:00:54,00:00:57,00:00:57,00:01:09,00:01:16,00:01:18,00:01:21,00:01:25,00:01:26,00:01:33,00:01:33,00:01:33,00:01:38,00:01:44,00:01:45,00:01:53,00:01:57,00:02:01,00:02:03,00:02:19,00:02:20,00:02:33,00:02:33,00:02:34,00:02:48,00:02:50,00:03:12,00:03:21,00:03:23,00:03:24,00:03:28,00:03:34,00:03:34,00:03:35,00:03:38,00:03:39,00:03:40,00:03:40,00:03:42,00:03:42,00:03:48,00:03:49,00:03:54,00:03:55,00:04:03,00:04:06,00:04:07,00:04:10,00:04:11,00:04:16,00:04:21,00:04:26,00:04:27,00:04:27,00:04:28,00:04:30,00:04:33,00:04:41,00:04:49,00:04:50,00:04:51,00:04:54,00:04:55,00:04:59,00:05:16,00:05:16,00:05:27,00:05:34,00:05:37,00:05:46,00:05:50,00:05:53,00:06:07,00:06:16,00:06:24,00:06:25,00:06:26,00:06:30,00:06:38,00:06:38,00:06:42,00:06:44,00:06:46,00:06:53,00:07:00,00:07:00

It is time in HH:MM:SS (as series in time dataframe)
I'm interested in finding / visualising amount of data points in (for example) 10 second window and plotting it as histogram barplot.

A: # make it a list
time_series = "00:00:08,00:00:24,00:00:27,00:00:36,00:00:36,00:00:37,00:00:42,00:00:43,00:00:44,00:00:47,00:00:54,00:00:57,00:00:57,00:01:09,00:01:16,00:01:18,00:01:21,00:01:25,00:01:26,00:01:33,00:01:33,00:01:33,00:01:38,00:01:44,00:01:45,00:01:53,00:01:57,00:02:01,00:02:03,00:02:19,00:02:20,00:02:33,00:02:33,00:02:34,00:02:48,00:02:50,00:03:12,00:03:21,00:03:23,00:03:24,00:03:28,00:03:34,00:03:34,00:03:35,00:03:38,00:03:39,00:03:40,00:03:40,00:03:42,00:03:42,00:03:48,00:03:49,00:03:54,00:03:55,00:04:03,00:04:06,00:04:07,00:04:10,00:04:11,00:04:16,00:04:21,00:04:26,00:04:27,00:04:27,00:04:28,00:04:30,00:04:33,00:04:41,00:04:49,00:04:50,00:04:51,00:04:54,00:04:55,00:04:59,00:05:16,00:05:16,00:05:27,00:05:34,00:05:37,00:05:46,00:05:50,00:05:53,00:06:07,00:06:16,00:06:24,00:06:25,00:06:26,00:06:30,00:06:38,00:06:38,00:06:42,00:06:44,00:06:46,00:06:53,00:07:00,00:07:00"
time_series = time_series.split(',')

def histogram_from_time_series(_time_series):
    time_list = []

    for item in _time_series:
        t = item.split(":")
        try:
            time_list.append(datetime.datetime(year= 1970, month=1, day=1, hour=int(t[-3]), minute=int(t[-2]), second=int(t[-1]))) # has to be a datetime for it to work
        except IndexError:
            time_list.append(datetime.datetime(year= 1970, month=1, day=1, minute=int(t[-2]), second=int(t[-1])))

    _dict = {'Timestamp': time_list,} # make a dict from list
    _df = pd.DataFrame(_dict)   # make df from dict

    _df.insert(0, 'A', 1) # create a column and fill it with int(1)

    grouped = _df.groupby(pd.Grouper(key="Timestamp", axis=0, freq='30S')).sum() # group in given frequency and sum the 'A'
    # https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases

    grouped.plot.bar(grid=True, figsize=(9,9)) # plot histogram

histogram_from_time_series(time_series)

Ok so I did it myself. Sharing if someone needs it later.


text:
Q: Proxy an HTTP Live Stream via a secure, tokenized URL in Java I'm trying to proxy an HTTP Live Stream through a Java servlet.  Essentially, the proxy will act as the endpoint for the encrypted, tokenized URL.  The servlet will then decrypt the URL and, if valid, request the HTTP Live Stream video from the streaming server and return the stream to the client.  Obviously, I never want the actual URL to the streaming content to be sent to the client, nor for the client to access it directly - I always want the stream to pass through the proxy.
Since the HTTP Live Stream is just HTTP, I assumed a simple HTTP proxy would work. However, I have not had any luck.  I have gotten it as far as the browser knowing to display the video player (it's receiving the correct MIME type), and I can see the network request grow to the size of the video stream.  Unfortunately, the video never actually plays.
Ideally, I would love to use an existing product (open source preferable), but I'm happy to roll my own if none is available (although I can't imagine I'm the only one who wants to do this).
Any thoughts/suggestions/solutions would be greatly appreciated!


text:
Q: Append somecode to all links in a div I want to append a code after all links with mp3 extension in a specific div.
Here is the code I am trying :
$("#Temp_Div").find('a[href$="mp3"]').append('');

The problem is $(this).href It doesn't return the href of link. it returns undefined

A: If this is a DOM object you should just be using:
this.href

The (more verbose, less efficient) jQuery way of writing it would be:
$(this).attr('href');

In any event, the .append() call won't work as written because this isn't actually being set at all.
You need to call .each() with the matched elements with a callback function.  jQuery will then ensure that this is set to the current DOM object.
Like this:
$("#Temp_Div").find('a[href$="mp3"]').each(function() {
    $(this).append('');
});

A: href is an attribute so you have to use the attr function, example:
$("#Temp_Div").find('a[href$="mp3"]').each(function() { $(this).append(''); });

Your can review the documentation

A: This should work for you:
$("#Temp_Div").find('a[href$="mp3"]').each(function() {
    $(this).after('');
});

this will refer to the a tag. (You don't need to wrap it in a jquery object to get the href)
I think you also want to use after rather than append as this will add the link after the other link rather than inside it.
Example

A: Try $(this).attr('href') instead, this should work.

A: Try this.href if the element is anchor


text:
Q: Using setId() to assign known Ids from variable I have a RelativeLayout, with four rows of three buttons. I have the IDs created in an XML file like so:
<resources>
    <item type="id" name="row1" />
    <item type="id" name="button1" />
    <item type="id" name="button2" />
    <item type="id" name="button3" />
    <item type="id" name="row2" />
    <item type="id" name="button4" />
    <item type="id" name="button5" />
    ...
</resources>

And I can find which button was pressed with this:
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button1:
            // do something
            break;
        case R.id.button2:
            // do something else
            break;
        case R.id.button3:
            // i'm lazy, do nothing
            break;
    }
}

But I can't figure out how to assign the IDs to the buttons when they're being created in the loop. Ideally I'd like to use setId(R.id.myKnownId) in a loop, but I can't.
Does anyone have any idea how I could do this, other than hard-coding it in after the buttons have been created?
Edit: Code added.
for ( int j = 1 ; j < 5 ; j ++ ) {
        int rowtemp = j;
        currentRow.setTag("row"+rowtemp);
        currentRow.setId(rowtemp); //<-- I want to add R.id.definedId here

        for (int i = 1; i < 4; i++) {

            Button btn = new Button(this);
            int temp = buttonNumber;
            btn.setId(temp); //<-- same thing here
            btn.setTag("button"+buttonNumber);
            btn.setText(buttonNumber + "");
            btn.setOnClickListener(this);
            }
            buttonNumber++;
        }
}


text:
Q: iOS 7 - Long running background task Similar to iOS long-running background timer with "location" background mode but not exactly.
Our app needs to send occasional geolocation data in the background. Works fine in foreground but it, of course, gets terminated after 3 minutes. So I need to implement something like this. Has anyone done this in C# and, if so, would you be willing to share?
https://stackoverflow.com/a/18962839/462935
Thanks!

A: You can only have your app wake up on significant location changes. Please see CLLocationManager while app is in background state.
You cannot simply run your app in the background indefinitely, which is part of iOS's design for minimal power usage. It would be good to read Apple's documentation on App State and Multitasking.


text:
Q: Global variable in javascript doesn't changed     $check = "";

    $.ajax({
        url: "check.php",
        type: "POST",
        cache: false,
        data: $name + "=" + $value,
        success: function(data){
            $check = data;
            alert($check);
        }
    });

    alert($check);

The first msg is "Hello"
The second msg is "" Why ?

A: $.ajax is an asynchronous function, it returns immediately and calls the success callback when the success response is received.
Therefore, When the alert($check) at the bottom of your code is executed, the value of $check is not yet modified by the callback of ajax. That's why you see the empty string.

A: jquery ajax function by default is async. so the execute dosent wait for the functions value to be returned. so mayb because you are working on local development server. and the ajax post request is fast and you are returning word hello in response of you post request so the first alert message is "Hello"
and then the execution continues and returns alerts you of the $chek local value again


text:
Q: Displaying selected values only in VB6 I am trying to display students in a datagrid that have "yes" as active. If the student has "no" as active, the form has to hide it and only show the students with "yes".
The problem that I am recieving now is

Syntax error in FROM clause.

code:
Private Sub Form_Load()
Dim sql As String

connSearch.Open connstr
Adodc1.ConnectionString = conn.connstr

sql = "select * from Table1 where Active  <>" & "'No'"

Adodc1.RecordSource = sql
Set StudentTable.DataSource = Adodc1
Adodc1.Refresh
Adodc1.Visible = False
End Sub

A: What is Active?
If Active is Boolean data type (Yes/No), it's optional values are True or False. In that case your query is:
"select * from Table1 where Active <> False"

If Active is String data type; are 'no' and 'No' the same values? you are better converting all to lower or upper case:
"select * from Table1 where Ucase(Active) <> 'NO'"

Edit: Modified Code
Dim sql As String

sql = "select * from Table1 where [Active] <> 'No'"
Adodc1.ConnectionString = conn.connstr
Adodc1.CommandType = adCmdText
Adodc1.RecordSource = sql
Set StudentTable.DataSource = Adodc1
Adodc1.Refresh
Adodc1.Visible = False


text:
Q: MS SQL CONTAINS with Ampersand Search I have a FULLTEXT column called 'name', which may contain multiple words per row.  Using CONTAINS, I can search for a variable number of words, and it works, except when one of the words has an ampersand in it.
Example: name = 'Bob Brown AB&CD'
This works:
CONTAINS(name, '"*Bo*" AND "*Br*"')

These do not (any search of the word with the ampersand):
CONTAINS(name, '"*AB*"')
CONTAINS(name,'"*AB&CD*"')
CONTAINS(name,'"*&*"')

I realize why the last search wouldn't work, since CONTAINS only searches from the beginning of words.
Is the ampersand being processed by FULLTEXT as a word-break?  If so, that might explain why a search including the ampersand would fail.  But it wouldn't explain why
CONTAINS(name, '"*AB*"')
CONTAINS(name, '"*CD*"') (assuming FULLTEXT sees "CD" as a different word)

would fail.
How can I mitigate the search so it returns the row if I search for "AB&CD" or just "AB" or just "CD"?
P.S.  Dynamic SQL is not an option, so I cannot concatenate a variable number of LIKEs.

A: I found my answer, apparently.  I set
STOPLIST = OFF

on my FULLTEXT index, and I can now search by "AB" and "AB&CD" successfully.


text:
Q: Waterman butterfly projection in Mapnik Like the title says, how would someone configure Mapnik to use the Waterman butterfly projection ?
Otherwise, what other tools would be able to render using this projection ?

A: I don't think mapnik or proj4 are able to render that kind of projection.
According to that excellent post, Openlayers with protovis library would be able to render not exactly the Waterman projection but the Fuller projection (also called Dymaxion).
You even have an online example here.

A: It's not for Mapnik, but at least the Polyhedral Geographic Projections plugin for d3.js can render that projection.

Example from http://bl.ocks.org/mbostock/4458497:
<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  background: #fcfcfa;
}

.stroke {
  fill: none;
  stroke: #000;
  stroke-width: 3px;
}

.fill {
  fill: #fff;
}

.graticule {
  fill: none;
  stroke: #777;
  stroke-width: .5px;
  stroke-opacity: .5;
}

.land {
  fill: #222;
}

.boundary {
  fill: none;
  stroke: #fff;
  stroke-width: .5px;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.geo.polyhedron.v0.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960,
    height = 550;

var projection = d3.geo.polyhedron.waterman()
    .rotate([20, 0])
    .scale(118)
    .translate([width / 2, height / 2])
    .precision(.1);

var path = d3.geo.path()
    .projection(projection);

var graticule = d3.geo.graticule();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var defs = svg.append("defs");

defs.append("path")
    .datum({type: "Sphere"})
    .attr("id", "sphere")
    .attr("d", path);

defs.append("clipPath")
    .attr("id", "clip")
  .append("use")
    .attr("xlink:href", "#sphere");

svg.append("use")
    .attr("class", "stroke")
    .attr("xlink:href", "#sphere");

svg.append("use")
    .attr("class", "fill")
    .attr("xlink:href", "#sphere");

svg.append("path")
    .datum(graticule)
    .attr("class", "graticule")
    .attr("clip-path", "url(#clip)")
    .attr("d", path);

d3.json("/mbostock/raw/4090846/world-50m.json", function(error, world) {
  svg.insert("path", ".graticule")
      .datum(topojson.feature(world, world.objects.land))
      .attr("class", "land")
      .attr("clip-path", "url(#clip)")
      .attr("d", path);

  svg.insert("path", ".graticule")
      .datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
      .attr("class", "boundary")
      .attr("clip-path", "url(#clip)")
      .attr("d", path);
});

d3.select(self.frameElement).style("height", height + "px");

</script>


text:
Q: Python3 find groups of strictly increasing " float values" within a list I cannot find a solution to find groups of strictly increasing "float values" within a list. All examples I find online are all group by "integers" type values. A simple example of what I am looking for is code that picks up the float value sequence as well...see my list below for clarity:
l = [8, 9, 10, -1.2, -1.1 ,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]
the code below returns only the integer numbers and simply ignores the floats. If I would use the "round" function to change the list into integers, it would defeat the whole purpose of the effort...
What I would like to achieve is an output of strictly increasing "float values" from the list above returning the output values of:
[[8, 9, 10],[-1.2,-1.1,-1.0] , [7, 8], [1.2, 2.3, 3.4]]
Code to explain the problem best:
def groupSequence(x):
    it = iter(x)
    prev, res = next(it), []

    while prev is not None:
        start = next(it, None)

        if prev + 1 == start:
            res.append(prev)
        elif res:
            yield list(res + [prev])
            res = []
        prev = start

l = [8, 9, 10, -1.2, -1.1 ,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]
print(list(groupSequence(l)))

#current output:
[[8, 9, 10], [7, 8]]
#desired output
[[8, 9, 10],[-1.2,-1.1,-1.0] , [7, 8], [1.2, 2.3, 3.4]]
Any help would be much appreciated.

A: The problem is in this line:
if prev + 1 == start:

The floats in your sequence doesn't increase by one: -1.2 + 1 <> -1.1
if start and start > prev:


text:
Q: Display Report Contents Where Column A Equal B in SSRS
From the image above, I want viewers of my SSRS report to see data where PaymentFound column is equal to 'N' without limiting it in my T-Sql query and without hiding any column in my report.
How do I achieve this in SSRS?

A: I am assuming you want to hide the rows for which the PaymentFound value is Y.
There are 2 ways to do that,
1) Add filter on dataset so it will filter the values out with PaymentFound= Y
You can add filter as,
    Dataset->RightClick-> DatasetProperties->Filter->Add-> then
 Expression : PaymentFound
 Operator:  =
 Value: 'N'

2) Right click on row set the expression for the visibility as
= IIF(Fields!PaymentFound.Value = "Y",True,False)


text:
Q: How do I print a field from a pipe-separated file? I have a file with fields separated by pipe characters and I want to print only the second field.  This attempt fails:
$ cat file | awk -F| '{print $2}'
awk: syntax error near line 1
awk: bailing out near line 1
bash: {print $2}: command not found

Is there a way to do this?

A: The pipe character needs to be escaped so that the shell doesn't interpret it.  A simple solution:
$ awk -F\| '{print $2}' file

Another choice would be to quote the character:
$ awk -F'|' '{print $2}' file

A: Or just use one command:
cut -d '|' -f FIELDNUMBER

A: The key point here is that the pipe character (|) must be escaped to the shell. Use "\|" or "'|'" to protect it from shell interpertation and allow it to be passed to awk on the command line.

Reading the comments I see that the original poster presents a simplified version of the original problem which involved filtering file before selecting and printing the fields. A pass through grep was used and the result piped into awk for field selection. That accounts for the wholly unnecessary cat file that appears in the question (it replaces the grep <pattern> file).
Fine, that will work. However, awk is largely a pattern matching tool on its own, and can be trusted to find and work on the matching lines without needing to invoke grep. Use something like:
awk -F\| '/<pattern>/{print $2;}{next;}' file

The /<pattern>/ bit tells awk to perform the action that follows on lines that match <pattern>.
The lost-looking {next;} is a default action skipping to the next line in the input. It does not seem to be necessary, but I have this habit from long ago...

A: Another way using awk
awk 'BEGIN { FS = "|" } ; { print $2 }'

A: And 'file' contains no pipe symbols, so it prints nothing.  You should either use 'cat file' or simply list the file after the awk program.


text:
Q: EF 6 Code-Based Migration: Add not null property to existing entity I want to add a not-null, foreing key column to an existing table.

Environment: EF 6,Code-First, Code-Based Migration

//Code from Migration class for new entity Currency
CreateTable("dbo.Currency",
                c => new
                    {
                        CurrencyID = c.Int(nullable: false, identity: true),
                        Code = c.String(nullable: false, maxLength: 3, fixedLength: true, unicode: false),
                        Denomination = c.String(nullable: false, maxLength: 50, unicode: false),
                    })
                .PrimaryKey(t => t.CurrencyID);

AddColumn("dbo.Collection", "CurrencyID", c => c.Int(nullable: false));

//Code from Seed() method in Configuration class
context.Currencies.AddOrUpdate(
    new Currency
    {
        Code = "USD",
        Denomination = "Dollar"
    }
);

//Here i get an exception. Collection is the existing table
context.Database.ExecuteSqlCommand( "update collection set CurrencyID = 1 );

Exception message:

The UPDATE statement conflicted with the FOREIGN KEY constraint
  "FK_dbo.Collection_dbo.Currency_CurrencyID". The conflict occurred in
  table "dbo.Currency", column 'CurrencyID'.

A: Problem solved, here are enumerated by order the steps i followed:

*

*Change the foreign key property mapping to Not Required

*Seed only the primary key values

*Update-Database

*Change back the property to Required

*Add new migration and seed the values for foreign key column

*Update-Database


text:
Q: SQLite: avoiding cycles in depth-limited recursive CTE I'm using a recursive Common Table Expression in SQLite to traverse a graph. How can I avoid cycles in the traversal while also limiting the depth of the search?
For example, here's a very basic graph, represented as an edge list, with 3 nodes (in my case, the graph is directed but most edges are linked in both directions, similar to what's shown below):
sqlite> CREATE TABLE edges (source INTEGER, target INTEGER, label TEXT);
sqlite> INSERT INTO edges VALUES (1, 2, "down");
sqlite> INSERT INTO edges VALUES (2, 1, "up");
sqlite> INSERT INTO edges VALUES (2, 3, "down");
sqlite> INSERT INTO edges VALUES (3, 2, "up");

I could recursively find all children of node 1 with a maximum depth of 5 as follows (level is the depth of traversal):
sqlite> WITH RECURSIVE children(id, level) AS
   ...>   (SELECT 1, 0
   ...>    UNION SELECT target, children.level+1
   ...>            FROM edges
   ...>            JOIN children ON edges.source = children.id
   ...>           WHERE children.level < 5)
   ...> SELECT * FROM children;
1|0
2|1
1|2
3|2
2|3
1|4
3|4
2|5

Note that, for instance, node 1 is traversed 3 times with paths 1 (depth=0), 1,2,1 (depth=2), and either 1,2,3,2,1 or 1,2,1,2,1 (depth=4). If I'd used UNION ALL, I'd get some more (e.g., both 1,2,1,2,1 and 1,2,3,2,1).
My problems are thus:

*

*UNION (as opposed to UNION ALL) does not filter all the duplicates because the depth is stored in the accumulated rows, so it only filters rows with the same descendant AND depth

*Removing the depth constraint would theoretically allow UNION to avoid duplicates, but without a LIMIT or some other bound, it would make the search go into infinite recursion (not to mention the fact that I'd lose the ability to do depth-limited traversals)

Also note that I'm using SQLite without extensions (via Python), so there are no array operations or other features that might help out. I'll provide a solution I came up with as an answer below, but I hope someone else knows a better one.

A: By encoding the visited nodes on each row, one can avoid cycling on a node within a single traversal. If the node names are predictable, such as integers, then a simple delimited list will work:
sqlite> WITH RECURSIVE children(id, path, level) AS
   ...>   (SELECT 1, ",1,", 0  -- initial ',' is so instr() check below works
   ...>    UNION ALL SELECT target, children.path || target || ",", children.level+1
   ...>                FROM edges
   ...>                JOIN children ON edges.source = children.id
   ...>               WHERE children.level < 5
   ...>                 AND NOT instr(children.path, "," || target || ","))
   ...> SELECT * FROM children;
1|,1,|0
2|,1,2,|1
3|,1,2,3,|2

This does not prevent traversing to the same node through different paths, though. Consider adding another row:
sqlite> INSERT INTO edges VALUES (1, 3, "down");

Then the statement above would produce the following results:
1|,1,|0
2|,1,2,|1
3|,1,3,|1
3|,1,2,3,|2
2|,1,3,2,|2

Also the use of string concatenation and substring checking might not be the most performant.


text:
Q: Can't install 'usethis' package I'm using R-4.1.1 and the last version of Rstudio.
My goal is to use the ggradar package but I cannot install it with install.packages because:

le package 'ggradar' is not available for this version of R

So I would like to install the application like this:
devtools::install_github("ricardo-bion/ggradar", dependencies=TRUE)

I managed to install devtools but when I try to:
library(devtools)

there is this error:

Error: le package 'usethis' nécessaire pour 'devtools', mais est introuvable

When I trying to install devtools with
install.packages("devtools",dependencies =TRUE)

it doesn't work. So finally, I try to install the package usethis
install.packages("usethis")

but I can't do it: I have a big error which ends with:

Warning in install.packages :
installation of package 'usethis' had non-zero exit status

Can you help me please?

A: I don't know the exact reason for your case, but things like  this can happen as a result of an inconsistent package set. It is in general a good idea to update installed packages before installing new ones.
As you have seen, package usethis depends on devtools, see:  https://CRAN.R-project.org/package=usethis that also shows that usethis is availabe for R 4.1.1.
In inconsistency already happened, i.a. due to an upgrade from R 4.1.0 or other installations, de-installation of the suspect packages, or just deletion of the user library can help in most cases.
How to do this depends on the operating system.


text:
Q: Unable to find function in FOR loop My version output in RStudio,
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          4
minor          0.4
year           2021
month          02
day            15
svn rev        80002
language       R
version.string R version 4.0.4 (2021-02-15)
nickname       Lost Library Book

My MRE:
N = 32;
dx = 1.0;
m = 1;
for (i in 1:5) {
 a[i] = 0.5*(1+sin(2*pi*m*i*dx/N));
}
plot(a);
par(new=TRUE)
halfN = N/2;
delk = 2*pi/N;
dt = 0.5;

for (m in 1:80) {
  ahat = fft(a);
  for (i in 1:N) {
    if ((i-1) <= halfN) k <-
        (i-1)*delk
    if ((i-1) > halfN) k <-
        (i-1-N)*delk
    k2 = k*k;
    ahat[i] = ahat[i]/(1 + k2*dt);
}
  a = fft(fft(a), inverse = TRUE)/length(a);
}
plot(a)

I get an empty output plot as follows:
my_fft_plot_a
I am expecting to get the sinusoidal wave as initialized in the 1st for loop & fft() of the same to solve the diffusion equation.
Where am I going wrong with the code


text:
Q: USRP B200 mini Transmitter trouble I have trouble when using my USRP b200 mini. Indeed, I wasn't able to use it in transmitter mode. I work with two b100 and one b200.
Until now, if I use one USRP b100 in transmitter mode and another one in receiver mode, everything works. If I use one USRP b100 in transmitter mode and my USRP b200 in receiver mode everything still works. But if I do the opposite, I am not able to detect my transmitted signal anymore.
Can someone could help me please ?
I use these C++ code lines to parameter my USRP:
void Radio_Tx_Rx::initialize(int TX){
printf("%s",KYEL);
if (TX){
  cout << "TRANSMITTER INITIALISATION " << endl;
    string usrp_addr("type=b200");
    usrp = uhd::usrp::multi_usrp::make(usrp_addr);
    usrp->set_tx_rate(fe);
    usrp->set_tx_freq(fc);
    usrp->set_tx_gain(20); //I tested gain from 0 to 80 with a step of 10
    usrp->set_tx_antenna("TX/RX");
    uhd::stream_args_t
            stream_args("fc32");
    tx_stream = usrp->get_tx_stream(stream_args);
    cout << " " << string(50, '-') << endl;
    usrp->issue_stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
} else {
   cout << " RECEIVER INITIALISATION "<< endl;
    string usrp_addr("type=b100");
    usrp = uhd::usrp::multi_usrp::make(usrp_addr);
    usrp->set_rx_rate(fe);
    usrp->set_rx_freq(fc);
    usrp->set_rx_antenna("TX/RX");
    uhd::stream_args_t
            stream_args("fc32");
    rx_stream = usrp->get_rx_stream(stream_args);
    cout << " " << string(50, '-') << endl;
    usrp->issue_stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
printf("%s", KNRM);

}


text:
Q: What is the difference between Amazon Linux and RedHat Enterprise Linux on AWS EC2? I am very new to this and I don't even know if I should ask this question here or on Stackoverflow or ServerFault.
The Question
I wish to set up a EC2 instance on Amazon Web Services. My understanding is RedHat Enterprise Linux(RHEL) cost $0.21/hour for an m1.Small more than Amazon Linux (which is free). Is my understanding correct?
Is there any difference between the performance of RHEL and Amazon Linux? If I am looking for a free Linux which one should I go with in AWS EC2?

A: Usually, the price you pay for the "Enterprise" versions (RHEL, SLES) isn't for a bonus in performance, but for a bonus in service. For example, a certain to-remain-unnamed provider of "enterprise" databases won't offer you any support unless you are running the database on a certified Linux (i.e., SLES, RHEL). If you don't have support contracts to worry about, there's little to be had in the "enterprise" distributions that is worth the price.
IMVHO.

A: Red Hat pricing details are here http://aws.amazon.com/rhel/ and Amazon Linux is here: http://aws.amazon.com/amazon-linux-ami/; as you say, RHEL implies additional cost, whilst Amazon Linux involves 'no additional charge' beyond the charges for running instances and related services.
Amazon Linux, like CentOS, is based on RHEL -- it is fundamentally a minimal/basic install of Red Hat Enterprise Linux (hence optimised for the purpose). Amazon are currently offering a year's free Amazon EC2 Micro Instance for new customers within the 'free usage tier', as per http://wpmu.org/would-you-like-a-free-server-for-a-year/. If you would like to try EC2 for free, because of the limited memory/resource availability for the 'Micro Instance', trying Amazon Linux makes sense.


text:
Q: Horizontal date axis incorrect on Excel line chart with secondary axis My Excel 2010 line chart has a secondary axis. Its horizontal date axis is incorrect.  Dates should range 1/1/2013 to 12/31/2013:

All date data is explicit [ex 3/8/2013]. Dates are M-F except for holidays. The last 2 dates are 12/30/2013 and 12/31/2013. There are 252 dates with the start of the range correctly listed in the horizontal edit window.

A: I had the same problem. I tried reducing how much data was included in my set and found that there was one specific entry that was causing the plot to revert to {1,2,3...} rather than the using dates entered. My date axis would behave completely fine until I included that one entry. There was nothing wrong with the formatting and for a while it was getting very frustrating.
It turns out I accidentally keyed in a date that does not exist. I had entered 11/31/2019, but the month of November only has 30 days. Instead of throwing an error when I originally input the erroneous date, Excel just stopped treating the whole set as dates when I included it in my data set.
I hope this helps!
Blake

A: I have a possible solution for this issue. I was trying to plot dates from an Excel plugin versus values on the Excel Scatter chart and but the dates were shown 1, 2, 3, 4, 5 etc.
What I found out which cleared the issue was that this can happen if you try to plot some dates that contain the time, and some dates that don't.
For instance, plotting on axis:
01.08.2015
01.08.2015  00:30:00
Won't work, but
01.08.2015  00:30:00
01.08.2015  00:34:00
Should work.

A: Revised; original answer wasn't accurate.
Kevin's answer almost nailed it.  Either a line chart or XY chart should work, but there appears to be a problem with the way the data range is specified for the chart.  The question and comments don't describe how the range is specified, so just verify that the series data range reflects the dates column of your data as the X values.
What is happening is that without the dates specified as the X values, it is using the sequence numbers of the values.  So your first date is input #1, the second is input #2, etc.  Excel stores dates as a day count, starting with January 1, 1900 being day 1.  When you format the axis with a date format, you get what Kevin described--sequence number 1, as a date, is 1/1/1900.  Your last input is entry number 252, which corresponds with 9/8/1900.

A: Short answers:

*

*Check chart type. Try specifying "Line" and not "X Y scatter".

*Just check you haven't got any impossible dates in your list.

Longer answers:

*

*I was having the same problem. My X axis was meant to show "real" dates, they were correctly specified in the sheet (or so I thought [see below]), but I was just seeing "default" dates from Jan-00 on the chart.

Couldn't work it out. Eventually went to chart type. Saw that the chart was set as an X Y scatter. Changed in to Line. All instantly sorted.
Of course, the chart might not display your data spaced how you want. As line charts and X Y charts are different: https://excel-example.com/charts/difference-line-chart-scatter-chart
Hope this might help someone.

*Check you don't have any impossible dates. I thought my dates were good. And 99% of them were. But, for some reason, my date list included 31/09/2012... September doesn't have 31 days. This seemed to be throwing it off as well. Once I resolved that. And then deleted and reinstated the horizontal axis, it started working again.

A: It's hard to troubleshoot this without seeing your data sheet or where the x-axis data came from, but if you entered the data for the date column like this:

1
  2
  3
  4

Then Excel will default to interpreting those as days since the beginning of "the era."  You can cure this by entering the dates in full, like this:

1/1/2013
  1/2/2013
  1/3/2013
  1/4/2013

Additionally, it appears that your graph is ending in August (or maybe early September).  If you have fewer than 365 observations -- because, for example, holidays and weekends are excluded -- then, again, inputting the actual dates will help.
If you already have input the dates, it might be that your graph isn't using those cells as the x-axis labels.  In that case, you can click on the graph, then "select data," then specify "horizontal (category) axis labels."

A: Make sure that the cells you are referencing (as axis labels) are "text" category and not "date" or another category. THEN, in the horizontal axes additional formatting dialogue, click "axes options", under "axis type" make sure "Text axis" is checked.  This should help.
One issue I had was I had to create new cells that were "text" from the get-go. If I changed the original cells from "date" to "text" (and even rewrote in the dates), the chart would not fix itself. BUT, once I created new "text" cells, filled them with the correct labels, and referenced to those new cells as the correct data, the axis labels changed and were correct.

A: Check that both series 1 and series 2 have horizontal (Category) Axis labels. if you've built your chart without an overall chart data range, the series have independent horizontal (category) axis labels, if one of them is blank, then the dates will be ignored and points will be treated as sequential from 01/01/1900.  To check, in the Select Data Source dialogue for your chart, click on series 1 in the legend Entries (Series) on the left then click the Edit button on the Horizontal (Category) Axis labels (on the right), repeat (and correct) for each Legend Entries (Series).

A: For me the answer was very simple. One of the cells in the range that contained the dates, contained some text instead of a valid date. It was the last cell.
My date range was too long and it included the last cell which had text in it. I reduced the length of the range by one cell to exclude the cell containing the text and the problem disappeared.
My series definition was:
=SERIES(ActualData!$E$3,ActualData!$A$4:$A$20,ActualData!$E$4:$E$20,1)
So I edited it to read this, and it fixed the problem
=SERIES(ActualData!$E$3,ActualData!$A$4:$A$19,ActualData!$E$4:$E$19,1)
NOTE that all of my date cells were formatted as Date (as they should be) not Text.

A: The Primary Axis Data set has to have the dates as the horizontal labels.  If you move the Data set with the dates as the horizontal labels to the secondary axis, what you describe happens.

A: Via Chart Design > Select Data Source
I removed all references to table headers (i.e., Series Name)
and then re-added them.  This fixed the issue.
Chart Option

Series Option

A: Treat labels as text in horizontal axis chart style should be ticked. Its the option in updated version of spreadsheet


text:
Q: Toggable tabs in an AngularJS single page application? I have a MEAN.JS application running. It is a Single Page Application using AngularJS' hashtag routing.
I would like to implement Bootstrap's toggable tabs, but for them to work they use hashtags to switch tabs (e.g. www.example.com/#tab1 and www.example.com/#tab2). All fine and dandy, except for that I cannot use hashtags that way due to AngularJS' routing. Any workarounds to make toggable tabs working in an AngularJS Single Page Application environment?
Thanks in advance, I'll accept the answer that helps me solve this.

A: The fact that you are using AngularJS routes should not prevent you from using the AngularJS variant of the Bootstrap tabs.
See the following link.
http://angular-ui.github.io/bootstrap/#/tabs


text:
Q: PHP Showing iFrame on Response I had an earlier post here but the answer didn't help at all. I have an upload feature like this:
<iframe class="iframe" name="message" src="upload.php" style="display:none;"></iframe>
<form action="upload.php" method="post" enctype="multipart/form-data" target="message">
    Select a file: <input type="file" name="upload">
    <input type="submit">
</form>

And i'm trying to do something like this:
$('.iframe').fancybox({
    'hideOnContentClick': true
});

So when upload.php gives a response ("file successfully uploaded") it goes into the iframe which is great. But I need the iframe to show. How do I unhide the iframe after upload.php has responded with a message?

A: Do you really have to have an inline iframe? You could try to submit the form via ajax and display the response in fancybox without the inline iframe like
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data" target="message">
    Select a file: <input type="file" name="upload">
    <input type="submit">
</form>

Notice that I added an ID to the form so we can manipulate it through that selector. Then the jQuery  :
$("#uploadForm").bind("submit", function() {
 $.ajax({
   type     : "POST",
   cache    : false,
   url      : "upload.php",
   success  : function(data) {
    $.fancybox(data.responseText,{
      'hideOnContentClick': true
    });
   }
 });
 return false;
});


text:
Q: Is there an easy way to make a local client on a local machine talking to a local server think that it is talking to a server on the internet? I have a local (HTTP) server running on my (Linux) machine (listening on 127.0.0.1:port) and a local application that connects to it as a client. Both the server and client applications are proprietary and I can only change some basic config for both. I have had this set up working fine until recently when the client application was updated. The client application now seems to require that the server it connects to must be "on the internet" so it is disallowing connections to 127.0.0.1 and other "local-like" addresses such as 10.0.*.* and 192.168.*.*.
As a workaround, I am now using ngrok to get a remote address for my local server and the client application happily works with that. However, that is a manual/slow process to run ngrok and update the client application's config and it requires an internet connection and going through ngrok's servers.
I am wondering if there is a way to "fake" an "internet-like" IP address to resolve directly to my local machine.
I have looked into "dynamic DNS" solutions but they require changes to router config that I often don't have control over.
What I am thinking is along the lines of setting some porn site's "internet-like" IP to "resolve" to my local machine on my local machine using some kind of "virtual network adapter" BUT I don't want to spend a lot of time building such a set up. Hence, the question, is there an EASY way to do this?

A: You can add as an alias a "real" IP on the server, i.e. 1.2.3.4/32 and try connecting to this address form the client application, if it's on the same computer. If your client application in on a different computer, use something like 1.2.3.4/24 for the server and 1.2.3.5/24 for the client, provided they're both in the same LAN. This type of addresses is not assigned in the internet, so you won't face any connectivity problems.

A: use iptables?
iptables -t nat  -I OUTPUT --src 0/0 --dst dest_ip -p tcp --dport 80 -j REDIRECT --to-ports 80

(not sure about the chain though)
This should in effect redirects --transparently-- any traffic going to dest_ip:80 to localhost:80.
the des_ip is any ip that makes the application happy.

A: You could try an ip address in one of the less well-known reserved, or not routable, ranges, betting on a poor implementation in your client-server application.
Refer to https://en.m.wikipedia.org/wiki/Reserved_IP_addresses

A: I would use virtualization. You can make a fake little world for your software to live in. This can be as elaborate or as simple as you want. The benefit here is that you can use public IP addresses without messing up networking for the entire LAN you are attached to. Just make sure that the virtual interfaces are set to "host only" or "virtual network only".
You could even make two machines. One client and one server both in the public subnet, so they can talk to each other without routing. This could exist completely in the virtual network and not even be visible to the host, if you desired.

A: Maybe you can use an Internet simulator like INetSim. It simulates (provides fake) common internet services, so the program thinks it's on the Internet. It is e.g. used for analyzing the network behaviour of malware in a closed and safe environment, and this program is then used to trick it to believe it is the Internet, while it's actually not.
It seems like the same scenario as your, so take a look at it and see if you can use it!


text:
Q: CMD + r not working in Xcode version 10.1 in Mojave (10.14.2) After updating the Xcode ⌘R not working in Mojave (10.14.2).
I have downloaded the Xcode the latest Xcode and updated the Mac OS X version also
Mac OS X version: 10.14.2
Xcode Version: 10.1


text:
Q: Settings values to Session Variable from Javascript I have a shopping cart, for the Time Slot selection for product delivery i want to display Date for the next one week, First Column(Per Day in Per Row), and TimeSlots in another column, the format like below:
Column1                            Column2
Aug 19, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 20, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 21, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 22, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 23, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 24, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM
Aug 25, 2013    [RadioButton]10:00AM    [RadioButton]12:00PM

I tried using gridview with radiobuttonlist (for Time Slots), but the problem is user is able to select Time for Every Days. So as an alternative i am trying to check the TimeSlot selected at the javascript end and because i want the Slot accessible for next checkout wizard, i want to store the selected time slot in the session. I am able to validate the Time Slot if not selected, and get the value in the alert, if selected. However when i try to save the value to session from hidden field (saved on button click at client end), i am not getting the session value to other pages. Below is the code i am trying:
 <script>
        function SaveToHiddenField() {
            if ($("input:radio:checked").length > 0) {
                $radio = $("input:radio:checked");
                document.getElementById('<%= hdnField.ClientID %>').value = $radio.val();
                <% Session["Slot"] = hdnField.Value; %>
                window.location.href='default2.aspx'
                return true;
            }
            else {
                alert("Nothing Selected");
                return false;
            }
        }
    </script>

<asp:Button ID="btnSession" runat="server" Text="Save to Session" OnClientClick="return SaveToHiddenField()" />
<asp:HiddenField ID="hdnField" runat="server" />

Can anyone tell me whats wrong i am doing, or any other alternative which could be the better option for my query.

A: Issue is resolved, on the button click i wrote below code:
Session["Slot"] = hdnField.Value;
        Response.Redirect("default2.aspx");

Now when the page is redirect to default2.aspx, i have the session value.
Thanks Everyone,
Specially @JasonP.

A: You can use ASP.NET AJAX Page Methods to store and retrieve session values, like this:
Code-behind for default1.aspx:
[WebMethod(EnableSession = true)]
public static void StoreSessionValue(string theValue)
{
    HttpContext.Current.Session["TheValueToStore"] = theValue;
}

Now in your markup for default1.aspx, use jQuery to call this page method, like this:
$.ajax({
    type: "POST",
    url: "defaul1.aspx/StoreSessionValue",
    data: "{'theValue': document.getElementById('<%= hdnField.ClientID %>').value}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        window.location.href='default2.aspx';
    }
});

Code-behind for default2.aspx:
[WebMethod(EnableSession = true)]
public static string RetrieveSessionValue()
{
    return HttpContext.Current.Session["TheValueToStore"].ToString();
}

Now in your markup for default2.aspx, use jQuery to call this page method, like this:
$.ajax({
    type: "POST",
    url: "defaul1.aspx/RetrieveSessionValue",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        // Do something with the session value that came back in the variable "msg"
    }
});

A: In C#
Session["MySes"] = "SessionValue";

In Javascript
 var ScriptSes = "<%= Session["MySes"]%>";

in html
 <input type="button"     value="Save to Session"  onclick="SaveToHiddenField()" />

In html use html button tag when you use asp.net button control it loads page then your variable session value destroy so you cannot get session value . so use html input type button instead of asp.net button controller


text:
Q: Mysql and Java search matching multiple values in multiple columns I need to speed up a search.
Currently we let our users input a name: John Doe
Then in Java we split that string to create multiple values (or "terms") ["John", "Doe"] and loop through the terms provided doing a select in the database looking for that term in a number of relevant columns:
// For each term in the string[]
SELECT *
  FROM Person p
 WHERE 1=1
   AND (p.idNumber = '#{term}'
          OR LOWER(p.firstName) LIKE '%#{term}%'
          OR LOWER(p.lastName) LIKE '%#{term}%'
          OR LOWER(p.companyName) LIKE '%#{term}%'
          OR p.phone = '#{term}');

at the end of the loop we use Java to do an intersection of the matched rows so that all matches are unique.
persons = (List<Person>)CollectionUtils.intersection(persons, tmpPersons);

I'm planning on changing this to a dynamic SQL statement to match all terms provided in one sql statement and removing the CollectionUtils.intersection but before I go through that process is there another way to do this that produce a faster search?

A: You search can't use any index, that's why it's slow. What you're doing is a fulltext search, so try to use the existing feature.
Some details:
Why no index can be used?

*

*You're converting the column value to lowercase

*You're searching with '%' + ...

You're needlessly converting term to lowercase in every line again and again.
And you've probably never heard of SQL injection.
Would dynamic SQL help?
Probably yes, as fewer data would have to be transfered, but the more complicated query could be a problem for the optimizer. Mysql is not believed to be the smartest. Anyway, fulltext search is much faster as it uses an index.
What if fulltext search doesn't do exactly what I need?
You can try use it for getting a superset of what you want and filter further.
You could try to mimic it by creating a kitchen sink table containing all searchable text which would be updated by triggers, but this is quite some work and you won't get as fast as the engine itself.


text:
Q: How to get total sum of a column in ng-repeat I am trying to get the sum of a column in My ng-repeat table. I shared the image of the table below this paragraph.

Code of the table is given below.

     Ref No	Model	IMEI	Color	Warranty	Branch	Party	Date of Sell	Amount

 {{ x.sno }} 	 {{ x.p_model }} 	 {{ x.imei }} 	 {{ x.color }} 	 {{ x.warrenty }} 	 {{ x.branch }} 	 {{ x.party }} 	 {{ x.dsell }} 	 {{ x.amount | number:2 }}

							Grand Total	{{ grandtotal }}

My Controller code given below.

Jsone fetch from the server:
{"message":[{"0":"2","sno":"2","1":"Huawei P9 Lite ","p_model":"Huawei P9 Lite ","2":"545454545454","imei":"545454545454","3":"White","color":"White","4":"CGC","warrenty":"CGC","5":"50","amount":"50","6":"1","sell":"1","7":"27\/02\/2017","dsell":"27\/02\/2017","8":"1","transfer":"1","9":"MANSOURA","branch":"MANSOURA","10":"Cloud International Co Will","party":"Cloud International Co Will"},{"0":"3","sno":"3","1":"Samsung Galaxy J7 6","p_model":"Samsung Galaxy J7 6","2":"456545454545545","imei":"456545454545545","3":"Gold","color":"Gold","4":"Gasham","warrenty":"Gasham","5":"100","amount":"100","6":"1","sell":"1","7":"27\/02\/2017","dsell":"27\/02\/2017","8":"1","transfer":"1","9":"MANSOURA","branch":"MANSOURA","10":"Cloud International Co Will","party":"Cloud International Co Will"}]}

I need to display the total sum value of the Amount column in the Grand Total area.

A: As I said in my comment, one way to solve this could be by using a custom filter that would look like :
(function() {
  'use strict';

  angular
    .module('Test', [])
    .filter('sumByColumn', function () {
      return function (collection, column) {
        var total = 0;

        collection.forEach(function (item) {
          total += parseInt(item[column]);
        });

        return total;
      };
    });
})();

You could then call that filter on your collection by specifying which column you want to sum:
{{ Approve | sumByColumn: 'amount' }}

The advantage of using a filter here, IMHO, is that it is reusable. Whenever you need to sum a specific column on any data, you can do it using this filter again.
Of course I advise you to improve it by checking that the column value is a number for example...etc...Since it is a filter, you can easily write tests for it.
I've created a JsFiddle in order to demonstrate how it works within your context https://jsfiddle.net/7b3q2q5p/4/

A:

     Ref No	Model	IMEI	Color	Warranty	Branch	Party	Date of Sell	Amount

 {{ x.sno }} 	 {{ x.p_model }} 	 {{ x.imei }} 	 {{ x.color }} 	 {{ x.warrenty }} 	 {{ x.branch }} 	 {{ x.party }} 	 {{ x.dsell }} 	 {{ x.amount | number:2 }}

							Grand Total	{{ grandtotal }}


text:
Q: python Convert Encoding:LookupError: unknown encoding: ansi Because my cdv file is encoded as utf-8, opening it with Excel will cause distortion, and when I then convert it to the standard ANSI encoding, I get this error:
code:
import chardet

def convertEncoding(from_encode,to_encode,old_filepath,target_file):
    f1=file(old_filepath)
    content2=[]
    while True:
        line=f1.readline()
        content2.append(line.decode(from_encode).encode(to_encode))
        if len(line) ==0:
            break

    f1.close()
    f2=file(target_file,'w')
    f2.writelines(content2)
    f2.close()

convertFile = open('4321.csv','r')
data = convertFile.read()
print chardet.detect(data)
if chardet.detect(data)['encoding']=='utf-8':
    convertFile.close()
    convertEncoding(chardet.detect(data)['encoding'], "ansi", "4321.csv", "4321_bak.csv")

error:
{'confidence': 0.99, 'encoding': 'utf-8'}
Traceback (most recent call last):
  File "/Users/allenlee/Desktop/convert/convert.py", line 24, in <module>
    convertEncoding(chardet.detect(data)['encoding'], "ansi", "4321.csv", "4321_bak.csv")
  File "/Users/allenlee/Desktop/convert/convert.py", line 8, in convertEncoding
    content2.append(line.decode(from_encode).encode(to_encode))
LookupError: unknown encoding: ansi
[Finished in 0.1s with exit code 1]

Thanks for your concern.

A: OK,I find the answer.Thanks to @falsetru
#coding:utf-8

import chardet

def convertEncoding(from_encode,to_encode,old_filepath,target_file):
    f1=file(old_filepath)
    content2=[]
    while True:
        line=f1.readline()
        content2.append(line.decode(from_encode).encode(to_encode))
        if len(line) ==0:
            break

    f1.close()
    f2=file(target_file,'w')
    f2.writelines(content2)
    f2.close()

convertFile = open('1234.csv','r')
data = convertFile.read()
convertFile.close()

convertEncoding(chardet.detect(data)['encoding'], "utf-8", "1234.csv", "1234_bak.csv")

A: There's no ansi encoding in Python Standard Encodings.
Choose appropriate encodings from following link: Standard Encodings


text:
Q: Padding integers with zeros in Helm value I have a need to construct Kubernetes objects with name containing three digits padded with leading zeros.
For example with an iteration, I am trying to create StatefulSets with names
"XXXX-001"
"XXXX-002"
...

I have tried
printf "%s has **%3d** dogs." .Name .NumberDogs.

but the %3d isn't padding this to 3 digits.
And I tried to look into Helm Template Function List, but could not find anything which can help my scenario.

A: The printf template function uses the Go fmt package internally, and its documentation has the rules for constructing the % strings.  %3d should request a string that is (at least) three characters wide, but the default padding is with spaces; you need to include a 0 modifier as well to get zero padding.
printf "%03d dogs" .NumberDogs