text:
Q: Implementing a sortable list I am using Ruby on Rails 3.0.9, jQuery 1.6.2 and jQuery UI. I have the following HTML list:

    <%= link_to 'NAME', '#' %>

    <%= link_to 'SURNAME', '#' %>

    <%= link_to 'AGE', '#' %>

    Test name1 value

    Test surname1 value

    Test age1 value

    ...

    ...

    ...

I would like to make that sortable using JavaScript (if possible using jQuery and jQuery UI, not external plugin). That is, by clicking on the NAME, SURNAME or AGE I would like to list items by the "pseudo-column"\"link" clicked.
For instance:
When I click on NAME I would like to have:
 NAME*     SURNAME     AGE
---------------------------
 Name1     Surname1    20
 Name2     Surname2    25
 Name3     Surname3    30
 Name4     Surname4    24
 ...       ...         ...

When I click on AGE I would like to have:
 NAME      SURNAME     AGE*
---------------------------
 Name1     Surname1    20
 Name4     Surname4    24
 Name2     Surname2    25
 Name3     Surname3    30
 ...       ...         ...

How can I do\code that? What do you advice about (maybe I have to use a HTML
... instead of

...)?

A: I'd recommend you have a look at Railscast 240: Search, Sort, Paginate with Ajax.  Just skip the ajax part if it's unnecessary.
You'll be able to use
 tags if you prefer them to the
 markup because essentially you are just setting an order param when you click the link.

A: If you used a table you could use one of the many table / sorting plugins like: http://tablesorter.com/docs/
Also i think a table would surely be better suited for that kind of data. (and more semantically correct)

A: I'd suggest the same thing as Andy: use a js module to do it client side (assuming that the whole set of data is sent to the client at once). I'd recommend data tables.

A: I once tried to make sorting functionality without a plugin. But when i want to make additional functionality like filter, pagination, etc, I became overwhelmed. So i'd recommend metasearch for sorting and filtering and combine it with kaminari for pagination. For ajax, use Chaker Nakhli suggestion. it's worth trying.


text:
Q: Errors with table names in SQL Server Management Studio I am brand spanking new to SQL Server and programming itself. So bear with me please.
I have a database called ex. "name" and my query code for it and it executes just fine but all the table names in the query are red. It is only with this specific database. I have another query with a different database with no errors and it runs fine as well. Thank you

A: There are cases where the local cache used by IntelliSense becomes stale.
Refreshing the cache is easy but not necessarily obvious.
There are two ways to refresh the cache:

1) Go to Edit -> IntelliSense -> Refresh Local Cache and
2) Hit Ctrl+Shift+R.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why subtracting a negative is the same as adding a positive. Why subtracting a negative same as adding positive and adding a negative same as subtracting a positive why.i didn't get the logic why subtracting
2-(-3)=5. Pls give me a logical answer

A: There is some deep theory behind this, but here is the rundown:

*

*-3 is what is known as the 'additive inverse' of 3 (basically the opposite)

*Subtraction is just the inverse (opposite) of addition

*The inverse of an inverse of something is the original thing (think of a double negation, like "I am not not going to the park" = "I am going to the park")

*a-b is the same as a+(-b)

*So, 2-(-3)=2+(-(-3))=2+3=5

I hope this helps :D


text:
Q: Which Win API does QtSerialPort use? There are servral USB libraries out there. I have tried libusb and it won't work for me. I cannot connect my USB device with that library because my driver for that USB device is using usbser.sys driver. My USB device is a Communication Device Class (CDC).
The only USB library that works for me is QtSerialPort (I have not tested Win32 API yet) and now to the question: If QtSerialPort only works for my USB device, what API does QtSerialPort use then? Does QtSerialPort use internal Win32 API functions, or own internal API?

A: On Windows, QtSerialPort uses the Windows API to communicate with serial ports (CreateFile, WriteFile, ReadFile, SetCommTimeouts, etc.).
You can read the relevant source code here:
https://github.com/qt/qtserialport/blob/dev/src/serialport/qserialport_win.cpp


text:
Q: Linking from my Actions on Google to a web url I have a Dialogflow fulfillment integrated with Google Assistant. Right now whenever using voice with Google Assistant, every time the assistant finishes responding, it tries to catch a user response. This is problematic, because I have a simple response with a rich response that is a BasicCard with a url button link. If the user clicks on the link before the assistant finishes reading out the text response, then the user would be taken back to the Action after clicking on the link when the assistant finishes responding, which is a bad experience. Is there a solution for this?
It seems like the reason it goes back is because the assistant wants to prompt the user for a response. Is it possible to stop the Action from whatever it's doing once the user clicks on the link? Or would it be possible to not prompt the user for a response after the assistant responds?
I'm using node.js and I have tried both conv.ask and conv.add, but they both automatically catch audio from the user right away after the voice response finishes from the Action.
I am using an iOS device for testing.


text:
Q: Authenticate user in spring boot with react login form I have added spring security to my project and I am trying to do user Authentication. I am using CrudRepository to look up the user and verify the details are correct. I have been able to get it working using springs out of the box login page. My problem is that I want to authenticate the user through my react login page. The Spring boot app is at 8080 while the react app is 3000. I have seen custom login page set ups but the login page was in the same location as the spring boot app. My question is, is it possible for the login page to live elsewhere, is there a sign in end point I can send my request to to authenticate the user? Or is there some config I can add to tell spring to use the user details coming from the front end to authenticate the user.
On a side not I understand the NoOpPasswordEncoder shouldn't be used, this is just a POC and will not be going to production. Thanks
My security config file looks like below:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService)
}

@Override
protected void configure(HttpSecurity http) throws Exception {
             http
            .authorizeRequests()
            .antMatchers("/**").hasRole("ADMIN")
            .and()
            .formLogin();
}

@Bean
public PasswordEncoder getPasswordEncoder(){
    return NoOpPasswordEncoder.getInstance();
}

UserDetailsServiceImpl:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private UserRepository userRepository;

public UserDetailsServiceImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Optional< UserEntity > user= userRepository.findByEmail(email);
    user.orElseThrow(()-> new UsernameNotFoundException("Not found: " + email));
    return user.map(UserInfo::new).get();
}

}
UserDetailsImpl
public class UserInfo implements UserDetails {
private String userName;
public UserInfo(UserEntity userEntity){
this.userName=userEntity.getEmail();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return Arrays.asList(new SimpleGrantedAuthority("ADMIN"));
}

@Override
public String getPassword() {
    return "TestPassword";
}

@Override
public String getUsername() {
    return userName;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

}
Spring Security Log:

Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4529048e, org.springframework.security.web.context.SecurityContextPersistenceFilter@c247b02, org.springframework.security.web.header.HeaderWriterFilter@ecfff32, org.springframework.web.filter.CorsFilter@6addfa22, org.springframework.security.web.csrf.CsrfFilter@629cf53c, org.springframework.security.web.authentication.logout.LogoutFilter@7b38db21, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3b18009f, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@78f1d29, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@15405ba1, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@74b521c, org.springframework.security.web.session.SessionManagementFilter@3c65f2e1, org.springframework.security.web.access.ExceptionTranslationFilter@531b1778, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@458704ee]

A: While development you can make entry in package.json file as
"proxy": "http://localhost:8080/"

