Quantcast
Channel: Active questions tagged visual-studio-code - Stack Overflow
Viewing all 97327 articles
Browse latest View live

Unable to run python file in terminal using .py in vscode [closed]

$
0
0

I am completely new to Python and VSCode, as in first day using it but I thought I wasn't doing too bad.

I've tried changing the PATH using "system env" but to no avail.

The problem could still be I am using the wrong directory (?), I've used the one displayed in the bottom left of Python

New PC as well running Windows 10 latest version and the 64 bit version of VSCode and Python, if that matters.

I hope that's enough information to go off and I promise I will get better at requesting help as I go.

Thanks in advance.


Can't open jupyter notebook in VSCode

$
0
0

Perhaps a stupid question, but I recently switched to Visual Studio Code for Python and R.

I would like to use Jupyter Notebooks too, so I have installed the ms-python extension, and also the jupyter package, as described here. However, after reloading, I don't have a command Python: Create Blank New Jupyter Notebook, and if I open existing notebooks, the HTML/CSS is shown instead of an actual notebook view. I haven't found anything related to this problem online yet.

Getting an environment variable set in VSCODE based on CMake variant

$
0
0

I'm using Pybind11 to make C++/Python modules and apparently the output .DLLs need to be in the PYTHONPATH for the module to be imported (appending to sys.path does not work).

I'm using CMake variants to set various builds, and that makes separate output directories per variant.

I'm at a loss to find a way to set the PYTHONPATH environment variable in the integrated terminals (and jupyter notebooks) based on my chosen variant.

Any suggestions?

"terminal.integrated.env.windows": {
        "PYTHONPATH": "${workspaceRoot}\\build\\${variant:platform}"
    },

does not work (it doesn't seem to substitute ${variant:platform}).

in the .env file, neither ${workspaceRoot} nor ${variant:platform} seem to be available

how to debug 'extern' in c with vscode

$
0
0

I'm not familiar with c compiler,I know how to use gcc or g++ in terminal

I have

main.c

#include <stdio.h>

int count;
extern void write_extern();

int main()
{
   count = 5;
   write_extern();
}

support.c

#include <stdio.h>

extern int count;

void write_extern(void)
{
   printf("count is %d\n", count);
}

gcc main.c support.c

and the output file a.out works fine

but if I debug with vscode or code-runner plugin error shows

/"main Undefined symbols for architecture x86_64: "_write_extern", referenced from: _main in main-217186.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

my launch.json and task.json look like this:

"configurations": [
        {
            "name": "clang build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb",
            "preLaunchTask": "clang build active file"
        }
    ]
{
    "tasks": [
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            }
        }
    ],
    "version": "2.0.0"
}

how to config this?

Vscode on Ubuntu is not printing terminal progress bars correctly

$
0
0

From my understanding displaying progress bars in terminals work by refreshing and updating the line, giving the illusion of progress happening. My vscode on my ubuntu machine is not doing that correctly, however. Below is how vscode prints progress bars on my ubuntuenter image description here

As opposed to how Ubuntu's default terminal prints progress bars enter image description here

Notice in the default terminal towards the bottom, where it says 'Epoch 1, Epoch 2, etc'. Each progress bar takes up one line. Is there a way to fix vscode such that it does the same? By the way, I have vscode installed the exact same way on a windows computer, and it prints everything perfectly. Also, this happens to all kinds of progress bars, even when doing things like pip install [some module]

vscode: dagger generated code not detected

$
0
0

I've created a gradle project. This is build-gradle:

