text:
Q: Failed to execute MAVEN goal using netbeans 7.3.1, JDK 7x64 does not work on Win 8 64-bit I'm new and I'm starting with maven using NETBEANS now install 7.3.1, JDK 7x64, I formatted my Win 8 64-bit machine now I have problems with NETBEANS or MAVEN've tried everything, create the variables JAVA_HOME, I installed maven NETBEANS matter and I have the same error.
I've used VirtualBox with Win Xp and perfect running Maven, I have no connection error not use proxy, but in Win 8 does not work, I turned off antivirus, Firewall
mvn.bat -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee6 -DarchetypeVersion=1.5 -DarchetypeRepository=http://repo.maven.apache.org/maven2 -DgroupId=com.mycompany -DartifactId=mavenproject1 -Dversion=1.0-SNAPSHOT -Dpackage=com.mycompany.mavenproject1 -Dbasedir=C:\\Users\\jaime\\Documents\\NetBeansProjects -Darchetype.interactive=false --batch-mode archetype:generate -X -e

Downloading: http://repo.maven.apache.org/maven2/org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar

Downloading: http://repo.maven.apache.org/maven2/org/apache/ant/ant/1.8.1/ant-1.8.1.jar
  [DEBUG] Writing resolution tracking file C:\Users\jaime.m2\repository\org\codehaus\groovy\groovy\1.8.3\groovy-1.8.3.jar.lastUpdated
  [DEBUG] Writing resolution tracking file C:\Users\jaime.m2\repository\org\apache\ant\ant\1.8.1\ant-1.8.1.jar.lastUpdated

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.2:generate (default-cli) on project standalone-pom: Execution default-cli of goal org.apache.maven.plugins:maven-archetype-plugin:2.2:generate failed: Plugin org.apache.maven.plugins:maven-archetype-plugin:2.2 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.codehaus.groovy:groovy:jar:1.8.3, org.apache.ant:ant:jar:1.8.1: Could not transfer artifact org.codehaus.groovy:groovy:jar:1.8.3 from/to central (http://repo.maven.apache.org/maven2): GET request of: org/codehaus/groovy/groovy/1.8.3/groovy-1.8.3.jar from central failed: Connection reset -> [Help 1]

A: I've run into similar issues and never tracked down the exact problem, but somewhere along the line, reinstalling Java sets it right.


text:
Q: How to reduce the Committed Memory of an application? I have a game exe, and I want to reduce it's memory usage. I currently use EmptyWorkingSet function to keep Working Set around 10.000-50.000 KBs. However the system commits 1.000.000 KBs for the game. How can I reduce this amount programmatically (via windows dll functions etc.) or in any other way?
Image   PID Hard Faults/sec Commit (KB) Working Set (KB)    Shareable (KB)  Private (KB)
An Online Game.exe  3228    0   1.117.252   53.320  6.720   46.600

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nested for loop inside do while to keep player's turns in order This is a beginning attempt to create a turn counter for a simple turn-based game.  Although it's currently an infinite loop, I'm curious if there's a better or more elegant way to do what I want to do - keep players turns in order throughout a complete game.
public class Main {
    public static void main(String args[]){

        int i;     // player turn counter
        int j = 6; // number of players created + 1

        do {
            for (i=1; i < j; i++){
                System.out.println("Player " + i);  // just for visualization
            }
        }while (true);
    }
}

I'm extremely new with java. I have found that basic for loops need +1 to avoid counting -1 lower.
My while condition will be a check for a winner, say:
while(winner == false)

or
while(!winner)

A: Your method seems to be the best case scenario right now.
Other methods involve using arrays which will just complicate things here.
Though to save the nested loop, you can just add the condition of !winner to the for loop
for (i=1; i < j && winner == false; i++)
    {
        System.out.println("Player " + i);
        if(i==j)
            i=1;
    }

this will work as good and will save the other loop.

A: That is completely fine, just a few observations while(winner == false) as a single = means assignment and == means comparison.


text:
Q: Correct way to create a editable component fetching data from server? I have a component called EditProfile where the user can update the info of their profile. Below is simplified version of component.
class EditProfile extends Component {
  state = {
    editable: false,

    //main form data goes below here
    username: "",
    fullname: "",
    country: "",
    gender: "",
    description: "",

  };
  setGender = e => {
    this.setState({ gender: e.target.value });
  };

  onInputChange = e => {
    this.setState({ errors: {} });
    this.setState({ [e.target.name]: e.target.value });
  };

  static getDerivedStateFromProps = (nextProps, prevState) => {
    if (nextProps.profile.username !== prevState.username) {
      return { username: nextProps.profile.username };
    }
  };
  render() {

    return (

Personal Information

        <input
          type="text"
          className="ProfileSignUp__username"
          placeholder="Username"
          name="username"
          value={this.state.username}
          onChange={this.onInputChange}
        />
        {this.state.errors.username}
        <input
          type="text"
          className="ProfileSignUp__fullname"
          placeholder="Fullname"
          name="fullname"
          value={this.state.fullname}
          onChange={this.onInputChange}
        />
        {this.state.errors.fullname}

          Save Profile

    );
  }
}

const mapStateToProps = state => ({
  profile: state.profile
});

As you can see the value on state is set from getDerivedStateFromProps.I want to wait till the profile is received from server in mapStateToProps.After that I want to update the value in state with the props from profile.Once that is done I want to switch to editable mode. The program should not care about the props and I can freely update the value in state. But with the current way the value in state is set correctly once the data is received from the server but I cannot update it. Can anyone suggest me correct pattern to do that?

A: I figured out a way to do this. You can do something like this in getDerivedStateFromProps
  static getDerivedStateFromProps = (nextProps, prevState) => {
    //After the data is fetched once from the server
    //editable is set to true and this function never runs
    //It just sets the value of state from props one time
    if (
      nextProps.profile &&
      nextProps.profile.loggedIn &&
      !prevState.editable
    ) {
      return {
        username: nextProps.profile.username,
        fullname: nextProps.profile.fullname,
        gender: nextProps.profile.gender,
        description: nextProps.profile.description,
        userImage: nextProps.profile.userImage,
        editable: true
      };
    }
  };


text:
Q: Change ionic bundle identifier not working in IOS I hade to create a new Ionic app since the first one stopped working.
After that It got new numbers in the end of the name (i.e old name com.ionicframework.test420004, new name com.ionicframework.test122446).
I changed it everywhere (search and replace in VisualStudio 2015) I could find in the project.
IOS still looks for local (downloaded) files with the path of the wrong application name.
Does anybody know how to change it?

A: In this scenario you have to build it using cordova on a Apple computer. You can't build it and add the platform on a pc and the export the platform to an Apple computer.


text:
Q: Series of FileReadLine command Searching in files for some code lines. My script for first line:
FileReadLine, OutputVar, C:\Files\prog.txt, 1
If (OutputVar = "FileRead, OutputVar, C:\Files\prog1.txt")
    MsgBox Code line found
else
    MsgBox Code line not found

How searching by this method in some area? Lines from 50 to 250, 205 to 551, etc.

A: Use a file parsing loop: http://ahkscript.org/docs/commands/LoopReadFile.htm
Loop, read, C:\Files\prog.txt
{
    If (A_LoopReadLine = "FileRead, OutputVar, C:\Files\prog1.txt") {
        MsgBox, An interesting code line was found.
    } Else If (A_LoopReadLine = "blablabla") {
        MsgBox, An interesting code line was found.
    } Else If (A_LoopReadLine = "some other text line") {
        MsgBox, An interesting code line was found.
    ;} Else {
    ;    MsgBox, Nothing important was found
    ;}

}


text:
Q: Hosting static file for Download Python Tornado Hey I am struggling to have a static file available for download using Python and Tornado on my server.
class templateHandler(tornado.web.RequestHandler):
def get(self):
    self.write("""
    <a href="/download"> Download </a>
    """)

application = tornado.web.Application([
(r"/", MyFormHandler),
(r"/results", MyFormHandler),
(r"/multi", MyFileHandler),
(r"/upload",MyFileHandler),
(r'/download',tornado.web.StaticFileHandler,{'path':"L:/Template.csv"}),
(r'/template', templateHandler),
(r"/SFA",SFAHandler),
])

Can someone help me out. I am not 100% certain on how the file handler works.
Thanks for your help!
EDIT:
Here is the error message:
ERROR:root:Uncaught exception GET /download (10.18.4.160)
HTTPRequest(protocol='http', host='IPadress', method='GET', uri='/download', version='HTTP/1.1', remote_ip='IPaddress', body='', headers={'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', >'Referer': 'IPadress/template', 'Host': 'IPaddress', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20100101 Firefox/17.0'})
Traceback (most recent call last):
  File "WEB.PY LOCATION", line >988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
TypeError: get() takes at least 2 arguments (1 given)
ERROR:root:500 GET /download (IPaddress) 0.00ms

A: I'm thinking it has to do with StaticFileHandler.get expecting a path, usually it does not serve a single file, but instead serves a directory of files, and takes a filename i don't have time to dig into it right now but it sshould be something like
(r'/download/(.*)',tornado.web.StaticFileHandler,{'path':"L:/"}),
now if you go to
/download/Template.csv it should serve it.  Sorry I don't have time right now to look into source to confirm


text:
Q: Database time data retrieval, time based queries I am new to time manipulation or time arithmetic operations
and am currently developing a navigation system with Web server based information and currently I have this Database that contains a table peek hours whose columns are id, start_time, end_time , edge_id, day_of_the_week, edge_weight
 ------------------------------------------------------------------------
|                  Peek Hours                                           |
 ------------------------------------------------------------------------
|    |            |           |         |                 |             |
| id | start_time |  end_time | edge_id | day_of_the_week | edge_weight |
|    |            |           |         |                 |             |
 ------------------------------------------------------------------------

I am using PHP as a webservice and so based on the current time i want to get all the records that would fit this equation
start_time< current_time < end_time

A: As the other comments suggest, you didn't look very hard.
 SELECT *
 FROM peek_hours
 WHERE start_time < NOW()
 AND NOW() < end_time

You can also do this:
 SELECT *
 FROM peek_hours
 WHERE NOW() between start_time AND end_time

Although BETWEEN is "less than or equal to".


text:
Q: CUDA error: invalid device ordinal when using python 3.9 I'm trying to excute a code, but I keep geting this error when compiling this piece of code:
  import tensorflow as tf

  from xba import XBA

  import torch

  torch.tensor([1, 2, 3, 4]).to(device="cuda:2")

torch.tensor([1, 2, 3, 4]).to(device="cuda:2") generates this error: "
RuntimeError: CUDA error: invalid device ordinal
CUDA kernel errors might be asynchronously reported at some other API call,so the
stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

AnyIdea about the origine of the bug, it's just the first line of code!!

A: "cuda:2"

selects the third GPU in your system.  If you don't have 3 GPUs (at least) in your system, you'll get this error.
Assuming you have at least 1 properly installed and set up CUDA GPU available, try:
"cuda:0"


text:
Q: Git: untrack a file in local repo only and keep it in the remote repo I have a NetBeans file "nbproject/project.properties" that always shows up in the "Changes not staged for commit" section (when I do git status). How could I move this to the Untracked files section (without adding it to .gitignore) ? I tried this command git rm --cached but what happened is the file shows as untracked in my local repo and got removed in the remote one but what I want is to keep it in remote and untrack only in local repo.

A: You could update your index:
cd /root/folder/of/your/repo
git update-index --assume-unchanged nbproject/project.properties

and make sure it never shows as "updated" in your current repo.
That means it won't ever be pushed, but it is still present in the index.
(and it can be modified at will in your local working tree).

*

*to revert that state (from git-ready):

git update-index --no-assume-unchanged <file>

*

*to see all assume unchanged files (from Gabe Kopley's comment)

git ls-files -v | grep '^h '


text:
Q: Dropping column using tidyverse and base R - the difference While trying to fit a randomForest and to use select to choose/drop columns of data frame by name I ended up with a strange behaviour:
library(MASS)
library(dplyr)
library(purrr)
library(randomForest)

train = base::sample(1:nrow(Boston), nrow(Boston)/2)
glimpse(Boston)
p <- ncol(Boston) - 1
ps <- 1:p
map_dbl(ps, ~mean(randomForest(x = select(Boston[train,], -medv),
                           y = select(Boston[train,], medv),
                           xtest = select(Boston[-train,], -medv),
                           ytest = select(Boston[-train,], medv),
                           mtry = .x, ntree = 500)$test$mse))

This ended up with following error:

Error in randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train,  :
    length of response must be the same as predictors
  In addition: Warning message:
  In randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train,  :
    The response has five or fewer unique values.  Are you sure you want to do regression?

However, when I defined x, y, xtest, ytest with base R the formula works:
map_dbl(ps, ~mean(randomForest(x = Boston[train, -14],
                           y = Boston[train, 14],
                           xtest = Boston[-train, -14],
                           ytest = Boston[train, 14],
                           mtry = .x, ntree = 500)$test$mse))

[1] 119.9225 132.5212 136.7131 139.7398 142.9167 144.2151 145.0587 146.9056 148.7087 148.1903 150.3910
  [12] 151.5579 151.2323

So I have checked if these two different ways of subsetting my dataset give the same results... and the do.
all(select(Boston[train,], -medv) == Boston[train, -14])
all(select(Boston[train,], medv) == Boston[train, 14])
all(select(Boston[-train,], -medv) == Boston[-train, -14])
all(select(Boston[-train,], medv) == Boston[-train, 14])

All of these results in TRUE. Why the first subsetting approach with use of select ends up with error in randomForest model then? What is the other way to drop the column using their name? (something like Boston[,-"medv"] which obviously doesn't work.

A: The issue is with the y's in randomForest. They need to be vectors and not data.frames.
If you use dplyr::select it always returns a data.frame.
str(dplyr::select(Boston, medv)
'data.frame':   506 obs. of  1 variable:
 $ medv: num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

compared to selecting a single column via base R
str(Boston[, 14])
 num [1:506] 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

To get the same result as dplyr when selecting 1 column, you need drop = FALSE in a data.frame single column select.
str(Boston[, 14, drop = FALSE])
'data.frame':   506 obs. of  1 variable:
 $ medv: num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

For getting your code correct you can use as_vector from purrr to force the data.frame containing medv into a vector.
map_dbl(ps, ~mean(randomForest(x = dplyr::select(Boston[train,], -medv),
                               y = as_vector(dplyr::select(Boston[train,], medv)),
                               xtest = dplyr::select(Boston[-train,], -medv),
                               ytest = as_vector(dplyr::select(Boston[-train,], medv)),
                               mtry = .x, ntree = 500)$test$mse))

[1] 22.36214 15.52031 13.24707 12.22685 12.32809 11.82220 11.91149 11.65336 12.05399 12.16599 12.63174 12.79196 12.41167

A: Run the following code, we can see that the second and fourth lines are actually different.
identical(select(Boston[train,], -medv), Boston[train, -14])
# [1] TRUE
identical(select(Boston[train,], medv), Boston[train, 14])
# [1] FALSE
identical(select(Boston[-train,], -medv), Boston[-train, -14])
# [1] TRUE
identical(select(Boston[-train,], medv), Boston[-train, 14])
# [1] FALSE

The key is select(Boston[train,], medv) returns a data frame, but Boston[train, 14] returns a vector. It looks like we need to provide a vector to the y and ytest argument.
As a result, the following will work because pull from the dplyr package returns a vector.
map_dbl(ps, ~mean(randomForest(x = select(Boston[train,], -medv),
                               y = pull(Boston[train,], medv),
                               xtest = select(Boston[-train,], -medv),
                               ytest = pull(Boston[-train,], medv),
                               mtry = .x, ntree = 500)$test$mse))

We can also use pluck from the purrr package.
map_dbl(ps, ~mean(randomForest(x = select(Boston[train,], -medv),
                               y = pluck(Boston[train,], "medv"),
                               xtest = select(Boston[-train,], -medv),
                               ytest = pluck(Boston[-train,], "medv"),
                               mtry = .x, ntree = 500)$test$mse))

One final thing, I think for your second example, the ytest argument should be Boston[-train, 14], you lack a minus sign.


text:
Q: collecting terms in a Differential Equation in Maple Is there anyway to make maple collect terms in a differential equation? say for example
$\dot{y}+y=3\dot{y}-7y$  so I get automatically $2\dot{y}-8y=0$

A: [> s:=y'(x)+y(x)=3y'(x)-7y(x):
   t:=lhs(s)-rhs(s);

                                -2y'(x)+8y(x)=0


text:
Q: JComponent - set transparent background I have on a panel a JTable and a JLabel. I set it a background image but I can't get rid of that grey background from the table and label.
How can I do it?

A: Try doing .setOpaque(false); on your JTable and JLabel


text:
Q: An unexpected error has occurred. Please retry your request later I have a problem with open graph.
When I use debug facebook tools I have this error message :
"error": {
  "message": "An unexpected error has occurred. Please retry your request later.",
  "type": "OAuthException",
  "code": 2
}

When I use Graph API Explorer with token generator :
Type POST : https://graph.facebook.com/1145358260/univercial:read
Add a New field : lesson   http://www.filmslive.net/cours-6
It's ok!!!
This is my code :

    <title>Univercial | Read <?php echo $nom; ?>Lesson</title>
    <meta property="fb:app_id" content="429852050395283" />
    <meta property="og:type" content="univercial:Lesson" />
    <meta property="og:url" content="http://www.filmslive.net/cours-6">
    <meta property="og:title" content="Read <?php echo $nom; ?> Lesson" />
    <meta property="og:description" content="1ére Plateform d'interraction entre les jeunes étudiants du Maroc" />
    <meta property="og:image" content="http://www.filmslive.net/images/200_200.jpg" />
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />

                            <form>
                                <input class="float_left bouton_vert" type="button" value="Read" onclick="postRead()" />
                            </form>

Result : alert('erreur')
I can use feed, but, I can't use publish_actions.


text:
Q: Is there any way to implement system() function I tried to re-implement the system() library function. But I am not getting the output if i pass ps or ls command as an argument from the main. Thanks.
Original code:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
#define buf_size 512

int main(int argc, char *argv[])
{
    pid_t pid;
    char *buf[buf_size];
    int ret = 0;
    char ch;
    int i = 0;
    int j = 0;

    if (argc != 2)
        error(1, 0, "Too many of less number of arguments\n");

    for (i = 1; i < argc; i++) {
        *(buf + j) = argv[i];
        j++;
    }
    buf[j] = '\0';
    pid = fork();
    if (pid == -1) {
        error(1, 0, "error in creating the sub-process\n");
    } else if (pid == 0) {
        execv("bin/sh", buf);
    } else {
        wait(NULL);
    }
}

Edited code after reading some comments in this post:
int main(int argc, char *argv[])
{
    pid_t pid;
    int ret;

    if (argc != 2)
        error(1, 0, "Too many of less number of arguments\n");
    pid = fork();
    if (pid == -1) {
        error(1, 0, "error in creating the sub-process\n");
    } else if (pid == 0) {
        ret = execv("/bin/sh", argv);
        if (ret == -1)
            error(1, 0, "error in execv() system call\n");
    } else {
        wait(NULL);
    }
}

A: You were not far from the solution.
The main thing you miss is that you should have launch /bin/sh -c ls instead of bin/sh ls
The corrections:

*

*do not write buf[j] = "\0";, instead I increased the for loop size (notice the i<= argc)

*launch /bin/sh (forgot leading /)

*add sh and -c to sh options. (see man execv)

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>

int main(int argc, char *argv[])
{
    pid_t pid;
    char * buf[4];

    if (argc != 2)
        error(1, 0, "Too many of less number of arguments\n");

    buf[0] = "sh";
    buf[1] = "-c";
    buf[2] = argv[1];
    buf[3] = NULL;

    pid = fork();
    if (pid == -1) {
        error(1, 0, "error in creating the sub-process\n");
    } else if (pid == 0) {
        execv("/bin/sh", buf);
        perror("execv");
   } else {
        wait(NULL);
    }
}


text:
Q: Display attribute on standard style sheet effecting my handheld style sheet? I am trying have some images hidden when viewed on a desktop but visible when viewed on a mobile device.  I have 2 separate styles linked like this:
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="handheld.css" media="only screen and (max-device-width:480px)"/>

but when i use the display: none; or visibility: hidden; on the style.css it also hides it on my mobile, why is this?  Other styling to the handheld.css work fine and only on my phone.

A: You haven't put a media query on style.css, so it gets used for all devices.
You need to either exclude it from handheld devices, or have handheld.css override those rules.


text:
Q: Move sheet when drop-down menu is selected I want to implement a function that moves to the selected sheet when selecting the drop-down menu (sheet name) in Google spreadsheet, but it's not working well.
The menu shows all the seat names, but if you select that particular seat, nothing will happen.
I keep searching and searching, but I don't see a clear solution. What should I do? Please help me.
The code I wrote is as follows.
code.gs
function onOpen() {
  createMenu()
}

function createMenu(){
  const ui = SpreadsheetApp.getUi()
  const menu = ui.createMenu("Sidebar")
  menu.addItem("Open Sidebar", "openSidebar");
  menu.addToUi()
}

function openSidebar() {
  ss = SpreadsheetApp.getActiveSpreadsheet();
  var html = HtmlService.createTemplateFromFile('sidebar')
  .evaluate()
  .setTitle('Salesforce')
  .setWidth(400);

  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
  .showSidebar(html);
}

sidebar.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>

    <body>
    <button id = "moveButton" class="button alert">Move</button>

    <select name="Available sheets" onchange="moveSheet()" style="width:280px;height:30px;">
      <? var sheets=ss.getSheets(); ?>
      <? for(var i=0;i<sheets.length;i++) { ?>
        <option value=<?=sheets[i].getName()?>> <?= sheets[i].getName()?></option>
      <? } ?>
    </select>

  <script>
    function myJsFunction(){
      var name = document.getElementsByName("Available sheets")[0].value;
    }

    function moveSheet(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName(name);

      if(sheet !=null){
        ss.moveActiveSheet(sheet);

      }else{
       //
      }
    }

    document.getElementById("moveButton").addEventListener("click",moveSheet());
     //google.script.run.withSuccessHandler(name);
    };
  </script>
  </body>
</html>

A: I believe your goal is as follows.

*

*You want to move the sheet by selecting the sheet name from the dropdown list at the sidebar of Spreadsheet.

When I saw your showing script, I thought that you are trying to run the Google Apps Script at the sidebar. At the sidebar and dialog of Spreadsheet, the Javascript is run with the client browser. On the other hand, Google Apps Script is run on the internal server side of Google. I thought that this might be the reason for your issue.
When your showing script is modified for achieving your goal, how about the following modification?
Google Apps Script side: code.gs
In this modification, your function of openSidebar is modified and a new function of moveSheet is added.
Here, in order to move the active sheet, activate() is used.
function moveSheet(e) {
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName(e).activate();
}

function openSidebar() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var options = ss.getSheets().map(s => {
    var sheetName = s.getSheetName();
    return `<option value="${sheetName}">${sheetName}</option>`;
  }).join("");
  var html = HtmlService.createTemplateFromFile('sidebar');
  html.options = options;
  var h = html.evaluate().setTitle('Salesforce').setWidth(400);
  SpreadsheetApp.getUi().showSidebar(h);
}

HTML side: sidebar.html
I modified select tag and removed moveSheet().
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>
  <button id="moveButton" class="button alert">Move</button>
  <select name="Available sheets" onchange="google.script.run.moveSheet(this.value)" style="width:280px;height:30px;">
    <?!= options ?>
  </select>

  <script>
    document.getElementById("moveButton").addEventListener("click",moveSheet());
     //google.script.run.withSuccessHandler(name);
    };
  </script>
</body>

</html>

*

*When you run openSidebar, a sidebar is opened. And, you can see the dropdown list including the sheet names. When you change the dropdown list, the active sheet is changed to the sheet of the selected sheet name.

References:

*

*HTML Service: Templated HTML

*activate()


text:
Q: Accessing object attributes in pyqt window in separate module I have a main window created in one python module. This module also contains a class definition used to create an object called my_settings.
I also have a separate module which creates a another window (which should be in a different module for various reasons). This window allows various inputs such as opening a file and storing some settings once buttons are clicked blaa blaa.
What I want to do is then amend the attributes of my_setttings. A simplified version of the code is:
MAIN MODULE
class MainWindow(QMainWindow):

    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)

        QMainWindow.__init__(self)
        uic.loadUi(self.some_directory + "arc_custom_main.ui", self)

        self.some_button.clicked.connect(self.open_some_widget)

    def open_some_widget(self):
        widget = widget_in_other_module(self)
        widget_in_other_module.exec_()

app = QApplication(sys.argv)
my_settings=settings()
_mainWindow = MainWindow()
_mainWindow.show()

SEPERATE MODULE
class widget_in_other_module(QDialog):

    def __init__(self, parent):

        my_settings.temppath = my_settings.OutputDir

        QDialog.__init__(self)
        self.parent = parent
        my_settings.some_attribute= foo

        uic.loadUi("some.ui", self)

        self.pushButtonOpenMain.clicked.connect(self.openMain)

    def openMain(self):
        my_settings.some_other_attibute=bar

The problem I have is that I can't find a way to be able to access my_settings in the openMain method of widget_in_other_module. I'm a bit of a newbe to qt and can't for the life of me work out where I should pass my_settings. For various reasons I need all the functionality of widget_in_other_module to be outside of the main module (mostly to do with readability and future planed changes to the main module). I've tried as much as I can think of e.g. including it as a parameter in the line self.pushButtonOpenMain.clicked.connect(self.openMain,my_settings) but this doesn't seem to be allowed. Am I missing something basic here?

A: Instantiate settings variable in separate module and import this varable where you need it. It could be object of a class or just dictionary.
storage.py
class Settings:
    def __init__(self):
        print("Settings")

my_settings = Settings()

MainWindow.py
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
from Widget import Widget

from storage import my_settings

class MainWindow(QMainWindow):

    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)
        QMainWindow.__init__(self)
        self.open_some_widget()

    def open_some_widget(self):
        widget = Widget()
        widget.show()
        widget.test()
        self._widget = widget

my_settings.foo = 10

app = QApplication(sys.argv)
_mainWindow = MainWindow()
_mainWindow.show()
app.exec_()

Widget.py
from PyQt5.QtWidgets import QWidget

from storage import my_settings

class Widget(QWidget):

    def test(self):
        print(my_settings.foo)


text:
Q: regex comment matching code in java not working properly I have this code for Identifying the comments and print them in java
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("(\\/\\*((.|\n)*)\\*\\/)|\\/\\/.*");
        String code = "";
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext())
        {
            code+=(scan.nextLine()+"\n");

        }
        Matcher matcher = pattern.matcher(code);
        int nxtBrk=code.indexOf("\n");
        while(matcher.find())
        {

            int i=matcher.start(),j=matcher.end();
            if(nxtBrk<i)
            {
                System.out.print("\n");
            }
            System.out.print(code.substring(i,j));
            nxtBrk = code.indexOf("\n",j);

        }

    scan.close();
    }

}

