"Cannot use import statement outside a module" - Danger System with React - ecmascript-6

I am using Danger JS with React app created using create-react-app. So I have a dangerfile.js like below in the Root directory of the project.
import {message, danger} from "danger"
const modifiedMD = danger.git.modified_files.join("- ")
message("Changed Files in this PR: \n - " + modifiedMD)
The import works in this case. But when I am trying to install a plugin like danger-plugin-eslint the import doesn't work.
import {message, danger} from "danger"
import eslint from 'danger-plugin-eslint'
const modifiedMD = danger.git.modified_files.join("- ")
message("Changed Files in this PR: \n - " + modifiedMD)
eslint()
The error says -
SyntaxError: Cannot use import statement outside a module
I am new to react. Am I missing anything? Any help is appreciated!

I faced this error today and as I didn't found the solution anywhere, here one solution that worked for me: just drop the import or requirement lines.
Just this should work fine
const modifiedMD = danger.git.modified_files.join("- ")
message("Changed Files in this PR: \n - " + modifiedMD)

Related

Vue - i18n custom translations

I have VUE app with vue-i18n plugin.
I would like to load 'custom path' for translations when app is loaded.
The app is not loading the translations? What am I doing wrong?
File: i18n/index.js
/* eslint-disable */
import { createI18n } from "vue-i18n";
import Message from "#/localization/MyCity/en.json"
const i18n = createI18n({
// default locale
locale: "en",
// translations
messages: Message
});
export default i18n;
File: main.ts
import i18n from "./i18n";
const app = createApp(App).use(i18n)
app.mount("#app");
I tried the code above and the translations are not loading. Do you have any suggestions? This even might be the wrong approach to this problem. Do you have any other suggestion.
Topic 2:
Later on I will try and make dynamic translations based on deployment. I would like to make it fast and simple so I was thinking creating .env file with variable MY_CITY_NAME and do it like this import Message from "#/localization/${MY_CITY_NAME}/en.json".
I guess your problem might be that you are not specifying language of your Messages object.
Try this:
const i18n = createI18n({
...
messages: {
en: Message
}
});

Getting error in react app -> " export 'MessageTeam' (imported as 'MessageTeam') was not found in 'stream-chat-react' "

I am using stream api to create a chat app. But getting this error while importing MessageTeam i.e a inbuild component in stream-chat-react.
import React from "react";
import { MessageTeam, useMessageContext } from "stream-chat-react";
const TeamMessage = () => {
const { message } = useMessageContext();
return (
<MessageTeam
message={{ ...message, user: {} }}
/>
);
};
export default TeamMessage;
Bro found the solution use MessageSimple instead worked great for me.
MessageTeam component was removed in this commit.
Refer documentation for latest components.
MessageTeam is not more supported for Stream V10, try unistalling V10 and install V9. It should sove your problem.

Web-scraping a link from web-page

New to web-scraping here. I basically want to extract a link from a web page into my jupyter notebook as shown in the image below :
Following is the code that I tried out:
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
import requests
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen as uReq
flipkart_url = "https://www.flipkart.com/search?q=" + 'acer-aspire-7-core-i5'
uClient = uReq(flipkart_url)
flipkartPage = uClient.read()
flipkart_html = bs(flipkartPage, "html.parser")
#Since I am only interested in the class "_1AtVbE col-12-12"
bigboxes = flipkart_html.findAll("div", {"class": "_1AtVbE col-12-12"})
Now here's the thing, I don't exactly understand what bigboxes is storing. The type of bigboxes is bs4.element.ResultSet, the length is 16.
Now if I run:
box = bigboxes[0]
productlink = "https://www.flipkart.com" + box.div.div.div.a['href']
I am getting an error. However when I run:
box = bigboxes[2]
productlink = "https://www.flipkart.com" + box.div.div.div.a['href']
I am successfully able to extract the link. Can someone please explain to me why the third element was able to read the link? I have a basic knowledge of HTML (at least I thought so) and I don't understand the layers to it. What exactly is bigboxes storing? Clearly, the HTML script shows no layers as such.
Your class filter is not very specific.
The first and second elements are pointing to html nodes which do not contain the link. Thus you are getting error.
A more specific class to check could be: _13oc-S
bigboxes = flipkart_html.findAll("div", {"class": "_13oc-S"})

import json in javascript doesn't seem to succeed