plugins {
    id 'java'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.amazonaws:aws-lambda-java-core:1.2.0'
    implementation 'com.amazonaws:aws-lambda-java-events:2.2.7'
    implementation 'com.amazonaws:aws-java-sdk-s3:1.11.754'
    implementation 'com.amazonaws:aws-java-sdk-dynamodb:1.11.754'

    implementation 'org.apache.logging.log4j:log4j-api:2.13.0'
    implementation 'org.apache.logging.log4j:log4j-core:2.13.0'
    runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0'
    runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0'

    implementation 'com.opencsv:opencsv:5.1'

    implementation 'com.google.dagger:dagger:2.27'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.27'

    testImplementation('org.junit.jupiter:junit-jupiter:5.6.1')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

task buildZip(type: Zip) {
    from compileJava
    from processResources
    into('lib') {
        from configurations.runtimeClasspath
    }
}

build.dependsOn buildZip

As you can see I've set up dagger dependencies:

implementation 'com.google.dagger:dagger:2.27'
annotationProcessor 'com.google.dagger:dagger-compiler:2.27'

My component is:

@Component(modules = DaggerTransporterModule.class)
public interface TransporterMaker {

    SOCTransporter maker();

}

After having performed an gradle build, dagger artifacts are generated:

I've took a look on generated code:

$ tree build/classes/java/main/net/gencat/soc/lambda/config/
build/classes/java/main/net/gencat/soc/lambda/config/
├── DaggerTransporterMaker$Builder.class
├── DaggerTransporterMaker.class
├── DaggerTransporterModule.class
├── DaggerTransporterModule_ProvideContactServiceFactory.class
├── DaggerTransporterModule_ProvideCSVDaoFactory.class
├── DaggerTransporterModule_ProvideCSVDaoFactory$InstanceHolder.class
├── DaggerTransporterModule_ProvideDynamoDBDaoFactory.class
├── DaggerTransporterModule_ProvideDynamoDBDaoFactory$InstanceHolder.class
├── DaggerTransporterModule_ProvideS3DaoFactory.class
├── DaggerTransporterModule_ProvideS3DaoFactory$InstanceHolder.class
└── TransporterMaker.class

As you can see, dagger artifacts are generated correctly.

Nevertheless, I'm not able to use them inside vscode:

enter image description here

Gradle is running fine:

$ gradle compileJava

BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed

Any ideas?

In VScode, how do I open a file from the line it's being imported on?

$
0
0

I'm importing various items from a file in vscode. The module exists, but seems to be missing some of the items. I can see the module definitely exists on the filesystem, and vscode even shows me the file name:

enter image description here

I'd like to open the file directly from where it's imported, using the same logic VScode itself uses to import the module. I would have thought right clicking would allow me to do this ('Go to implementation') sounds like it would open the file, but it doesn't do anything.

Obviously I could open a shell and start code pointing to that file, but that's a workaround rather than an actual solution.

How do I open a file being imported in vscode?

enter image description here

C++ - begin() returns the end() iterator with a non-empty list

$
0
0

As the question suggest, I'm having a very strange behavior with iterators and lists. So, the (class) problem asks for a function that erase all elements that meet a condition from a list and, when I tried to cover the case where I have a list where all elements are the same I found out that the last element persisted.

Here is the code:

void esborra_tots(list<Estudiant>& t, int x) {
    list<Estudiant>::iterator it;
    list<Estudiant>::iterator itend = t.end();

    for (it = t.begin(); it != t.end(); it++) {
        if ((*it).consultar_DNI() == x) {

            t.erase(it);
            if (t.empty()) return;
            else it = t.begin();
        }
    }
}

I've used itend just to see the value while debugging. Here is the session: See that the list *t* is not empty but t.begin() returns the same as t.end()

How is this possible? PD: I'm not searching for other approaches to the problem.


Set up Neovim integration in VS code

$
0
0

Currently a (neo)vim user, I read that VS Code supports neovim backend integration, but after searching I cannot find how to set it up.

Can someone explains how to set up neovim integration in VS Code?

Thank you.

PS : I use both linux and windows so if there are some OS specifity you could mention it.

How to stop vscode beautify or prettier from preserving newlines when formatting javascript code?

$
0
0

I want to remove all the newlines/extra lines when I save the code. I found this settings in Atom but not in VSCode. How can I do that?

Pylint unresolved import errors in VSCode (go-to definition works)

$
0
0

I'm trying to use a Python testing framework via VSCode and think I've managed to get it almost working.

The current symptoms are that for the testing framework's modules:

  1. Go-to definition, peek and related functionality works
  2. pylint throws unresolved import errors

Other standard/pip-installed modules work fine.

What I have done is:

  1. Created a Python venv and configured VSCode to use it as my interpreter
  2. Set up the Python venv's activate script to update PYTHONPATH and GIT_REPO (a requirement of the framework)
  3. Added the following to .vscode/settings.json:
"python.pythonPath": "/path/to/my/venv/bin/python",
    "python.testing.pytestEnabled": true,
    "python.testing.nosetestsEnabled": false,
    "python.testing.unittestEnabled": false,
    "python.envFile": "${workspaceFolder}/.env",
    "python.autoComplete.extraPaths": [
        "/path/to/the/framework/lib"
    ],

I got the python.autoComplete.extraPaths thing from this question and it was the step that got go-to definition and similar functionality working.

  1. Added the following to .env in the workspace folder:
    GIT_REPO=/path/to/the/framework
    PYTHONPATH=$GIT_REPO/lib

How to setup vscode settings for Python formatter?

$
0
0

Somehow my formatter isn't working. I pip installed yapf , but when I do cntr+shift+p -> Format Document or Shift + Alt + F on a selected code, it doesn't change. I heard it autoformattes on save, but that didn't work either.

I am trying to follow the guide here

https://code.visualstudio.com/docs/python/editing#_formatting

It mentions I should edit this part in the settings

"python.formatting.yapfArgs": ["--style", "{based_on_style: chromium, indent_width: 20}"],

But when I search this, this is the only thing I see

https://snipboard.io/9sCB8H.jpg

What I am trying to do at the moment is set the indent to 4 spaces, and also adjust the max line length.

This are what my settings look like for formatting

https://snipboard.io/LXklRI.jpg

VS Code Intellisense for javascript not giving suggestions?

$
0
0

picture

Is there a way to get suggestions like div.appendChild here?

It feels like I'm missing a lot of suggestions.

Stuff like addEventListener doesn't show up.

Or is that just something that isn't possible?

VS Code run and debug Python in Docker using docker-compose

$
0
0

Configuring VS Code for easy-to-use environment. I would like to have a simple way to launch Python script in Docker and attach debugger.

What do I have working good:

  1. Created Dockerfile and docker-compose.yaml to run docker-compose up|start correctly.
  2. I'm able to attach to running docker container and debug my code.

What do I want to get?

One single button to launch and attach at once.

I need to start application using docker-compose. I do not want to configure docker-run tasks in VS Code.

My code and ideas:

Dockerfile:

FROM python:3.6-alpine
RUN mkdir -p /work/
WORKDIR /work/
COPY ./python/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY ./python/src/ .
CMD python -m ptvsd --host 0.0.0.0 --port 5678 --wait run.py < tests/input.txt > tests/output.txt

docker-compose.yaml

version: "3.7"
services:
    py-service:
        container_name: py-container
        image: py-image
        build:
            context: ./
        volumes:
            - ./python/src/:/work
        ports:
            - 5678:5678

launch.json configurations:

   { // simple attach to running container - works good
        "name": "Python Attach",
        "type": "python",
        "request": "attach",
        "pathMappings": [
            {
                "localRoot": "${workspaceFolder}/python/src/",
                "remoteRoot": "/work/"
            }
        ],
        "port": 5678,
        "host": "127.0.0.1"
    },
    { // launch docker container and attach to debugger - NOT works
        "name": "Run Py in Docker",
        "type": "docker",
        "request": "launch",
        "platform": "python",
        "preLaunchTask": "docker-compose-start",
        "python": {
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/python/src/",
                    "remoteRoot": "/work/"
                }
            ],
            "projectType": "general",
            "host": "127.0.0.1",
            "port": 5678,
        },
    },