Now when I try the code against this input
 /*This is a program to calculate area of a circle after getting the radius as input from the user*/
\#include<stdio.h>
int main()
{ //something

It outputs right and only the comments. But when I give the input
 /*This is a program to calculate area of a circle after getting the radius as input from the user*/
\#include<stdio.h>
int main()
{//ok
}
/*A test run for the program was carried out and following output was observed
If 50 is the radius of the circle whose area is to be calculated
The area of the circle is 7857.1429*/

The program outputs the whole code instead of just the comments. I don't know what wrong is doing the addition of that last lines.
EDIT: parser is not an option because I am solving problems and I have to use programming language . link https://www.hackerrank.com/challenges/ide-identifying-comments

A: Parsing source code with regular expressions is very unreliable. I'd suggest you use a specialized parser. Creating one is pretty simple using antlr. And, since you seem to be parsing C source files, you can use the C grammar.

A: Your pattern, shorn of its Java quoting (and some unnecessary backslashes), is this:
(/\*((.|
)*)\*/)|//.*

That's fine enough, except that it has just greedy quantifiers which means that it will match from the first /* to the last */. You want non-greedy quantifiers instead, to get this pattern:
(/\*((.|
)*?)\*/)|//.*

Small change, big consequence since it now matches to the first */ after the /*. Re-encoded as Java code.
Pattern pattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

(Be aware that you are very close to the limit of what it is sensible to match with regular expressions. Indeed, it's actually incorrect since you might have strings with /* or // in. But you'll probably get away with it…)


text:
Q: How do I send keystrokes to a serial port in vb.net? I am trying to send a ctrl-x keystroke to COM2 and I ahve to code to open the port and read and write but when I tried to send Chr(Keys.ControlKey + Keys.X) it did not work. any ideas?

A: If this is interactive, the event that passes KeyChar will already pass a Char type that will be the CONTROL-X.
If your trying to generate the value, then Control-X is really just what letter is X in the alphabet. Its the 24th letter, and in ASCII that would just be 24 or 0x18.
So maybe you want a constant for it that would just be Chr(24).


text:
Q: How to set the bootorder for a vm in vsphere 5.x with pysphere I am using the following python code to set the extra_config parameter bios.bootOrder:
#!/bin/env python
from pysphere import VIServer, VITask
from pysphere.resources import VimService_services as VI

server = VIServer()
server.connect("vcenter-server", "myusername", "supersecrete")

vm = server.get_vm_by_name( 'targetvm' )
vm.set_extra_config({'bios.bootOrder': 'cdrom,hdd'}, sync_run=True)

Unfortunately the reconfiguration task finishes successfully but the boot sequence does not change.
Reportedly the script worked with ESXi 4.x.
May anyone faced the same problem?

A: I've found a solution. The API changed with vSphere 5. Therefore the above code does not work anymore.
... may helpful for someone else: https://gist.github.com/st0ne-dot-at/9984414

A: Here is a fairly crude script, but serves the purpose of an example that uses pyvmomi to set the boot order to cd, works equally well for booting from the network(pxe) booting VM's too:

#!/usr/bin/python
import sys
import time
import time
import atexit
import argparse
from pyVmomi import vim, vmodl
from pyVim import connect
from pyVim.connect import Disconnect, SmartConnect, GetSi

system = sys.argv[1]

        inputs = {'vcenter_ip': 'ip.ad.re.ss',
          'vcenter_password': 'passwd',
          'vcenter_user': 'user',
          'vm_name' : system,
          'operation' : 'stop',
          'force' : True,
          }

# Functions

def get_obj(content, vimtype, name):
    objct = None
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            objct = c
            break
    return objct

si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'])
content = si.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])
vm.PowerOff()

# Set to boot from cd/network. #'d out is what you'd use for network/pxe booting

#bn                  = vim.option.OptionValue(key='bios.bootDeviceClasses',value='allow:cd')
bn                  = vim.option.OptionValue(key='bios.bootDeviceClasses',value='allow:net')
vmconf              = vim.vm.ConfigSpec()
vmconf.extraConfig  = [bn]
vm.ReconfigVM_Task(vmconf)
time.sleep(10)
vm.PowerOnVM_Task()
time.sleep(30)

# Set system to boot from hdd again

bn                  = vim.option.OptionValue(key='bios.bootDeviceClasses',value='allow:hd,cd,fd,net')
vmconf              = vim.vm.ConfigSpec()
vmconf.extraConfig  = [bn]
vm.ReconfigVM_Task(vmconf)


text:
Q: How do I drop rows from a Pandas dataframe based on data in multiple columns? I know how to delete rows based on simple criteria like in this stack overflow question, however, I need to delete rows using more complex criteria.
My situation:  I have rows of data where each row has four columns containing numeric codes.  I need to drop all rows that don't have at least one code with a leading digit of less than 5.  I've currently got a function that I can use with dataframe.apply that creates a new column, 'keep', and populates it with 1 if it is a row to keep.  I then do a second pass using that simple keep column to delete unwanted rows.  What I'm looking for is a way to do this in a single pass without having to create a new column.
Example Data:
   a | b | c | d
0 145|567|999|876
1 999|876|543|543

In that data I would like to keep the first row because in column 'a' the leading digit is less than 5.  The second row has no columns with a leading digit of less than 5, so that row needs to be dropped.

A: This should work:
In [31]:
df[(df.apply(lambda x: x.str[0].astype(int))).lt(5).any(axis=1)]

Out[31]:
     a    b    c    d
0  145  567  999  876

So basically this takes the first character of each column using the vectorised str method, we cast this to an int, we then call lt which is less than row-wise to produce a boolean df, we then call any on the df row-wise to produce a boolean mask on the index which use to mask the df. So breaking the above down:
In [34]:
df.apply(lambda x: x.str[0].astype(int))

Out[34]:
   a  b  c  d
0  1  5  9  8
1  9  8  5  5

In [35]:
df.apply(lambda x: x.str[0].astype(int)).lt(5)

Out[35]:
       a      b      c      d
0   True  False  False  False
1  False  False  False  False

In [37]:
df.apply(lambda x: x.str[0].astype(int)).lt(5).any(axis=1)

Out[37]:
0     True
1    False
dtype: bool

EDIT
To handle NaN values you add a call to dropna:
In [39]:
t="""a,b,c,d
0,145,567,999,876
1,999,876,543,543
2,,324,344"""
df = pd.read_csv(io.StringIO(t),dtype=str)
df

Out[39]:
     a    b    c    d
0  145  567  999  876
1  999  876  543  543
2  NaN  324  344  NaN

In [44]:
df[(df.apply(lambda x: x.dropna().str[0].astype(int))).lt(5,axis=0).any(axis=1)]

Out[44]:
     a    b    c    d
0  145  567  999  876
2  NaN  324  344  NaN


text:
Q: How do I delimit a named parameter in JPQL? I would like to write a JPQL query like this:
SELECT f
  FROM Foo f
 WHERE f.bar LIKE '[:bar]%'

This cannot be parsed properly by EclipseLink, which can't figure out that the trailing ]% is actually not part of the named parameter name.
I am aware of the ESCAPE keyword, but I'm not sure that would fix my problem.  What are my spec-sanctioned options?

A: I'd say: create your query object with your query:
SELECT f FROM Foo f WHERE f.bar LIKE :bar

And then set the "bar" parameter by calling
query.setParameter("bar", "["+bar+"]%");


text:
Q: Redshift COPY command raises error if S3 prefix does not exist When I run this COPY command:
COPY to_my_table (field1, field2, etc)
FROM s3://my-service-f55b83j5vvkp/2018/09/03
CREDENTIALS 'aws_iam_role=...'
JSON 'auto' TIMEFORMAT 'auto';

I get this error:
The specified S3 prefix '2018/09/03' does not exist

Which makes sense, because my S3 bucket does not have any file in that specific prefix. However, this is part of a daily job to load data, where sometimes there's something to load, but some other times there's nothing to load.
I checked the COPY documentation and it doesn't seem to be any way to avoid the error and just don't do anything if there are no objects under that prefix. Maybe I am missing something?

A: I would like to suggest here, how we have solved this problem in our case, though its simple solution but may be helpfull to others. Jon Scot has suggested good option in comment that I liked. But, unfortuanetely in our case, we coundn't do it as system adding files to S3 was not in our controll. So not sure it its your case too.
I think you could solve your problem multiple ways, but here are two options that I suggest.
1) As you may be running cron job to load data to Redshift, put a file existence check before executing the Copy command, like below.
path=s3://my-service-f55b83j5vvkp/2018/09/03
count=\`s3cmd ls $path | wc -l\`

if [[ $count -eq 1 ]]; then
    //Your Redshift copy code goes here.
else
    echo "Nothing to load"
fi

Advantage of this options is your saving some cost though may be completely negligible.
2) dummy file without records, that will eventually load no data to Redshift.


text:
Q: Optimize DownValues: extract "non-patterns" from Alternatives Introduction
As we know, when we assign DownValues to a symbol, Mathematica creates a dispatch table for "non-pattern" definitions (i.e. expressions that, when used as patterns, can match only single expression), and can match such definition in constant time (independent of number of definitions).
To match definitions containing "real patterns" (in the sense of expressions that "appear to be able to" match more than one expression) Mathematica tries them one by one, so in worst case Mathematica needs time linear in number of such definitions.
Main question
How can we decompose arbitrary pattern containing Alternatives to collection of separate patterns that when used as DownValues will give exactly the same outputs (and possible side effects) as single pattern, but, if possible, will take advantage of dispatching mechanism for "non-pattern" expressions.
Context
I'm creating a user modifiable predicate: somethingQ. Users will be able to declare arbitrary patterns for which predicate will give True. Expected number of such patterns can grow to the order of $10^6$, but most of them are expected to be "non-pattern" expressions.
In the context of somethingQ it will be "natural" to declare patterns similar to f[g[a | b | c | _h], x]. I could try to document that giving separate patterns: f[g[a], x], f[g[b], x], f[g[c], x], f[g[_h], x] will give somethingQ better performance, but explaining in detail when to decompose pattern and when not to (e.g f[g[a | b], _h] should non be decomposed) is difficult and decomposing patterns by hand can be tedious. Instead of burdening users with understanding DownValues matching and manual decomposition, I'd like to automate this process.
Benchmarks
When we have $10^6$ "non-pattern" expressions "hidden" inside Alternatives we can get noticeable performance gain by assigning "non-pattern" expressions to separate DownValues and gathering "real patterns" to single down value with Alternatives.
To test it let's create $10^6$ patterns with Alternatives, first $9 \times 10^5$ patterns contains only Alternatives of non-pattern expressions rest contains also "real patterns":
ClearAll[a, b, c, g, h, x]
patts = Join[
    {a | Unique[]}, Table[Unique[] | Unique[], 9 10^5],
    {b | _g}, Table[Unique[] | Blank@Unique[], 10^5], {c | _h}
];

Assign them to DownValues of somethingQ:
somethingQ // ClearAll
DownValues@somethingQ = HoldPattern@somethingQ@# :> True & /@ patts;
somethingQ@_ = False;

and test time of calling somethingQ for arguments matching first and last non-pattern and "real pattern" giving True and pattern giving False:
somethingQ@a // RepeatedTiming   (* {2.8*10^-7, True} *)
somethingQ@c // RepeatedTiming   (* {0.14, True} *)
somethingQ@g[] // RepeatedTiming (* {0.13, True} *)
somethingQ@h[] // RepeatedTiming (* {0.14, True} *)
somethingQ@x // RepeatedTiming   (* {0.14, False} *)

Matching expressions from first down value is fast, but matching last down values is slow since Mathematica needs to test all down values one by one.
Putting all patters in one huge Alternatives makes matching last down values three times faster:
somethingQ // ClearAll
somethingQ[Join @@ patts] = True;
somethingQ@_ = False;

somethingQ@a // RepeatedTiming   (* {3.*10^-7, True} *)
somethingQ@c // RepeatedTiming   (* {0.042, True} *)
somethingQ@g[] // RepeatedTiming (* {0.037, True} *)
somethingQ@h[] // RepeatedTiming (* {0.042, True} *)
somethingQ@x // RepeatedTiming   (* {0.042, False} *)

Extracting non-patterns and putting them in separate down values while putting all "real patterns" in one Alternatives gives constant time for all expressions matched by "non-pattern" down values. Worst case time for matching "real patterns" is linear in number of only "real patterns", not in number of all patterns as previously:
somethingQ // ClearAll
DownValues@somethingQ = HoldPattern@somethingQ@# :> True & /@
    Append[#@Symbol, Alternatives @@ #@Blank]& @
    GroupBy[List @@ Join @@ patts, Head];
somethingQ@_ = False;

somethingQ@a // RepeatedTiming   (* {2.*10^-7, True} *)
somethingQ@c // RepeatedTiming   (* {1.8*10^-7, True} *)
somethingQ@g[] // RepeatedTiming (* {4.*10^-7, True} *)
somethingQ@h[] // RepeatedTiming (* {0.0055, True} *)
somethingQ@x // RepeatedTiming   (* {0.0055, False} *)

Of course here extraction of "non-pattern" expressions was trivial since all patterns had known simple structure, but I'm looking for a general way of extracting them from arbitrary patterns.

A: We can create a recursive top-down parser that, for each sub-expression, of pattern, will call itself on parts of this sub-expression, assemble results, and return pair containing, as first element, list of "non-pattern" expressions and, as second element, "real pattern", that in DownValues will be equivalent to given pattern sub-expression.
Recursion stops on expressions treated as "real patterns" by DownValues and on expressions free of _Alternatives.
When _Alternatives are encountered, we look for first alternative containing _Condition, _PatternTest, or _Pattern, matching this alternative can have side effects (binding variable to a name, done by Pattern, is here also considered a side effect). We leave all alternatives behind it alone, since extracting non-patterns from them could change behavior: f[patt /; sideEffect[] | a] := result is not equivalent to f[a] := result; f[patt /; sideEffect[]] := result. From alternatives before first with possible side-effect we extract non-pattern expressions.
Parser, with behavior sketched above, is implemented in following package.
BeginPackage@"DecomposePattern`"; Unprotect@"`*"; ClearAll@"`*"

DecomposePattern::usage = "DecomposePattern[patt] \
returns {{expr1, expr2, ...}, newPatt} expression, \
where expri are pattern-free expressions matched by patt, \
created by replacing Alternatives, present in patt, \
with their consecutive pattern-free elements. \
newPatt is pattern patt with pattern-free elements of Alternatives \
removed if possible. If expri are only expressions matched by patt, \
then newPatt is Alternatives[].";

Begin@"`Private`"; ClearAll@"`*"

$patternPatt = _Blank | _BlankNullSequence | _BlankSequence | _Condition |
    _Except | _IgnoringInactive | _KeyValuePattern | _Optional |
    _OptionsPattern | _OrderlessPatternSequence |_Pattern | _PatternSequence |
    _PatternTest | _Repeated | _RepeatedNull;

$sideEffectPatt = _Condition | _PatternTest | _Pattern;

hold // Attributes = HoldAllComplete;

parse[alt_Alternatives] := Module[{held, lastBeforeSidEffPos, parsed},
    held = hold @@ Unevaluated@alt;
    (* Since patterns in alternatives are tested in order,
       and in ...Values non-patterns are always tried before patterns,
       then f[patt /; sideEffect[] | a] := ... is not equivalent to
       f[a] := ...; f[patt /; sideEffect[]] := ...,
       so we don't extract non-patterns that are in alternatives after
       first pattern with possible side effects. *)
    lastBeforeSidEffPos = Replace[
        Position[held,
            patt_ /; Not@FreeQ[Unevaluated@patt, $sideEffectPatt],
            {1}, 1, Heads -> False
        ],
        {{} :> Length@held, {{i_}} :> i - 1}
    ];
    parsed = Alternatives @@ parse /@ Take[held, lastBeforeSidEffPos];
    {
        Union @@ parsed[[All, 1]],
        Replace[
            Flatten[
                parsed[[All, 2]] |
                Alternatives @@ hold /@ Drop[held, lastBeforeSidEffPos]
            ],
            Verbatim[Alternatives]@patt_ :> patt
        ]
    }
]
parse[patt : $patternPatt] := {{}, hold@patt}
parse[
    (expr : (h : Except[HoldPattern@Symbol@___, _Symbol] /;
        MemberQ[Attributes@h, Flat | OneIdentity])[___]) |
    (expr_ /; FreeQ[Unevaluated@expr, _Alternatives])
] :=
    If[FreeQ[Unevaluated@expr, $patternPatt],
        {{hold@expr}, Alternatives[]}
    (* else *),
        {{}, hold@expr}
    ]
parse[expr : h_[args___]] :=
    With[{parsed = parse /@ Unevaluated@{h, args}},
        If[TrueQ[Times @@ (Length[#1]&) @@@ parsed <= $maxNonPattProduct],
            {
                #1[##2] & @@@ Tuples@parsed[[All, 1]]
                ,
                Replace[
                    Position[parsed,
                        {_, Except@Verbatim@Alternatives[]},
                        {1}, 2, Heads -> False
                    ],
                    {
                        {} :> Alternatives[],
                        (* If there's only one part with pattern we can
                           replace this part with pattern-only version. *)
                        {{pos_}} :> ReplacePart[hold@expr, {1, pos - 1} ->
                            RuleCondition@parsed[[pos, 2]]],
                        _ :> hold@expr
                    }
                ]
            }
        (* else *),
            {{}, hold@expr}
        ]
    ]
parse // Attributes = HoldAllComplete;

DecomposePattern // Options = {
    "SideEffectFree" -> None,
    "MaxNonPatternProduct" -> 10^6
};
DecomposePattern[patt_, OptionsPattern[]] :=
    Block[
        {
            $sideEffectPatt = Replace[OptionValue@"SideEffectFree",
                {None -> $sideEffectPatt, x_ :> Except[x, $sideEffectPatt]}
            ],
            $maxNonPattProduct = OptionValue@"MaxNonPatternProduct"
        },
        DeleteCases[parse@patt, hold, Infinity, Heads -> True]
    ]

End[]; Protect@"`*"; EndPackage[];

Simple usage examples:
ClearAll[a, b, c, d, e, f, g, h]

f[g[a | b | c | _h], x] // DecomposePattern
(* {{f[g[a], x], f[g[b], x], f[g[c], x]}, f[g[_h], x]} *)

f[g[a | b], _h] // DecomposePattern
(* {{}, f[g[a | b], _h]} *)

f[a | b | c, d | e] // DecomposePattern
(* {{f[a, d], f[a, e], f[b, d], f[b, e], f[c, d], f[c, e]}, Alternatives[]} *)

f[a | b | c, d | _h | e] // DecomposePattern
(* {{f[a, d], f[a, e], f[b, d], f[b, e], f[c, d], f[c, e]}, f[a | b | c, _h]} *)

Complex example with held patterns:
(* Assign some values to test possible evaluation leaks. *)
c := (Print@"evaluation leaked: c"; 0)
f := (Print@"evaluation leaked: f"; 1)
a | __h | b | HoldPattern[c | f[a | _g | b, f[c | d]]] | HoldPattern[f][e] | _?f | g // DecomposePattern
(* {
    {
        a, b, HoldPattern[f][e], HoldPattern[c],
        HoldPattern[f[a, f[c]]], HoldPattern[f[a, f[d]]],
        HoldPattern[f[b, f[c]]], HoldPattern[f[b, f[d]]]
    },
    __h | HoldPattern[f[_g, f[c | d]]] | _?f | g
} *)
ClearAll[c, f]

If we are sure that certain pattern, that potentially could have side effects, is free of them, we can set "SideEffectFree" option:
DecomposePattern[a | _?f | b | _?g | c]
DecomposePattern[a | _?f | b | _?g | c, "SideEffectFree" -> Verbatim[PatternTest][_, f]]
DecomposePattern[a | _?f | b | _?g | c, "SideEffectFree" -> Verbatim[PatternTest][_, f | g]]
(* {{a}, _?f | b | _?g | c} *)
(* {{a, b}, _?f | _?g | c} *)
(* {{a, b, c}, _?f | _?g} *)


text:
Q: when i start my vue.js project i receive : "We're sorry but app doesn't work properly without JavaScript enabled. Please enable it to continue." I want to create a chat with vue.js, socket.js and node.js, I created an API before and I want to add socket.js but when I start the app the app correctly connects to my API and to socket .js but I see in the response request: "We're sorry but the application is not working properly without JavaScript enabled. Please enable it to continue." I searched but I can't find :(
the code of  main.js (vue.js) script :
    import Vue from 'vue'
    import App from './App.vue

   import { io } from "socket.io-client";
   io();

   Vue.config.productionTip = false

  new Vue({
     render: h => h(App),
  }).$mount('#app')

the code of index.js (API) :
const express = require('express')
const userRoute = require('./routes/userRoutes')
const messageRoute = require('./routes/messageRoutes')
const mongoose = require('mongoose')
const { createServer } = require("http");
const { Server } = require("socket.io");
require('dotenv').config()

const app = express()
const httpServer = createServer(app);
const io = new Server(httpServer, {
    cors: {
        origin: "*",
        credentials: true
    }
});

app.use(express.json())

mongoose.connect('mongodb+srv://'+ process.env.DB_NAME + ':' + process.env.DB_PASSWORD + '@' + process.env.DB_IP + '/' + process.env.DB_NAME +'?retryWrites=true&w=majority', {useNewUrlParser: true});

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', ['http://localhost:8080']);
    res.append('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE');
    res.append('Access-Control-Allow-Headers', ['*']);
    next();
});

app.use('/users', userRoute)
app.use('/messages', messageRoute)

io.on("connection", (socket) => {
    console.log(socket.id)
    io.emit('news','Voici un nouvel élément envoyé par le serveur')
});

httpServer.listen(process.env.APP_PORT, () => {
    console.log("Serveur à l'écoute")
})

thank you for your answers


text:
Q: ASP.NET MVC app on .NET 4 do not find ViewBag and model in view I had Visual Studio 2017, Visual Studio 2019 and old project in .NET 4 (ASP.NET website). Everything works perfectly on Windows 10 64 bit the last build, then I uninstall VS 2017 today.
After I uninstalled Visual Studio 2017, I now get this error:

Error CS0103  The name 'ViewBag' does not exist in the current context
  Error CS0103  The name 'model' does not exist in the current context

But when I check Visual Studio Installer I have already .NET Framework 4 and ASP.NET MVC 4 installed.
I have this in my web.config file:
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

Am I missing an ASP.NET MVC 3 framework? But when I try to install I got this error:

Is there any solution?

Update:
I try this solution: The name 'ViewBag' does not exist in the current context - Visual Studio 2015, but does not work for me
I got this error:

But when I check it in Visual Studio 2019 Installer, I had already installed

I also try to install Visual Studio 2017 back and VS 2015, but I had still the same error and is it not possible to install ASP MVC 3
But when I run webapp in Visual Studio, webpage works fine

A: Check your MVC framework version, you need to have MVC framework 4.0. You can try to install from this link https://www.microsoft.com/ru-ru/download/details.aspx?id=30683

A: I have no MVC 3 project. So this is just guessing.
The Visual Studio Installer for 2019 only shows support for MVC 4.

Maybe this download helps. If it is not what you already tried.


text:
Q: How to execute subroutine in parallel? I want to know how to execute two subroutines in parallel.
In Perl Tk, I am using  one buttons widget and text widget.
Button : is to execute the parser function
Text   : is to display the print statement of the parser
Thing is that after executing the parser function only the text widget is getting executed
[because Perl support sequential execution]
But I want both of them to be executed in parallel.

A: Implement a fork and have the child process launch the second subroutine and communicate the results to the parent process via interprocess communication (IPC).
You can also try to use threads, though it would not be my recommended solution
P.S. The discussion on this SO question should also prove informative, though is not 100% the duplicate of your need:
How can I signal a forked child to terminate in Perl?


text:
Q: Detect Chrome and Safari in Javascript I would like display the message "You are not using Chrome, CLICK HERE for download Chrome. But I don't want display message if the browser used is Safari. In practice I want especially convince people who use IE (too crappy) and FF (too heavy) or any others browser (except Safari because is not bad and because any other third party browser who could be installed on Apple OS will have bad performance) to use instead Chrome (ideal choice for my app for a best user experience).
I found a script who seem to be well adapted for make a reliable detection, but I don't know how to customize the code:
var BrowserDetect = {
init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString: function (data) {
    for (var i=0;i<data.length;i++) {
        var dataString = data[i].string;
        var dataProp = data[i].prop;
        this.versionSearchString = data[i].versionSearch || data[i].identity;
        if (dataString) {
            if (dataString.indexOf(data[i].subString) != -1)
                return data[i].identity;
        }
        else if (dataProp)
            return data[i].identity;
    }
},
searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    }
]

};
BrowserDetect.init();

Can somebody help? If needed I found the script here:
http://www.quirksmode.org/js/detect.html

A: Answering the question... :)
If you really want to use it, then just use BrowserDetect.browser as your guide.
I used the code from http://www.quirksmode.org/js/detect.html.

//-->


text:
Q: Relation between independence number and maximum order of induced tree? For a graph $G$, let $t(G)$ be the maximum order of a vertex-subset that induces a tree in $G$, and $\alpha(G)$ be the independence number of $G$ (maximum size of independent set in $G$).
I find a relation states without proof that
$$t(G)\le 2\alpha(G)$$
and want to know why.
My feeling is that take a maximum independent set $I$, and a neighbor of each of them (if any), then their union has size less than $2\alpha(G)$. But why the induced graph on them must contain a cycle or a forest with two components?

A: Let $T$ be an induced tree in $G$ of maximum number of vertices (so $v_T=t(G)$), and we are going to construct an independent set $I$ in $T$ so that $|I|\ge v_T/2$, which implies $\alpha(G)\ge t(G)/2$.
Algorithm of finding such an independent set
Set $T_0:=T$. Set $U_0:=V(T_0)$, $L_0=\emptyset$, $I_0=\emptyset$ as "unlabeled", "labeled", and independent vertex-sets, respectively. We will always keep $T_i$ an induced subtree of $T$ and the union of disjoint sets $U_i$, $L_i$, and $I_i$ equal to $V(T)$ during the algorithm.
At step $i\ge 0$, picking a unlabeled leaf $v$, if any, of the tree $T_i$ (recall a tree contains at least 1 leaf, i.e., a degree 1 vertex), set
$$I_{i+1}:=I_i\cup\{v\},$$
$$T_{i+1}:=T_i\setminus \{v\},$$
and
$$U_{i+1}:=U_i\setminus\{u,v\},$$
$$L_{i+1}:=L_{i}\cup\{u\},$$
where $u$ is the unique vertex in $T_i$ adjacent to $v$ if any, otherwise $U_{i+1}:=U_i\setminus\{v\}$ and $L_{i+1}:=L_i$.
If there is no such unlabeled leaves, we set
$$I_{i+1}:=I_i,$$
$$U_{i+1}:=U_i,$$
$$L_{i+1}:=L_{i},$$
$$T_{i+1}:=T_i\setminus \{\text{labeled leaves in $T_i$}\}.$$
Then we go to next step. And the algorithm terminates if $U_k$ becomes empty.
It is easy to check $T_i,U_i,L_i,I_i$ satisfy the mentioned properties.
As all vertex of $T$ fall in the final independent set or labeled set, and at each step, the number of vertex included in $L_i$ is no more than that in $I_i$ (with the notations in the algorithm, note that the vertex $u$ can already be in the labeled set, or in the final step, the tree is an isolated vertex.). Therefore
$$|I_m|\ge |L_m|\ge v_T/2$$
after final step $m$.

A: Given any subtree $T$ of $G$, I will show how to construct an independent set $I$ from $T$ with the property that $|T|\leq 2|I|$.
The construction is iterative. Start by letting $I_0$ be the leaf (i.e. degree $1$) vertices of $T$, and for all $k\geq 0$ let $I_{k+1}$ be the leaf vertices of $T\setminus I_k$. Let $J_k=I_{2k}$ except when $I_{2k}$ is an edge, in which case we let $J_k$ be one of the two vertices of $I_{2k}$ chosen arbitrarily. This is done to ensure that $J_k$ is an independent set, since the only way for a connected graph to have adjacent leaf vertices is if the graph is an edge.
Set $I=\cup_{k\geq 0}J_k$. We use the following two properties to finish the proof:

*

*$I$ is an independent set

*$|J_k|\geq |I_{2k+1}|$ for all $k\geq 0$
Property (1) can be seen using a simple proof by contradiction - adjacent vertices of $I$ would have to belong to distinct $J_i,J_j$ but this is impossible by construction. Property (2) follows from the existence of the surjection from $I_{2k}$ to $I_{2k+1}$ given by sending each vertex in $I_{2k}$ to its unique neighbor in $I_{2k+1}$, together with the observation that if $J_k\not=I_{2k}$ then $I_{2k+1}$ is empty. Thus,
$$
|I|=\sum_{k\geq 0}|J_{k}|\geq \sum_{k\geq 0}|I_{2k+1}|=|T\setminus I|,
$$
showing that $2|I|\geq |T|$ and thus we have found the desired independent set.
Finally, apply this construction to any tree with $|T|=t(G)$ to obtain an independent set $I$ satisfying
$$
t(G)\leq 2I\leq 2\alpha(G),
$$
with the latter inequality coming from the definition of $\alpha(G)$.

A: More strongly, if $b(G)$ is the maximum order of any induced bipartite subgraph in $G$, then $b(G) \le 2\alpha(G)$.
(If $H$ is an induced bipartite subgraph of order $b(G)$, and $A \cup B$ is the bipartition of $V(H)$, then either $|A| \ge \frac12 b(G)$ or $|B| \ge \frac12 b(G)$, and both $A$ and $B$ are independent sets in $G$. Therefore $\alpha(G) \ge \frac12 b(G)$.)
Since a tree is just one specific kind of bipartite graph, $t(G) \le b(G) \le 2\alpha(G)$, as desired.


text:
Q: CakePhp mysql raw query error I'm new to cakephp. I'm trying to search through mysql tables. I want to use nested query.
 class TableController extends AppController{
 .
 .
 public function show(){
    $this->set('discouns', $this->DiscounsController->query("SELECT * FROM discoun as Discoun WHERE gcil_id = 1"));//(SELECT id FROM gcils WHERE genre = 'Shoes' AND company_name = 'Adidas')"));
}

}
Error:
 Error: Call to a member function query() on a non-object

I've also tried
public function show(){
    $this->DiscounsController->query("SELECT * FROM count as Count WHERE ctr_id = (SELECT id FROM ctrs WHERE genre = 'Shoes' AND company_name = 'Adidas')");
}

Error:
 Error: Call to a member function query() on a non-object

File: C:\xampp\htdocs\cakephppro\myapp\Controller\CountsController.php
Please help. I've been trying this for last few hours. :/

A: As mentioned in the comments there are a few problems with your code.
Firstly, you are trying to call the query() method on a Controller, whereas you should be executing it on a Model, as it is models that handle database queries and the controller should simply be used to call these methods to get the data and pass them to the view.
The second thing is that you are executing a very simple SQL query raw instead of using CakePHPs built in functions <- Be sure to read this page in full.
Now for your problem, as long as you have setup your model relationships correctly and followed the correct naming conventions, this should be your code to run your SQL query from that controller:
public function show(){
    $this->set('discouns', $this->Discouns->find('all', array(
        'conditions' => array(
            'gcil_id' => 1,
            'genre' => 'shoes',
            'company_name' => 'Adidas'
        )
    ));
}

A: query() is not a Controller, but a Model method. That's what the error (Call to a member function on a non-object) is trying to tell you.
So the correct call would be:
$this->Discount->query()
But you are calling this in a TableController, so unless Table and Discount have some type of relationship, you won't be able to call query().
If the Table does have a relationship defined you will be able to call:
$this->Table->Discount->query()
Please not that query() is only used when performing complex SQL queries in scenarios where the standard methods (find, save, delete, etc.) are less practical.

A: $this->Counts->find('all',array(
  'conditions' => array(
    'ctrs.genre' => 'Shoes',
    'ctrs.company_name' => 'Adidas'
  ), 'recursive' => 1
));

The above is with tables named counts and ctrs.
This is assuming you have the model set up to have some sort of relationship between the counts table and the ctrs table.  It's kind of hard to tell in your code exactly what you tables are.
The CakePHP book should have all the answers you need.  One of the reasons to run CakePHP over regular PHP is the FIND statement.  Once you have your models set up correctly, using the find statement should be really easy.
http://book.cakephp.org/2.0/en/models.html


text:
Q: How to play mp3 file in a mvc project using javascript? I would look at similar topics.But I don't understand. There are more than one project in mvc solution. I would like to play an audio file using javascript in cshtml in the "voucher" project.This file is in the "content" folder under the "main" project. I can relate to the projects at the controller level.But I had a problem with the view level.
<script>
var audio = new Audio();
audio.src = ""; // I could not add the path of the file.
audio.play();
</script>

I've tried this way:
audio.src = "@Server.MapPath("~/Content/sounds/beep.wav")";

I've also tried using html5. But again I could not access the other project in the "src". I tried converting the audio file into a byte on the controller part. But I didn't have a useful result.

A: You can serv like this:
    [HttpGet]
        public ActionResult GetAudioFile(string filename)
        {
string filePath = Server.MapPath(Url.Content($"~/Content/sounds/{filename}"));
            var bytes = new byte[0];

            using (var fs = new FileStream(filePath , FileMode.Open, FileAccess.Read)
            {
                var br = new BinaryReader(fs);
                long numBytes = new FileInfo(fileLocation).Length;
                buff = br.ReadBytes((int)numBytes);
            }

            return File(buff, "audio/mpeg", "file.mp3");
        }

And then in your java script code:
function Sound(source, volume, loop)
{
    this.source = source;
    this.volume = volume;
    this.loop = loop;
    var son;
    this.son = son;
    this.finish = false;
    this.stop = function()
    {
        document.body.removeChild(this.son);
    }
    this.start = function()
    {
        if (this.finish) return false;
        this.son = document.createElement("embed");
        this.son.setAttribute("src", this.source);
        this.son.setAttribute("hidden", "true");
        this.son.setAttribute("volume", this.volume);
        this.son.setAttribute("autostart", "true");
        this.son.setAttribute("loop", this.loop);
        document.body.appendChild(this.son);
    }
    this.remove=function()
    {
        document.body.removeChild(this.son);
        this.finish = true;
    }
    this.init = function(volume, loop)
    {
        this.finish = false;
        this.volume = volume;
        this.loop = loop;
    }
}

Also used like this way:
var url= 'ControllerName/GetAudioFile?filename=yourfilename '
var foo = new Sound("url", 100, true);
foo.start();
foo.stop();
foo.start();
foo.init(100, false);

A: i tried the following code:
<script>
    $(document).ready(function () {
var url = "@Url.Content("~/Content/sounds/notificationSound.mp3")";
    new Audio(url).play();
}</script>

The code worked when I refresh the page. Then I pressed ctrl + f5. But this time not worked. The error message is displayed on the screen. Error message :

Uncaught (in promise) DOMException


text:
Q: Transition to next page I am trying to redirect to another page after 32 seconds. I need a smooth transition to the second page. Right now the transition is very abrupt and doesnt look very good. Any ideas?
This is my query:
function redirect() {
                window.location = $('a').attr('href');

            }

            setTimeout(redirect, 32000);

HTML5:

A: You can't redirect with a fading effect.
You have to use ajax to perform such animation.
But you can try this
function redirect() {
    $('body').fadeOut(1000,function(){
        window.location = $('a').attr('href');
    });
}
setTimeout(redirect, 31000);

you will have a 1s fadeOut before redirecting (and having no fadeIn, just the abrupt loading of the next page)


text:
Q: Best way of SELECT on large table with filter to filter out around 1m rows with indexes I have a table billing_billcycleorders that contains a foreign key billing_cycle_id. There are around 0.9m records for a particular billing_cycle_id. I want to select the data in the chunks for ~5000 (or any best way possible).
The query result is exponentially increasing for values of billing_cycle_id with the higher number of records.
I have run EXPLAIN ANALYZE on the query
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, format text)
SELECT DISTINCT
    "billing_billcycleorders"."id",
    "billing_billcycleorders"."created",
    "billing_billcycleorders"."updated",
    "billing_billcycleorders"."deleted",
    "billing_billcycleorders"."deleted_date",
    "billing_billcycleorders"."billing_cycle_id",
    "billing_billcycleorders"."order_id",
    "billing_billcycleorders"."pickrr_awb",
    "billing_billcycleorders"."amount",
    "billing_billcycleorders"."delivery_bill",
    "billing_billcycleorders"."rto_bill",
    "billing_billcycleorders"."pickup_bill",
    "billing_billcycleorders"."surcharge",
    "billing_billcycleorders"."cod_bill",
    "billing_billcycleorders"."qc_bill",
    "billing_billcycleorders"."qcf_bill",
    "billing_billcycleorders"."secure_shipment_charge",
    "billing_billcycleorders"."cod_amount",
    "billing_billcycleorders"."meta_details"
FROM
    "billing_billcycleorders"
WHERE
    (
        "billing_billcycleorders"."billing_cycle_id" = 685081 AND "billing_billcycleorders"."id" > 0
    )
ORDER BY "billing_billcycleorders"."id" ASC
LIMIT 1000

Explain Analyze: https://explain.depesz.com/s/k9rq7

A: Paging through a table with OFFSET / LIMIT incurs the cost of walking through the combined number of rows and gets increasingly expensive.
Base your data pages on an index instead. You can start with LIMIT 1000 like you have it, but instead of OFFSET in subsequent pages, use:
...
WHERE ...
AND   billing_billcycleorders.id > $greatest_id_of_last_batch  -- !
LIMIT 1000;

$greatest_id_of_last_batch being the greatest ID of the previous data page. That matches your sort order ORDER BY "billing_billcycleorders"."id" ASC. And id is a the PK, so it's unique.
Be sure to have a multicolumn index on (billing_cycle_id, id) to support this. See:

*

*Optimize query with OFFSET on large table
And, of course, drop the DISTINCT at the top, that's doing nothing useful in this query (except making it expensive).
Aside: with a million rows per billing cycle, list-partitioning the table by billing_cycle_id might be a good option ...


text:
Q: celery how to implement single queue with multiple workers executing in parallel I am currently running celery 4.0.2 with a single worker like this:
celery.py:
app = Celery('project',
         broker='amqp://jimmy:jimmy123@localhost/jimmy_vhost',
         backend='rpc://',
         include=['project.tasks'])

if __name__ == '__main__':
    app.start()
    app.name

tasks.py:
from .celery import app
from celery.schedules import schedule
from time import sleep, strftime

app.conf.beat_schedule = {
    'planner_1': {
        'task': 'project.tasks.call_orders',
        'schedule': 1800,
    },
    'planner_2': {
        'task': 'project.tasks.call_inventory',
        'schedule': 900,
    },
}

I used the following command to run with beat:
 celery -A project worker -l info --concurrency=3 --beat -E

Right now it is only a single queue with only one worker running.

My question is how to run celery with multiple workers and single queue so that tasks are executed in parallel using multiprocessing without duplication?

I looked up on the internet, how to run celery with multiprocessing. According to this article:

celery worker -l info -P processes -c 16
  will result in a single message consumer delegating work to
  16 OS-level pool processes.  Each OS-level process can be assigned to different CPU in a multicore environment, and as such it will process tasks
  in parallel, but it will not consume messages in parallel.

can using the -p processes argument solve my problem? Also but what is meant by, "it will process tasks in parallel, but it will not consume messages in parallel"?


text:
Q: get array from an array of array using value I have an array of array like this
$data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);

I have value 9908. When I search 9908 then the value  array("9908","1","5") should be printed. I have used array_search() but I have not got any success
How I can print the array after finding the value

A: Try this:
var_dump($data[array_search("9908", array_column($data, 0))]);

To expand it,

array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

array_search Searches the array for a given value and returns the first corresponding key if successful.

Edit:
To add some control over it:
$index = array_search("9908", array_column($data, 0));
if($index !== false){
    // do your stuff with $data[$index];
    var_dump($data[$index]);
}

Dumps:
array(3) {
  [0]=>
  string(4) "9908"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "5"
}

A: Perhaps this can help:
<?php
function search_first_row($needle, $haystack){
  $data = $haystack;
  $desired_value = $needle;
  foreach($data as $row){
    if($row[0] == $desired_value){
        return $row;
    }
  }
}

A:  $data=array(
    array("9900","1","7"),
    array("9901","1","7"),
    array("9902","1","7"),
    array("9903","1","4"),
    array("9904","3","8"),
    array("9908","1","5")
);
$searchValue = '9908';

for($i=0; $i<count($data); $i++){
    $innerArray = $data[$i];

    for($j=0; $j<count($innerArray); $j++){
        if($innerArray[$j] == $searchValue){
            print_r($innerArray);
        }
    }
}

A: try this :
    $data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);
foreach ($data as $key => $value) {

    if( in_array("9908",$value)){
        $findindex = $key;
}
}
var_dump($data[$findindex]);


text:
Q: Index (zero based) in sql query in c# I don't understand this error in this sql query.
The error is

Index (zero based) must be greater than or equal to zero

My code c# in error this is :
        sql = @String.Format(" UPDATE `tbl_csv` ");
        sql += String.Format(" SET ");
        sql += String.Format(" xAAA = 1, ");
        sql += String.Format(" xBBB = {0},  ");
        sql += String.Format(" xCCC = {1},  ");
        sql += String.Format(" xDDD = {2} ");
        sql += String.Format(" WHERE Id IN ({3}); ",
            ddlBBB.SelectedValue.ToString(),
            ddlCCC.SelectedValue.ToString(),
            ddlDDD.SelectedValue.ToString(),
            Base64ForUrlDecode(Request.QueryString["sId"].ToString()));

But If try this diiferent version of sql query I don't have error and the output of query is correct:
        sql = @String.Format(" UPDATE `tbl_csv` ");
        sql += String.Format(" SET ");
        sql += String.Format(" xAAA = 1, ");
        sql += String.Format(" xBBB = '" + ddlBBB.SelectedValue.ToString() + "',  ");
        sql += String.Format(" xCCC = '" + ddlCCC.SelectedValue.ToString() + "',  ");
        sql += String.Format(" xDDD = '" +  ddlDDD.SelectedValue.ToString() + "' ");
        sql += String.Format(" WHERE Id IN (" + Base64ForUrlDecode(Request.QueryString["sId"].ToString()) + "); ",
            ddlBBB.SelectedValue.ToString(),
            ddlCCC.SelectedValue.ToString(),
            ddlDDD.SelectedValue.ToString(),
            Base64ForUrlDecode(Request.QueryString["sId"].ToString()));

Output :
UPDATE `tbl_csv`
SET xAAA = 1,
 xBBB = 'N',
 xCCC = 'N',
 xDDD = 'N'
WHERE
    Id IN ('2357');

How to do resolve this?
Can you help me?
Thank you in advance for any help, really appreciated.

A: Assuming you are actually seeing:

Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

This is because you haven't supplied any values to string.Format - i.e.
string s = string.Format("add {0} and {1}", "foo", 123);
// s now == "add foo and 123"

However! In your case adding the values is not a good fix - you should use SQL parameters, not concatenation. The bad fix would be something like:
string sql = string.Format(@"
UPDATE `tbl_csv`
SET    xAAA = 1, xBBB = {0},
       xCCC = {1}, xDDD = {2}
WHERE Id IN ({3});",
       ddlBBB.SelectedValue.ToString(),
       ddlCCC.SelectedValue.ToString(),
       ddlDDD.SelectedValue.ToString(),
       Base64ForUrlDecode(Request.QueryString["sId"].ToString()));

The good fix would be something like:
const string sql = @"
UPDATE `tbl_csv`
SET    xAAA = 1, xBBB = @xBBB,
       xCCC = @xCCC, xDDD = xDDD
WHERE Id IN (@Id);"

adding appropriate ADO.NET parameters to your command, noting that IN doesn't usually like parameters unless your database has some kind of "split" function, and that different servers have different ways of expressing parameters - instead of @foo it might be :foo, or simply ?, etc.

A: You have to add the correct parameters to each separate string.format function.
sql += String.Format(" xBBB = {0},", ddlBBB.SelectedValue.ToString());
sql += String.Format(" xCCC = {0},", ddlCCC.SelectedValue.ToString());
sql += String.Format(" xDDD = {0} ", ddlCCC.SelectedValue.ToString());
sql += String.Format(" WHERE Id IN ({0}); ", Base64ForUrlDecode(Request.QueryString["sId"].ToString()));

You cannot just add the parameters to the last function. All functions are resolved on their own and then added to the string.
Also, you should be very careful when adding values from your webpage directly in an sql query. If you intend to execute these queries directly on a database, you should always encode the input.


text:
Q: ERROR: failed building wheel when installing spectral-cube (astropy) I'm trying to install the package spectral-cube from the astropy project using pip (22.0.4). I get a long error which ends with this:

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for casa-formats-io.
Failed to build casa-formats-io.
ERROR: Could not build wheels for casa-formats-io, which is required to install pyproject.toml-based projects

Even after downloading casa-formats-io from their github I still get this error.
I've also tried installing this using conda, but the error is the same.
I'm using MacOS 12.3. But I had the problem with older versions.
I'm kind of confused as to what I can do.
Thanks for the help!

A: I was able to fix my own problem. The error appeared because the package I was trying to download wasn't available/compatible with the newest python version (3.10). So, I simply uninstalled Python and downloaded an older version (3.8).
Thanks anyways :)


text:
Q: loading and using config files in python without arbitrary strings I have an application with a config yaml file that looks like this (in reality it's much bigger):
amount_of_allowed_users: 10

I load the file to a variable named config and when I need to access the info I do:
config['amount_of_allowed_users']

however this seems precarious to me as it an arbitrary string in my code. what are the best practices when handling config file data?
In C# you would use Xml Serialization to create the config files and then deserialize it, are there similar methods in python?

I could have a python file act as a config file however it seems much less flexible.


text:
Q: Google Analytics: createScreenView and createItemWithTransactionId in Swift 2 I'm trying to update my Google Analytics code, I have found subjects about but all are different, in some files it's gonna work and not in the others, I don't know if I implement it as well, the part of the code:
/*******************************
 * Tracker écran
 ********************************/

let tracker = GAI.sharedInstance().defaultTracker

tracker.set(kGAIDescription, value: "Demande Envoyé")

let eventTracker: NSObject = GAIDictionaryBuilder.createScreenView().build()

tracker.send(eventTracker as! [NSObject : AnyObject])

/*******************************
 * Tracker transaction
 ********************************/

var rangeName = ""

if let startRange = String(xml).rangeOfString("<Logement>"), endRange = String(xml).rangeOfString("</Logement>") where startRange.endIndex <= endRange.startIndex {
    rangeName = String(xml)[startRange.endIndex..<endRange.startIndex]
} else {
    print("invalid input")
}

tracker.send(NSObject = GAIDictionaryBuilder.createItemWithTransactionId(String(format: (NSUserDefaults.standardUserDefaults().objectForKey("ApplicationUniqueIdentifier")!) as! String + String(id)), name: rangeName, sku: "", category: Configuration.MyVariables.typeForm, price: 1, quantity: 1, currencyCode: "").build() as! [NSObject : AnyObject])

The screenView is working, but I it an error for the transaction:

Cannot assign to immutable expression of type 'NSObject.Type'

A: In your last line, you are trying to assign your newly created object to the NSObject class, hence the Cannot assign to immutable expression of type 'NSObject.Type' error.
You should create your transaction item the same way as the screen view so you should change your code to make it look like this:
let eventTracker2: NSObject = GAIDictionaryBuilder.createItemWithTransactionId(String(format: (NSUserDefaults.standardUserDefaults().objectForKey("ApplicationUniqueIdentifier")!) as! String + String(id)), name: rangeName, sku: "", category: Configuration.MyVariables.typeForm, price: 1, quantity: 1, currencyCode: "").build()

tracker.send(eventTracker2 as! [NSObject : AnyObject])


text:
Q: jQuery Datatables performance I use jQuery with Datatables to display about 300 database rows. The table is on a jQuery UI dialog and is downloaded with an AJAX request. After the download I want to create jQuery UI Buttons on every row for edit and delete. This takes long time (on some 'weak' clients) and it's really annoying. Is there a way to make it faster? I tried INPUT type="button" and is a bit faster but ugly. Any Ideas/Suggestions? Thank you in advance!!!
EDIT
the last 2 lines inserting the buttons here is some of the code:
    $('

').dialog({
        parent : '#wdw1000',
        autoOpen : false,
        closeOnEscape : false,
        height : 500,
        maxHeight : 500,
        minHeight : 500,
        minWidth : 700,
        position : [479, 68],
        title : 'Arrivals',
        width : 1000
    });
    DWM.showForm("1000", "arrivals", "Arrivals", "Arrivals");
    $("#wdw1000_tbl").dataTable({
        "bJQueryUI" : true,
        "bPaginate" : false,
        "bProcessing" : true,
        "bLengthChange" : false,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : false,
        "bAutoWidth" : false,
        "sScrollY" : "300px",
        "sDom" : "<\"H\"lfr>tS<\"F\"ip>",
        "fnInitComplete" : function() {
            this.fnSettings().oScroller.fnScrollToRow(64);
        },
        "bDeferRender" : false,
        "oLanguage" : {
            "sProcessing" : "Επεξεργασία...",
            "sLengthMenu" : "Δείξε _MENU_ στοιχεία",
            "sZeroRecords" : "Δεν βρέθηκαν στοιχεία που να ταιριάζουν",
            "sInfo" : "Εμφάνηση _START_ έως _END_ από _TOTAL_ στοιχεία",
            "sInfoEmpty" : "Εμφάνηση 0 έως 0 από 0 στοιχεία",
            "sInfoFiltered" : "(εφαρμογή φίλτρου σε _MAX_ συνολικά στοιχεία)",
            "sInfoPostFix" : "",
            "sSearch" : "Αναζήτηση:",
            "oPaginate" : {
                "sFirst" : "Πρώτη",
                "sPrevious" : "Προηγούμενη",
                "sNext" : "Επόμενη",
                "sLast" : "Τελευταία"
            }
        },
        "aaData" : [['168', '00:10-1', '1339708200', 'TRA 232', 'Sundsvall', 'SDL', '', '', '', '0', '', '0', '3', 'Cancelled', 'CAN', '

', '

'],
                    ['169', '00:45-1', '1339710300', 'AEE 261', 'Varkaus', 'VRK', '', '', '', '0', '', '0', '5', 'New Time', 'NET', '

', '

'],
                    ['170', '01:15-1', '1339712100', 'FPO 228', 'Indianapolis', 'IND', '', '', '', '0', '', '0', '5', 'Diverted', 'DIV', '

', '

'],
    .
    .
    .
                    ['300', '08:10+1', '1339909800', 'LT 3620', 'Sao Joao', 'QSJ', '', '', '', '0', '', '0', '3', '', '', '

', '

']],
        "aoColumns" : [{
            "bVisible" : false
        }, {
            "aDataSort" : [2, 1],
            "sClass" : "alignLeft",
            "sTitle" : "STM",
            "sWidth" : "100px"
        }, {
            "bVisible" : false
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "FN",
            "sWidth" : "100px"
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "CITY"
        }, {
            "bVisible" : false
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "VIA"
        }, {
            "bVisible" : false
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "EST",
            "sWidth" : "100px"
        }, {
            "bVisible" : false
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "ACT",
            "sWidth" : "100px"
        }, {
            "bVisible" : false
        }, {
            "sClass" : "alignCenter Editable",
            "sTitle" : "BAG",
            "sWidth" : "100px"
        }, {
            "sClass" : "alignLeft",
            "sTitle" : "REM"
        }, {
            "bVisible" : false
        }, {
            "sTitle" : " ",
            "sWidth" : "10px",
            "bSortable" : false,
            "sClass" : "Edit"
        }, {
            "sTitle" : " ",
            "sWidth" : "10px",
            "bSortable" : false,
            "sClass" : "Delete"
        }]
    });
    $('#wdw1000_tbl div.Edit').button ({ icons : {primary : 'ui-icon-pencil'},text : false,label : 'Edit'});
    $('#wdw1000_tbl div.Delete').button ({ icons : {primary : 'ui-icon-pencil'},text : false,label : 'ui-icon-trash'});

A: I approached a similar performance problem by using mRender and  fnRowCallback, there I separated the display content from the sorting content and returned an empty content for the display in the mRender function. This reduced the initialization time dramatically.
fnRowCallback is called whenever a row is made visible, so here I created my more "complex" markup. In your example the buttons, in my case I had 2000 rows and some links inside the table that took 15 seconds to display. After applying my fix it was reduced to less than one second. If you are interested in some more detailed code examples just check out my blog post

A: You can insert these buttons only when a row catches a mouseover event, and remove them on mouseout? Then you can also probably reuse the DOM elements :)
my 2 cents,
Aurelien

A: Have you considered using the datatables editor that has this functionality built in?
I used the datatables editor for a project that did exactly what you are looking for (the rows were inventory, and the client wanted to be able to add/delete)
http://editor.datatables.net/
And an example:
http://editor.datatables.net/release/DataTables/extras/Editor/examples/inlineControls.html


text:
Q: Does the stack grow continuously? I'm wondering why this code isn't working as expected.
typedef char uint8;

  int main(int argc, const char * argv[]) {
  // insert code here...

  uint8 number_1 = 3;
  uint8 number_2 = 1;
  uint8 *PointerToNumber = &number_1;

  printf("%d \n", *PointerToNumber);
  ++PointerToNumber;
  printf("%d \n", *PointerToNumber);

  return 0;
}

This program prints 3 and -112. However shouldn't it print 3 and 1 if the stack grows continuously?
So if I'm pointing to number_1 and then increasing the pointer address of type uint8 shouldn't it then point to number_2 since it was declared right after number_2?

A: ++PointerToNumber;
printf("%d \n", *PointerToNumber);

is cause for undefined behavior. It's pointless trying to justify any behavior. The behavior of the program could change with changes to optimization level, different compiler options, and a different compiler.
In this case, an optimizer could choose not to allocate any space for number_2 since it is not used in the function.

A: All right as someone commented, number-2 is probably at the next lower address after number_1.
So instead of doing ++PointerToNumber, --PointerToNumber creates the expected result (printing "1").


text:
Q: If $a_n \to \infty$ and $b_n \to \infty$ and $\exists n_0, \forall n > n_0: a_n < b_n$, then $a_n/b_n \to 0$ I need to prove that
$\log(n)/n\to 0$. Surely $\exists n_0, \forall n > n_0 \log(n) < n$. I want to give a general proof. That is:
for any sequence $a_n \to \infty$ and $b_n \to \infty, \exists n_0, \forall n > n_0: a_n < b_n \lim_{n \to \infty} a_n/b_n = 0$.
Is it actually true? How can I prove it?

A: It is false : take $a_n = n$ and $b_n = 2n$

A: Let us consider as a counterexample
$$a_n=n-1 \quad b_n=n$$
To prove the given limit by $x=e^y$ we have
$$\frac{\log x}{x}=\frac{y}{e^y} \to 0 \implies \frac{\log n}{n}\to 0$$


text:
Q: Promise on older versions of javascript I am currently working with typescript and the new ECMAscript 6 feature Promise. My question is, can I use the Promise feature if my TypeScript gets compiled to a f.e. ECMAscript 3 js-file? I mean the Promise wasn't implemented at this version.

A: You can use a polyfill:
https://www.npmjs.com/package/es6-promise-polyfill
To install:
bower install es6-promise-polyfill

To use:
<script src="bower_components/es6-promise-polyfill/promise.min.js"></script>
<script>
  var promise = new Promise(...);
</script>


text:
Q: Mongoose.js update single attribute only if defined/changed How would I go about changing the attribute 'avatar' only if it is defined?
update: function(req, res){
    Student.findOneAndUpdate({ _id: req.params.id }, {
      first_name        : req.body.first_name,
      last_name         : req.body.last_name,
      _school           : req.body._school,
      _teacher          : req.body._teacher,
      grade             : req.body.grade,
      language          : req.body.language,
      avatar            : avatar,
      address           : req.body.address,
      city              : req.body.city,
      state             : req.body.state,
      zip               : req.body.zip,
      _guardians        : req.body._guardians,
      updated_at        : req.body.updated_at,
      active            : req.body.active   },
    function(err, student){
        if(err) res.render('error', { error: 'Error updating student'});
        res.redirect('/admin/students');
    });
}

I am looking for something like this:
var avatar = req.file ? req.file.fieldname : user.avatar;
Then use the var avatar within the update param of 'findOneAndUpdate'
Any help would be greatly appreciated!
Thanks!

A: I dont know your app or its logic, so I dont know how you want to parse and define avatar, so it is up to you (it can be similar to what you posted).
But otherwise, you can do something simple like this.
update: function(req, res){
    var options = {
      first_name        : req.body.first_name,
      last_name         : req.body.last_name,
      _school           : req.body._school,
      _teacher          : req.body._teacher,
      grade             : req.body.grade,
      language          : req.body.language,
      address           : req.body.address,
      city              : req.body.city,
      state             : req.body.state,
      zip               : req.body.zip,
      _guardians        : req.body._guardians,
      updated_at        : req.body.updated_at,
      active            : req.body.active   }

    if (avatar) {
        options.avatar = avatar;
    }

    Student.findOneAndUpdate({ _id: req.params.id }, options,
    function(err, student){
        if(err) res.render('error', { error: 'Error updating student'});
        res.redirect('/admin/students');
    });
}


text:
Q: How to share a custom Arcmap .mxd and toolbar? Using Arc 10.3.1, I created two tools (via Modelbuilder) which are in their own toolbox.
I then created a new Arcmap toolbar, named "Wetland Rating", and added the two tools, each with their own buttons, to that toolbar.  The toolbar is to be used in conjunction with a purpose-built .mxd.  Please see the two following images:

The .mxd and toolbox are stored on my organization's network path/folder.  Everything works fine when I load the .mxd and use the tool buttons.
However, other users in the organization need to access this .mxd and its toolbar buttons.  Here's the problem: when those users load the mxd, its layers display correctly, but my toolbar and its buttons do not appear.  The .mxd is useless without the associated toolbar.  How can I share this .mxd/toolbar with other users?

A: There are many ways to save your working content on Arcmap such as geodatabases (*.gdb), *.mxd and map packages (*.mpk). *gdb and *mpk formats are widely used for working in groups or transferring complete data within teams. But unfortunately they do not store your customizations on creation of shortcut keys, changing toolbar menu content etc.
For that purpose Arcmap provides the excellent guide to save these small customizations.


text:
Q: Why can't I delete the MutatingWebhookConfiguration I created? I'm experimenting with mutating admission controllers, and I seem to be able to create one, but not delete it, why is this?
Creating webhook config:
apiVersion: admissionregistration.k8s.io/v1beta1
kind: MutatingWebhookConfiguration
metadata:
  name: webhook
webhooks:
  - name: webhook.test.com
    clientConfig:
      service:
        name: my-service
        namespace: my-role
        path: "/foo"
      caBundle: "XXX"
    rules:
      - operations: ["CREATE", "UPDATE"]
        apiGroups: ["*"]
        apiVersions: ["*"]
        resources: ["pods"]
        scope:       "Namespaced"
    failurePolicy: Fail

Attempting to delete it: kubectl delete MutatingingWebhookConfiguration webhook
Response: error: the server doesn't have a resource type "MutatingingWebhookConfiguration"
I believe that error often has to do with the different versions of different resources, but I don't see why I would be able to create but not delete.

A: This was a silly mistake, I forgot to lowercase the resource name when using Kubectl, so kubectl delete mutatingwebhookconfiguration webhook works just fine.


text:
Q: jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}' I'm trying to use an xcom_pull inside an SQL phrase executed by a Snowflake operator in Airflow.
I need the task_id name to use a variable since I want to support different tasks.
I tried this syntax but seems it is not being rendered ok.
Anyone has an idea how to do it?
This is the Python code:
for product, val in PRODUCTS_TO_EXTRACT_INC.items():
       product_indicator, prefix = val

       params['product_prefix'] = prefix

       calculate_to_date = SnowflakeOperator(
            dag=dag,
            task_id=f'calculate_to_date_{prefix}',
            snowflake_conn_id = SF_CONNECTION_ID,
            warehouse=SF_WAREHOUSE,
            database=BI_DB,
            schema=STG_SCHEMA,
            role=SF_ROLE,
            sql= [  """
                    {SQL_FILE}
                    """.format(SQL_FILE="{% include '" + QUERIES_DIR + ETL + "/calculate_to_date.sql'" + " %}")
                ],
            params=params
        )

This is the SQL code for calculate_to_date.sql:
select '{{{{ (ti.xcom_pull(key="return_value", task_ids=["calculate_from_date_{}"])[0][0]).get("FROM_DATE") }}}}'.format(params.product_prefix) AS TO_DATE

This is the error message:
File "/home/airflow/gcs/dags/Test/queries/fact_subscriptions_events/calculate_to_date.sql", line 11, in template
select '{{{{ (ti.xcom_pull(key="return_value", task_ids=["calculate_from_date_{}"])[0][0]).get("FROM_DATE") }}}}'.format(params.product_prefix)
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

A: the correct syntax is
select '{{ (ti.xcom_pull(key="return_value", task_ids="calculate_from_date_{}".format(params.product_prefix))[0]).get("FROM_DATE") }}' AS TO_DATE

it works like a charm