In a firebase functions project I want to have some settings in a settings.json and then import the settings in my typescript files. For some reason, the import doesn't seem to succeed and I can't see or figure out why.
My folder/file structure looks like this:
src
- database
- index.ts <-- only exports uppercase.ts
- uppercase.ts
- regions.ts
In uppercase.ts I import regions.ts to use the functions object with the configuration to deploy on europe-west1.
import { functionsEUWest1 } from '../regions';
export const uppercase = functionsEUWest1.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => {
//Code as can be found in the tutorials of firebase.
});
In the regions, I try to read the settings from settings.json to use for the configuration.
import functions from 'firebase-functions';
import settings from "./settings.json";
const region: any = settings.region;
export const functionsEUWest1 = functions.region(region);
And this is the content of settings.json
{
"region": "europe-west1"
}
The folder/file structure of the build output is the same (only in lib instead of src but this is by default configured by firebase).
When I try to deploy my functions, I get the following error:
Error: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'region' of undefined
at Object.<anonymous> (<local basepath>\functions\lib\regions.js:9:57)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (<local basepath>\functions\lib\database\uppercase.js:3:19)
at Module._compile (module.js:653:30)
When I look into the build output in the file regions.js, I can't detect any rarity of transpiled code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const firebase_functions_1 = __importDefault(require("firebase-functions"));
const settings_json_1 = __importDefault(require("./settings.json"));
const region = settings_json_1.default.region;
exports.functionsEUWest1 = firebase_functions_1.default.region(region);
//# sourceMappingURL=regions.js.map
Also the settings.json is copied to the build location and is in the same folder as regions.js. Yet the property default from setting_json_1 is undefined and I can't figure out what goes wrong.
Edit
I added 2 settings to the tsconfig.json. I did this cause it was advised in several articles I found:
"resolveJsonModule": true,
"esModuleInterop": true
After some more research I came up later on, I figured out it wasn't the json import that didn't seem to work, but it looks like the setting
"esModuleInterop": true
doesn't seem to work together with firebase or perhaps more specific: firebase functions, for so far as I can see and conclude.
The research to the conclusion
First I wanted to figure out if import in TypeScript does work at all, so I created 3 .ts files and one .json file and one of the .ts files I put in a folder. Then I generated the tsconfig.json with
tsc --init
and I added the 2 settings (resolveJsonModule and esModuleInterop). I transpiled the .ts files to .js files and ran the code with node. And this works, I saw the setting value from the .json file printed in the console.
The .ts file that imported the .json file has these lines of code:
import settings from "./settings.json";
console.log('from test.ts: ' + settings.setting1);
export const Settings = settings;
This got transpiled to:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var settings_json_1 = __importDefault(require("./settings.json"));
console.log('from test.ts: ' + settings_json_1.default.setting1);
exports.Settings = settings_json_1.default;
Now, I don't understand this code completely because I don't know what __importDefault or mod are.
But this code along with the other code does do what it suppose to do: read the setting from the .json file and print it in the console. So importing .json files does work. So it got to do something with firebase.
The next step I did, was creating a clean firebase project which uses functions and hosting. In the by the firebase CLI genrated index.ts in the functions/src folder, I changed the code to this:
import functions from 'firebase-functions';
import settings from "./settings.json";
const setting1 = settings.setting1;
export const helloWorld = functions.region('europe-west1').https.onRequest((request, response) => {
response.send("Hello from Firebase! Settings1 value = " + setting1);
});
And I also added the same 2 settings to tsconfig.json (resolveJsonModule and esModuleInterop). When I try to deploy this function to the firebase cloud, I got an error that is the same as I mentioned in my Question post:
TypeError: Cannot read property 'region' of undefined
But this time, I didn't had a property region in my .json file. So the fact I had region in my code in the question post and the fact I didn't look at the line numbers of the stacktrace, mislead me, making me think the .json import didn't work. But it is working.
The cause of the error is the method region that is called on the firebase_functions_1.default. For some reason, default is undefined and that is generating the error. This made me also realise I really miss the name of the object or objects in the error. What I would like to see is something like
TypeError: Cannot read property 'region' of undefined (firebase_functions_1.default)
So, back to the problem, I still got the error, but it wasn't cause by the .json import. To figure out what the actual cause was, I first reverted the "esModuleInterop" setting in the tsconfig.json, which results in errors in the import section in my index.ts. I had to change the imports back to
import * as functions from 'firebase-functions';
import * as settings from "./settings.json";
And now, the deploy to the firebase cloud works again, with importing a .json file. Also, the transpiled code looks different without using the "esModuleInterop" setting:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const functions = require("firebase-functions");
const settings = require("./settings.json");
const setting1 = settings.setting1;
exports.helloWorld = functions.region('europe-west1').https.onRequest((request, response) => {
response.send("Hello from Firebase! Settings1 value = " + setting1);
});
//# sourceMappingURL=index.js.map
It no longer has the default property on firebase_functions_1 but instead now just has functions.
It depends on some of your build and tsconfig settings. I've seen the above working for some people, where it uses the default export. But for me (Webpack with json-loader) this is what I use to import JSON files:
import * as settings from "./settings.json";
And of course, in my case, I add a definition like so to my global.d.ts file:
declare module "*.json";
Just so TS won't complain about it.