tasks.json to run docker-compose command

{
  "label": "docker-compose-start",
  "type": "shell",
  "command": "docker-compose up"
},

The trouble is that execution of Run Py in Docker starts normally my container, but is not able to attach debugger and fails on time out. While container is still running and waiting for attachment. Could this be fixed somehow?

UPDATE

Finally I was able to launch and debug! Here is my task.json:

{
  "label": "docker-compose-start",
  "type": "shell",
  "command": "docker-compose up --build -d",
  "isBackground": true,
  "problemMatcher": [
    {
      "pattern": [{ "regexp": ".", "file": 1, "location": 2, "message": 3, }],
      "background": {
        "activeOnStart": true,
        "beginsPattern": "^(Building py-service)$",
        "endsPattern": "^(Creating|Recreating|Starting) (py-container) ... (done)$",
      }
    },
  ],
},

launch.json:

{
    "name": "run py",
    "type": "python",
    "request": "attach",
    "preLaunchTask": "docker-compose-start",
    "pathMappings": [
        {
            "localRoot": "${workspaceFolder}/python/src/",
            "remoteRoot": "/work/"
        }
    ],
    "port": 5678,
    "host": "127.0.0.1"
},

After all I've got an inconvenience with showing all docker up|build output into Problems. VS Code asks to continue each time, but Enter helps.