As for in java web application you can provide custom authentication request matcher and authentication entry point:
@Autowired
RestAuthEntryPoint restAuthEntryPoint;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/**").hasRole("ADMIN")
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(restAuthEntryPoint) <- to support REST
        .and()
        .formLogin().loginProcessingUrl("/fooLogin"); <- credentials checked here
}

To support REST and handle unauthorized access to :
@Component
public class RestAuthEntryPoint implements AuthenticationEntryPoint{

@Override
public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException) throws IOException {

    // send error response to the client (401 unauthorized)
    response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}

}
Login form submission(basic) in react:
 axios({
         method:'post',
         url:'//fooLogin',
         params:{
                username: this.state.email,
                password: this.state.password
            },
         config: { headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
        })
        .then(
            //authentication success...
        })
        .catch(error=>{
            var errResp = error.response;
            if(errResp.status === 401){
               //Ex: show login page again...
            }

        })


text:
Q: Android : background thread Team,
I need to run a background thread in my application. Could you please share the best practices  where to initiate the thread so that keeps running irrespective of the Activity is being shown and things to consider. The purpose of this background thread is to fire transactions from the Simulator to the server and get the response back from the host.
thanks,
Ramesh

A: I solved this by having a custom application object hold a reference to the background thread (an AsyncTask in my case). The app object stays alive as long as your process runs. In other words, it won't get killed if your activity dies, for example if your change the phone orientation. An activity would set the current activity on the AsyncTask on creation, and unset the activity on the AsyncTask when the activity goes away. The AsyncTask would clear its own reference from the app object once it finished. I blogged about this here.

A: Sounds like you want a Service. Check out the Services section on the Application Fundamentals dev guide page.


text:
Q: SQL UPDATE on with data from same table I have a next situation with a table, Need to update rows from rows in same table, as you see here:
TABLE

ID
SN
FID

1
12345
1

2
1122
2

3
12345-RG
NULL

4
1122-RG
NULL

I need to UPDATE row 3 from row 1 Column FID(Same SN, different ending only on the end -RG)
Update row 4 FROM row 2 Column FID(Same SN, different ending -RG)
So the result should be:
TABLE

ID
SN
FID

1
12345
1

2
1122
2

3
12345-RG
1

4
1122-RG
2

I have tried many ways but I don't get with this... I tried declaring a temp table and trying to compare from there but still with this issue...

A: Asuming [SN] is being augmented with -RG
Example
with cte as (
Select *
      ,NV = max(FID) over (partition by replace(SN,'-RG','') )
 From YourTable
)
Update cte set FID = NV
 --Where FID is null  -- Optional

The Updated Table
ID  SN          FID
1   12345       1
2   1122        2
3   12345-RG    1
4   1122-RG     2


text:
Q: node package.json WARN engine express@2.5.9 This is my package.json
{
  "author": "***",
  "name": "***",
  "email": "***",
  "url": "***",
  "version": "***",
  "homepage": "***",
  "description": "***",
  "bugs": "***",
  "repository": {
    "type": "git",
    "url": "***"
  },
  "scripts": {
    "start": "node server.js"
  },
  "license": "Apache License",
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.10.0",
    "compression": "^1.2.2",
    "connect-flash": "^0.1.1",
    "connect-livereload": "^0.5.2",
    "connect-mongo": "^0.4.2",
    "consolidate": "^0.10.0",
    "cookie-parser": "^1.3.3",
    "ejs": "^1.0.0",
    "errorhandler": "^1.3.2",
    "express": "^4.10.6",
    "express-jwt": "^1.0.0",
    "express-logger": "0.0.3",
    "express-session": "^1.9.3",
    "express-validator": "^2.7.0",
    "formidable": "^1.0.16",
    "helmet": "^0.6.1",
    "jsonwebtoken": "^3.2.2",
    "lodash": "^2.4.1",
    "method-override": "^2.3.0",
    "mongoose": "^3.8.21",
    "morgan": "^1.5.0",
    "passport": "^0.2.1",
    "passport-local": "^1.0.0",
    "serve-favicon": "^2.2.0",
    "socket.io": "^1.2.1",
    "socketio-jwt": "^2.3.5"
  },
  "devDependencies": {
    "del": "^0.1.3",
    "expect.js": "^0.3.1",
    "express": "^4.10.6",
    "gulp": "^3.8.10",
    "gulp-angular-templatecache": "^1.4.2",
    "gulp-autoprefixer": "^1.0.1",
    "gulp-concat": "^2.4.1",
    "gulp-csso": "^0.2.9",
    "gulp-express": "^0.1.2",
    "gulp-if": "^1.2.5",
    "gulp-jasmine": "^1.0.1",
    "gulp-jshint": "^1.9.0",
    "gulp-minify-html": "^0.1.6",
    "gulp-mocha": "^2.0.0",
    "gulp-ng-annotate": "^0.3.4",
    "gulp-protractor": "0.0.11",
    "gulp-rename": "^1.2.0",
    "gulp-replace": "^0.5.0",
    "gulp-ruby-sass": "^0.7.1",
    "gulp-uglify": "^1.0.1",
    "jasmine-core": "^2.1.2",
    "jshint-stylish": "^1.0.0",
    "karma": "^0.12.25",
    "karma-chrome-launcher": "^0.1.5",
    "karma-html-reporter": "^0.2.4",
    "karma-jasmine": "^0.3.0",
    "karma-phantomjs-launcher": "^0.1.4",
    "karma-spec-reporter": "0.0.13",
    "mocha": "^2.1.0",
    "protractor": "^1.4.0",
    "run-sequence": "^1.0.1",
    "supertest": "^0.15.0",
    "yargs": "^1.3.2"
  },
  "engines": {
    "node": ">=0.10.x"
  }
}

when I run
npm install

I've got :
npm WARN engine express@2.5.9: wanted: {"node":">= 0.4.1 < 0.7.0"} (current: {"node":"0.10.33","npm":"1.4.28"})

Does anyone know where the warning come from ?


text:
Q: wglCreateContextAttribsARB function crashes I try to write down code from this tutorial. I have the code of InitializeOGL():
bool Ogl::InitializeOGL(bool vSync)
{
  cout<<"Init OpenGL"<<endl;
  int pixelFormat;
  PIXELFORMATDESCRIPTOR pixelFormatDescriptor;
  int result;
  char *vendorChar, *rendererChar;

  hDC = GetDC(hWnd);
  if(!hDC)
    return false;

  pixelFormat = ChoosePixelFormat(hDC,&pixelFormatDescriptor);
  if(pixelFormat==0)
    return false;

  result = SetPixelFormat(hDC,pixelFormat,&pixelFormatDescriptor);
  if(result!=1)
    return false;

  HGLRC tempDeviceContext = wglCreateContext(hDC);
  wglMakeCurrent(hDC,tempDeviceContext);

  // glewExperimental = GL_TRUE;
  if(glewInit()!=GLEW_OK)
    return false;

  int attribList[5] =
  {
    WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
    WGL_CONTEXT_MINOR_VERSION_ARB, 1, 0
  };

  hGLRC = wglCreateContextAttribsARB(hDC,0,attribList);
  if(hGLRC!=NULL)
  {
    wglMakeCurrent(NULL,NULL);
    wglDeleteContext(tempDeviceContext);
    result = wglMakeCurrent(hDC,hGLRC);
    if(result!=1)
      return false;
  }

  vendorChar = (char*)glGetString(GL_VENDOR);
  rendererChar = (char*)glGetString(GL_RENDERER);

  strcpy_s(videoCardInfo,vendorChar);
  strcat_s(videoCardInfo,"-");
  strcat_s(videoCardInfo,rendererChar);

  if(vSync)
    result = wglSwapIntervalEXT(1);
  else
    result = wglSwapIntervalEXT(0);

  if(result!=1)
    return false;

  int glVersion[2] = {-1,-1};
  glGetIntegerv(GL_MAJOR_VERSION,&glVersion[0]);
  glGetIntegerv(GL_MINOR_VERSION,&glVersion[1]);

  cout<<"Initializing OpenGL"<<endl;
  cout<<"OpenGL version"<<glVersion[0]<<"."<<glVersion[1]<<endl;
  cout<<"GPU"<<videoCardInfo<<endl;

  return 0;
}

When I try to change context version to OpenGL 3.1, here crashes wglCreateContextAttribsARB()
function (Pointer for this is getting in LoadExtensions() correctly). When I try to create OpenGL 4.0 here crashes function wglSwapIntervalEXT(). My graphic card handles only OpenGL 3.1.
My question is how to succefully init OpenGL context here? What I have to do to create OpenGL context in version 3.1.

A: There are a couple of things that need to be mentioned here:
1. Driver Version
If your graphics card / driver only support OpenGL 3.1, then WGL_CONTEXT_MAJOR_VERSION_ARB and friends are generally going to be undefined. Before OpenGL 3.2 introduced core / compatibility, context versions were not particularly meaningful.

*

*This requires support for either WGL_ARB_create_context or WGL_ARB_create_conext_profile.

2. Incorrect usage of ChoosePixelFormat and SetPixelFormat
PIXELFORMATDESCRIPTOR pixelFormatDescriptor; // <--- Uninitialized

At minimum, the Win32 API needs you to initialize the size field of this structure. In years past, the size of structures was used to determine the version of Windows that a particular piece of code was written for. These days structures like PIXELFORMATDESCRIPTOR are generally static in size because they are used by a part of Windows that is deprecated (GDI), but if you do not set the size you can still thoroughly confuse Windows. Furthermore, you need to flag your pixel format to support OpenGL to guarantee that you can use it to create an OpenGL render context.
Also note that once you set the pixel format for a device context on Windows, it cannot be changed. Generally, this means if you want to create a dummy render context to initialize your extensions you should also create a dummy window with a dummy pixel format. After you initialize your extensions, you can use wglChoosePixelFormatARB (...) and its associated functions to select the pixel format for your main window's device context.
This is (was) particularly important back in the days before FBOs when you wanted to implement multi-sampling. You cannot get a multi-sample pixel format using ChoosePixelFormat (...), but you need to call ChoosePixelFormat (...) to setup the extension necessary to get a multi-sample pixel format. Kind of a catch 22.


text:
Q: Split a column by group I have some data that looks a little bit like this:
test.frame <- read.table(text = "name   amounts
                                JEAN  318.5,45
                             GREGORY 1518.5,67,8
                              WALTER  518.5
                               LARRY  518.5,55,1
                               HARRY  318.5,32
                         ",header = TRUE,sep = "")

I'd like it to look more like this ...
name   amount
JEAN  318.5
JEAN 45
GREGORY 1518.5
GREGORY 67
GREGORY 8
WALTER  518.5
LARRY  518.5
LARRY  55
LARRY  1
HARRY  318.5
HARRY  32

It seems like there should be a straightforward way to break out the "amounts" column, but I'm not coming up with it. Happy to take a "RTFM page for this particular command" answer. What's the command I'm looking for?

A: (test.frame <- read.table(text = "name   amounts
                                JEAN  318.5,45
                             GREGORY 1518.5,67,8
                              WALTER  518.5
                               LARRY  518.5,55,1
                               HARRY  318.5,32
                         ",header = TRUE,sep = ""))

#      name     amounts
# 1    JEAN    318.5,45
# 2 GREGORY 1518.5,67,8
# 3  WALTER       518.5
# 4   LARRY  518.5,55,1
# 5   HARRY    318.5,32

tmp <- setNames(strsplit(as.character(test.frame$amounts),
                split = ','), test.frame$name)

data.frame(name = rep(names(tmp), sapply(tmp, length)),
           amounts = unlist(tmp), row.names = NULL)

#       name amounts
# 1     JEAN   318.5
# 2     JEAN      45
# 3  GREGORY  1518.5
# 4  GREGORY      67
# 5  GREGORY       8
# 6   WALTER   518.5
# 7    LARRY   518.5
# 8    LARRY      55
# 9    LARRY       1
# 10   HARRY   318.5
# 11   HARRY      32

A: The fastest way (probably) will be data.table
library(data.table)
setDT(test.frame)[, lapply(.SD, function(x) unlist(strsplit(as.character(x), ','))),
                  .SDcols = "amounts", by = name]

 ##       name amounts
 ## 1:    JEAN   318.5
 ## 2:    JEAN      45
 ## 3: GREGORY  1518.5
 ## 4: GREGORY      67
 ## 5: GREGORY       8
 ## 6:  WALTER   518.5
 ## 7:   LARRY   518.5
 ## 8:   LARRY      55
 ## 9:   LARRY       1
 ## 10:  HARRY   318.5
 ## 11:  HARRY      32

A: A generalization of David Arenburg's solution would be to use my cSplit function. Get it from the Git Hub Gist (https://gist.github.com/mrdwab/11380733) or load it with "devtools":
# library(devtools)
# source_gist(11380733)

The "long" format would be what you are looking for...
cSplit(test.frame, "amounts", ",", "long")
#        name amounts
#  1:    JEAN   318.5
#  2:    JEAN      45
#  3: GREGORY  1518.5
#  4: GREGORY      67
#  5: GREGORY       8
#  6:  WALTER   518.5
#  7:   LARRY   518.5
#  8:   LARRY      55
#  9:   LARRY       1
# 10:   HARRY   318.5
# 11:   HARRY      32

But the function can create wide output formats too:
cSplit(test.frame, "amounts", ",", "wide")
#       name amounts_1 amounts_2 amounts_3
# 1:    JEAN     318.5        45        NA
# 2: GREGORY    1518.5        67         8
# 3:  WALTER     518.5        NA        NA
# 4:   LARRY     518.5        55         1
# 5:   HARRY     318.5        32        NA

One advantage with this function is being able to split multiple columns at once.

A: This isn't a super standard format, but here is one way you can transform your data. First, I would use stringsAsFactors=F with your read.table to make sure everything is a character variable rather than a factor. Alternatively you can do as.character() on those columns.
First I split the values in the amounts using the comma then I combine values with the names column
md <- do.call(rbind, Map(cbind, test.frame$name,
    strsplit(test.frame$amounts, ",")))

Then I paste everything back together and send it to read.table to do the variable conversion
read.table(text=apply(md,1,paste, collapse="\t"),
    sep="\t", col.names=names(test.frame))

Alternatively you could just make a data.frame from the md matrix and do the class conversions yourself
data.frame(names=md[,1], amount=as.numeric(md[,2]))

A: Here is a plyr solution:
Split.Amounts <- function(x) {
  amounts <- unlist(strsplit(as.character(x$amounts), ","))
  return(data.frame(name = x$name, amounts = amounts, stringsAsFactors=FALSE))
}

library(plyr)

ddply(test.frame, .(name), Split.Amounts)

Using dplyr:
library(dplyr)

test.frame %>%
  group_by(name) %>%
  do(Split.Amounts(.))


text:
Q: Error saving this JS in WSO2-Integration Studio I use Integration Studio,
and I have always used inside my Xml files js script,
But this time I still get an error saving this inline JS, and I really can't understand the reason of this error.
<script language="js"><![CDATA[var elements = mc.getProperty('elementsFromJson');
         var payload = [];
         for(let i = 0; i <= elements.length; i++){
         var id= elements[i].id;
         var type= elements[i].type;
         var couple= {"id":id ,"type":type};
         print(couple);
         payload.push(couple);
         }
    var payloadFinale = {payload};
    print('result in JSON: ' + payloadFinale);
    var data= mc.setPayloadJSON(payloadFinale);]]></script>

So would be great your help in case you use Integration studio as me,
thank you for your time.

A: You have issues in the following lines.
for(let i = 0; i <= elements.length; i++){

Here change let => var
var payloadFinale = {payload};

The above syntax is wrong, not sure what you are trying to achieve here. Probably, you can remove the above line, when you do mc.setPayloadJSON it would be saved as a proper JSON.


text:
Q: Mac OS: shell not recognising scp I'm trying to execute the below command on my new MacBook and was getting the '-bash: sudo scp: command not found' error.
Please help me fixing this issue.
sudo scp -i Pem_File_Name.pem PHP_File_Name.php centos@Host_Path:/var/www/html/Folder_Name/

The Pen_File_Name, PHP_File_Name and Host_Path are replaced with their respected values.
Thanks in advance.
Geeth.

A: From the error, I'd guess that you have something other than a normal space (maybe a non-breaking space) between "sudo" and "scp". The reason I think this is that the error message says the command "sudo scp" was not found -- but the command should be "sudo" (which should then run "scp" as a separate command). This means that for some reason bash is treating "sudo scp" as a single word instead of two.


text:
Q: Turning on a mobile phone (SGS2) automatically / remotely I want to use my phones as a remote camera system that charges via a solar panel however I was wondering whether there is any way to turn the phone on automatically or remotely.
Thats to say, if the phone runs out of battery and turns off, is there anyway to turn it back on automatically or remotely?

A: If the phone is rooted, here is what you can do.
(Optional) Rename /system/bin/playlpm:
adb shell remount
adb shell mv /system/bin/playlpm /system/bin/playlpm-original

Then create a playlpm file locally and put the following:
#!/system/bin/sh
/system/bin/reboot

And push it to the target:
adb push playlpm /system/bin

Then give it a proper permission:
adb shell chmod 0755 /system/bin/playlpm
adb shell chown root.shell /system/bin/playlpm

Now, whenever phone is connected to a power supply, it is going to (re)boot automatically. That's, if its battery has drained it will boot up when a power will be available from solar panel.
Also see:

*

*Auto Power on Android when the charger is Connected

*Programmatically auto-power on the phone

*Is there a way to auto-power on the phone

*[root] NoMoarPowah!


text:
Q: Prove the energy is constant in a PDE?
I calculated the
$$
\begin{align}
\frac{dE(t)}{2\,dt} & = \int_\Omega u_tu_{tt}+DuDu_t+u^3u_t\,dx \\
& =\int_\Omega [u_t(u_{tt}-\Delta u)+u^3u_t] \, dx+\int_{\partial \Omega} u_t \frac{\partial u}{\partial v} \, ds = \int_{\partial \Omega} u_t \frac{\partial u}{\partial v} \, ds
\end{align}
$$
However, I don't know how to prove $$\int_{\partial \Omega} u_t \frac{\partial u}{\partial v}ds$$ is zero by the conditions given in the problem?
Can anyone help me about this? Thanks so much!
Can anyone help me explain why $u_t\cong 0$ on $\partial \Omega$?
Thanks so much!:)

A: Notice $u_t\cong 0$ on $\partial \Omega$!


text:
Q: How to avoid NullPointerException when using custom Views or SurfaceViews I created a custom SurfaceView called CaptureView and tried to add it into main.xml file:
<dev.recorder.client.CaptureView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/capturePreview"/>

The application seems to work fine but if I switch from main.xml tab to Layout in Eclipse the text NullPointerException appears instead of layout preview.
In the Activity I binded the controls the following way:
setContentView(R.layout.main);

    bindControls();

private void bindControls()
{
    videoPreview = (CaptureView)findViewById(R.id.capturePreview);

    txtstatus = (TextView)findViewById(R.id.txtMode);
    txtTimer = (TextView)findViewById(R.id.txtTime);
}

Does anyone know how this issue could be solved?

A: make sure that you are initializing the view in onFinishInflate and not in the constructor.
the layout preview code might initialize your control through a different code path.


text:
Q: bash Syntax Madness - How to get third until last command line argument into an array I have it working but cannot believe that the syntax should be that mad. All I want to do is to get the all arguments beginning with the third into an array.
E.g.
script.sh foo bar value1 value2 value3

Should give me an array containing value1, value2, and value3. This array is the used to provide the parameters in a new function:
./runpy /dsnormalize.py "${values[@]}"

This works:
args=( "$@" )
length=$((${#args[@]}-2))
values=(${args[@]:$length:2})

Please tell me this is not the correct way. I usually ended up with a string containing all values.
How does bash handle strings and integers anyway?
And is the difference between ${} and $()?
Thanks for your help,
Karsten

A: The correct syntax is:
args_from_third=("{@:3}")

It's not necessary to insert the length, because the default is "the rest of the arguments".
It's certainly true that bash parentheses are complicated. The two I use here:
VARIABLE=(...)

This creates an array called VARIABLE, whose values are the whitespace delimited elements of the string ....
"${@:start:length}"

This expands to length arguments starting at argument start; if length is omitted, it uses all the rest of the arguments. The arguments are separated by space characters. Because the expression is quoted, each argument (but not the space delimiters) is treated as though it were quoted.
${...} covers a lot of possibilities, including substring, search-and-replace and case-changing. Look at the bash manual for details.

A: A much easier way to do this is by using shift to remove the fixed arguments.
first_arg=$1
second_arg=$2
shift 2
the_rest=("$@")

And:

How does bash handle strings and integers anyway? And is the difference between ${} and $()?

${} is used to get a variable's value. The curly brackets are optional if you're just writing $foo, but they're required for anything more complicated, such as accessing elements of an array.
$() captures the output of a command, similar to backticks. This is different from $(( )), which is what you're using.
$(( )) evaluates an arithmetic expression. It lets you do basic integer and boolean operations.


text:
Q: Find the limit of the sequence $a_n=n\sin{\frac{\pi}{2n}}$ Find the limit of the sequence
$$a_n=n\sin{\frac{\pi}{2n}}$$
I would like to know how to find this limit. The question says the answer is $\pi/2$, but I've failed to find this result.

A: We have that $\frac{\pi}{2n} \to 0$ and $\lim_{x \to 0}\frac{\sin{x}}{x}=1$
Using these,we have that:
$$n\sin{\frac{\pi}{2n}}=\frac{\frac{\pi}{2} \sin{\frac{\pi}{2n}}}{\frac{\pi}{2n}} \to \frac{\pi}{2} \times 1=\frac{\pi}{2}$$

A: This problem is equivalent to the following
$$\lim_{n \to \infty} n \cdot \sin \left( \frac{\pi}{2n} \right) = \lim_{n \to \infty} \frac{\sin \left( \frac{\pi}{2n} \right)}{1/n} = \lim_{n \to \infty} \frac{ (\pi/2) \cdot \sin \left( \frac{\pi}{2n} \right)}{\pi/2n}$$
A common limit is
$$\lim_{a \to \infty} \frac{\sin(1/a)}{1/a} \xrightarrow{a \mapsto 1/u} \lim_{u \to 0^+} \frac{\sin(u)}{u} = 1 $$
Clearly, we can cancel in the below limit
$$\lim_{n \to \infty} \frac{ (\pi/2) \cdot \sin \left( \frac{\pi}{2n} \right)}{\pi/2n} = \frac{\pi}{2}$$

A: $\sin(\pi/2n)\sim \frac{\pi}{2n}$ for large $n$ by first order Taylor's.
Thus your limit
$$
n\frac{\pi}{2n}=\frac{\pi}{2}
$$


text:
Q: Zoom In and Out in Text widget tkinter I am trying to make a clone of Notepad but stuck in zoom in and zoom out functionality. I was able to make a zoom in and out functionality by changing the text size each time user presses the zoom in and out option but I think it is not the real implementation because I think it is not actually zooming in or zooming out.
With lots of searching I came to know that Canvas have scale method which can be used to implement the zoom-in functionality and I am able make functionality to zoom in and out of the text widget but it does not affect the text sizes. And according to this the scale method in Canvas only changes the coordinates of the widgets.
What have I done so far?
import tkinter as tk

root = tk.Tk()
root.state('zoomed')
font = ('Courier', 10)

def zoom(zoom_scale):
    global font

    font = (font[0],) + (font[1] + 1,)
    text.config(font=font)

canvas = tk.Canvas(root)
frame = tk.Frame(canvas)
zoom_scale = tk.Scale(root, orient='vertical', from_=1, to=500)
zoom_scale.config(command=lambda args: zoom(zoom_scale))

zoom_scale.set(10)

text = tk.Text(frame, font=font)
text.grid(row=0, column=0)

canvas.create_window(0, 0, anchor='nw', window=frame)
# make sure everything is displayed before configuring the scroll region
canvas.update_idletasks()

canvas.configure(scrollregion=canvas.bbox('all'))
canvas.pack(fill='both', side='left', expand=True)
zoom_scale.pack(fill='y', side='right')
root.mainloop()

In Notepad, the text size does not increase. I think the text-widget is zooming keeping the text-size same. So how can I make a functionality to zoom in and out of the TEXT like NOTEPAD?

A: Scaling the canvas will not cause embedded widgets to grow or shrink. The only way to implement zoom is to change the size of the font in the text widget.
The following code is a modified version of your code. The things to notice are:

*

*the code uses a Font object for the font

*the scale doesn't use lambda; instead it directly calls zoom

*zoom will configure the size of the font object, which causes the text widget to zoom

*the canvas and frame inside the canvas have been removed.

*the root widget has been given an explicit size via geometry, to keep the window from growing and shrinking when the text widget grows or shrinks

import tkinter as tk
from tkinter.font import Font

root = tk.Tk()
root.geometry("500x500")
font = Font(family="Courier", size=10)

def zoom(size):
    font.configure(size=size)

zoom_scale = tk.Scale(root, orient='vertical', from_=1, to=500)
zoom_scale.config(command=zoom)
text = tk.Text(root, font=font)

zoom_scale.pack(fill='y', side='right')
text.pack(side="left", fill="both", expand=True)

zoom_scale.set(10)

root.mainloop()


text:
Q: Numpy How to make a moving(growing) sum of table contents without a for loop? Due to the fact english is not my first language it is very hard to me to explain simply the problem I am trying to solve in the topic, and thus I am sorry.
So instead of trying to explain with bare words I am going to give an example.
Let's say we have an array that is instantiated like this:
weight = np.arange(1, (n + 1)).astype('float64')

So the array looks like this:
[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

Now what I want to do is to have an array of moving sums(let's call it norm), summarizing the array norm and operations would look like this:
index, norm(new array), weight, operation
  0        1               1     0+1 = 1
  1        3               2     0+1+2 = 3
  2        6               3     0+1+2+3 = 6
  3        10              4     0+1+2+3+4 = 10
  .         .              .      .
  .         .              .      .
  .         .              .      .
  9        55              10    0+1+2+3+...+10 = 55

I hope it is understandable.
How do I achieve this result without looping through the weight array?

A: numpy.cumsum does exactly this:
np.cumsum(weight)


text:
Q: php 7.0 Call to undefined function filter_var() I'm trying to use PHPMailer (which I downloaded from GitHub) to send emails from php scripts.
PHPMailer uses the filter_var() php function to validate email addresses and, as far as I can tell, is part of the filters module that has now been incorporated into the core php product (I'm using php 7.0 on Ubuntu).
I've written a simple script to replicate the problem here :-
<?php

    if (filter_var('myname@mydomain.com', FILTER_VALIDATE_EMAIL)) {
      echo("Correct");
    }
    else {
      echo( "WRONG!!!");
    }

?>

I get the following error message :-
Fatal error: Call to undefined function filter_var() in test2.php on line 3

Grateful of someone can point out what I'm missing.

A: Configure your php.ini file
D:\xampp\php\php.ini
[filter]
; http://php.net/filter.default
;filter.default = unsafe_raw
; http://php.net/filter.default-flags
;filter.default_flags =


text:
Q: php implode (101) with quotes Imploding  a simple array
would look like this
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

and that would return this
 lastname,email,phone

great, so i might do this instead
$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";

and now i have what I want a nice pretty csv string
 'lastname','email','phone'

is there a better way to do this, it feels to me like there should be an optional parameter for implode am I missing something ?

A: $id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";

Or
$ids = sprintf("'%s'", implode("','", $id ) );

A: $ids = sprintf("'%s'", implode("','", $ids ) );

A: You could use array_map():
function add_quotes($str) {
    return sprintf("'%s'", $str);
}

$csv =  implode(',', array_map('add_quotes', $array));

DEMO
Also note that there is fputcsv if you want to write to a file.

A: No, the way that you're doing it is just fine. implode() only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).

A: Don't know if it's quicker, but, you could save a line of code with your method:
From
$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";

To:
$array = array('lastname', 'email', 'phone');
$comma_separated = "'".implode("','", $array)."'";

A: Alternatively you can create such a function:
function implode_with_quotes(array $data)
{
    return sprintf("'%s'", implode("', '", $data));
}

A: try this code :
$data = 'ABC,DEF,GHI';

$str = "'".str_replace(',',"','",$data)."'";

echo $str;

A: $array = array('lastname', 'email', 'phone');

echo "'" . implode("','", $array) . "'";

A: If you want to use loops you can also do:
$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo

A: If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....
$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...
foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.

A: Another possible option, depending on what you need the array for:
$array = array('lastname', 'email', 'phone');
echo json_encode($array);

This will put '[' and ']' around the string, which you may or may not want.

A: Don't forget to escape your data!
If you want to put data in a CSV file without fputcsv function or put it in a SQL query use this code:
$comma_separated = "'" . implode("','", array_map('addslashes', $array)) . "'";

This code avoids SQL injection or data fragmentation when input array contains single quotation or backslash characters.

A: Another solution is achieved using implode + preg_replace as follows:
$a = ['A', 'B', 'C'];
implode(',', preg_replace('/^(.*)$/', '"$1"', $a)); // "A","B","C"
$b = [];
implode(',', preg_replace('/^(.*)$/', '"$1"', $b)); // empty string

As you can see this also saves you from checking if the array is empty.

A: you can do it this way also
<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>

A: I think this is what you are trying to do
$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";


text:
Q: git branch restoration after merge If I merge a git feature branch back onto master, is it best to then delete the branch?
Let's say 6 months later, I want to resurrect that deleted branch (assume a freshly cloned repo).  Is there a way to easily re-create it or find its history assuming it was merged back onto master?  What is the best way to do this?
From reading other questions, I see that if I can find the head of that branch I can re-create it easily, but how do I go about doing that?  Some other Q&A responses reference the "reflog" command, but this doesn't return anything useful if I have freshly cloned the repo.

A: Whether or not it's best to delete a branch once merged depends on what the branch means to your workflow. If it's a branch that's being used to prepare a new release, which gets merged into master once the release is ready, then you'll want to keep it around. If it's a throwaway branch for developing a single feature, then it's usually preferable to delete it so you don't clutter your git branch output with dozens of completed branches.
If you want to re-create a deleted branch later, all you'll need to do is find the SHA that corresponds to its last commit. If you don't have the reflog handy, you'll have to try to find this with git log. The easiest way to do this would be to search for the merge commit with something like:
# This should match the message of the merge commit, if you kept the default.
git log --grep=branch-name

Once you find the merge commit, you'll see two parents listed:
commit 38bf1d168e73f9fa708c334e50f256578d5c2d8f
Merge: a08b280 d7725b0

The first parent is the state of master before the merge; the second is the state of the branch that was merged in, which is what you want. Recreate your branch there and check it out with:
git checkout -b branch-name d7725b0

As a sidenote, this will only work if the merge wasn't a fast-forward merge. A fast-forward merge just zips HEAD up to the ref that's being merged, so it doesn't create a merge commit. You can force git to always make a new commit when you merge by using:
git merge --no-ff branch-name

And if you always want this to be the case you can set it in your config:
git config branch.master.mergeoptions  "--no-ff"


text:
Q: Связь асинхронного фреймворка vkbottle с Django3 Требуется связать vkbottle и django3 для интеграций бота с сайтом. Бот должен иметь возможность спокойно использовать django-orm и работать со всеми моделями всех приложений. Вариант с написанием API в Django и работа с ним из бота - не подходит.
Проблема в том, что первая библиотека асинхронная, а вот сама django - не совсем. У меня никак не получается связать всё это в одном проекте. Были попытки поиграться с asyncio, получить loop, передать его конструктору Bot, создавать новый и передать его, но всё это или совсем не работало, или работало, но не правильно. После чего удалось всё "адекватно" завести используя celery. Я отправляю все callback-и в очередь, а таски получают их и отправляют в асинхронную функцию. Да, пример работает, но мне кажется это просто ужасный костыль, и ко всему прочему очень неудобный.

Один человек подсказал направление:

Ты конечно можешь попробовать порыться в исходниках django/asgiref и найти как грамотно привязаться к главному лупу, и с ненулевой вероятностью это получится сделать, но в миллиард раз быстрее будет просто создать где-нибудь отдельный поток, в нем новый луп, и от него уже плясать

Но, к сожалению, для этого у меня ума не хватило. Сейчас нет желания продолжать делать проект с такой архитектурой, так как в это уже начинает оборачиваться головной болью, но другого выхода я к сожалению не вижу.
Случайно наткнулся на django/channels, но не понимаю, сможет оно мне помочь, или нет.
Буду безмерно благодарен любому, кто поможет выбраться из этой ужасной ямы.

A: Вообще лучший способ это не использовать джангу. А так можно разделить код, вынести орм (есть синк/асинк орм типа encode/orm) и уже импортировать её в веб фреймворк и бота. Засовывать бота в джангу очень плохая идея и делать так не надо.


text:
Q: java override during object creation in the following java code a JButton is created but at the same time one of its methods gets overridden.
Qestion: is there a name for overriding in this way while creating the object?
the code:
   JButton myButton;
   myButton = new JButton ("ok"){

        @Override
        public void setText(String text) {
            super.setText(text +", delete");
        }

the jbutton's label is now "ok, delete"

A: That's an anonymous class. From Java in a Nutshell

An anonymous class is a local class
  without a name. An anonymous class is
  defined and instantiated in a single
  succinct expression using the new
  operator. While a local class
  definition is a statement in a block
  of Java code, an anonymous class
  definition is an expression, which
  means that it can be included as part
  of a larger expression, such as a
  method call. When a local class is
  used only once, consider using
  anonymous class syntax, which places
  the definition and use of the class in
  exactly the same place.

It's a common means of providing a specialisation of a base class without explicitly defining a new class via the class expression.


text:
Q: make rebuild target depending on zip file Why make rebuilds the target (I suppose) if the dependency is a binary file?
To reproduce:

*

*create (and enter it) a new empty directory

*download the GameLift SDK (it is just an example: the Makefile content on this question is an example with this file)

*create a simple Makefile with the content below

*issue more times the make command

all: GameLift_12_22_2020/GameLift-SDK-Release-4.0.2/GameLift-Cpp-ServerSDK-3.4.1/CMakeLists.txt

GameLift_12_22_2020/GameLift-SDK-Release-4.0.2/GameLift-Cpp-ServerSDK-3.4.1/CMakeLists.txt: GameLift_12_22_2020.zip
    unzip -oq GameLift_12_22_2020.zip

I would have expected to see the unzip command to be executed only first time I issue the make command, but it continue to be executed in next make runs... why?

A: There are two possibilities, we cannot know which is the case with the information you've provided.
The first is that the file GameLift_12_22_2020/GameLift-SDK-Release-4.0.2/GameLift-Cpp-ServerSDK-3.4.1/CMakeLists.txt is not present in the zip file, so the second time make runs it looks to see if that file exists and it doesn't, so it re-runs the rule.  If, in the same directory you run make, you use ls GameLift_12_22_2020/GameLift-SDK-Release-4.0.2/GameLift-Cpp-ServerSDK-3.4.1/CMakeLists.txt (after the unzip runs) and you get "file not found" or similar, this is your problem.
If that's not it, then the problem is that the timestamp of the file in the zip file is older than the zip file itself, and when unzip unpacks the file it sets the timestamp to this older time.
So when make goes to build it finds the CMakeLists.txt file but the modification time is older than the zip file, so make unpacks the zip file again to try to update it.
You can use ls -l to see the modification time on that file.  If this is the case you should touch the file when you unpack it, so it's newer:
GameLift_12_22_2020/GameLift-SDK-Release-4.0.2/GameLift-Cpp-ServerSDK-3.4.1/CMakeLists.txt: GameLift_12_22_2020.zip
        unzip -oq GameLift_12_22_2020.zip
        touch $@


text:
Q: Selenium Webdriver (Firefox) - Content Security Policy error while scraping website multiple times I'm trying to scrape one particular website with Selenium Webdriver (Firefox), and after 9th time, it says:
Content Security Policy: The page's settings blocked the loading of a resource at eval ("script-src").

When I open browser console to see what's happening, it says: 429 Too many requests
Is there any way to avoid that?
I'm using this code to open Geckodriver
`
opt = webdriver.FirefoxOptions()
        opt.page_load_strategy = 'eager'  #  or complete

        #user_agent = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'

        #opt.add_argument(f'user-agent={user_agent}')
        opt.add_argument('--disable-gpu')
        opt.add_argument('--disable-browser-side-navigation')
        opt.add_argument('--disable-dev-shm-usage')
        opt.add_argument('--no-sandbox')
        #opt.add_argument('enable-automation')
        opt.headless = False

        proxy = Proxy({
                'proxyType': ProxyType.MANUAL,
                'httpProxy': random.choice(proxies),
                'ftpProxy': random.choice(proxies),
                'sslProxy': random.choice(proxies),
                'noProxy': '127.0.0.1:22225' # set this value as desired
                })

        opt.set_preference("general.useragent.override", random.choice(agents))

        driver = webdriver.Firefox(options = opt, proxy=proxy)
        wait = WebDriverWait(driver, 10)

`
I've tried to change user agents and rotate proxies, but no luck
Note: I need to wait exactly 60 minutes and then I can scrape for another 9 times


text:
Q: How do you record changes when activating document.body.contentEditable Is it possible to record the changes that have happened when using either:
document.designmode = true

or
document.contenteditable = true

With specific reference to if the information shown on the website is retrieved from a database. Also, thank you in advanced for the help.

A: They key is that the edited content will be available in the dom and can be accessed via dom methods any time. It is on the part of the developer to design a system which can read the changes, perform caparison and sand save it in the back end if necessary.

function addRevision() {

  let revContainer = document.getElementById('revisions');

  revContainer.appendChild(document.createElement('br'));
  revContainer.appendChild(document.createTextNode('Revision'));

  revContainer.appendChild(document.createElement('br'));
  revContainer.appendChild(document.createTextNode(document.getElementById('editable').innerHTML))

}

 Hello Editbale (change me)

<input type="button" value="Add Revision" onClick="addRevision()">


text:
Q: Xcode warning: "NSArray may not respond to -addObject" In my header file, I have this code:
@interface TableViewController : UIViewController
{
    IBOutlet UITableView *tblListData;
    NSArray *arryData;
}

In my class declaration file, I have this implementation:
- (void)viewDidLoad
{
    arryData = [[NSArray alloc] initWithObjects:@"iPhone",@"iPod",@"MacBook",nil];
    [super viewDidLoad];
}

Now I get this Xcode warning: NSArray may not respond to -addObject for the following code:
- (IBAction)AddButtonAction:(id)sender
{
    [arryData addObject:@"Mac Mini"];
    [tblListData reloadData];
}

And, sure enough, my NSArray is not responding to addObject! :(
What should I do?

A: If you look up the docs, you'll see that NSArray is actually an immutable array (i.e. it can not be modified). That's why the -addObject: message is not implemented. Instead, you will need to use NSMutableArray.


text:
Q: Disable multiple instances of onSubmit trigger during submissions I have a form with onSubmit trigger, Which will be used as an domain wide add - on.The add - on can be used
for many forms.
I need to disable the multiple submit triggers, instead run only 1 instance currently.
Say the form submissions arrive at same time, I need to avoid the duplicate instances of the script running when the current script is running.
I tried to use lock service
function onFormSubmit(e) {
    // lock the document response
    var lock = LockService.getDocumentLock();
    if (lock.hasLock()) return;
    //do some tasks
    lock.releaseLock();
}

How do I make a script (addon) to run as a single instance.
UPDATE: This code too, doesnt achive the intended functionality
function OnSubmits(e) {
    var releaseLock;

    releaseLock = function() {
        lock.releaseLock();

    }

    var lock = LockService.getDocumentLock();
    lock.tryLock(1);
    if (!lock.hasLock()) {
        return;
    }
    var value = cUseful.Utils.expBackoff(function() {
        releaseLock();
        return PropertiesService.getScriptProperties().getProperty('key');
    });
    if (value == null) value = 0;
    else value++;
    cUseful.Utils.expBackoff(function() {
        var folder = DriveApp.getFolderById("1wFGMh38JGarJd8CaiaOynlB7iiL_Pw6D");
        folder.addFile(DriveApp.getFileById(DocumentApp.create('Document Name ' + value).getId()));
        PropertiesService.getScriptProperties().setProperty('key', value);
    });

    releaseLock();
}


text:
Q: Switching callstack for C++ functions Here's my previous question about switching C callstacks. However, C++ uses a different calling convention (thiscall) and may require some different asm code. Can someone explain the differences and point to or supply some code snippets that switch C++ callstacks (preferably in GCC inline asm)?
Thanks,
James

A: The code given in the previous question should work fine.
The thiscall calling convention differs only in who is responsible for popping the arguments off the stack. Under the thiscall calling convention, the callee pops the arguments (and additionally, the this pointer is passed in ecx); under the C calling convention, the caller pops the arguments. This does not affect context switches.
However, if you're going to do context switches yourself, note that you need to save and restore the registers as well (probably on the stack) in addition to switching stacks.
Note, by the way, that C++ doesn't always use thiscall -- it's only used for methods with a fixed number of arguments (and apart from that, it's a Microsoftism... g++ doesn't use it).

A: Note the ABI for C++ is not explicitly defined.
The idea was that compiler manufactures are able to use the optimal calling convention for the situation and thus make C++ faster.
The down side of this is that each compiler has its own calling convention thus code from different compilers are not compatable (even code form different versions (or even different optimization flags) of the same compiler can be incompatable).


text:
Q: Listing Types in a Column with count Selecting all types whether the column value or not I have a table for example Persons with person type(Private, Public, Government, Businessman, Jobless). Type can be null or Empty. I am saving type value in Person table with no Master Table. I want to select all grouped types with count by wheather the type exists or not.
I know it is a bit strange but the requirements are like this. Below are the scripts:
CREATE TABLE [Persons](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [FULLNAME] [varchar](50) NULL,
    [TYPE] [varchar](10) NULL
) ON [PRIMARY]

  INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('ABD', 'Private');
  INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('DEF', 'Government');
  INSERT INTO Persons(FULLNAME,[TYPE]) VALUES('DEF', 'Jobless');

The result should look like as follows:
TYPE                             COUNT
Private                          1
Public                           0
Government                       1
Businessman                      0
Jobless                          1

A: You can create a Common Table Expression (CTE) of all the possible types using with clause and left join it with the persons table.
with types (type)
as (
    select 'Private' from dual
    union all
    select 'Public' from dual
    union all
    select 'Government' from dual
    union all
    select 'Businessman' from dual
    union all
    select 'Jobless' from dual
    )
select t.type,
    count(p.type) "COUNT"
from types t
left outer join Persons p on t.type = p.type
group by t.type;

A: In case you use MS Sql Server not Oracle (as syntax of your DDLs suggest):
  select all_types.type, count(distinct persons.id) from (
      select 'Private' as type union all
      select 'Public' union all
      select 'Government' union all
      select 'Businessman' union all
      select 'Jobless'
      ) all_types left outer join Persons on (all_types.type=persons.type)
      group by all_types.type;


text:
Q: Create Cloud Composer environment with a private repository using Terraform I'm trying to create a Cloud Composer environment with a PyPI package from a private repository using Terraform. Cloud Composer supports private PyPI repositories. However, configuring a private repository requires an existing composer bucket.
When using Terraform to create an environment, the bucket and environment is created in one go. As far as I can see, the environment creation will fail before there is a chance to write the configuration file to the bucket. Is there any way to create a Cloud Composer environment with a private repository using Terraform?
This is roughly what I'm trying to do:
resource "google_composer_environment" "test" {
  provider = google-beta
  project = var.project_id
  region = var.region
  config {
    software_config {
      image_version = "composer-2.0.0-airflow-2.1.4"
      pypi_packages = {
        mypackage = "*"  # from a private PyPI repo
      }
    ...

A: I'm leaving this as community wiki response for community visibility for this kind of questions. For features, I suggest is to go directly to the project site and request the feature there:

*

*Terraform Provider Issues
This will alert the developers of the missing/requested features and it will be taking into consideration. For this case you can track the progress of this case on the issue link you created. Also, you can see the list of upconming features/bugs inside the project goals dashboard but as mention in the description the ETA is up to the team to provide.


text:
Q: A single checkbox input incorrectly passing the value I've spent a few hours looking at all the relevant answers here and I'm still not able to figure out why this is happening.
I'm trying to capture a yes/no type of answer from the users.
I'm using following checkbox input. I could use radio buttons and possibly make it work, but there is a reason I want it to be a single check box user interface.
PROBLEM: No matter whether I check or uncheck the checkbox a '0' is always passed to the server. When I check the checkbox I expect '1'.
html :
<input type="hidden" name="hardtofind" id="hardtofindField" value="0">
<input type="checkbox" name="hardtofind" id="hardtofindField" value="1">I'm having hard time finding information I'm looking for

<input type="button" id="submitButton" class="rbutton" value="Submit">

jquery:

php:
session_start();
if(isset($_GET['hardtofind']) && !empty($_GET['hardtofind']) ){
$hardtofind = $_GET['hardtofind'];
}

UPDATE:
Thanks for pointing out the duplicate ids. I introduced that problem while trying to fix the original problem.
When I remove the hidden filed (so no duplicate IDs). I'm still stuck with the same problem where it always passes '1' now.
What do I need to change so that when the single checkbox is unchecked it passes '0' and when checked '1'?
new html:
<input type="checkbox" name="hardtofind" id="hardtofindField" value="1">I'm having hard time finding information I'm looking for

<input type="button" id="submitButton" class="rbutton" value="Submit">

Thank you so much for your time.

A: Your jQuery is picking up this element, as it is the first match:
<input type="hidden" name="hardtofind" id="hardtofindField" value="0">

...which has a value of 0, and sending that to the server.
Use a different id in order to get the expected result.


text:
Q: Java: clone() and equality checks Perhaps I don't understand how clone() works. Shouldn't the return value equal the caller?
int[] nums = new int[] {0, 1, 2};
int[] list = nums.clone();
nums.equals(list); //returns false. Why?

for (int ket = 0; ket < list.length; ket++) {

       System.out.println(list[ket] == nums[ket]); //prints out true every time
}

list == nums //false

A: Oscar Reyes has the correct answer. I'll just add that Arrays.equals() does exactly the sort of equality comparison that you're looking for.
int[] nums = new int[] {0, 1, 2};
int[] list = nums.clone();
System.out.println(Arrays.equals(nums, list)); // prints "true"

A: Because the equals implementation of array is the same as Object which is
public boolean equals( Object o ) {
   return this == o;
}

 See this also this question
and in both cases you tested, that's false.  The reference values of the original and the copy are two different objects (with the same value but still different object references).
What the clone method does is create a copy of the given object. When the new object is created, its reference is different from the original. That's why equals and == yield false.
If you want to test for equality two arrays, do as mmyers here: Arrays.equals():

A: Have a look at the javadoc for Objet.clone(), it clearly states that while it is typically the case that: "x.clone().equals(x)" will be true, this is not an absolute requirement.

A: because num.equals doesnt check for the equality of the elements, but it checks whether the two variables point to the same object. In your case, although the elements are the same, but nums and lists point to two different objects.
you could use java.util.Arrays.equals(...) function to do the comparison.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#equals%28int[],%20int[]%29

A: nums.equals(list); //false
list == nums; //false
Reason :
By default equals() will behave the same as the "==" operator and compare object locations. here nums and list have different  memory locations.
/* But, equals method is actually meant to compare the contents of 2 objects, and not their location in memory.
So for accomplishing it you can override equals() method. */
list[ket] == nums[ket] //True
The clone is a shallow copy of the array. So, both refers same memory locations. hence it returns true