Download CSV from an iPython Notebook

I run an iPython Notebook server, and would like users to be able to download a pandas dataframe as a csv file so that they can use it in their own environment. There's no personal data, so if the solution involves writing the file at the server (which I can do) and then downloading that file, I'd be happy with that.
How about using the FileLinks class from IPython? I use this to provide access to data directly from Jupyter notebooks. Assuming your data is in pandas dataframe p_df:
from IPython.display import FileLink, FileLinks
p_df.to_csv('/path/to/data.csv', index=False)
p_df.to_excel('/path/to/data.xlsx', index=False)
FileLinks('/path/to/')
Run this as a notebook cell and the result will be a list of links to files downloadable directly from the notebook. '/path/to' needs to be accessible for the notebook user of course.
For not too large tables you can use the following code:
import base64
import pandas as pd
from IPython.display import HTML
def create_download_link( df, title = "Download CSV file", filename = "data.csv"):
csv = df.to_csv()
b64 = base64.b64encode(csv.encode())
payload = b64.decode()
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>'
html = html.format(payload=payload,title=title,filename=filename)
return HTML(html)
df = pd.DataFrame(data = [[1,2],[3,4]], columns=['Col 1', 'Col 2'])
create_download_link(df)
If you want to avoid storing CSVs on the server, you can use this Javascript alternative that create the CSV on the client-side:
from IPython.display import Javascript
js_download = """
var csv = '%s';
var filename = 'results.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % data_in_dataframes.to_csv(index=False).replace('\n','\\n').replace("'","\'")
Javascript(js_download)
Basically, it creates a CSV string in python from the pd dataframe and use it in a small js script that creates a CSV file on the client side and open a saving dialog to save it on the user computer. I tested in my iPython env and it works like a charm!
Note that I am escaping the \n. If I don't do so, the js script string will have the CSV variable written on multiple lines.
For example, print "var csv = '%s'" % industries_revenues.to_csv(index=False).replace('\n','\\n') results to this:
var csv = 'Industry,sum_Amount\nBanking,65892584.0\n(...)Finance,20211917.0\n'
Instead of print "var csv = '%s'" % industries_revenues.to_csv(index=False) without the \n escaping that results on a multiple lined and therefore errored javascript:
var csv = 'Industry,sum_Amount
Banking,65892584.0
(...)
Finance,20211917.0
'
I also escape the ' not to break the variable string in javascript.
A function that creates a csv download link, based on Coen Jonker's answer and similar to Yasin Zähringer's answer except that it uses IPython.display.FileLink so that there is no need to create html code.
The function has an optional delete prompt so you can delete the file after download to keep the notebook server clean.
# Import a module to create a data frame
import pandas
# Import a module to display a link to the file
from IPython.display import FileLink
# Import a module to delete the file
import os
# Create a download function
def csv_download_link(df, csv_file_name, delete_prompt=True):
"""Display a download link to load a data frame as csv within a Jupyter notebook
Parameters
----------
df : pandas data frame
csv_file_name : str
delete_prompt : bool
"""
df.to_csv(csv_file_name, index=False)
display(FileLink(csv_file_name))
if delete_prompt:
a = input('Press enter to delete the file after you have downloaded it.')
os.remove(csv_file_name)
# Create an example data frame
df = pandas.DataFrame({'x':[1,2,3],'y':['a','b','c']})
# Use the function to diplay a download link
csv_download_link(df, 'file_name.csv')
This is mostly for people who use jupyter notebooks on their own machine. On a shared machine, the use of os.remove might be problematic depending on how you set up file write permissions.
You can use the fact that the notebook can display html for objects, and data urls, to make the content of a csv downloadable:
import urllib
class CSV(object):
def _repr_html_(self):
html = []
html.append("{},{},{}".format(
"user",
"age",
"city"
)
)
html.append("{},{},{}".format(
"Alice",
"39",
"New York"
)
)
html.append("{},{},{}".format(
"Bob",
"30",
"Denver"
)
)
html.append("{},{},{}".format(
"Carol",
"27",
"Tulsa"
)
)
export = '\n'.join(html)
export = urllib.quote(export.encode("utf-8"))
csvData = 'data:application/csv;charset=utf-8,' + export
return "<a download='export.csv' href='{}' target='_blank'>csv file</a>".format(csvData)
CSV()
The simple method that I found was:
df.to_csv('~/Desktop/file_name.csv')
My simple approach to download all the files from the jupyter notebook would be by simply using this wonderful command
!tar cvfz my_compressed_file_name.tar.gz *
This will download all the files of the server including the notebooks.
In case if your server has multiple folders, you might be willing to use the following command. write ../ before the * for every step up the directory.
tar cvfz zipname.tar.gz ../../*
Hope it helps..