How to make visual studiio code allow special characters(%) as emmet?

$
0
0

I have added the following snippet to my jina-html.json file

"open block": {"prefix": "%%","body": ["{% $1 %}$2"]},

When I hit tab it does nothing except a regular tab

When I change the prefix to a letter character it works and any other special character does not work either. Is there a way to make it work with special characters?


pandas iat : vscode vs jupiterlab

$
0
0

I used some code that works on vscode :

df.iat[row_marker,column_marker] = thisText

At first df is not defined, row_marker,column_marker equal zero;It creates new line and column correctly !

I tried the same code in jupiterlab but got an IndexError : I assume it is because the column number is not knowed....

Why is this working in vscode but not in JupiterLab ?What is the method to add new values manually when we don't know the size of the dataframe ?


New comment : the dataframe exist but is empty

Debugging Electron render process with VSCode Chrome debugger

$
0
0

Setting up an angular + electron debug configuration and it's slowly but surely crushing my soul. For some reason breakpoints aren't hitting in the render process (VSCode is showing the error Breakpoint ignored because generated code not found (source map problem?)").

My debug config looks like this (full repo is here):

// .vscode/launch.json{"version": "0.2.0","configurations": [    {"type": "node","request": "launch","name": "Electron: Main","protocol": "inspector",      // Prelaunch task compiles main.ts for Electron & starts Angular dev server."preLaunchTask": "Build: All","cwd": "${workspaceFolder}","runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron","runtimeArgs": ["--remote-debugging-port=9223", "--serve", "."],"windows": {"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"      }    },    {"name": "Electron: Renderer","type": "chrome","request": "attach","port": 9223,"webRoot": "${workspaceFolder}","timeout": 30000,"urlFilter": "http://localhost:4200/*",      // Source map overrides are copied from Angular CLI debugging recipe.      // See: https://github.com/Microsoft/vscode-recipes/tree/master/Angular-CLI"sourceMaps": true,"sourceMapPathOverrides": {"webpack:/*": "${webRoot}/*","/./*": "${webRoot}/*","/src/*": "${webRoot}/*","/*": "*","/./~/*": "${webRoot}/node_modules/*"      }    }  ],"compounds": [    {"name": "Electron: All",      // The main process should be started before renderer to prevent timeout."configurations": ["Electron: Main", "Electron: Renderer"]    }  ]}
// .vscode/tasks.json{"version": "2.0.0","tasks": [    {"label": "Build: All","type": "shell","command": "npm run electron:serve-tsc && ng serve","isBackground": true,"group": {"kind": "build","isDefault": true      },"problemMatcher": {"owner": "typescript","source": "ts","applyTo": "closedDocuments","fileLocation": ["relative", "${cwd}"],"pattern": "$tsc","background": {"activeOnStart": true,"beginsPattern": "^.*","endsPattern": "^.*Compiled successfully.*"        }      }    }  ]}

I can debug the main process just fine with the above config, which is awesome. The chrome debugger also seems to be attaching correctly (can see the outputs in the debug console), but sadly breakpoints aren't hitting.

Just adding debugger; statements to the Angular code lets me debug in the chrome devtools in the Electron window, but it would be far far better to debug inside VSCode.

Is this even possible to do??

VSCode Extension, how to open treeItem in editor when selected in treeView? [duplicate]

$
0
0

I'm building an extension for VSCode that lists files in a location that the user sets. I can get the files to show up in the TreeView that I have created based on the tree-view-sample for nodeDependencies. I have a TreeViewProvider that generates the list of files to be displayed in the TreeView. The problem that I have run into is that I don't understand how to get one of these items to open in the editor when a user clicks on it.

The class that I have created for a File is the following:

export class File extends vscode.TreeItem {constructor(    public readonly label: string,    public readonly location: string,    public readonly collapsibleState: vscode.TreeItemCollapsibleState,    public readonly command?: vscode.Command) {    super(label);}get tooltip(): string {    return `${this.label}`;}iconPath = {    light: path.join(__filename, '..', '..', 'resources', 'light', 'note.svg'),    dark: path.join(__filename, '..', '..', 'resources', 'dark', 'note.svg')};contextValue = 'note';}

I am guessing that I need a supply a command? to tell VSCode to open the File in the editor window when a user clicks on the TreeItem in the TreeView?

I don't expect a handout answer, but if someone could point me at a working example or in the right direction I would appreciate it.

Can author be specified in jupyter notebook markdown so nbconvert uses it for PDF article author?

$
0
0

Using VS Code Notebook Editor I can have Python and Markdown cells. Eventually I want make a PDF article using nbconvert and include the author. I can make a nbconvert template that includes the author, but I feel like I'm playing with fire.

Is there a way to include the author directly in the notebook markdown?

FYI, here is how I currently use a template (borrowed heavily from the default article template).

$ python3 -m nbconvert --to pdf --template article2col.tplx --TemplateExporter.exclude_input=True 'MyJupyterNotebook.ipynb'
$ cat article2col.tplx ((=- Default to the notebook output style -=))((*- if not cell_style is defined -*))    ((* set cell_style = 'style_jupyter.tplx' *))((*- endif -*))((=- Inherit from the specified cell style. -=))((* extends cell_style *))%===============================================================================% Latex Article%===============================================================================((*- block docclass -*))\documentclass[10pt,twocolumn,a4paper,twoside]{article}\setlength{\columnseprule}{0.4pt}\usepackage{titling}\setlength\droptitle{-3\baselineskip}\usepackage[raggedright]{titlesec}% \titlespacing*{\section} {0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}\titlespacing*{\section} {0pt}{0\baselineskip}{0ex}((*- endblock docclass -*))((* block author *))\author{Author Name Goes Here}((* endblock author *))

Debugging standalone Typescript file in React project using VScode

$
0
0

I've a React project created using create react app. Sometimes I want to play with typescript code in a separate file and debug it.

VSCode requires the generated .js folder to be set in the debug configuration, otherwise the following message appears.

Cannot launch program 'File.ts' setting the 'outFiles' attribute might help.

Or if set to "outFiles": ["${fileDirname}/*.js"]:

Cannot launch program 'File.ts' because corresponding JavaScript cannot be found.

I can't find where the project is generating the .js files. It seems create react app uses webpack, which should use ts-loader. It generates a bundle.js file, but I can't even find it in the workspace folder either.

For reference, my full launch.json. Any help is appreciated. Thanks!

{"version": "0.2.0","configurations": [         // Not working        {"type": "node","request": "launch","name": "Debug File","program": "${file}","outFiles": ["${fileDirname}/*.js"]      },      {"type": "node","name": "Run tests","request": "launch","args": ["test","--runInBand"         ],"cwd": "${workspaceFolder}","console": "integratedTerminal","internalConsoleOptions": "neverOpen","disableOptimisticBPs": true,"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/react-scripts","protocol": "inspector"      },      {"name": "Chrome","type": "chrome","request": "launch","url": "http://localhost:3000","webRoot": "${workspaceRoot}/src"     }   ]}
Viewing all 97327 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>