text:
Q: Running multiple SQL Server versions on Always On I need to install 3 instances of SQL Server, using 3 difference SQL versions on 2 VM's.
I need to install (all Enterprise Ed) 2008, 2012 and 2014.
I want to use Always On, however not sure how I can do this given it is not available with 2008 so I was thinking I can do:
2008 : Active/Passive failover using Windows clustering
2012/4: Always-On
But the above sounds a bit clunky ...
Anyone done this before or idea on the best way to implement the above please?
Thank you


text:
Q: Re organizing a JSON database to remove duplicates Right now my JSON database looks like this:
[{'srcStationName': 'Central', 'srcStationID': 1, 'dstName': 'Central',
 'dstID': 1, 'octopusAdultFare': 0, 'octopusStudentFare': 0,
 'singleAdultFare': 0, 'octopusChildFare': 0, 'octopusElderlyFare': 0,
 'octopusDisabledFare': 0, 'singleChildFare': 0, 'singleElderlyFare': 0},
 {'srcStationName': 'Central', 'srcStationID': 1, 'dstName': 'Admiralty',
 'dstID': 2, 'octopusAdultFare': 4.6, 'octopusStudentFare': 3,
 'singleAdultFare': 5, 'octopusChildFare': 3, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleChildFare': 3, 'singleElderlyFare': 3},
 {'srcStationName': 'Central', 'srcStationID': 1, 'dstName': 'Tsim Sha Tsui',
 'dstID': 3, 'octopusAdultFare': 10, 'octopusStudentFare': 5,
 'singleAdultFare': 11, 'octopusChildFare': 5, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleChildFare': 5, 'singleElderlyFare': 5},

 {'srcStationName': 'Heng On', 'srcStationID': 101, 'dstName': 'Fortress
 Hill', 'dstID': 30, 'octopusAdultFare': 21.5, 'octopusStudentFare': 10.7,
 'singleAdultFare': 24, 'octopusChildFare': 10.7, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleChildFare': 12, 'singleElderlyFare': 12},
 {'srcStationName': 'Heng On', 'srcStationID': 101, 'dstName': 'North Point',
 'dstID': 31, 'octopusAdultFare': 21.5, 'octopusStudentFare': 10.7,
 'singleAdultFare': 24, 'octopusChildFare': 10.7, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleChildFare': 12, 'singleElderlyFare': 12},
 {'srcStationName': 'Heng On', 'srcStationID': 101, 'dstName': 'Quarry Bay',
 'dstID': 32, 'octopusAdultFare': 21.5, 'octopusStudentFare': 10.7,
 'singleAdultFare': 24, 'octopusChildFare': 10.7, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleChildFare': 12, 'singleElderlyFare': 12}]

Since there are the same "srcStations" and multiple "destinations", my desired result is I want to convert to a format like below:
{1: {1: {'octopusAdultFare': 0, 'octopusStudentFare': 0, 'octopusChildFare':
 0, 'octopusElderlyFare': 0, 'octopusDisabledFare': 0, 'singleAdultFare': 0,
 'singleChildFare': 0, 'singleElderlyFare': 0}, 2: {'octopusAdultFare': 4.6,
 'octopusStudentFare': 3, 'octopusChildFare': 3, 'octopusElderlyFare': 2,
 'octopusDisabledFare': 2, 'singleAdultFare': 5, 'singleChildFare': 3,
 'singleElderlyFare': 3}, 3: {'octopusAdultFare': 10, 'octopusStudentFare':
 5, 'octopusChildFare': 5, 'octopusElderlyFare': 2, 'octopusDisabledFare': 2,
 'singleAdultFare': 11, 'singleChildFare': 5, 'singleElderlyFare': 5},

 101: {1: {'octopusAdultFare': 21.5, 'octopusStudentFare': 10.7
 'octopusChildFare': 10.7, 'octopusElderlyFare': 2, 'octopusDisabledFare':
 2, 'singleAdultFare': 24, 'singleChildFare': 12, 'singleElderlyFare': 12},
 2: {'octopusAdultFare': 21.5, 'octopusStudentFare': 10.7, 'octopusChildFare':
 10.7, 'octopusElderlyFare': 2, 'octopusDisabledFare': 2,
 'singleAdultFare': 24, 'singleChildFare': 12, 'singleElderlyFare': 12}, 3: {'octopusAdultFare':
 21.5, 'octopusStudentFare': 10.7, 'octopusChildFare': 10.7,
 'octopusElderlyFare': 2, 'octopusDisabledFare': 2, 'singleAdultFare':
 24, 'singleChildFare': 12, 'singleElderlyFare': 12}
}

Where the first "1", and the "101" key is the 'srcStationID', and the corresponding Object contains "dstIDs" as keys and their prices. I need help to write a function in python that will do this conversion for me and will write the result to a JSON file. Thank you.

A: I was able to do it with the following code:
newData = []
entities = {}
for entity in data:
    if not entity['srcStationID'] in entities:
        entities[entity['srcStationID']] = {
            entity['dstID'] : {
                'octopusAdultFare' : entity.get('octopusAdultFare'),
                'octopusStudentFare' : entity.get('octopusStudentFare'),
                'octopusChildFare' : entity.get('octopusChildFare'),
                'octopusElderlyFare' : entity.get('octopusElderlyFare'),
                'octopusDisabledFare' : entity.get('octopusDisabledFare'),
                'singleAdultFare' : entity.get('singleAdultFare'),
                'singleChildFare' : entity.get('singleChildFare'),
                'singleElderlyFare' : entity.get('singleElderlyFare')
            }
        }
    else:
        entities[entity['srcStationID']][entity['dstID']] = {
            'octopusAdultFare' : entity.get('octopusAdultFare'),
            'octopusStudentFare' : entity.get('octopusStudentFare'),
            'octopusChildFare' : entity.get('octopusChildFare'),
            'octopusElderlyFare' : entity.get('octopusElderlyFare'),
            'octopusDisabledFare' : entity.get('octopusDisabledFare'),
            'singleAdultFare' : entity.get('singleAdultFare'),
            'singleChildFare' : entity.get('singleChildFare'),
            'singleElderlyFare' : entity.get('singleElderlyFare')
        }


text:
Q: Change text in WordPress search bar I need to change the text in the standard WordPress search bar from "Search this site" to just Search.  I haven't been able to figure it out.  Anyone know how?

A: pls refer this: https://codex.wordpress.org/Creating_a_Search_Page. one way is to change text in placeholder attribute of input text


text:
Q: Irrational to the Power of Irrational It is true that an irrational number to the power of an irrational number could be rational. I am curious about the following:
Are there conditions that imply irrational to the power of irrational will be rational ?

A: We can find a class of examples using the fact that, for $k$ integer, $\ln k$ is irrational  (as a consequence of Gelfond-Schneider theorem) and
$e^{\ln k}=k$ is rational.


text:
Q: UITableview not scrolling to the bottom cell if using UITableViewAutomaticDimension and estimatedRowHeight I am facing a strange issue with UITableView if I enable the UITableViewAutomaticDimension property.
I am fetchign some data from the server and I have kept my UITableView cell set to accept dynamic content and increase the height as per the content so far what i have done is

*

*Set the number of lines of the UILabel to zero so that it grows as per the content

*Added the below code inside the viewDidLoad method
self.myTable.estimatedRowHeight = 200
self.myTable.rowHeight = UITableViewAutomaticDimension

Now after i fetch the data from the server i reload the table and go to the last cell of the table view but my problem is when i reload my entire table after the webservice call,
the table view animates and scrolls to the top of the screen and is not visible unless I scroll it down.
I searched and googled but i was not able to find any solution to this but if any of you have every came across this kind of situation please guide me out.
I have even added the below line of code before returning the cell in the cellForRowAtIndexPath but still am stuck with the same issue
cell.layoutSubviews()

here's the code which i have added to scroll to the bottom cell after the successful service call
self.myTable.scrollToRowAtIndexPath(NSIndexPath(forRow: self.myArray.count - 1, inSection: 1), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)


text:
Q: Spring Integration http inbound gateway mapped response headers - being duplicated? I'm trying to set the content-type of a response for an image host service, so I have an http:inbound-gateway that looks like this:
<int-http:inbound-gateway request-channel="receiveChannel"
                          reply-channel="responseChannel"
                          path="/profile/photo"
                          mapped-response-headers="Content-Type"
                          message-mappers="messageConverterList"
                          supported-methods="GET"/>

... and a service activator that looks like this:
<int:service-activator
    input-channel="receiveChannel"
    output-channel="imageResponseChannel"
    expression="@profileService.getPhoto(payload.userId)"/>

... which returns a byte[] of jpeg image data. I have a header enricher that looks like this:
<int:header-enricher
    input-channel="imageResponseChannel"
    output-channel="responseChannel">
    <int:header
        name="Content-Type"
        expression="'image/jpeg'"/>
</int:header-enricher>

But when I run the project I get a response with headers like this:
< HTTP/1.1 200 OK
< Set-Cookie: JSESSIONID=9uw5c136fia6s9ivxgivy1yc;Path=/
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Content-Type: image/jpeg
< Content-Type: application/octet-stream
< Content-Length: 6563
< Server: Jetty(8.1.3.v20120416)

Notice that the content-type is repeated, but it's my understanding that mapped-response-headers should grab the headers from the message, and not determining it from the payload.
Any ideas? Thanks in advance!
*EDIT: I changed the inbound-gateway to reference a custom message-mappers below, but I still get the same result.
<util:list id="messageConverterList">
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list><value>image/jpeg</value></list>
        </property>
    </bean>
</util:list>

*EDIT 2: Turns out it should have been message-converters, but I didn't get an error because I modified the file in target and not src. I made the correction and this is the output I get:
< HTTP/1.1 200 OK
< Content-Type: image/jpeg
< Content-Type: image/jpeg
< Content-Length: 209582
< Server: Jetty(6.1.10)

Better, but not perfect. Here's a simple reproduction project of the issue: http://dl.dropbox.com/u/92800052/http.tar.gz
you can run it with
mvn package jetty:run

and see the output with
curl -v http://localhost:8080/http/photo > /dev/null

A: By default several HttpMessageConverters (from the core Spring Web lib) are registered for the inbound gateway. One of those is ByteArrayHttpMessageConverter, and it's default content-type is "application/octet-stream". Could you try setting the "message-converters" attribute on your gateway so that it references a List-typed bean that contains a single instance of ByteArrayHttpMessageConverter (e.g. you can use util:list) - rather than relying on the default converters, and then on that instance set the supportedMediaTypes property to 'image/jpeg'.
AFAIK, the ByteArrayHttpMessageConverter should not try setting a Content-Type header if one is already present (i.e. from the mapped response headers), but I just want to check and see if that change does indeed bypass the duplication.
Also, can you please let us know what version of Spring Integration you are using?
Thanks,
Mark


text:
Q: Wokspace variables en Laravel Blade tengo el siguiente problema:
Existen dos colecciones, una llamada $guias y la otra $procesos, necesito presentar todos los elementos de $guias y sólo los que tengan la misma fecha en $procesos. Ambas colecciones traen los datos que necesito y la parte del controlador está funcionando sin problemas, $guias puede tener varios elementos para una fecha, mientras que $procesos sólo un elemento por fecha.
Este es el código:
                @php($fecha='2000-01-01')
                @foreach($guias as $guia)

                        ....mostrar las columnas de $guia....

                    @if($fecha!=$guia->fechaGuia)
                       @php($fecha=$guia->fechaGuia)
                       @php($salidas = $procesos->filter(function($item) {
                                       return $item->fechaGuia == $fecha;
                                     })->first()
                            )
                       @isset($salidas)

                                ....mostrar las columnas de $procesos....

                       @endisset
                    @endif
                 @endforeach

El problema lo tengo en la variable $fecha:
Undefined variable: fecha (View: C:\xampp\htdocs\..\resources\views\guia\index.blade.php)

Comprobé el código eliminando $fecha y escribiendo una fecha en forma manual y todo funciona tal como debería.
Ya había tenido problemas con las variables, por ejemplo, no es lo mismo
@php
 $i=1;
@endphp

que
@php($i=1)

sólo en el último caso queda disponible la variable para ser usada más adelante con sentencias @php
¿Alguna idea de cómo se manejan los espacios de variables en Blade?
Les agradezco por haber leído hasta acá y más si me pudieran ayudar.


text:
Q: Are mutable hashmap keys a dangerous practice? Is it bad practice to use mutable objects as Hashmap keys?  What happens when you try to retrieve a value from a Hashmap using a key that has been modified enough to change its hashcode?
For example, given
class Key
{
    int a; //mutable field
    int b; //mutable field

    public int hashcode()
        return foo(a, b);
    // setters setA and setB omitted for brevity
}

with code
HashMap<Key, Value> map = new HashMap<Key, Value>();

Key key1 = new Key(0, 0);
map.put(key1, value1); // value1 is an instance of Value

key1.setA(5);
key1.setB(10);

What happens if we now call map.get(key1)?  Is this safe or advisable?  Or is the behavior dependent on the language?

A: It has been noted by many well respected developers such as Brian Goetz and Josh Bloch that :

If an object's hashCode() value can change based on its state, then we
  must be careful when using such objects as keys in hash-based
  collections to ensure that we don't allow their state to change when
  they are being used as hash keys. All hash-based collections assume
  that an object's hash value does not change while it is in use as a
  key in the collection. If a key's hash code were to change while it
  was in a collection, some unpredictable and confusing consequences
  could follow. This is usually not a problem in practice — it is not
  common practice to use a mutable object like a List as a key in a
  HashMap.

A: Hash maps use hash code and equality comparisons to identify a certain key-value pair with a given key. If the has map keeps the key as a reference to the mutable object, it would work in the cases where the same instance is used to retrieve the value. Consider however, the following case:
T keyOne = ...;
T keyTwo = ...;

// At this point keyOne and keyTwo are different instances and
// keyOne.equals(keyTwo) is true.

HashMap myMap = new HashMap();

myMap.push(keyOne, "Hello");

String s1 = (String) myMap.get(keyOne); // s1 is "Hello"
String s2 = (String) myMap.get(keyTwo); // s2 is "Hello"
                                        // because keyOne equals keyTwo

mutate(keyOne);

s1 = myMap.get(keyOne); // returns "Hello"
s2 = myMap.get(keyTwo); // not found

The above is true if the key is stored as a reference. In Java usually this is the case. In .NET for instance, if the key is a value type (always passed by value), the result will be different:
T keyOne = ...;
T keyTwo = ...;

// At this point keyOne and keyTwo are different instances
// and keyOne.equals(keyTwo) is true.

Dictionary myMap = new Dictionary();

myMap.Add(keyOne, "Hello");

String s1 = (String) myMap[keyOne]; // s1 is "Hello"
String s2 = (String) myMap[keyTwo]; // s2 is "Hello"
                                    // because keyOne equals keyTwo

mutate(keyOne);

s1 = myMap[keyOne]; // not found
s2 = myMap[keyTwo]; // returns "Hello"

Other technologies might have other different behaviors. However, almost all of them would come to a situation where the result of using mutable keys is not deterministic, which is very very bad situation in an application - a hard to debug and even harder to understand.

A: If key's hash code changes after the key-value pair (Entry) is stored in HashMap, the map will not be able to retrieve the Entry.
Key's hashcode can change if the key object is mutable. Mutable keys in HahsMap can result in data loss.

A: This will not work. You are changing the key value, so you are basically throwing it away. Its like creating a real life key and lock, and then changing the key and trying to put it back in the lock.

A: This is not safe or advisable.  The value mapped to by key1 can never be retrieved.  When doing a retrieval, most hash maps will do something like
Object get(Object key) {
    int hash = key.hashCode();
    //simplified, ignores hash collisions,
    Entry entry = getEntry(hash);
    if(entry != null && entry.getKey().equals(key)) {
        return entry.getValue();
    }
    return null;
}

In this example, key1.hashcode() now points to the wrong bucket of the hash table, and you will not be able to retrieve value1 with key1.
If you had done something like,
Key key1 = new Key(0, 0);
map.put(key1, value1);
key1.setA(5);
Key key2 = new Key(0, 0);
map.get(key2);

This will also not retrieve value1, as key1 and key2 are no longer equal, so this check
    if(entry != null && entry.getKey().equals(key))

will fail.

A: As others explained, it is dangerous.
A way to avoid that is to have a const field giving explicitly the hash in your mutable objects (so you would hash on their "identity", not their "state"). You might even initialize that hash field more or less randomly.
Another trick would be to use the address, e.g. (intptr_t) reinterpret_cast<void*>(this) as a basis for hash.
In all cases, you have to give up hashing the changing state of the object.

A: There are two very different issues that can arise with a mutable key depending on your expectation of behavior.
First Problem: (probably most trivial--but hell it gave me problems that I didn't think about!)
You are attempting to place key-value pairs into a map by updating and modifying the same key object. You might do something like Map<Integer, String> and simply say:
int key = 0;
loop {
    map.put(key++, newString);
}

I'm reusing the "object" key to create a map. This works fine in Java because of autoboxing where each new value of key gets autoboxed to a new Integer object. What would not work is if I created my own (mutable) Integer object:
MyInteger {
   int value;

   plusOne(){
      value++;
   }
}

Then tried the same approach:
MyInteger key = new MyInteger(0);
loop{
   map.put(key.plusOne(), newString)
}

My expectation is that, for instance, I map 0 -> "a" and 1 -> "b". In the first example, if I change int key = 0, the map will (correctly) give me "a". For simplicity let's assume MyInteger just always returns the same hashCode() (if you can somehow manage to create unique hashCode values for all possible states of an object, this will not be an issue, and you deserve an award). In this case, I call 0 -> "a", so now the map holds my key and maps it to "a", I then modify key = 1 and try to put 1 -> "b". We have a problem! The hashCode() is the same, and the only key in the HashMap is my MyInteger key object which has just been modified to be equal to 1, so It overwrites that key's value so that now, instead of a map with 0 -> "a" and 1 -> "b", I have 1 -> "b" only! Even worse, if I change back to key = 0, the hashCode points to 1 -> "b", but since the HashMap's only key is my key object, it satisfied the equality check and returns "b", not "a" as expected.
If, like me, you fall prey to this type of issue, it's incredibly difficult to diagnose. Why? Because if you have a decent hashCode() function it will generate (mostly) unique values. The hash value will largely take care of the inequality problem when structuring the map but if you have enough values, eventually you'll get a collision on the hash value and then you get unexpected and largely inexplicable results. The resultant behavior is that it works for small runs but fails for larger ones.
Advice:
To find this type of issue, modify the hashCode() method, even trivially (i.e. = 0--obviously when doing this, keep in mind that the hash values should be the same for two equal objects*), and see if you get the same results--because you should and if you don't, there's likely a semantic error with your implementation that's using a hash table.
*There should be no danger (if there is--you have a semantic problem) in always returning 0 from a hashCode() (although it would defeat the purpose of a Hash Table). But that's sort of the point: the hashCode is a "quick and easy" equality measure that's not exact. So two very different objects could have the same hashCode() yet not be equal. On the other hand, two equal objects must always have the same hashCode() value.
p.s. In Java, from my understanding, if you do such a terrible thing (as have many hashCode() collisions), it will start using a red-black-tree as opposed to ArrayList. So when you expect O(1) lookup, you'll get O(log(n))--which is better than the ArrayList which would give O(n).
Second Problem:
This is the one that most others seem to be focusing on, so I'll try to be brief. In this use case, I try to map a key-value pair and then I do some work on the key and then want to come back and get my value.
Expectation: key -> value is mapped, I then modify key and try to get(key). I expect that will give me value.
It seems kind of obvious to me that this wouldn't work but I'm not above having tried to use things like Collections as a key before (and quite quickly realizing it doesn't work). It doesn't work because it's quite likely that the hash value of key has changed so you won't even be looking in the correct bucket.
This is why it's very inadvisable to use collections as keys. I would assume, if you were doing this, you're trying to establish a many-to-one relationship. So I have a class (as in teaching) and I want two groups to do two different projects. What I want is that given a group, what is their project? Simple, I divide the class in two, and I have group1 -> project1 and group2 -> project2. But wait! A new student arrives so I place them in group1. The problem is that group1 has now been modified and likely its hash value has changed, therefore trying to do get(group1) is likely to fail because it will look in a wrong or non-existent bucket of the HashMap.
The obvious solution to the above is to chain things--instead of using the groups as keys, give them labels (that don't change) that point to the group and therefore the project: g1 -> group1 and g1 -> project1, etc.
p.s.
Please make sure to define a hashCode() and equals(...) method for any object you expect to use as a key (eclipse and, I'm assuming, most IDE's can do this for you).
Code Example:
Here is a class which exhibits the two different "problem" behaviors. In this case, I attempt to map 0 -> "a", 1 -> "b", and 2 -> "c" (in each case). In the first problem, I do that by modifying the same object, in the second problem, I use unique objects, and in the second problem "fixed" I clone those unique objects. After that I take one of the "unique" keys (k0) and modify it to attempt to access the map. I expect this will give me a, b, c and null when the key is 3.
However, what happens is the following:
map.get(0) map1: 0 -> null, map2: 0 -> a, map3: 0 -> a
map.get(1) map1: 1 -> null, map2: 1 -> b, map3: 1 -> b
map.get(2) map1: 2 -> c, map2: 2 -> a, map3: 2 -> c
map.get(3) map1: 3 -> null, map2: 3 -> null, map3: 3 -> null

The first map ("first problem") fails because it only holds a single key, which was last updated and placed to equal 2, hence why it correctly returns "c" when k0 = 2 but returns null for the other two (the single key doesn't equal 0 or 1). The second map fails twice: the most obvious is that it returns "b" when I asked for k0 (because it's been modified--that's the "second problem" which seems kind of obvious when you do something like this). It fails a second time when it returns "a" after modifying k0 = 2 (which I would expect to be "c"). This is more due to the "first problem": there's a hash code collision and the tiebreaker is an equality check--but the map holds k0, which it (apparently for me--could theoretically be different for someone else) checked first and thus returned the first value, "a" even though had it kept checking, "c" would have also been a match. Finally, the 3rd map works perfectly because I'm enforcing that the map holds unique keys no matter what else I do (by cloning the object during insertion).
I want to make clear that I agree, cloning is not a solution! I simply added that as an example of why a map needs unique keys and how enforcing unique keys "fixes" the issue.
public class HashMapProblems {

   private int value = 0;

   public HashMapProblems() {
       this(0);
   }

   public HashMapProblems(final int value) {
       super();
       this.value = value;
   }

   public void setValue(final int i) {
       this.value = i;
   }

   @Override
   public int hashCode() {
       return value % 2;
   }

   @Override
   public boolean equals(final Object o) {
       return o instanceof HashMapProblems
            && value == ((HashMapProblems) o).value;
   }

   @Override
   public Object clone() {
       return new HashMapProblems(value);
   }

   public void reset() {
       this.value = 0;
   }

   public static void main(String[] args) {
       final HashMapProblems k0 = new HashMapProblems(0);
       final HashMapProblems k1 = new HashMapProblems(1);
       final HashMapProblems k2 = new HashMapProblems(2);
       final HashMapProblems k = new HashMapProblems();
       final HashMap<HashMapProblems, String> map1 = firstProblem(k);
       final HashMap<HashMapProblems, String> map2 = secondProblem(k0, k1, k2);
       final HashMap<HashMapProblems, String> map3 = secondProblemFixed(k0, k1, k2);

       for (int i = 0; i < 4; ++i) {
           k0.setValue(i);
           System.out.printf(
                "map.get(%d) map1: %d -> %s, map2: %d -> %s, map3: %d -> %s",
                i, i, map1.get(k0), i, map2.get(k0), i, map3.get(k0));
           System.out.println();
       }
   }

   private static HashMap<HashMapProblems, String> firstProblem(
        final HashMapProblems start) {
       start.reset();
       final HashMap<HashMapProblems, String> map = new HashMap<>();

       map.put(start, "a");
       start.setValue(1);
       map.put(start, "b");
       start.setValue(2);
       map.put(start, "c");
       return map;
   }

   private static HashMap<HashMapProblems, String> secondProblem(
        final HashMapProblems... keys) {
       final HashMap<HashMapProblems, String> map = new HashMap<>();

       IntStream.range(0, keys.length).forEach(
            index -> map.put(keys[index], "" + (char) ('a' + index)));
       return map;
   }

   private static HashMap<HashMapProblems, String> secondProblemFixed(
        final HashMapProblems... keys) {
       final HashMap<HashMapProblems, String> map = new HashMap<>();

       IntStream.range(0, keys.length)
            .forEach(index -> map.put((HashMapProblems) keys[index].clone(),
                    "" + (char) ('a' + index)));
       return map;
   }
}

Some Notes:
In the above it should be noted that map1 only holds two values because of the way I set up the hashCode() function to split odds and evens. k = 0 and k = 2 therefore have the same hashCode of 0. So when I modify k = 2 and attempt to k -> "c" the mapping k -> "a" gets overwritten--k -> "b" is still there because it exists in a different bucket.
Also there are a lot of different ways to examine the maps in the above code and I would encourage people that are curious to do things like print out the values of the map and then the key to value mappings (you may be surprised by the results you get). Do things like play with changing the different "unique" keys (i.e. k0, k1, and k2), try changing the single key k. You could also see how even the secondProblemFixed isn't actually fixed because you could also gain access to the keys (for instance via Map::keySet) and modify them.

A: I won't repeat what others have said. Yes, it's inadvisable. But in my opinion, it's not overly obvious where the documentation states this.
You can find it on the JavaDoc for the Map interface:

Note: great care must be exercised if mutable objects are used as map
keys. The behavior of a map is not specified if the value of an object
is changed in a manner that affects equals comparisons while the
object is a key in the map

A: Behaviour of a Map is not specified if value of an object is changed in a manner that affects equals comparision while object(Mutable) is a key. Even for Set also using mutable object as key is not a good idea.
Lets see a example here :
public class MapKeyShouldntBeMutable {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Map<Employee,Integer> map=new HashMap<Employee,Integer>();

    Employee e=new Employee();
    Employee e1=new Employee();
    Employee e2=new Employee();
    Employee e3=new Employee();
    Employee e4=new Employee();
    e.setName("one");
    e1.setName("one");
    e2.setName("three");
    e3.setName("four");
    e4.setName("five");
    map.put(e, 24);
    map.put(e1, 25);
    map.put(e2, 26);
    map.put(e3, 27);
    map.put(e4, 28);
    e2.setName("one");
    System.out.println(" is e equals e1 "+e.equals(e1));
    System.out.println(map);
    for(Employee s:map.keySet())
    {
        System.out.println("key : "+s.getName()+":value : "+map.get(s));
    }
}

  }
 class Employee{
String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public boolean equals(Object o){
    Employee e=(Employee)o;
    if(this.name.equalsIgnoreCase(e.getName()))
            {
        return true;
            }
    return false;

}

public int hashCode() {
    int sum=0;
    if(this.name!=null)
    {
    for(int i=0;i<this.name.toCharArray().length;i++)
    {
        sum=sum+(int)this.name.toCharArray()[i];
    }
    /*System.out.println("name :"+this.name+" code : "+sum);*/
    }
    return sum;

}

}

Here we are trying to add mutable object "Employee" to a map. It will work good if all keys added are distinct.Here I have overridden equals and hashcode for employee class.
See first I have added "e" and then "e1". For both of them equals() will be true and hashcode will be same. So map sees as if the same key is getting added so it should replace the old value with e1's value. Then we have added e2,e3,e4 we are fine as of now.
But when we are changing the value of an already added key i.e "e2" as one ,it becomes a key similar to one added earlier. Now the map will behave wired. Ideally e2 should replace the existing same key i.e e1.But now map takes this as well. And you will get this in o/p :
 is e equals e1 true
{Employee@1aa=28, Employee@1bc=27, Employee@142=25, Employee@142=26}
key : five:value : 28
key : four:value : 27
key : one:value : 25
key : one:value : 25

See here both keys having one showing same value  also. So its unexpected.Now run the same programme again by changing e2.setName("diffnt"); which is e2.setName("one"); here ...Now the o/p will be this :
 is e equals e1 true
{Employee@1aa=28, Employee@1bc=27, Employee@142=25, Employee@27b=26}
key : five:value : 28
key : four:value : 27
key : one:value : 25
key : diffnt:value : null

So by adding changing the mutable key in a map is not encouraged.

A: To make the answer compact:
The root cause is that HashMap calculates an internal hash of the user's key object hashcode only once and stores it inside for own needs.
All other operations for data navigation inside the map are doing by this pre-calculated internal hash.
So if you change the hashcode of the key object (mutate) it will be still stored nicely inside the map with the changed key object's hashcode (you could even observe it via HashMap.keySet() and see the altered hashcode).
But HashMap internal hash will not be recalculated of course and it will be the old stored one and the map won't be able to locate your data by the provided mutated key object new hashcode. (e.g. by HashMap.get() or HashMap.containsKey()).
Your key-value pairs will be still inside the map but to get it back you will need that old hash code value that was given when you put your data into the map.
Notice that you also will be unable to get data back by the mutated key object taken right from the HashMap.keySet().


text:
Q: CVXR Elementwise multiplication of matrix with vector I want to use CVXR to find the optimal values of a vector. In the objective function i need to multiply a matrix with a vector in an elementwise way:
b: Nx1 vector
X: Nxp matrix
result: Nxp matrix
Example:
# Set the dims
N <- 50
p <- 5
X <- matrix(rnorm(N*p), N, p)

# to find the optimal values using optim() one could simply have a numeric object
# say the optimal values are 0.1, -0.2, 0.3, -0.5, 0.6
b <- c(0.1, -0.2, 0.3, -0.5, 0.6)

# Then we can have the Nxp matrix with the product
# (where column i of X is multiplied by element i of b) is given by
X*b

b is the vector of coefficient to be optimised.
Using CVXR one must declare
b <- Variable(p)

as Variable object with uses the matrix form, therefore later we can't really multiply as in the previous case.
Also, we don't want to create a matrix of b: Nxp because we need to have one optimal value for all N observations of the i-th column (therefore the mul_elemwise(X, X*b) option wouldn't work as it would give different optimal values for different observations of N - if I am not mistaken).
thanks,

A: To recap: this is the R behavior:
> m <- 2
> n <- 3
> A <- matrix(c(1,2,3,4,5,6),m,n)
> A
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> x <- c(1,2)
> A*x
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    4    8   12
>

This is essentially
A[i,j]*x[i]

R behind the scenes extends (recycles) x to have it as many elements as A and then does elementwise multiplication in a columnwise fashion.
In CVXR things are a bit different. %*% is for matrix multiplication and * is for elementwise multiplication. But CVXR does not do this recycling. So for A*x it requires A and x to have the same shape (i.e. an (mxn) matrix).
This means we need to do this extending (recycling) ourselves. This can be written as follows:
> x %*% t(rep(1,n))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2

So we can write:
> A * (x %*% t(rep(1,n)))
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    4    8   12

This is what we can use in the CVXR model:
> library(CVXR)
> x <- Variable(m)
> Y <- Variable(m,n)
> e <- t(rep(1,n))
> e
     [,1] [,2] [,3]
[1,]    1    1    1
> problem <- Problem(Minimize(0),list(x == c(1,2), Y == A * (x %*% e)) )
> sol <- solve(problem)
> sol$status
[1] "optimal"
> sol$getValue(x)
     [,1]
[1,]    1
[2,]    2
> sol$getValue(Y)
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    4    8   12
>


text:
Q: Overloading the << operator inside a class I usually keep my classes in 2 files : class.h and class.cpp
I want to do something like cout << myclass;
I have found examples like :
friend ostream& operator<<(ostream &os, XXLint)
{ // do stuff
}

But the above function gets explicited right after the declaration.
How should I declare it in myclass.h in order to be able to use it in myclass.cpp ? And also what would the entire function's header be in the .cpp file ( eg : myclass::myclass() ).

A: In the class definition in the header:
struct Foo
{
  int a, b;
  friend std::ostream& operator<<(std::ostream &os, const Foo&);
};

In an implementation (e.g. .cpp file):
std::ostream& operator<<(std::ostream &os, const Foo& f)
{
  return os << f.a << " " << f.b;
}


text:
Q: Insert multiple values to an API query i´m pretty new and unexpirenced at API´s. I´m using postman to get some seluts from a database.
https://www.website.com/xmlapi/api.php?cid=abc&auth=123456&command=product&model={{model}}
I´ve created the value of the key model as a variable. Now I want to get more than 1 result from the API for ex. 5 Values:
123456
654321
987456
253698
521251
How can I include this list of values into postman?
I also have a csv file for upload.
I want to get back one xml file with all values of the key model.
Can anybody help?
Best regards
Christian

A: I've imagine you are going to send a GET request.You can include necessary API parameters in your API call,If it is a Post request you may use model class to get a xml back. Also follow this
See below example :
  [HttpGet("number-count/{Num1}/{Num2}/{Num3}/{Num4}/{Num5}/")]
        public ActionResult GetNumberData(int Num1, int Num2, int Num3, int Num4, int Num5)
        {
            try
            {
                return Ok(_service.GetNumberConsumption(Num1,Num2,Num3,Num4,Num5));

            }
            catch (Exception ex)
            {
                return NoContent();
            }
        }