id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
7a8fac9b262c9b6e163e29afe857f67327e97c01 | Stackoverflow Stackexchange
Q: How to setOnNavigationItemListener on BottomNavigationView in android using Kotlin? I use kotlin-android-extension and I can call bottomNavigationView id from layout file to kotlin file. I can use bottomNavigationView.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener {}), but whats next?
As far as I know in Java, there is another function called onNavigationItemSelected, but I can't find it in kotlin.
this is the example code I want to use in Java but cannot write it in kotlin.
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorites:
case R.id.action_schedules:
case R.id.action_music:
}
return true;
}
});
A: You can use below code
bottom_navigation.setOnNavigationItemSelectedListener {
var selectedFragment: Fragment = A()
when (it.itemId) {
R.id.action_item1 -> selectedFragment = A()
R.id.action_item2 -> selectedFragment = B()
R.id.action_item3 -> selectedFragment = C()
}
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.frame_layout, selectedFragment)
transaction.commit()
return@setOnNavigationItemSelectedListener true
}
| Q: How to setOnNavigationItemListener on BottomNavigationView in android using Kotlin? I use kotlin-android-extension and I can call bottomNavigationView id from layout file to kotlin file. I can use bottomNavigationView.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener {}), but whats next?
As far as I know in Java, there is another function called onNavigationItemSelected, but I can't find it in kotlin.
this is the example code I want to use in Java but cannot write it in kotlin.
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorites:
case R.id.action_schedules:
case R.id.action_music:
}
return true;
}
});
A: You can use below code
bottom_navigation.setOnNavigationItemSelectedListener {
var selectedFragment: Fragment = A()
when (it.itemId) {
R.id.action_item1 -> selectedFragment = A()
R.id.action_item2 -> selectedFragment = B()
R.id.action_item3 -> selectedFragment = C()
}
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.frame_layout, selectedFragment)
transaction.commit()
return@setOnNavigationItemSelectedListener true
}
A: use must add annotation for return the lambda only
bottomNavigation.setOnNavigationItemSelectedListener { item ->
when(item.itemId){
R.id.home -> {}
R.id.group -> {}
R.id.profile -> {}
}
return true
}
A: bottomNavigationView.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.action_favorites -> { }
R.id.action_schedules -> { }
R.id.action_music -> { }
}
true
}
note that last line seems to miss the return keyword, but
The last expression in a lambda is considered the return value:
from https://kotlinlang.org/docs/reference/lambdas.html
Moreover, @setOnNavigationItemSelectedListener creates a
local final fun <anonymous> (it: Menuitem) : Boolean
wrapping what follows, so in some answers this will have the effect of executing the when block only when the listener is set (only one time), and the callback will be just a return true statement.
A: This is my code using the new Navigation component.
Let me know if you need help with nav ui.
bottom_nav.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.home -> {
findNavController(R.id.nav_host_fragment)
.navigate(R.id.mainFragment)
}
R.id.search -> {
findNavController(R.id.nav_host_fragment)
.navigate(R.id.searchFragment)
}
R.id.inapppurchases -> {
findNavController(R.id.nav_host_fragment)
.navigate(R.id.inappPurchasesFragment)
}
R.id.settings -> {
findNavController(R.id.nav_host_fragment)
.navigate(R.id.settingsFragment)
}
}
true
}
A: You can use this format of code:
bottomNavigation.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.action_favorites -> {
}
R.id.action_schedules -> {
}
R.id.action_music -> {
}
}
true
}
A:
return boolean in each block because setOnNavigationItemSelectedListener expects return type
fun initViews() {
bottomNavigationView.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.action_menu_media -> {
true
}
R.id.action_menu_tag -> {
true
}
R.id.action_menu_home -> {
true
}
else -> {
true
}
}
}
}
A: kotlin:
use setOnItemSelectedListener
bottomNavigationView.setOnItemSelectedListener { item: MenuItem ->
when (item.itemId) {
R.id. ... -> {
Add your code
true
}
else ->
true
}
| stackoverflow | {
"language": "en",
"length": 409,
"provenance": "stackexchange_0000F.jsonl.gz:887014",
"question_score": "18",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611224"
} |
d943dbaadecd6ea666f05f5f5fbdc9725a011690 | Stackoverflow Stackexchange
Q: How to get BottomNavigation item view reference for TapTargetView I have a Bottom Navigation View and I'm using TapTargetView library to guide the user on how to use certain features. If I pass the Bottom Navigation View then TapTargetView will highlight the whole bottom bar which I don't want that.
My question is how can I highlight the specific item in the Bottom Navigation View?
TapTargetView.showFor(this, TapTarget.forView(findViewById(R.id.home), "Home page", "We have cool features for you"),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
itemClicked();
}
});
Thanks.
A: I have found the solution, here is it:
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
TapTargetView.showFor(this, TapTarget.forView(bottomNavigationView.findViewById(R.id.home), "Home page", "We have cool features for you"),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
itemClicked();
}
});
| Q: How to get BottomNavigation item view reference for TapTargetView I have a Bottom Navigation View and I'm using TapTargetView library to guide the user on how to use certain features. If I pass the Bottom Navigation View then TapTargetView will highlight the whole bottom bar which I don't want that.
My question is how can I highlight the specific item in the Bottom Navigation View?
TapTargetView.showFor(this, TapTarget.forView(findViewById(R.id.home), "Home page", "We have cool features for you"),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
itemClicked();
}
});
Thanks.
A: I have found the solution, here is it:
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
TapTargetView.showFor(this, TapTarget.forView(bottomNavigationView.findViewById(R.id.home), "Home page", "We have cool features for you"),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
itemClicked();
}
});
A: I havent actually tried this, but i think this should work
TapTargetView.showFor(this, TapTarget.forView(YOURBOTTOMNAVIGATIONVIEW.getChildAt(YOUR VIEW POSITION), "Home
page", "We have cool features for you"),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
itemClicked();
}
});
| stackoverflow | {
"language": "en",
"length": 164,
"provenance": "stackexchange_0000F.jsonl.gz:887020",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611241"
} |
e8eae03ecf0e9ba26c9555f1f1bae08b2598e53e | Stackoverflow Stackexchange
Q: R keras package Error: Python module tensorflow.contrib.keras.python.keras was not found I have keras installed with devtools from GitHub in R and TensorFlow installed in Python.
However when I run an example Keras command like:
model <- keras_model_sequential()
I get the following:
Error: Python module tensorflow.contrib.keras.python.keras was not
found.
Detected Python configuration:
python: C:\Python35\python.exe
libpython: C:/Python35/python35.dll
pythonhome: C:\Python35
version: 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)]
Architecture: 64bit
numpy: C:\Python35\lib\site-packages\numpy
numpy_version: 1.13.0
tensorflow: C:\Python35\lib\site-packages\tensorflow
python versions found:
C:\Python35\python.exe
C:\Python27\\python.exe
C:\Python35\\python.exe
C:\Python36\\python.exe
A: First, you can install the R tensorflow package from here.
Then, you can just install the latest tensorflow version, using install_tensorflow function, as shown in this answer.
After that, just install and update R-keras library. It should use the last version of TensorFlow now, and this could potentially solve your problem. Also, make sure you install the tensorflow version that matches your Python version.
| Q: R keras package Error: Python module tensorflow.contrib.keras.python.keras was not found I have keras installed with devtools from GitHub in R and TensorFlow installed in Python.
However when I run an example Keras command like:
model <- keras_model_sequential()
I get the following:
Error: Python module tensorflow.contrib.keras.python.keras was not
found.
Detected Python configuration:
python: C:\Python35\python.exe
libpython: C:/Python35/python35.dll
pythonhome: C:\Python35
version: 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)]
Architecture: 64bit
numpy: C:\Python35\lib\site-packages\numpy
numpy_version: 1.13.0
tensorflow: C:\Python35\lib\site-packages\tensorflow
python versions found:
C:\Python35\python.exe
C:\Python27\\python.exe
C:\Python35\\python.exe
C:\Python36\\python.exe
A: First, you can install the R tensorflow package from here.
Then, you can just install the latest tensorflow version, using install_tensorflow function, as shown in this answer.
After that, just install and update R-keras library. It should use the last version of TensorFlow now, and this could potentially solve your problem. Also, make sure you install the tensorflow version that matches your Python version.
A: I faced a similar problem and below steps helped to overcome the issue.
*
*Install TensorFlow and Keras from rstudio github.
*
*devtools::install_github("rstudio/tensorflow")
*devtools::install_github("rstudio/keras")
*Execute the below
*
*tensorflow::install_tensorflow()
*tensorflow::tf_config()
A: I had a similar problem with a conda installation on a Mac (so using install_keras(method = 'conda', conda = '/opt/anaconda3/bin/conda'), which created a virtual environment called r-reticulate under ~/.conda/envs. Then when I tried to instantiate a model just like you do, I was getting an error 'Error: Python module tensorflow.python.keras was not found.'
For me what resolved it is after loading library(keras) execute use_condaenv("r-reticulate", required = TRUE) and then everything worked.
A: I had a similar problem. Restart rstudio, load keras and tensorflow libraries, and type use_condaenv("r-tensorflow"). That fixed it for me.
A: I faced a similar problem.
The issue was solved by updating the tensorflow module from 1.0.1 to 1.2.1
A: In Windows, I tried all above given solution but didn't work.
It worked for me when I created env using, both in spyder and R
conda create -n keras-tf tensorflow keras
In windows
library(keras)
library(tensorflow)
use_condaenv("keras-tf", required = T)
In Python
import tensorflow as tf
A: Some times your env and system don't have any problems, it is just the way how you configure Tensorflow and Keras that cause these errors to be raised.
below is how I fixed mine:
{install.packages("tensorflow")
install.packages("keras")
tensorflow::tf_config()
mytf <- tf$compat$v1}
the configuration results shows the following output:
2021-12-09 11:43:39.007746: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-12-09 11:43:39.007931: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
TensorFlow v2.6.2 ()
Python v3.7 (C:/Users/myName/AppData/Local/r-miniconda/envs/r-reticulate/python.exe)
then type:
install_keras()
after that you can test:
mnist <- keras::dataset_mnist() ; mnist
this will give you an output like:
$train
$train$x
, , 1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
....
$train$y
[1] 5 0 4 1 9 2 1 3 1 4 3 5 3 6 1 7 2 8 6 9 4 0 9 1 1 2 4 3 2 7 3 8 6 9 0 5 6 0 7 6 1 8 7 9 3
[46] 9 8 5 9 3 3 0 7 4 9 8 0 9 4 1 4 4 6 0 4 5 6 1 0 0 1 7 1 6 3 0 2 1 1 7 9 0 2 6 7 8 3 9 0 4
[91] 6 7 4 6 8 0 7 8 3 1 5 7 1 7 1 1 6 3 0 2 9 3 1 1 0 4 9 2 0 0 2 0 2 7 1 8 6 4 1 6 3 4 5 9 1
[136] 3 3 8 5 4 7 7 4 2 8 5 8 6 7 3 4 6 1 9 9 6 0 3 7 2 8 2 9 4 4 6 4 9 7 0 9 2 9 5 1 5 9 1 2 3
[181] 2 3 5 9 1 7 6 2 8 2 2 5 0 7 4 9 7 8 3 2 1 1 8 3 6 1 0 3 1 0 0 1 7 2 7 3 0 4 6 5 2 6 4 7 1
[226] 8 9 9 3 0 7 1 0 2 0 3 5 4 6 5 8 6 3 7 5 8 0 9 1 0 3 1 2 2 3 3 6 4 7 5 0 6 2 7 9 8 5 9 2 1
[271] 1 4 4 5 6 4 1 2 5 3 9 3 9 0 5 9 6 5 7 4 1 3 4 0 4 8 0 4 3 6 8 7 6 0 9 7 5 7 2 1 1 6 8 9 4
[316] 1 5 2 2 9 0 3 9 6 7 2 0 3 5 4 3 6 5 8 9 5 4 7 4 2 7 3 4 8 9 1 9 2 8 7 9 1 8 7 4 1 3 1 1 0
[361] 2 3 9 4 9 2 1 6 8 4 7 7 4 4 9 2 5 7 2 4 4 2 1 9 7 2 8 7 6 9 2 2 3 8 1 6 5 1 1 0 2 6 4 5 8
[406] 3 1 5 1 9 2 7 4 4 4 8 1 5 8 9 5 6 7 9 9 3 7 0 9 0 6 6 2 3 9 0 7 5 4 8 0 9 4 1 2 8 7 1 2 6
[451] 1 0 3 0 1 1 8 2 0 3 9 4 0 5 0 6 1 7 7 8 1 9 2 0 5 1 2 2 7 3 5 4 9 7 1 8 3 9 6 0 3 1 1 2 6
[496] 3 5 7 6 8 3 9 5 8 5 7 6 1 1 3 1 7 5 5 5 2 5 8 7 0 9 7 7 5 0 9 0 0 8 9 2 4 8 1 6 1 6 5 1 8
[541] 3 4 0 5 5 8 3 6 2 3 9 2 1 1 5 2 1 3 2 8 7 3 7 2 4 6 9 7 2 4 2 8 1 1 3 8 4 0 6 5 9 3 0 9 2
[586] 4 7 1 2 9 4 2 6 1 8 9 0 6 6 7 9 9 8 0 1 4 4 6 7 1 5 7 0 3 5 8 4 7 1 2 5 9 5 6 7 5 9 8 8 3
[631] 6 9 7 0 7 5 7 1 1 0 7 9 2 3 7 3 2 4 1 6 2 7 5 5 7 4 0 2 6 3 6 4 0 4 2 6 0 0 0 0 3 1 6 2 2
[676] 3 1 4 1 5 4 6 4 7 2 8 7 9 2 0 5 1 4 2 8 3 2 4 1 5 4 6 0 7 9 8 4 9 8 0 1 1 0 2 2 3 2 4 4 5
[721] 8 6 5 7 7 8 8 9 7 4 7 3 2 0 8 6 8 6 1 6 8 9 4 0 9 0 4 1 5 4 7 5 3 7 4 9 8 5 8 6 3 8 6 9 9
....
[ reached getOption("max.print") -- omitted 9000 entries ]
| stackoverflow | {
"language": "en",
"length": 1396,
"provenance": "stackexchange_0000F.jsonl.gz:887052",
"question_score": "20",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611325"
} |
02baf8d220681c06e1cac483135cfb04451a2a93 | Stackoverflow Stackexchange
Q: Calculating Percentile in Python Pandas Dataframe I'm trying to calculate the percentile of each number within a dataframe and add it to a new column called 'percentile'.
This is my attempt:
import pandas as pd
from scipy import stats
data = {'symbol':'FB','date':['2012-05-18','2012-05-21','2012-05-22','2012-05-23'],'close':[38.23,34.03,31.00,32.00]}
df = pd.DataFrame(data)
close = df['close']
for i in df:
df['percentile'] = stats.percentileofscore(close,df['close'])
The column is not being filled and results in 'NaN'. This should be fairly easy, but I'm not sure where I'm going wrong.
Thanks in advance for the help.
A: df.close.apply(lambda x: stats.percentileofscore(df.close.sort_values(),x))
or
df.close.rank(pct=True)
Output:
0 1.00
1 0.75
2 0.25
3 0.50
Name: close, dtype: float64
| Q: Calculating Percentile in Python Pandas Dataframe I'm trying to calculate the percentile of each number within a dataframe and add it to a new column called 'percentile'.
This is my attempt:
import pandas as pd
from scipy import stats
data = {'symbol':'FB','date':['2012-05-18','2012-05-21','2012-05-22','2012-05-23'],'close':[38.23,34.03,31.00,32.00]}
df = pd.DataFrame(data)
close = df['close']
for i in df:
df['percentile'] = stats.percentileofscore(close,df['close'])
The column is not being filled and results in 'NaN'. This should be fairly easy, but I'm not sure where I'm going wrong.
Thanks in advance for the help.
A: df.close.apply(lambda x: stats.percentileofscore(df.close.sort_values(),x))
or
df.close.rank(pct=True)
Output:
0 1.00
1 0.75
2 0.25
3 0.50
Name: close, dtype: float64
| stackoverflow | {
"language": "en",
"length": 104,
"provenance": "stackexchange_0000F.jsonl.gz:887060",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611347"
} |
3d78bc8c1486aa3f28a58c6981d72f0b0c7c64df | Stackoverflow Stackexchange
Q: Cannot create a directed graph using from_pandas_dataframe from networkx I'm learning networkx library and use twitter retweet directed graph data.
I first read the datasets into pandas df (columns are 'from','to','weight') and wanted to put a first 300 rows(retweet) into a graph using below code:
tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
target='to',edge_attr=True)
I thought that it correctly created a graph but when I run tw_small.is_directed(), it says False(undirected graph) and I drew a graph using nx.draw() but it doesn't show the direction either.
Could someone help me find a correct way to make a directed graph?
Thanks.
A: Add the optional keyword argument create_using=nx.DiGraph(),
tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
target='to',edge_attr=True,
create_using=nx.DiGraph())
| Q: Cannot create a directed graph using from_pandas_dataframe from networkx I'm learning networkx library and use twitter retweet directed graph data.
I first read the datasets into pandas df (columns are 'from','to','weight') and wanted to put a first 300 rows(retweet) into a graph using below code:
tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
target='to',edge_attr=True)
I thought that it correctly created a graph but when I run tw_small.is_directed(), it says False(undirected graph) and I drew a graph using nx.draw() but it doesn't show the direction either.
Could someone help me find a correct way to make a directed graph?
Thanks.
A: Add the optional keyword argument create_using=nx.DiGraph(),
tw_small = nx.from_pandas_dataframe(edges_df[:300],source='from',
target='to',edge_attr=True,
create_using=nx.DiGraph())
A: Instead of a dataframe you can write edgelist, it works for me, it shows me an error when I used from_pandas_dataframe : "AttributeError: module 'networkx' has no attribute 'from_pandas_dataframe"
Solution :
Graph = nx.from_pandas_edgelist(df,source='source',target='destination', edge_attr=None, create_using=nx.DiGraph())
You can test if your graph is directed or not using: nx.is_directed(Graph). You will get True.
| stackoverflow | {
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:887088",
"question_score": "21",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611449"
} |
8dd915cbedbf8bcf8bccd0c1d52364d7274742c8 | Stackoverflow Stackexchange
Q: aws-sdk: NoSuchKey: The specified key does not exist? In my nodejs project, I am using aws-sdk to download all the images from my s3 bucket, But I got this error- NoSuchKey: The specified key does not exist. But keys are correct and I can upload images with these keys.
My code is:
var AWS = require('aws-sdk');
s3 = new AWS.S3();
var params = {
Bucket: config.get("aws.s3.bucket"),
Key: config.get("aws.credentials.secretAccessKey")
};
s3.getObject(params, function (err, data) {
console.log("data");
if (err) console.log(err, err.stack); // an error occurred
else console.log(data);
});
}
Can anyone please tell me where I am doing wrong?
A: There are problems related to how to use aws-sdk and it should be as following example:
var aws = require('aws-sdk');
aws.config.update({
accessKeyId: {{AWS_ACCESS_KEY}},
secretAccessKey: {{AWS_SECRET_KEY}}
});
var s3 = new aws.S3();
var s3Params = {
Bucket: {{bucket name}},
Key: {{path to dedicated S3 Object (folder name + file/object
name)}}
};
s3.getObject(s3Params, function (err, data) {
//Continue handling the returned results.
});
replace the strings inside {{}} with correct data and it should work well.
| Q: aws-sdk: NoSuchKey: The specified key does not exist? In my nodejs project, I am using aws-sdk to download all the images from my s3 bucket, But I got this error- NoSuchKey: The specified key does not exist. But keys are correct and I can upload images with these keys.
My code is:
var AWS = require('aws-sdk');
s3 = new AWS.S3();
var params = {
Bucket: config.get("aws.s3.bucket"),
Key: config.get("aws.credentials.secretAccessKey")
};
s3.getObject(params, function (err, data) {
console.log("data");
if (err) console.log(err, err.stack); // an error occurred
else console.log(data);
});
}
Can anyone please tell me where I am doing wrong?
A: There are problems related to how to use aws-sdk and it should be as following example:
var aws = require('aws-sdk');
aws.config.update({
accessKeyId: {{AWS_ACCESS_KEY}},
secretAccessKey: {{AWS_SECRET_KEY}}
});
var s3 = new aws.S3();
var s3Params = {
Bucket: {{bucket name}},
Key: {{path to dedicated S3 Object (folder name + file/object
name)}}
};
s3.getObject(s3Params, function (err, data) {
//Continue handling the returned results.
});
replace the strings inside {{}} with correct data and it should work well.
A: This is because that img url doesnot exist with same user.Means that u put a img alone.jpeg in your postman when you upload image in aws.But in getobject you are posting image.jpg with same user.conclusion is that image should be same which you are uploading and then getting with same user. [when you are getting a getObject,you post this image with same user]
when you are uploading image to aws
[1]: https://i.stack.imgur.com/WLh5v.png
but when you use getObject with another image with same user(which user's token you are using ),it will give the same error.
When you user image.jpg instead [1]: https://i.stack.imgur.com/WLh5v.png
So use same image key.
use image key which is coming from aws's response instead of url.
| stackoverflow | {
"language": "en",
"length": 292,
"provenance": "stackexchange_0000F.jsonl.gz:887095",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611467"
} |
3d076e1b1dfbdcd2b270ea66c38fb4d0693d052a | Stackoverflow Stackexchange
Q: How JavaScript assigns `name` attribute of function? In JavaScript, when I define function like this
function aaa(){}
I can later access the name by name attribute:
aaa.name
which will return
"aaa"
However, when I define function via var, it technically should be anonymous function without name attribute:
var aaa=function(){}
But instead it assumes that aaa is function name and assigns it to name attribute:
aaa.name
will also return
"aaa"
How JavaScript decides what should be the name, especially considering the fact that assignments could use more complicated scenarios:
var aaa=bbb=function(){}
or
var aaa=arr[0]=function(){}
?
A: Javascript declares the name variable of the function by taking the left-hand side argument that is equal to the function, which is 'aaa' in all basic cases. In the first complex definition, you declared state above Javascript will take the variable ab and assign it to a function making the name 'ab'. In the final example, you provided it sets the function equal to a pointer in memory, which is not a defined variable, this sets the name property to an empty string because arr[0] is not a variable name but a pointer to memory.
Here is a JSFiddle displaying this.
| Q: How JavaScript assigns `name` attribute of function? In JavaScript, when I define function like this
function aaa(){}
I can later access the name by name attribute:
aaa.name
which will return
"aaa"
However, when I define function via var, it technically should be anonymous function without name attribute:
var aaa=function(){}
But instead it assumes that aaa is function name and assigns it to name attribute:
aaa.name
will also return
"aaa"
How JavaScript decides what should be the name, especially considering the fact that assignments could use more complicated scenarios:
var aaa=bbb=function(){}
or
var aaa=arr[0]=function(){}
?
A: Javascript declares the name variable of the function by taking the left-hand side argument that is equal to the function, which is 'aaa' in all basic cases. In the first complex definition, you declared state above Javascript will take the variable ab and assign it to a function making the name 'ab'. In the final example, you provided it sets the function equal to a pointer in memory, which is not a defined variable, this sets the name property to an empty string because arr[0] is not a variable name but a pointer to memory.
Here is a JSFiddle displaying this.
A: Something like this:
Inferred function names
Variables and methods can infer the name of an anonymous function from
its syntactic position (new in ECMAScript 2015).
var f = function() {};
var object = {
someMethod: function() {}
};
console.log(f.name); // "f"
console.log(object.someMethod.name); // "someMethod"
Read the entire blog. It will clear all your queries.
| stackoverflow | {
"language": "en",
"length": 252,
"provenance": "stackexchange_0000F.jsonl.gz:887108",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611510"
} |
fe14e7b292b73e4cbc8f974d3715622bed4dbd97 | Stackoverflow Stackexchange
Q: How to fix Cannot find module 'typescript' in Angular 4? I generated Angular 4 app 3 weeks ago using the @angular/cli. After 2 weeks, I tried to run it with the command line ng serve but I am prompted an error below:
Cannot find module 'typescript'
Error: Cannot find module 'typescript'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\mypc\Documents\Angular Projects\my-angular-app\node_modules\@angular\cli\models\config\config.js:5:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Do you have any idea how to fix this? Thanks.
A: I had a similar problem when I rearranged the folder structure of a project. I tried all the hints given in this thread but none of them worked.
After checking further I discovered that I forgot to copy an important hidden file over to the new directory. That was
.angular-cli.json
from the root directory of the @angular/cli project. After I copied that file over all was running as expected.
| Q: How to fix Cannot find module 'typescript' in Angular 4? I generated Angular 4 app 3 weeks ago using the @angular/cli. After 2 weeks, I tried to run it with the command line ng serve but I am prompted an error below:
Cannot find module 'typescript'
Error: Cannot find module 'typescript'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\mypc\Documents\Angular Projects\my-angular-app\node_modules\@angular\cli\models\config\config.js:5:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Do you have any idea how to fix this? Thanks.
A: I had a similar problem when I rearranged the folder structure of a project. I tried all the hints given in this thread but none of them worked.
After checking further I discovered that I forgot to copy an important hidden file over to the new directory. That was
.angular-cli.json
from the root directory of the @angular/cli project. After I copied that file over all was running as expected.
A: This should do the trick,
npm install -g typescript
A: I was able to solve this problem by removing node_modules then running npm install
A: Run: npm link typescript if you installed globally
But if you have not installed typescript try this command: npm install typescript
A: If you use yarn instead of npm, you can install typescript package for that workspace by running:
yarn add typescript
or you can install it globally by running:
sudo yarn global add typescript
to be available for any project.
A: For me just running the below command is not enough (though a valid first step):
npm install -g typescript
The following command is what you need (I think deleting node_modules works too, but the below command is quicker)
npm link typescript
A: If you don't have particular needs, I suggest to install Typescript locally.
NPM Installation Method
npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation
Yarn Installation Method
yarn global add typescript # Global installation
yarn add --dev typescript # Local installation
A: I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules.
A: I had a very similar problem after moving a working project to a new subdirectory on my file system. It turned out I had failed to move the file named .angular-cli.json to the subfolder along with everything else. After noticing that and moving the file into the subdirectory, all was back to normal.
A: Run 'npm install' it will install all necessary pkg .
A: If you have cloned your project from git or somewhere then first, you should type npm install.
A: The best way is to do: npm install or npm i
this way all dependencies will be added.
A: I had this same problem using npm run start-dev as configured my package.json ("start-dev": "nodemon src/index.ts"). When i used nodemon src/index.ts in cmd work just fine, but to use npm run start-dev i had to use npm link typescript, it solve the problem.
| stackoverflow | {
"language": "en",
"length": 516,
"provenance": "stackexchange_0000F.jsonl.gz:887118",
"question_score": "80",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611526"
} |
5bc180baa820ea21adb214ec04fb49b9790cf8d0 | Stackoverflow Stackexchange
Q: Turn a string back into a datetime timedelta A column in my pandas data frame represents a time delta that I calculated with datetime then exported into a csv and read back into a pandas data frame. Now the column's dtype is object whereas I want it to be a timedelta so I can perform a groupby function on the dataframe. Below is what the strings look like. Thanks!
0 days 00:00:57.416000
0 days 00:00:12.036000
0 days 16:46:23.127000
49 days 00:09:30.813000
50 days 00:39:31.306000
55 days 12:39:32.269000
-1 days +22:03:05.256000
Update, my best attempt at writing a for-loop to iterate over a specific column in my pandas dataframe:
def delta(i):
days, timestamp = i.split(" days ")
timestamp = timestamp[:len(timestamp)-7]
t = datetime.datetime.strptime(timestamp,"%H:%M:%S") +
datetime.timedelta(days=int(days))
delta = datetime.timedelta(days=t.day, hours=t.hour,
minutes=t.minute, seconds=t.second)
delta.total_seconds()
data['diff'].map(delta)
A: Use pd.to_timedelta
pd.to_timedelta(df.iloc[:, 0])
0 0 days 00:00:57.416000
1 0 days 00:00:12.036000
2 0 days 16:46:23.127000
3 49 days 00:09:30.813000
4 50 days 00:39:31.306000
5 55 days 12:39:32.269000
6 -1 days +22:03:05.256000
Name: 0, dtype: timedelta64[ns]
| Q: Turn a string back into a datetime timedelta A column in my pandas data frame represents a time delta that I calculated with datetime then exported into a csv and read back into a pandas data frame. Now the column's dtype is object whereas I want it to be a timedelta so I can perform a groupby function on the dataframe. Below is what the strings look like. Thanks!
0 days 00:00:57.416000
0 days 00:00:12.036000
0 days 16:46:23.127000
49 days 00:09:30.813000
50 days 00:39:31.306000
55 days 12:39:32.269000
-1 days +22:03:05.256000
Update, my best attempt at writing a for-loop to iterate over a specific column in my pandas dataframe:
def delta(i):
days, timestamp = i.split(" days ")
timestamp = timestamp[:len(timestamp)-7]
t = datetime.datetime.strptime(timestamp,"%H:%M:%S") +
datetime.timedelta(days=int(days))
delta = datetime.timedelta(days=t.day, hours=t.hour,
minutes=t.minute, seconds=t.second)
delta.total_seconds()
data['diff'].map(delta)
A: Use pd.to_timedelta
pd.to_timedelta(df.iloc[:, 0])
0 0 days 00:00:57.416000
1 0 days 00:00:12.036000
2 0 days 16:46:23.127000
3 49 days 00:09:30.813000
4 50 days 00:39:31.306000
5 55 days 12:39:32.269000
6 -1 days +22:03:05.256000
Name: 0, dtype: timedelta64[ns]
A: import datetime
#Parse your string
days, timestamp = "55 days 12:39:32.269000".split(" days ")
timestamp = timestamp[:len(timestamp)-7]
#Generate datetime object
t = datetime.datetime.strptime(timestamp,"%H:%M:%S") + datetime.timedelta(days=int(days))
#Generate a timedelta
delta = datetime.timedelta(days=t.day, hours=t.hour, minutes=t.minute, seconds=t.second)
#Represent in Seconds
delta.total_seconds()
A: You could do something like this, looping through each value from the CSV in place of stringdate:
stringdate = "2 days 00:00:57.416000"
days_v_hms = string1.split('days')
hms = days_v_hms[1].split(':')
dt = datetime.timedelta(days=int(days_v_hms[0]), hours=int(hms[0]), minutes=int(hms[1]), seconds=float(hms[2]))
Cheers!
| stackoverflow | {
"language": "en",
"length": 244,
"provenance": "stackexchange_0000F.jsonl.gz:887150",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611642"
} |
09e590846727234a7f5ef305668cc5d9724d9fd6 | Stackoverflow Stackexchange
Q: Flow Promise This type is incompatible with undefined undefined Get warning
on line:
Use Flow.js v.0.48.0.
Code sample:
...
import { Font, AppLoading } from 'expo';
...
export default class App extends Component {
async componentDidMount() {
await Font.loadAsync(fontsStore);
...
}
...
}
A: Found hack solution:
...
componentDidMount() {
this.loadFonts();
}
async loadFonts () {
await Font.loadAsync(fontsStore);
this.setState({ fontLoaded: true });
}
...
| Q: Flow Promise This type is incompatible with undefined undefined Get warning
on line:
Use Flow.js v.0.48.0.
Code sample:
...
import { Font, AppLoading } from 'expo';
...
export default class App extends Component {
async componentDidMount() {
await Font.loadAsync(fontsStore);
...
}
...
}
A: Found hack solution:
...
componentDidMount() {
this.loadFonts();
}
async loadFonts () {
await Font.loadAsync(fontsStore);
this.setState({ fontLoaded: true });
}
...
| stackoverflow | {
"language": "en",
"length": 65,
"provenance": "stackexchange_0000F.jsonl.gz:887180",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611750"
} |
4d1030bff8476de3aa99f235010be507a5a2205c | Stackoverflow Stackexchange
Q: why this error appears "all scheduled cores encountered errors in user code" is it related to core processor of servers? We are analyzing sequencing data while filtering and trimming fastq files encountered following error. Is the following error due to unavailability of core for processing commands?
Error in colnames<-(*tmp*, value = c("cs103_R1_dada.fastq", "cs110_R1_dada.fastq", : attempt to set 'colnames' on an object with less than two dimensions In addition: Warning message: In mclapply(seq_len(n), do_one, mc.preschedule = mc.preschedule, : all scheduled cores encountered errors in user code >
A: As pengchy suggested there may be something wrong with function.
try the same call by using lapply and error message will be more informative.
| Q: why this error appears "all scheduled cores encountered errors in user code" is it related to core processor of servers? We are analyzing sequencing data while filtering and trimming fastq files encountered following error. Is the following error due to unavailability of core for processing commands?
Error in colnames<-(*tmp*, value = c("cs103_R1_dada.fastq", "cs110_R1_dada.fastq", : attempt to set 'colnames' on an object with less than two dimensions In addition: Warning message: In mclapply(seq_len(n), do_one, mc.preschedule = mc.preschedule, : all scheduled cores encountered errors in user code >
A: As pengchy suggested there may be something wrong with function.
try the same call by using lapply and error message will be more informative.
A: To clarify on what @f2003596 and @HelloWorld said: This just means that a crash occurred within the function you called, i.e. while it was executing that function. But this does not necessarily mean that your function is incorrect. For example, you get the same error when a variable has not been found.
A: That would mean your R function has a crash.
A: Note: If you include an unexpected argument in mclapply you also can get this error message. I put mC.cores instead of mc.cores by mistake and I got it.
| stackoverflow | {
"language": "en",
"length": 204,
"provenance": "stackexchange_0000F.jsonl.gz:887192",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611788"
} |
6fedbfa736e8b764ec6d0cee58f4bfcd3be2abaa | Stackoverflow Stackexchange
Q: How I can extract data from R plot? As it’s writing on title, I would like to extract a specific data from R plot.
On my program, I use the qcc function with control chart R (It’s Quality Control).
#Background color
qcc.options(bg.margin = "white", bg.figure = "gray95")
#R graph ranges of a continuous process variable
qcc(data = Test,
type = "R",
sizes = 5,
title = "Sample R Chart Title",
digits = 2,
plot = TRUE)
And I obtained this R plot:
I would like to extract the point which is out of control and the data below the plot.
Can you help me?
Thank you for your answers.
For information :
table:
Day |Temperature
-------|---------------
1 |85
2 |85
3 |88
4 |83
5 |89
6 |90
7 |81
8 |82
9 |65
10 |300
| Q: How I can extract data from R plot? As it’s writing on title, I would like to extract a specific data from R plot.
On my program, I use the qcc function with control chart R (It’s Quality Control).
#Background color
qcc.options(bg.margin = "white", bg.figure = "gray95")
#R graph ranges of a continuous process variable
qcc(data = Test,
type = "R",
sizes = 5,
title = "Sample R Chart Title",
digits = 2,
plot = TRUE)
And I obtained this R plot:
I would like to extract the point which is out of control and the data below the plot.
Can you help me?
Thank you for your answers.
For information :
table:
Day |Temperature
-------|---------------
1 |85
2 |85
3 |88
4 |83
5 |89
6 |90
7 |81
8 |82
9 |65
10 |300
| stackoverflow | {
"language": "en",
"length": 137,
"provenance": "stackexchange_0000F.jsonl.gz:887202",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611823"
} |
6e4d60d91addcedd4eb6724c3c7a01cbf4299b2b | Stackoverflow Stackexchange
Q: itertools 'previous' (opposite of next) python I'm currently using something like
>> import itertools
>> ABC = [a, b, c]
>> abc = itertools.cycle( ABC )
>> next( abc )
a
>> next( abc )
b
>> next( abc )
c
I want my next call to be
>> previous( abc )
b
Is there a method in itertools that can accomplish this?
A: You can use deque from collections module and rotate method,
for example:
from collections import deque
alist=['a','b','c']
d=deque(alist)
current = d[0]
print(current) # 'a'
d.rotate(1) # rotate one step to the right
current = d[0]
print(current) # 'c'
d.rotate(-1) # rotate one step to the left
current = d[0]
print(current) # 'a' again
| Q: itertools 'previous' (opposite of next) python I'm currently using something like
>> import itertools
>> ABC = [a, b, c]
>> abc = itertools.cycle( ABC )
>> next( abc )
a
>> next( abc )
b
>> next( abc )
c
I want my next call to be
>> previous( abc )
b
Is there a method in itertools that can accomplish this?
A: You can use deque from collections module and rotate method,
for example:
from collections import deque
alist=['a','b','c']
d=deque(alist)
current = d[0]
print(current) # 'a'
d.rotate(1) # rotate one step to the right
current = d[0]
print(current) # 'c'
d.rotate(-1) # rotate one step to the left
current = d[0]
print(current) # 'a' again
A: You can write your own class to emulate an iterable object with next and previous. This is the simplest implementation:
class cycle:
def __init__(self, c):
self._c = c
self._index = -1
def __next__(self):
self._index += 1
if self._index>=len(self._c):
self._index = 0
return self._c[self._index]
def previous(self):
self._index -= 1
if self._index < 0:
self._index = len(self._c)-1
return self._c[self._index]
ABC = ['a', 'b', 'c']
abc = cycle(ABC)
print(next(abc))
print(next(abc))
print(next(abc))
print(abc.previous())
A: No, there isn't.
Because of the way Python's iteration protocol works, it would be impossible to implement previous without keeping the entire history of the generated values. Python doesn't do this, and given the memory requirements you probably wouldn't want it to.
A: Although deque is the way to go, here's another example:
Code
import itertools as it
class Cycle:
"""Wrap cycle."""
def __init__(self, seq):
self._container = it.cycle(seq)
self._here = None
self.prev = None
def __iter__(self):
return self._container
def __next__(self):
self.prev = self._here
self._here = next(self._container)
return self._here
Demo
c = Cycle("abc")
next(c)
# 'a'
next(c)
# 'b'
c.prev
# 'a'
| stackoverflow | {
"language": "en",
"length": 290,
"provenance": "stackexchange_0000F.jsonl.gz:887229",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44611890"
} |
b8282c391f4a825d952e216066b1a3e9ac0bfdd1 | Stackoverflow Stackexchange
Q: Swagger Codegen use existing class How can I get the swagger codegen to use an existing class instead of creating a new class? Is this possible? For instance I want to use org.springframework.data.domain.Page instead of swagger creating another page class.
A: It's not always possible to use --import-mappings if you have long list of mappings.
(At least in case of Windows, which has size-limit for string in command prompt.)
That is why better way do it: use mapping with swagger configuration file.
(And this option is not fully documented.)
Like that:
java -jar swagger-codegen-cli-2.3.1.jar generate -i myspec.yaml -l java -c myconfig.json
myconfig.json:
{
"hideGenerationTimestamp": true,
"dateLibrary": "java8",
"useRuntimeException": true,
"modelPackage": "org.my.package.model",
"apiPackage": "org.my.package.api",
"importMappings": {
"Page": "org.springframework.data.domain.Page",
"MySuperType": "org.my.SuperType"
}
}
| Q: Swagger Codegen use existing class How can I get the swagger codegen to use an existing class instead of creating a new class? Is this possible? For instance I want to use org.springframework.data.domain.Page instead of swagger creating another page class.
A: It's not always possible to use --import-mappings if you have long list of mappings.
(At least in case of Windows, which has size-limit for string in command prompt.)
That is why better way do it: use mapping with swagger configuration file.
(And this option is not fully documented.)
Like that:
java -jar swagger-codegen-cli-2.3.1.jar generate -i myspec.yaml -l java -c myconfig.json
myconfig.json:
{
"hideGenerationTimestamp": true,
"dateLibrary": "java8",
"useRuntimeException": true,
"modelPackage": "org.my.package.model",
"apiPackage": "org.my.package.api",
"importMappings": {
"Page": "org.springframework.data.domain.Page",
"MySuperType": "org.my.SuperType"
}
}
A: You could use --import-mappings, as it is explained here:
Sometimes you don't want a model generated. In this case, you can
simply specify an import mapping to tell the codegen what not to
create. When doing this, every location that references a specific
model will refer back to your classes.
You call this on swagger-codegen-cli generate, with the example you included it would be
--import-mappings Page=org.springframework.data.domain.Page
Although importMappings hasn't been included in the general configuration parameters here if you look at the code here you can see it's a List<String>.
I haven't used it with the maven plugin but looking at the doc and the code I'm guessing this should work:
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.2.2-SNAPSHOT</version>
<executions>
<execution>
...
<configuration>
...
<importMappings>
<importMapping>Page=org.springframework.data.domain.Page</importMapping>
</importMappings>
</configuration>
</execution>
</executions>
</plugin>
But this was recently changed, so it might be different if you're using an older version of the plugin. Before that changed it seems to be like this:
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.2.2-SNAPSHOT</version>
<executions>
<execution>
...
<configuration>
...
<configOptions>
<import-mappings>Page=org.springframework.data.domain.Page;Some=org.example.Some</import-mappings>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
According to the comment in that commit the old version should be supported too, but I haven't tried any of this so let me know if it works.
A: None of the answers mentioned here talked about what to add to the swagger yaml file,
in case someone is interested this is something that worked for me:
DisplayProperty:
type: object
properties:
name:
type: string
displayName:
$ref: '#/components/schemas/Text'
isRequired:
type: boolean
example: false
Text:
type: object
and then have this in the pom
<importMappings>
<importMapping>Text=com.--.--.--.--.Text</importMapping>
| stackoverflow | {
"language": "en",
"length": 378,
"provenance": "stackexchange_0000F.jsonl.gz:887282",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612080"
} |
7ace6b1e18581fd08645d4ab17cd223ee6cc0653 | Stackoverflow Stackexchange
Q: TypeScripts transpiles files which are non-executable It appears as though TypeScript is transpiling target files that are not executable.
I have to run chmod u+x <file> after transpilation to get the files to become executable.
This is the case, even if they have a hashbang:
#!/usr/bin/env node
How can I tell TypeScript / tsc to create files which are executable?
A: Changing file's permissions isn't typescript responsibility.
Solution 1.
Use a separate step in the build process in your package.json. For example:
{
"name": "temp",
"version": "1.0.0",
"scripts": {
"build": "tsc && chmod +x build/index.js"
},
"dependencies": {
"typescript": "^2.3.4"
}
}
Solution 2.
Write TypeScript Language Service Plugin. I think, in your case this is overengineering.
| Q: TypeScripts transpiles files which are non-executable It appears as though TypeScript is transpiling target files that are not executable.
I have to run chmod u+x <file> after transpilation to get the files to become executable.
This is the case, even if they have a hashbang:
#!/usr/bin/env node
How can I tell TypeScript / tsc to create files which are executable?
A: Changing file's permissions isn't typescript responsibility.
Solution 1.
Use a separate step in the build process in your package.json. For example:
{
"name": "temp",
"version": "1.0.0",
"scripts": {
"build": "tsc && chmod +x build/index.js"
},
"dependencies": {
"typescript": "^2.3.4"
}
}
Solution 2.
Write TypeScript Language Service Plugin. I think, in your case this is overengineering.
| stackoverflow | {
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:887293",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612118"
} |
bd86ee0fe0f92d487eb4536bb8758164ce18cd49 | Stackoverflow Stackexchange
Q: What are the differences between different gaussian functions in Matlab?
*
*y = gauss(x,s,m)
*Y = normpdf(X,mu,sigma)
*R = normrnd(mu,sigma)
What are the basic differences between these three functions?
A: Y = normpdf(X,mu,sigma) is the probability density function for a normal distribution with mean mu and stdev sigma. Use this if you want to know the relative likelihood at a point X.
R = normrnd(mu,sigma) takes random samples from the same distribution as above. So use this function if you want to simulate something based on the normal distribution.
y = gauss(x,s,m) at first glance looks like the exact same function as normpdf(). But there is a slight difference: Its calculation is
Y = EXP(-(X-M).^2./S.^2)./(sqrt(2*pi).*S)
while normpdf() uses
Y = EXP(-(X-M).^2./(2*S.^2))./(sqrt(2*pi).*S)
This means that the integral of gauss() from -inf to inf is 1/sqrt(2). Therefore it isn't a legit PDF and I have no clue where one could use something like this.
For completeness we also have to mention p = normcdf(x,mu,sigma). This is the normal cumulative distribution function. It gives the probability that a value is between -inf and x.
| Q: What are the differences between different gaussian functions in Matlab?
*
*y = gauss(x,s,m)
*Y = normpdf(X,mu,sigma)
*R = normrnd(mu,sigma)
What are the basic differences between these three functions?
A: Y = normpdf(X,mu,sigma) is the probability density function for a normal distribution with mean mu and stdev sigma. Use this if you want to know the relative likelihood at a point X.
R = normrnd(mu,sigma) takes random samples from the same distribution as above. So use this function if you want to simulate something based on the normal distribution.
y = gauss(x,s,m) at first glance looks like the exact same function as normpdf(). But there is a slight difference: Its calculation is
Y = EXP(-(X-M).^2./S.^2)./(sqrt(2*pi).*S)
while normpdf() uses
Y = EXP(-(X-M).^2./(2*S.^2))./(sqrt(2*pi).*S)
This means that the integral of gauss() from -inf to inf is 1/sqrt(2). Therefore it isn't a legit PDF and I have no clue where one could use something like this.
For completeness we also have to mention p = normcdf(x,mu,sigma). This is the normal cumulative distribution function. It gives the probability that a value is between -inf and x.
A: A few more insights to add to Leander good answer:
When comparing between functions it is good to look at their source or toolbox. gauss is not a function written by Mathworks, so it may be redundant to a function that comes with Matlab.
Also, both normpdf and normrnd are part of the Statistics and Machine Learning Toolbox so users without it cannot use them. However, generating random numbers from a normal distribution is quite a common task, so it should be accessible for users that have only the core Matlab. Hence, there is a redundant function to normrnd which is randn that is part of the core Matlab.
| stackoverflow | {
"language": "en",
"length": 292,
"provenance": "stackexchange_0000F.jsonl.gz:887295",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612125"
} |
4aea8c29192a11868afb6b432a3ed599829b32bf | Stackoverflow Stackexchange
Q: Is li tag in html a inline-level or block-level element? I really wonder is a li tag in HTML a inline-level or block-level element?
I find that a li tag in a p tag can break a new line, so it's kind of like a block, but it's embedded in a ul tag or a ol tag.
From this point of view, it's kind of like a inline-level element? Which is right?
A: An li element has a default display value of:
display:list-item
https://www.w3schools.com/cssref/css_default_values.asp
If it is set to display:block the default bullets will be hidden.
| Q: Is li tag in html a inline-level or block-level element? I really wonder is a li tag in HTML a inline-level or block-level element?
I find that a li tag in a p tag can break a new line, so it's kind of like a block, but it's embedded in a ul tag or a ol tag.
From this point of view, it's kind of like a inline-level element? Which is right?
A: An li element has a default display value of:
display:list-item
https://www.w3schools.com/cssref/css_default_values.asp
If it is set to display:block the default bullets will be hidden.
A: dd, dt and li are listing items in HTML so I think block level elemnt's rule will work same for all dd, dt and li. For more solid proof visit this link
https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
here you will find all block level element listed.
A: NOTE: This is intentionally invalid markup to prove a point about block context.
<!DOCTYPE html>
<html>
<body>
<div style="background-color:black;color:white;padding:20px;">
<p>
<ul>
<li>Hello</li>World
</ul>
Sagar
</p>
</div>
</body>
</html>
The W3School Definition of Inline and Block Element Stands as follows:
*
*An inline element does not start on a new line and only takes up as much width as necessary.
*A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
As you can see in the example above, even though I typed "Hello" inside of the li tag and immediately followed it with "World", the single li tag will not allow the "World" to be on the same line. This demonstrates that the li tag is taking 100% of the available width, proving that li is a block level element.
That is my point of view.
A: This is really moot, since an li element must occur with a block-level ul or ol.
A: Since it places theme selves one after one in a stacked manner, it is a block level element.
I am providing w3c documentation link where you can find more about this.
visit this link.
| stackoverflow | {
"language": "en",
"length": 346,
"provenance": "stackexchange_0000F.jsonl.gz:887297",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612134"
} |
c4e7ebce1e64a8724af4d699412e668cc3d2ef86 | Stackoverflow Stackexchange
Q: How to simulate hung task in linux? I just changed following configurations in /etc/sysctl.conf :
# Reboot 5 seconds after panic
kernel.panic = 5
# Panic if a hung task was found
kernel.hung_task_panic = 1
# Setup timeout for hung task to 300 seconds
kernel.hung_task_timeout_secs = 300
I want to test if kernel.hung_task_panic = 1 and kernel.hung_task_timeout_sec = 300 are working. How do I simulate the hung task in linux to test the two configurations. I am using Ubuntu 16.04 Server
A: You can freeze a filesystem and then trigger a write, like this:
# fsfreeze --freeze /path/to/mountpoint
# echo crap > /path/to/mountpoint/file
since you intend to trigger a crash, I strongly suggest you dd a few MB file to a tmpfs mountpoint, losetup (get /dev/loop0 or so), mkfs and finally mount that.
| Q: How to simulate hung task in linux? I just changed following configurations in /etc/sysctl.conf :
# Reboot 5 seconds after panic
kernel.panic = 5
# Panic if a hung task was found
kernel.hung_task_panic = 1
# Setup timeout for hung task to 300 seconds
kernel.hung_task_timeout_secs = 300
I want to test if kernel.hung_task_panic = 1 and kernel.hung_task_timeout_sec = 300 are working. How do I simulate the hung task in linux to test the two configurations. I am using Ubuntu 16.04 Server
A: You can freeze a filesystem and then trigger a write, like this:
# fsfreeze --freeze /path/to/mountpoint
# echo crap > /path/to/mountpoint/file
since you intend to trigger a crash, I strongly suggest you dd a few MB file to a tmpfs mountpoint, losetup (get /dev/loop0 or so), mkfs and finally mount that.
| stackoverflow | {
"language": "en",
"length": 134,
"provenance": "stackexchange_0000F.jsonl.gz:887298",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612136"
} |
801cef7b0b2aeca026ff78e789a32d4fe2d9a411 | Stackoverflow Stackexchange
Q: Get only visible element using pure javascript I have elements like below
<div class="one">send Message</div>
<div class="one">send Message</div>
<div class="one">send Message</div>
I have a web page where there is send Message buttons like above, in which only one button is visible at a time.Other two buttons are hidden via some javascript codes.So for example if 2nd button is visible , I should be able to get only that element.
So my code will be something like
document.querySelector(".one:visible");
In jquery the code is $(".one:visible"); , which works fine , But I need to know how to do this via pure javascript.
A: I have something shorter:
Array.from(document.querySelectorAll('.one')).filter(s =>
window.getComputedStyle(s).getPropertyValue('display') != 'none'
);
Returns all elements with attribute display block set.
| Q: Get only visible element using pure javascript I have elements like below
<div class="one">send Message</div>
<div class="one">send Message</div>
<div class="one">send Message</div>
I have a web page where there is send Message buttons like above, in which only one button is visible at a time.Other two buttons are hidden via some javascript codes.So for example if 2nd button is visible , I should be able to get only that element.
So my code will be something like
document.querySelector(".one:visible");
In jquery the code is $(".one:visible"); , which works fine , But I need to know how to do this via pure javascript.
A: I have something shorter:
Array.from(document.querySelectorAll('.one')).filter(s =>
window.getComputedStyle(s).getPropertyValue('display') != 'none'
);
Returns all elements with attribute display block set.
A: Use getBoundingClientRect. It will return height and width of zero if the element is not in the DOM, or is not displayed.
Note that this cannot be used to determine if an element is not visible due to visibility: hidden or opacity: 0. AFAIK this behavior is identical to the jQuery :visible "selector". Apparently jQuery uses offsetHeight and offsetWidth of zero to check for non-visibility.
This solution will also not check if the item is not visible due to being off the screen (although you could check that easily enough), or if the element is hidden behind some other element.
See also Detect if an element is visible (without using jquery)
A: var $el = document.querySelectorAll('.one');
var visibleElements;
for (var i = 0; i < $el.length; i++) {
var currentElement = $el[i];
var $style = window.getComputedStyle(currentElement, null);
if (!currentElement) {
return false;
} else if (!$style) {
return false;
} else if ($style.display === 'none') {
return false;
} else {
visibleElements.push(currentElement);
}
}
First we get all the elements using document querySelectorAll. Then, we need to iterate over all the elements. To get the style, use getComputedStyle.
After that :visible check only for display and we do it the same way.
A more comprehensive approach:
function isVisible(el) {
while (el) {
if (el === document) {
return true;
}
var $style = window.getComputedStyle(el, null);
if (!el) {
return false;
} else if (!$style) {
return false;
} else if ($style.display === 'none') {
return false;
} else if ($style.visibility === 'hidden') {
return false;
} else if (+$style.opacity === 0) {
return false;
} else if (($style.display === 'block' || $style.display === 'inline-block') &&
$style.height === '0px' && $style.overflow === 'hidden') {
return false;
} else {
return $style.position === 'fixed' || isVisible(el.parentNode);
}
}
}
This would check for any possible way an element could be visible in the dom to my knowledge minus the z-index cases.
A: If you're using the hidden attribute :
document.querySelector(".one:not([hidden])");
A: Here's something you can use, pure Javascript:
// Get all elements on the page (change this to another DOM element if you want)
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
if (isHidden(all[i]))
// hidden
else
// visible
}
function isHidden(el) {
var style = window.getComputedStyle(el);
return ((style.display === 'none') || (style.visibility === 'hidden'))
}
A: So all jQuery's :visible selector does is check the display property.
If that's all you want, this is all you'd need.
(window.getComputedStyle(el).getPropertyValue('display') !== 'none')
However, this is lacking in many use cases. If you seek a more comprehensive solution, keep reading.
Both Element.getBoundingClientRect() and window.getComputedStyle() are useful for determining if the element is visible and in the viewport.
You can't use getBoundingRect() alone to determine the visibility, and while you could use getComputedStyle() solely, it's not the optimal solution in terms of performance.
Both of these functions used in conjunction with each other is the best option (around 22% faster than getComputedStyle() alone.
function inViewport(els) {
let matches = [],
elCt = els.length;
for (let i=0; i<elCt; ++i) {
let el = els[i],
b = el.getBoundingClientRect(), c;
if (b.width > 0 && b.height > 0 &&
b.left+b.width > 0 && b.right-b.width < window.outerWidth &&
b.top+b.height > 0 && b.bottom-b.width < window.outerHeight &&
(c = window.getComputedStyle(el)) &&
c.getPropertyValue('visibility') === 'visible' &&
c.getPropertyValue('opacity') !== 'none') {
matches.push(el);
}
}
return matches;
}
With a usage example of...
var els = document.querySelectorAll('.one'),
visibleEls = inViewport(els);
This ensures that the display is not set to "none", the visibility is "visible", the width and height are greater than 0, and the element is within the bounds of the viewport.
| stackoverflow | {
"language": "en",
"length": 729,
"provenance": "stackexchange_0000F.jsonl.gz:887300",
"question_score": "14",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612141"
} |
7e783c11173f018081c34f42245f2dd4e9bba2af | Stackoverflow Stackexchange
Q: Write data to SSD1306 via I2C I'm using an SSD1306 OLED and have a question about it.
When writing data to its buffer via I2C, some libraries write 16 bytes every time.
For example:
void SSD1306::sendFramebuffer(const uint8_t *buffer) {
// Set Column Address (0x00 - 0x7F)
sendCommand(SSD1306_COLUMNADDR);
sendCommand(0x00);
sendCommand(0x7F);
// Set Page Address (0x00 - 0x07)
sendCommand(SSD1306_PAGEADDR);
sendCommand(0x00);
sendCommand(0x07);
for (uint16_t i = 0;i < SSD1306_BUFFERSIZE;) {
i2c.start();
i2c.write(0x40);
for (uint8_t j = 0;j < 16; ++j, ++i) {
i2c.write(buffer[i]);
}
i2c.stop();
}
}
Why don't they write 1024 bytes directly?
A: Most of the I2C libraries I've seen source code for, including that for the Aruduino, chunk the data in this fashion. While the I2C standard doesn't require this, as other poster mentioned, there may be buffer considerations. The .stop() command here might signal the device to process the 16 bytes just sent and prepare for more.
Invariably, you need to read the datasheet for your device and understand what it expects in order to display properly. They say "RTFM" in software, but hardware is at least as unforgiving. You must read and follow the datasheet when interfacing with external hardware devices.
| Q: Write data to SSD1306 via I2C I'm using an SSD1306 OLED and have a question about it.
When writing data to its buffer via I2C, some libraries write 16 bytes every time.
For example:
void SSD1306::sendFramebuffer(const uint8_t *buffer) {
// Set Column Address (0x00 - 0x7F)
sendCommand(SSD1306_COLUMNADDR);
sendCommand(0x00);
sendCommand(0x7F);
// Set Page Address (0x00 - 0x07)
sendCommand(SSD1306_PAGEADDR);
sendCommand(0x00);
sendCommand(0x07);
for (uint16_t i = 0;i < SSD1306_BUFFERSIZE;) {
i2c.start();
i2c.write(0x40);
for (uint8_t j = 0;j < 16; ++j, ++i) {
i2c.write(buffer[i]);
}
i2c.stop();
}
}
Why don't they write 1024 bytes directly?
A: Most of the I2C libraries I've seen source code for, including that for the Aruduino, chunk the data in this fashion. While the I2C standard doesn't require this, as other poster mentioned, there may be buffer considerations. The .stop() command here might signal the device to process the 16 bytes just sent and prepare for more.
Invariably, you need to read the datasheet for your device and understand what it expects in order to display properly. They say "RTFM" in software, but hardware is at least as unforgiving. You must read and follow the datasheet when interfacing with external hardware devices.
A: Segmenting data into more frames helps when the receiving device has not enough buffer space or is simply not fast enough to digest the data at full rate. The START/STOP approach might give the receiving device a bit of time to process the received data. In your specific case, the 16-byte chunks seem to be exactly one line of the display.
Other reasons for segmenting transfers are multi-master operations, but that doesn't seem to be the case here.
| stackoverflow | {
"language": "en",
"length": 273,
"provenance": "stackexchange_0000F.jsonl.gz:887338",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612271"
} |
788156a075744714703dda7cdb0e841d9b0ac6a1 | Stackoverflow Stackexchange
Q: Using Vector Drawable by drawing in Canvas
*
*I have a imported an SVG into my project as Vector Drawable.
*I have my custom view
I know how to display a vector drawable using an ImageView by code (http://www.androidhive.info/2017/02/android-working-svg-vector-drawables/)
, which is described in several articles, but:
How can I draw my vectors using my custom view and by code with canvas ?
Is this possible to do. And if so, can someone give me a hint.
A: To do this you need to convert the vector to a bitmap as follows:
private fun getVectorBitmap(context: Context, drawableId: Int): Bitmap? {
var bitmap: Bitmap? = null
when (val drawable = ContextCompat.getDrawable(context, drawableId)) {
is BitmapDrawable -> {
bitmap = drawable.bitmap
}
is VectorDrawable -> {
bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
}
}
return bitmap
}
Then you can use the vector as a bitmap normally with your canvas:
canvas?.drawBitmap(getVectorBitmap(context, R.drawable.ic_icon), 500f, 500f, canvasPaint)
| Q: Using Vector Drawable by drawing in Canvas
*
*I have a imported an SVG into my project as Vector Drawable.
*I have my custom view
I know how to display a vector drawable using an ImageView by code (http://www.androidhive.info/2017/02/android-working-svg-vector-drawables/)
, which is described in several articles, but:
How can I draw my vectors using my custom view and by code with canvas ?
Is this possible to do. And if so, can someone give me a hint.
A: To do this you need to convert the vector to a bitmap as follows:
private fun getVectorBitmap(context: Context, drawableId: Int): Bitmap? {
var bitmap: Bitmap? = null
when (val drawable = ContextCompat.getDrawable(context, drawableId)) {
is BitmapDrawable -> {
bitmap = drawable.bitmap
}
is VectorDrawable -> {
bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
}
}
return bitmap
}
Then you can use the vector as a bitmap normally with your canvas:
canvas?.drawBitmap(getVectorBitmap(context, R.drawable.ic_icon), 500f, 500f, canvasPaint)
A: I'm going to turn @pskink's comment into an answer as I'm not so advanced in android as to quickly realize what he meant. I had to read @Krishna's answer to understand. So credits to both of them.
Here it goes:
A vector drawable inherits Drawable that can be drawn directly into a canvas. First, get the drawable from the resources using an android context:
val drawable = yourContext.getDrawable(drawableId)
Then simply draw into the canvas with it. The next line tells the drawable to draw on the top left corner, with a size of 32x32 pixels:
drawable.setBounds(0, 0, 32, 32)
Finally draw it into the canvas:
drawable.draw(canvas)
| stackoverflow | {
"language": "en",
"length": 271,
"provenance": "stackexchange_0000F.jsonl.gz:887364",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612353"
} |
e9356d6810bf0a0f2d5642ba97e8f43cc36546cd | Stackoverflow Stackexchange
Q: Toggle Class based on scroll React JS I'm using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn't find that much info on it. So far I have...
I don't know if I'm using the right event listener or how to set the height etc.
And I'm not really setting inline styles...
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = { scrollBackground: 'nav-bg' };
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll(){
this.setState ({
scrollBackground: !this.state.scrollBackground
})
}
render() {
const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';
return (
<div>
<Navbar inverse toggleable className={this.state.scrollBackground}
onScroll={this.handleScroll}>
...
</Navbar>
</div>
);
}
}
export default App;
A: const [scroll, setScroll] = useState(false);
useEffect(() => {
window.addEventListener("scroll", () => {
setScroll(window.scrollY > specify_height_you_want_to_change_after_here);
});
}, []);
Then you can change your class or anything according to scroll.
<nav className={scroll ? "bg-black" : "bg-white"}>...</nav>
| Q: Toggle Class based on scroll React JS I'm using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn't find that much info on it. So far I have...
I don't know if I'm using the right event listener or how to set the height etc.
And I'm not really setting inline styles...
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = { scrollBackground: 'nav-bg' };
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll(){
this.setState ({
scrollBackground: !this.state.scrollBackground
})
}
render() {
const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';
return (
<div>
<Navbar inverse toggleable className={this.state.scrollBackground}
onScroll={this.handleScroll}>
...
</Navbar>
</div>
);
}
}
export default App;
A: const [scroll, setScroll] = useState(false);
useEffect(() => {
window.addEventListener("scroll", () => {
setScroll(window.scrollY > specify_height_you_want_to_change_after_here);
});
}, []);
Then you can change your class or anything according to scroll.
<nav className={scroll ? "bg-black" : "bg-white"}>...</nav>
A: It's Better
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isTop: true
};
this.onScroll = this.onScroll.bind(this);
}
componentDidMount() {
document.addEventListener('scroll', () => {
const isTop = window.scrollY < 100;
if (isTop !== this.state.isTop) {
this.onScroll(isTop);
}
});
}
onScroll(isTop) {
this.setState({ isTop });
}
render() {
return (
<div style={{ height: '200vh' }}>
<h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
</div>
);
}
}
render(<App />, document.getElementById('root'));
A: For those of you who are reading this question after 2020, I've taken @glennreyes answer and rewritten it using React Hooks:
const [scroll, setScroll] = useState(0)
useEffect(() => {
document.addEventListener("scroll", () => {
const scrollCheck = window.scrollY < 100
if (scrollCheck !== scroll) {
setScroll(scrollCheck)
}
})
})
Bear in mind that, useState has an array of two elements, firstly the state object and secondly the function that updates it.
Along the lines, useEffect helps us replace componentDidmount, the function written currently does not do any clean ups for brevity purposes.
If you find it essential to clean up, you can just return a function inside the useEffect.
You can read comprehensively here.
UPDATE:
If you guys felt like making it modular and even do the clean up, you can do something like this:
*
*Create a custom hook as below;
import { useState, useEffect } from "react"
export const useScrollHandler = () => {
// setting initial value to true
const [scroll, setScroll] = useState(1)
// running on mount
useEffect(() => {
const onScroll = () => {
const scrollCheck = window.scrollY < 10
if (scrollCheck !== scroll) {
setScroll(scrollCheck)
}
}
// setting the event handler from web API
document.addEventListener("scroll", onScroll)
// cleaning up from the web API
return () => {
document.removeEventListener("scroll", onScroll)
}
}, [scroll, setScroll])
return scroll
}
*Call it inside any component that you find suitable:
const component = () => {
// calling our custom hook
const scroll = useScrollHandler()
....... rest of your code
}
A: One way to add a scroll listener is to use the componentDidMount() lifecycle method. Following example should give you an idea:
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
state = {
isTop: true,
};
componentDidMount() {
document.addEventListener('scroll', () => {
const isTop = window.scrollY < 100;
if (isTop !== this.state.isTop) {
this.setState({ isTop })
}
});
}
render() {
return (
<div style={{ height: '200vh' }}>
<h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.isTop ? 'down' : 'up'}!</h2>
</div>
);
}
}
render(<App />, document.getElementById('root'));
This changes the Text from "Scroll down" to "Scroll up" when your scrollY position is at 100 and above.
Edit: Should avoid the overkill of updating the state on each scroll. Only update it when the boolean value changes.
A: I have changed @PouyaAtaei answer a bit for my use case.
import { useState, useEffect } from "react"
// Added distance parameter to determine how much
// from the top tell return value is updated.
// The name of the hook better reflects intended use.
export const useHasScrolled = (distance = 10) => {
// setting initial value to false
const [scroll, setScroll] = useState(false)
// running on mount
useEffect(() => {
const onScroll = () => {
// Logic is false tell user reaches threshold, then true after.
const scrollCheck = window.scrollY >= distance;
if (scrollCheck !== scroll) {
setScroll(scrollCheck)
}
}
// setting the event handler from web API
document.addEventListener("scroll", onScroll)
// cleaning up from the web API
return () => {
document.removeEventListener("scroll", onScroll)
}
}, [scroll, setScroll])
return scroll
}
Calling the hook:
const component = () => {
// calling our custom hook and optional distance agument.
const scroll = useHasScrolled(250)
}
A: This is yet another take / my take on hooks approach for on scroll displaying and hiding of a random page element.
I have been very much inspired from: Dan Abramov's post here.
You can check a full working example, in this CodeSandbox demo.
The following is the code for the useScroll custom hook:
import React, { useState, useEffect } from "react";
export const useScroll = callback => {
const [scrollDirection, setScrollDirection] = useState(true);
const handleScroll = () => {
const direction = (() => {
// if scroll is at top or at bottom return null,
// so that it would be possible to catch and enforce a special behaviour in such a case.
if (
window.pageYOffset === 0 ||
window.innerHeight + Math.ceil(window.pageYOffset) >=
document.body.offsetHeight
)
return null;
// otherwise return the direction of the scroll
return scrollDirection < window.pageYOffset ? "down" : "up";
})();
callback(direction);
setScrollDirection(window.pageYOffset);
};
// adding and cleanning up de event listener
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
});
};
And this hook will be consumed like this:
useScroll(direction => {
setScrollDirection(direction);
});
A full component using this custom hook:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import CustomElement, { useScroll } from "./element";
import Scrollable from "./scrollable";
function Page() {
const [scrollDirection, setScrollDirection] = useState(null);
useScroll(direction => {
setScrollDirection(direction);
});
return (
<div>
{/* a custom element that implements some scroll direction behaviour */}
{/* "./element" exports useScroll hook and <CustomElement> */}
<CustomElement scrollDirection={scrollDirection} />
{/* just a lorem ipsum long text */}
<Scrollable />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Page />, rootElement);
And lastly the code for CustomElement:
import React, { useState, useEffect } from "react";
export default props => {
const [elementVisible, setElementVisible] = useState(true);
const { scrollDirection } = props;
// when scroll direction changes element visibility adapts, but can do anything we want it to do
// U can use ScrollDirection and implement some page shake effect while scrolling
useEffect(() => {
setElementVisible(
scrollDirection === "down"
? false
: scrollDirection === "up"
? true
: true
);
}, [scrollDirection]);
return (
<div
style={{
background: "#ff0",
padding: "20px",
position: "fixed",
width: "100%",
display: `${elementVisible ? "inherit" : "none"}`
}}
>
element
</div>
);
};
A: These are two hooks - one for direction (up/down/none) and one for the actual position
Use like this:
useScrollPosition(position => {
console.log(position)
})
useScrollDirection(direction => {
console.log(direction)
})
Here are the hooks:
import { useState, useEffect } from "react"
export const SCROLL_DIRECTION_DOWN = "SCROLL_DIRECTION_DOWN"
export const SCROLL_DIRECTION_UP = "SCROLL_DIRECTION_UP"
export const SCROLL_DIRECTION_NONE = "SCROLL_DIRECTION_NONE"
export const useScrollDirection = callback => {
const [lastYPosition, setLastYPosition] = useState(window.pageYOffset)
const [timer, setTimer] = useState(null)
const handleScroll = () => {
if (timer !== null) {
clearTimeout(timer)
}
setTimer(
setTimeout(function () {
callback(SCROLL_DIRECTION_NONE)
}, 150)
)
if (window.pageYOffset === lastYPosition) return SCROLL_DIRECTION_NONE
const direction = (() => {
return lastYPosition < window.pageYOffset
? SCROLL_DIRECTION_DOWN
: SCROLL_DIRECTION_UP
})()
callback(direction)
setLastYPosition(window.pageYOffset)
}
useEffect(() => {
window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll)
})
}
export const useScrollPosition = callback => {
const handleScroll = () => {
callback(window.pageYOffset)
}
useEffect(() => {
window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll)
})
}
A: how to fix :
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
MenuNews
const [scroll, setScroll] = useState(false);
useEffect(() => {
window.addEventListener("scroll", () => {
setScroll(window.scrollY > specify_height_you_want_to_change_after_here);
});
}, []);
A: Approach without scroll event listener
import { useEffect, useState } from "react";
interface Props {
elementId: string;
position: string;
}
const useCheckScrollPosition = ({ elementId, position }: Props) => {
const [isOverScrollPosition, setIsOverScrollPosition] = useState<boolean>(false);
useEffect(() => {
if (
"IntersectionObserver" in window &&
"IntersectionObserverEntry" in window &&
"intersectionRatio" in window.IntersectionObserverEntry.prototype
) {
const observer = new IntersectionObserver((entries) => {
setIsOverScrollPosition(entries[0].boundingClientRect.y < 0);
});
const flagElement = document.createElement("div");
flagElement.id = elementId;
flagElement.className = "scroll-flag";
flagElement.style.top = position;
const container = document.getElementById("__next"); // React div id
const oldFlagElement = document.getElementById(elementId);
if (!oldFlagElement) container?.appendChild(flagElement);
const elementToObserve = oldFlagElement || flagElement;
observer.observe(elementToObserve);
}
}, [elementId, position]);
return isOverScrollPosition;
};
export default useCheckScrollPosition;
and then you can use it like this:
const isOverScrollPosition = useCheckScrollPosition({
elementId: "sticky-header",
position: "10px",
});
isOverScrollPosition is a boolean that will be true if you scroll over position provided value (10px) and false if you scroll below it.
This approach will add a flag div in react root.
Reference: https://css-tricks.com/styling-based-on-scroll-position/
| stackoverflow | {
"language": "en",
"length": 1554,
"provenance": "stackexchange_0000F.jsonl.gz:887369",
"question_score": "20",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612364"
} |
45cc5d9d7bf93fcb09df7d19ab9066653f12eac0 | Stackoverflow Stackexchange
Q: How to pass the index value of a ngFor loop into the component? I have a ngFor loop in my code.
and inside this ngFor loop I have a div, on clicking this div I want to pass the index value to the type script file.
I am new to Anglular 2 any help will be appreciated.
Eg:
`<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue()">
</div>
<div>`
A: <div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue(i)">
</div>
<div>`
passIndexValue(index){
console.log(index);//clicked index
}
You could also pass the value to the component like so (assuming below use of @Input)
<div *ngFor="let y of characters;let i = index">
<childComponent [index]="i">
</childComponent>
<div>`
And then pick up the value on the component object:
@Input() index: number;
And use it directly in the template of the child component like so:
<div id="mydivinstance_{{index}}"></div>
Thereby allowing a component to have a unique ID based on the *ngFor loop.
| Q: How to pass the index value of a ngFor loop into the component? I have a ngFor loop in my code.
and inside this ngFor loop I have a div, on clicking this div I want to pass the index value to the type script file.
I am new to Anglular 2 any help will be appreciated.
Eg:
`<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue()">
</div>
<div>`
A: <div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue(i)">
</div>
<div>`
passIndexValue(index){
console.log(index);//clicked index
}
You could also pass the value to the component like so (assuming below use of @Input)
<div *ngFor="let y of characters;let i = index">
<childComponent [index]="i">
</childComponent>
<div>`
And then pick up the value on the component object:
@Input() index: number;
And use it directly in the template of the child component like so:
<div id="mydivinstance_{{index}}"></div>
Thereby allowing a component to have a unique ID based on the *ngFor loop.
| stackoverflow | {
"language": "en",
"length": 158,
"provenance": "stackexchange_0000F.jsonl.gz:887387",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612400"
} |
7bba72ada61f5828657917effa126331092c3622 | Stackoverflow Stackexchange
Q: tensorflow import vgg16 failed I just do not understand why I have already downloaded the vgg16, and it still comes up with ImportError: No module named 'download'. My directory shows on the right top of the image.
A: I am assuming you downloaded vgg16.py from here.
It seems there is a download.py module in that repository that goes with vgg16.py.
Perhaps you should download the whole repo and put your 0618.py script inside the repo root and run it from there?
| Q: tensorflow import vgg16 failed I just do not understand why I have already downloaded the vgg16, and it still comes up with ImportError: No module named 'download'. My directory shows on the right top of the image.
A: I am assuming you downloaded vgg16.py from here.
It seems there is a download.py module in that repository that goes with vgg16.py.
Perhaps you should download the whole repo and put your 0618.py script inside the repo root and run it from there?
| stackoverflow | {
"language": "en",
"length": 82,
"provenance": "stackexchange_0000F.jsonl.gz:887428",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612503"
} |
3435f950a4e12ae8891106d5237c61e0b439d7c9 | Stackoverflow Stackexchange
Q: How to convert a Tableau extract data to csv (or xls) I have successfully converted from a Tableau .twbx file to .twb and now have a .tde file for the data. How can this .tde be converted to either .csv or .xls(x) ?
A: The Worksheet | Export | Data (or Crosstab to Excel)' appear to have done the trick: there are now anxlsxand a.csv` file with the relevant dataset included.
| Q: How to convert a Tableau extract data to csv (or xls) I have successfully converted from a Tableau .twbx file to .twb and now have a .tde file for the data. How can this .tde be converted to either .csv or .xls(x) ?
A: The Worksheet | Export | Data (or Crosstab to Excel)' appear to have done the trick: there are now anxlsxand a.csv` file with the relevant dataset included.
A: You can also export to CSV from the Data menu starting in version 10.3.
That command exports the entire data source, while the export commands on the worksheet menu export only the data referenced by the worksheet. Both are useful. One exports the entire data source, the other exports the fields used on the worksheet
Note to readers : See my answers below with screenshots on how to do this.
A: Building on @AlexBlakemore 's answer: from Version 10.2.2 there is a feature for Export to CSV. It is non intuitive how to find it: select the Data | (data source name) | Export to CSV :
| stackoverflow | {
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:887431",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612508"
} |
702b0a2c519c5eab5eaa1c1106f535f671516575 | Stackoverflow Stackexchange
Q: Using 'null' vs 'this' in apply or apply() and call() functions in javascript What is the difference between using this and null as the thisArg context to the apply() and call() methods?
function getMax(arr) {
return Math.max.apply(null, arr);
}
function getMax(arr) {
return Math.max.apply(this, arr);
}
A: max is a static function, so it doesn't matter what you pass as this, because this is not used. So your functions are equivalent.
| Q: Using 'null' vs 'this' in apply or apply() and call() functions in javascript What is the difference between using this and null as the thisArg context to the apply() and call() methods?
function getMax(arr) {
return Math.max.apply(null, arr);
}
function getMax(arr) {
return Math.max.apply(this, arr);
}
A: max is a static function, so it doesn't matter what you pass as this, because this is not used. So your functions are equivalent.
A: The signficance of using this is to set the current context when calling the method. For example:
function Human() {
this.getMax = function getMax(arr) {
console.log(this.constructor);
return Math.max.apply(this, arr);
}
}
var human = new Human();
human.getMax([1,2]);
Here, the console statement will out this.constructor as Human. Had it been otherwise, you would have got the context as window.
For the first case, when you pass null, it wont pass the context. This works here because Math.max expects paramters in comma seperated format a, b, c which is being handled when you do .apply.
| stackoverflow | {
"language": "en",
"length": 166,
"provenance": "stackexchange_0000F.jsonl.gz:887436",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612533"
} |
c2192b1254e7a02dcafed33ad362d9ff7dc222d0 | Stackoverflow Stackexchange
Q: Make BoxDecoration image faded/transparent I have the following snippet of code and I would like to make the image faded such that it does not interfere with other items in the container.
Is there a filter that could accomplish this?
child: new Card(
child: new Container(
decoration: new BoxDecoration(
color: const Color(0xff7c94b6),
image: new DecorationImage(
image: new ExactAssetImage('lib/images/pic1.jpg'),
)
)
)
)
A: You can simply use
ColorFiltered(
colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
child: YourWidget(),
)
| Q: Make BoxDecoration image faded/transparent I have the following snippet of code and I would like to make the image faded such that it does not interfere with other items in the container.
Is there a filter that could accomplish this?
child: new Card(
child: new Container(
decoration: new BoxDecoration(
color: const Color(0xff7c94b6),
image: new DecorationImage(
image: new ExactAssetImage('lib/images/pic1.jpg'),
)
)
)
)
A: You can simply use
ColorFiltered(
colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
child: YourWidget(),
)
A: Use Opacity class.
A widget that makes its child partially transparent.
Opacity(
opacity: 0.5,
child: Image.asset('images/lion.png'),
)
A: For those who wonder whether the performance is OK or not (since images and opacity are both resource-heavy things), here is my dig into the doc and the source code and the answer.
Conclusion: Use DecorationImage(colorFilter: ...) will be as fast as what official doc suggests. (But Opacity, ColorFilter widgets are not)
Firstly, we should not use Opacity or ColorFilter widget since it may trigger saveLayer and is expensive (by official doc).
Instead, we should
Use the Opacity widget only when necessary. See the Transparent image section in the Opacity API page for an example of applying opacity directly to an image, which is faster than using the Opacity widget.
Looking at the suggested method, we see the following sample:
Image.network(
'https://raw.githubusercontent.com/flutter/assets-for-api-docs/master/packages/diagrams/assets/blend_mode_destination.jpeg',
color: Color.fromRGBO(255, 255, 255, 0.5),
colorBlendMode: BlendMode.modulate
)
Now, the problem is, is the highly-voted answer, i.e. the following code, as fast as what the official doc mentions for Image widget?
Container(
child: Text('hi'),
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
image: new DecorationImage(
fit: BoxFit.cover,
colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
image: new NetworkImage(
'http://www.allwhitebackground.com/images/2/2582-190x190.jpg',
),
),
),
),
To answer this, let us look at Image.network's source. This constructor will directly fill in the colorBlendMode field of Image.
In Image's build, it will be directly passed to RawImage's colorBlendMode field.
Then, RawImage will create RenderImage (which is a RenderObject) and updates RenderImage._colorBlendMode.
Next, notice how RenderImage handles this -
BlendMode? _colorBlendMode;
set colorBlendMode(BlendMode? value) {
if (value == _colorBlendMode)
return;
_colorBlendMode = value;
_updateColorFilter();
markNeedsPaint();
}
...
/// If non-null, this color is blended with each image pixel using [colorBlendMode].
Color? get color => _color;
Color? _color;
set color(Color? value) {
if (value == _color)
return;
_color = value;
_updateColorFilter();
markNeedsPaint();
}
...
ColorFilter? _colorFilter;
void _updateColorFilter() {
if (_color == null)
_colorFilter = null;
else
_colorFilter = ColorFilter.mode(_color!, _colorBlendMode ?? BlendMode.srcIn);
}
A more dig into rendering/image.dart will show that, colorBlendMode (and _colorBlendMode will not be used in other places except to create this _colorFilter.
Thus, we know the two arguments of Image.network will finally go into RenderImage._colorFilter.
Indeed, that _colorFilter will be used in RenderImage.paint as
@override
void paint(PaintingContext context, Offset offset) {
...
paintImage(
canvas: context.canvas,
rect: offset & size,
image: _image!,
colorFilter: _colorFilter,
...
);
}
So we know it! It will be used in paintImage which communicates with native methods. No wonder it is faster than Opacity.
No go back to our DecorationImage. Inside painting/decoration_image.dart, we see DecorationImagePainter:
class DecorationImagePainter {
DecorationImagePainter._(this._details, ...);
final DecorationImage _details;
void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration) {
...
paintImage(
canvas: canvas,
rect: rect,
image: _image!.image,
colorFilter: _details.colorFilter,
...
);
}
}
Hey, that is exactly the same!
A: You can simply use a Stack widget and use a simple coloured container above the image with reduced opacity.
EG :
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/rendering.dart';
import './page2.dart';
import './page3.dart';
import './page4.dart';
void main() {
debugPaintSizeEnabled = true ;
return runApp(Start());
}
class Start extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'InIt',
home: Builder(builder: (context) {
return GestureDetector(
onTap: () {
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return Page2();
},
),
);
},
child: Scaffold(
body: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/page1.jpg'),
fit: BoxFit.fitHeight),
),
),
Container(
color: Color.fromRGBO(255, 255, 255, 0.19),
),
Container(
alignment: Alignment.center,
child: Center(
child: Text(
'LETS BE PRODUCTIVE TODAY',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50.0,
fontFamily: 'bold',
fontWeight: FontWeight.bold,
color: Color.fromRGBO(255, 255, 255, 1)),
),
),
),
Container(
margin: EdgeInsets.only(bottom: 10.0),
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RawMaterialButton(
onPressed: () {},
constraints:
BoxConstraints.tightFor(height: 10.0, width: 10.0),
shape: CircleBorder(),
fillColor: Colors.white,
),
Page2call(),
Page3call(),
Page4call(),
],
),
)
],
),
),
);
}),
);
}
}
class Page2call extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return RawMaterialButton(
onPressed: () {
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return Page2();
},
),
);
},
constraints: BoxConstraints.tightFor(height: 10.0, width: 10.0),
shape: CircleBorder(),
fillColor: Colors.white,
);
}
}
class Page3call extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return RawMaterialButton(
onPressed: () {
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return Page3();
},
),
);
},
constraints: BoxConstraints.tightFor(height: 10.0, width: 10.0),
shape: CircleBorder(),
fillColor: Colors.white,
);
}
}
class Page4call extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return RawMaterialButton(
onPressed: () {
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return Page4();
},
),
);
},
constraints: BoxConstraints.tightFor(height: 10.0, width: 10.0),
shape: CircleBorder(),
fillColor: Colors.white,
);
}
}
This is a fully practically implemented example. You can increase the opacity over here
to make the background even more faded, the fourth argument is for opacity:
Container(
color: Color.fromRGBO(255, 255, 255, 0.19),
),
This method also gives u the ability to chose the colour of the fading filter.
A: You could give your DecorationImage a ColorFilter to make the background image grey (use a saturation color filter) or semi transparent (use a dstATop color filter).
Code for this example is below.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) => new Scaffold(
appBar: new AppBar(
title: new Text('Grey Example'),
),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
new Card(
child: new Container(
child: new Text(
'Hello world',
style: Theme.of(context).textTheme.display4
),
decoration: new BoxDecoration(
color: const Color(0xff7c94b6),
image: new DecorationImage(
fit: BoxFit.cover,
colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.2), BlendMode.dstATop),
image: new NetworkImage(
'http://www.allwhitebackground.com/images/2/2582-190x190.jpg',
),
),
),
),
),
],
),
);
}
The Opacity widget is another option.
You could also pre apply the effect to the asset.
| stackoverflow | {
"language": "en",
"length": 1041,
"provenance": "stackexchange_0000F.jsonl.gz:887464",
"question_score": "79",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612599"
} |
904cf152764301577839965bcf4fd425f7536b03 | Stackoverflow Stackexchange
Q: how to use external jquery plugin in react I've built a React project using CRA. I need to use a plugin that is built using jquery. It's a datepicker but the calendar it's using is Bikram Sambat. The link to the datepicker code is Nepali Date Picker . I've done the following:
public/index.html
<link href="%PUBLIC_URL%/assets/nepaliDatePicker.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="%PUBLIC_URL%/assets/nepaliDatePicker.min.js"></script>
NepaliDate Component
import React, { Component } from 'react';
const $ = window.$;
export default class NepaliDate extends Component {
shouldComponentUpdate() {
return false;
}
componentDidMount() {
$('.date-picker').nepaliDatePicker({
dateFormat: '%D, %M %d, %y',
closeOnDateSelect: true
});
}
showDatePicker = () => {
$('.date-picker').nepaliDatePicker();
};
render() {
return (
<input
type="text"
value=""
name="date"
className="date-picker"
onFocus={this.showDatePicker}
/>
);
}
}
The datepicker isn't showing up.
A: Can use "react-load-script" to load 3rd part JS libraries. After install can use like below
import Script from 'react-load-script'
render(){
return(
<div>
<Script url="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"/>
<Script url="menu.js"/>
//.....Remaining code can be here
</div>
);
}
| Q: how to use external jquery plugin in react I've built a React project using CRA. I need to use a plugin that is built using jquery. It's a datepicker but the calendar it's using is Bikram Sambat. The link to the datepicker code is Nepali Date Picker . I've done the following:
public/index.html
<link href="%PUBLIC_URL%/assets/nepaliDatePicker.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="%PUBLIC_URL%/assets/nepaliDatePicker.min.js"></script>
NepaliDate Component
import React, { Component } from 'react';
const $ = window.$;
export default class NepaliDate extends Component {
shouldComponentUpdate() {
return false;
}
componentDidMount() {
$('.date-picker').nepaliDatePicker({
dateFormat: '%D, %M %d, %y',
closeOnDateSelect: true
});
}
showDatePicker = () => {
$('.date-picker').nepaliDatePicker();
};
render() {
return (
<input
type="text"
value=""
name="date"
className="date-picker"
onFocus={this.showDatePicker}
/>
);
}
}
The datepicker isn't showing up.
A: Can use "react-load-script" to load 3rd part JS libraries. After install can use like below
import Script from 'react-load-script'
render(){
return(
<div>
<Script url="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"/>
<Script url="menu.js"/>
//.....Remaining code can be here
</div>
);
}
A: Just follow instruction showed on Nepali-Date-Picker github page, install library with npm install and add CDN link to your html file inside public folder inside head element above root element, hope this resolve your issue.
| stackoverflow | {
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:887474",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612624"
} |
f74e7d729db4730b5f029993ff3b5f36e0bb8a03 | Stackoverflow Stackexchange
Q: How to avoid program to be detected as a trojan? I made a small program to detect mouse moving from a screen to another on multiscreen configuration and it is detected as a trojan on windows 10 by windows defender. On my pc it is not detected (windows 7 pro 64) by windows defender nor my antivirus.
I'm using just a few functions:
GetCursorPos(&P);
...
HWND hwnd = WindowFromPoint(P);
HWND hparent = GetParent(hwnd);
while (hparent)
{
hwnd = hparent;
hparent = GetParent(hwnd);
}
SetForegroundWindow(hwnd);
Is there something in that code that can be suspicious ?
Thanks
| Q: How to avoid program to be detected as a trojan? I made a small program to detect mouse moving from a screen to another on multiscreen configuration and it is detected as a trojan on windows 10 by windows defender. On my pc it is not detected (windows 7 pro 64) by windows defender nor my antivirus.
I'm using just a few functions:
GetCursorPos(&P);
...
HWND hwnd = WindowFromPoint(P);
HWND hparent = GetParent(hwnd);
while (hparent)
{
hwnd = hparent;
hparent = GetParent(hwnd);
}
SetForegroundWindow(hwnd);
Is there something in that code that can be suspicious ?
Thanks
| stackoverflow | {
"language": "en",
"length": 97,
"provenance": "stackexchange_0000F.jsonl.gz:887483",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612647"
} |
245ea08d86073cfc07a332a6670496c15539d080 | Stackoverflow Stackexchange
Q: Keras No module named models Try to run Keras in MacOSX, using a virtual environment
Versions
*
*MacOSX: 10.12.4 (16E195)
*Python 2.7
Troubleshooting
*
*Recreate Virtualenv
*Reinstall keras
Logs
(venv) me$sudo pip install --upgrade keras
Collecting keras
Requirement already up-to-date: six in /Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg (from keras)
Requirement already up-to-date: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already up-to-date: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already up-to-date: numpy>=1.9.1 in /Library/Python/2.7/site-packages (from theano->keras)
Requirement already up-to-date: scipy>=0.14 in /Library/Python/2.7/site-packages (from theano->keras)
Installing collected packages: keras
Successfully installed keras-2.0.5
(venv) me$ python -c "import keras; print(keras.__version__)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named keras
A: The underlying problem here is what when you use sudo, pip points to the global, system-level python and not the virtual-env python. That is why, when you install without sudo, it works seamlessly for you. You can check this by running sudo pip install --upgrade keras from within the virtualenv and then running python -c "import keras; print(keras.__version__)" outside the virtualenv.
| Q: Keras No module named models Try to run Keras in MacOSX, using a virtual environment
Versions
*
*MacOSX: 10.12.4 (16E195)
*Python 2.7
Troubleshooting
*
*Recreate Virtualenv
*Reinstall keras
Logs
(venv) me$sudo pip install --upgrade keras
Collecting keras
Requirement already up-to-date: six in /Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg (from keras)
Requirement already up-to-date: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already up-to-date: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already up-to-date: numpy>=1.9.1 in /Library/Python/2.7/site-packages (from theano->keras)
Requirement already up-to-date: scipy>=0.14 in /Library/Python/2.7/site-packages (from theano->keras)
Installing collected packages: keras
Successfully installed keras-2.0.5
(venv) me$ python -c "import keras; print(keras.__version__)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named keras
A: The underlying problem here is what when you use sudo, pip points to the global, system-level python and not the virtual-env python. That is why, when you install without sudo, it works seamlessly for you. You can check this by running sudo pip install --upgrade keras from within the virtualenv and then running python -c "import keras; print(keras.__version__)" outside the virtualenv.
| stackoverflow | {
"language": "en",
"length": 170,
"provenance": "stackexchange_0000F.jsonl.gz:887485",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612653"
} |
f6b9cc472f6325bf9770b6d2882a75355b0bb51c | Stackoverflow Stackexchange
Q: Not loading the texture with OBJ+MTL loader in three.js I have a problem. I wrote this function to load an obj and mtl model
(taken from:https://threejs.org/examples/#webgl_loader_obj_mtl):
var mtlLoader = new THREE.MTLLoader();
//mtlLoader.setTexturePath(path)
mtlLoader.setPath(path);
mtlLoader.load(material, function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath(path);
objLoader.load(model, function ( mesh ) {
mesh.position.set(x, y, z);
mesh.scale.set(s, s, s);
mesh.rotation.y = Math.PI;
mesh.castShadow = false;
mesh.receiveShadow = true;
scene.add(mesh);
if(handler) {
handler(mesh);
}
}, function(e){}, function(e){} );
});
Where material is file.mtl and model is file.obj. It works fine for this model: https://free3d.com/3d-model/hk416-with-animation-37927.html but it doesn't work for another obj+mtl. The texture is not loaded and I see only white model. Why?
I use three.js r85.
Thank you!!
| Q: Not loading the texture with OBJ+MTL loader in three.js I have a problem. I wrote this function to load an obj and mtl model
(taken from:https://threejs.org/examples/#webgl_loader_obj_mtl):
var mtlLoader = new THREE.MTLLoader();
//mtlLoader.setTexturePath(path)
mtlLoader.setPath(path);
mtlLoader.load(material, function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath(path);
objLoader.load(model, function ( mesh ) {
mesh.position.set(x, y, z);
mesh.scale.set(s, s, s);
mesh.rotation.y = Math.PI;
mesh.castShadow = false;
mesh.receiveShadow = true;
scene.add(mesh);
if(handler) {
handler(mesh);
}
}, function(e){}, function(e){} );
});
Where material is file.mtl and model is file.obj. It works fine for this model: https://free3d.com/3d-model/hk416-with-animation-37927.html but it doesn't work for another obj+mtl. The texture is not loaded and I see only white model. Why?
I use three.js r85.
Thank you!!
| stackoverflow | {
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:887487",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612657"
} |
89b124f8d9fd278f79f37afa9c4e3e51f010ed98 | Stackoverflow Stackexchange
Q: Angular animation not working in IE edge I added an animation to my component in Angular. However the animation WORKS FINE in Chrome and Firefox, but in IE Edge the animation is NOT triggerd although the styles are applied correctly on state change, but just without specified animation.
Does anyone have the same issue?
Here is my code:
animations: [
trigger('rowState', [
state('collapsed', style({
'height': 0,
'overflow-y': 'hidden'
})),
state('expanded', style({
'height': '*',
'overflow-y': 'hidden'
})),
transition('collapsed <=> expanded', [animate('1000ms ease-out')])
])
]
Thanks in advance
A: Web animation is not supported in edge, you should add the polyfill
Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it.
For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.
| Q: Angular animation not working in IE edge I added an animation to my component in Angular. However the animation WORKS FINE in Chrome and Firefox, but in IE Edge the animation is NOT triggerd although the styles are applied correctly on state change, but just without specified animation.
Does anyone have the same issue?
Here is my code:
animations: [
trigger('rowState', [
state('collapsed', style({
'height': 0,
'overflow-y': 'hidden'
})),
state('expanded', style({
'height': '*',
'overflow-y': 'hidden'
})),
transition('collapsed <=> expanded', [animate('1000ms ease-out')])
])
]
Thanks in advance
A: Web animation is not supported in edge, you should add the polyfill
Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it.
For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.
A: you need to add polyfill in polyfills.ts
remove comments from
import web-animations-js;
then run
npm install --save web-animations-js
| stackoverflow | {
"language": "en",
"length": 156,
"provenance": "stackexchange_0000F.jsonl.gz:887507",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612735"
} |
cd62c6e14b79a7a71d2a600c81fabe8394e6a7b2 | Stackoverflow Stackexchange
Q: Remove anti-aliasing for pandas plot.area I want to plot stacked areas with Python, and find out this Pandas' function:
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area();
However, the result is weirdly antialiased, mixing together the colors, as shown on those 2 plots:
The same problem occurs in the example provided in the documentation.
Do you know how to remove this anti-aliasing? (Or another mean to get a neat output for stacked representation of line plots.)
A: It looks like there are two boundaries.
Try a zero line width:
df.plot.area(lw=0);
| Q: Remove anti-aliasing for pandas plot.area I want to plot stacked areas with Python, and find out this Pandas' function:
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area();
However, the result is weirdly antialiased, mixing together the colors, as shown on those 2 plots:
The same problem occurs in the example provided in the documentation.
Do you know how to remove this anti-aliasing? (Or another mean to get a neat output for stacked representation of line plots.)
A: It looks like there are two boundaries.
Try a zero line width:
df.plot.area(lw=0);
A: Using a matplotlib stack plot works fine
fig, ax = plt.subplots()
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax.stackplot(df.index, df.values.T)
Since the area plot is a stackplot, the only difference would be the linewidth of the areas, which you can set to zero.
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area(linewidth=0)
The remaining grayish lines are then indeed due to antialiasing. You may turn that off in the matplotlib plot
fig, ax = plt.subplots()
ax.stackplot(df.index, df.values.T, antialiased=False)
The result however, may not be visually appealing:
| stackoverflow | {
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:887531",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612797"
} |
54560816e7e8bfdb71b70ea996f99e4083f04c71 | Stackoverflow Stackexchange
Q: How can I show full array without double clicking? When I am debugging and trying to see a large array, CLion shows only the first 50 elements. I need to double click to see the rest. Is there a way to increase this amount to about 1000 elements by default?
A: There's a registry value that controls the number of children shown by default as a workaround until we come up with some more convenient solution.
Open the registry (Ctrl+Shift+A -> Registry...) and set the cidr.debugger.value.maxChildren to the desired value.
From the related blog post:
While inspecting arrays during debug, you might notice there was a limit of 50 elements shown by default. To see more user had to explicitly expand the next 50 elements. This was done to reduce performance issues. However, sometimes a few elements with big indexes are needed, and it’s quite tiresome to click expand several times in a row.
In order to provide a solution to the problem, we’ve added a registry value to control the default number of composite value’s children.
| Q: How can I show full array without double clicking? When I am debugging and trying to see a large array, CLion shows only the first 50 elements. I need to double click to see the rest. Is there a way to increase this amount to about 1000 elements by default?
A: There's a registry value that controls the number of children shown by default as a workaround until we come up with some more convenient solution.
Open the registry (Ctrl+Shift+A -> Registry...) and set the cidr.debugger.value.maxChildren to the desired value.
From the related blog post:
While inspecting arrays during debug, you might notice there was a limit of 50 elements shown by default. To see more user had to explicitly expand the next 50 elements. This was done to reduce performance issues. However, sometimes a few elements with big indexes are needed, and it’s quite tiresome to click expand several times in a row.
In order to provide a solution to the problem, we’ve added a registry value to control the default number of composite value’s children.
| stackoverflow | {
"language": "en",
"length": 178,
"provenance": "stackexchange_0000F.jsonl.gz:887540",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612821"
} |
da459a48ec40c3e8d9519fdf23c52ed2eb7b7744 | Stackoverflow Stackexchange
Q: how to rename a file in a directory using current directory I want to rename a file (home/Desktop/ali/a/b.txt)
I wrote a bash file
#!/bin/bash
mv a/b.txt a/c.txt
and put it in ali directory,I navigate to ali directory in terminal but when I execute the bash file it can't find a/b.txt
I know mv home/Desktop/ali/a/b.txt home/Desktop/ali/a/c.txt will work fine, but is there any way to use current directory to shorten the addressing?
A: If you want to mv a local file, just leave the dir blank:
mv a/test.py a/test1.py
Anyway you can use pwd for that, but keep in mind that you need to run the script in the same dir!
mv `pwd`/a/test.py `pwd`/a/test1.py
| Q: how to rename a file in a directory using current directory I want to rename a file (home/Desktop/ali/a/b.txt)
I wrote a bash file
#!/bin/bash
mv a/b.txt a/c.txt
and put it in ali directory,I navigate to ali directory in terminal but when I execute the bash file it can't find a/b.txt
I know mv home/Desktop/ali/a/b.txt home/Desktop/ali/a/c.txt will work fine, but is there any way to use current directory to shorten the addressing?
A: If you want to mv a local file, just leave the dir blank:
mv a/test.py a/test1.py
Anyway you can use pwd for that, but keep in mind that you need to run the script in the same dir!
mv `pwd`/a/test.py `pwd`/a/test1.py
A: You don't need to provide the location if you are in that directory.
For example you have file A in desktop so you navigate there and do:
mv A B
File A was renamed to B in that directory
But if you want to do so from another location then you do
mv directory/A directory/newfilename
A: if you run script from Ali directory then your mv statement seems like
mv `pwd`/a/test.py `pwd`/a/test1.py
or
mv ./a/test.py ./a/test1.py
| stackoverflow | {
"language": "en",
"length": 191,
"provenance": "stackexchange_0000F.jsonl.gz:887580",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44612969"
} |
c672b48a8920e6667a26bec8fffb6b2f2d8cbee9 | Stackoverflow Stackexchange
Q: angular's @input vs viewchild for sending data from parent to child component I have implemented a same component more than once in one of my forms. I have to send data from parent to child components. I know that it can be achieved with @input or with viewchild. what is the performance issue of using one over the other? when should i use viewchild or input?
A: When you are using @Input(), for every change the ngOnChanges() will be called and causes more noise.
Using ViewChild() will not create any such noise. So, prefer using Viewchild over @Input()
| Q: angular's @input vs viewchild for sending data from parent to child component I have implemented a same component more than once in one of my forms. I have to send data from parent to child components. I know that it can be achieved with @input or with viewchild. what is the performance issue of using one over the other? when should i use viewchild or input?
A: When you are using @Input(), for every change the ngOnChanges() will be called and causes more noise.
Using ViewChild() will not create any such noise. So, prefer using Viewchild over @Input()
| stackoverflow | {
"language": "en",
"length": 99,
"provenance": "stackexchange_0000F.jsonl.gz:887605",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613057"
} |
8cdd09718d51552ec51e351d215a3cfaef8c858a | Stackoverflow Stackexchange
Q: The computed property "counter" is already defined in data This is my code
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<button v-on:click="increase">plus</button>
<p>Counter : {{ counter }}</p>
<p>Clicks : {{ clicks }}</p>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
counter : 0,
clicks : 0
},
methods:{
increase(){
this.clicks++;
}
},
computed:{
counter: function(){
return this.clicks * 2;
}
}
});
</script>
</body>
</html>
When I click on the button, the counter should double the number of clicks displayed, but it's not working.
This code is working though: COMPUTED PROPERTIES | VueJS 2 | Learning the Basics.
A: You have a counter property in your data and you also have a counter computed value. To fix your code, just remove the counter from data.
data:{
clicks : 0
},
This is addressed in the comments of the video you linked. If you notice, he never actually runs the code after he adds the computed.
That said I used his videos and courses as a resource myself when I was starting out. They are for the most part excellent.
| Q: The computed property "counter" is already defined in data This is my code
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<button v-on:click="increase">plus</button>
<p>Counter : {{ counter }}</p>
<p>Clicks : {{ clicks }}</p>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
counter : 0,
clicks : 0
},
methods:{
increase(){
this.clicks++;
}
},
computed:{
counter: function(){
return this.clicks * 2;
}
}
});
</script>
</body>
</html>
When I click on the button, the counter should double the number of clicks displayed, but it's not working.
This code is working though: COMPUTED PROPERTIES | VueJS 2 | Learning the Basics.
A: You have a counter property in your data and you also have a counter computed value. To fix your code, just remove the counter from data.
data:{
clicks : 0
},
This is addressed in the comments of the video you linked. If you notice, he never actually runs the code after he adds the computed.
That said I used his videos and courses as a resource myself when I was starting out. They are for the most part excellent.
| stackoverflow | {
"language": "en",
"length": 184,
"provenance": "stackexchange_0000F.jsonl.gz:887613",
"question_score": "17",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613084"
} |
8bf6a4014f41febedc39034b65ed8be90d1796b0 | Stackoverflow Stackexchange
Q: Click event doesn't fire on an audio element in chrome I have an audio element in my DOM.
I executed the following command and it seems like the click event does not fire for some reason:
$0.addEventListener('click',function(){console.log('click')});
When i tried adding a mouseover handler it worked as expected:
$0.addEventListener('mouseover',function(){console.log('mouseover')});
In Firefox the click event works properly.
Any ideas?
A:
"If the user agent exposes a user interface to the user by displaying controls over the media element, then the user agent should suppress any user interaction events while the user agent is interacting with this interface. (For example, if the user clicks on a video's playback control, mousedown events and so forth would not simultaneously be fired at elements on the page.)"
— from The Web Hypertext Application Technology Working Group
It's intended not to work, so "malicious" websites can't capture users' clicks on media controls. So it's not advisable to get around it in general cases; but if you really have to, you have to follow some hack like programmatically wrapping the audio element in a transparent element with a higher z-index (be careful with z-indices and transparency) and capturing the clicks for the said element.
| Q: Click event doesn't fire on an audio element in chrome I have an audio element in my DOM.
I executed the following command and it seems like the click event does not fire for some reason:
$0.addEventListener('click',function(){console.log('click')});
When i tried adding a mouseover handler it worked as expected:
$0.addEventListener('mouseover',function(){console.log('mouseover')});
In Firefox the click event works properly.
Any ideas?
A:
"If the user agent exposes a user interface to the user by displaying controls over the media element, then the user agent should suppress any user interaction events while the user agent is interacting with this interface. (For example, if the user clicks on a video's playback control, mousedown events and so forth would not simultaneously be fired at elements on the page.)"
— from The Web Hypertext Application Technology Working Group
It's intended not to work, so "malicious" websites can't capture users' clicks on media controls. So it's not advisable to get around it in general cases; but if you really have to, you have to follow some hack like programmatically wrapping the audio element in a transparent element with a higher z-index (be careful with z-indices and transparency) and capturing the clicks for the said element.
A: Directly, it wont work.
You will need to add a shimified div aroudn it to get the click event.
Javascript:
function onAudioElClick() {
console.log('click');
}
HTML:
<div onclick="onAudioElClick()" style="position:absolute; z-index:9999; width:300px; height:30px;"></div>
<audio></audio>`
A: It's very strange that mouseover works but click not.
If you will wrap audio element inside to other element like div then you can handle click event:
JavaScript:
<div>
audio element
<audio src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay></audio>
</div>
HTML:
var el = document.querySelector("div");
el.addEventListener('click',function(){console.log('click')});
https://jsfiddle.net/b3sbmqpj/
| stackoverflow | {
"language": "en",
"length": 275,
"provenance": "stackexchange_0000F.jsonl.gz:887624",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613124"
} |
b34ff3bad387cf7a8a435a92f07bbe8d0a5e6952 | Stackoverflow Stackexchange
Q: how to ignore lf,crlf difference in beyond compare folder compare? I have 2 same php file. one is download in win7, another is from linux.
I use folder compare function in beyond compare.
Beyond compare regards them as different file because one is PC, another one is UNIX.
Screenshot:
I would like to ignore this difference ,how to do ?
A: Can you check the session settings (In the menu under Settings -> Session Settings) if you compare also the line endings?
You find the flag on the botton of the options.
If you need a pre-check in folder compare you can use the following settings:
(See the different filesize 18 to 19 Byte - The difference is the LF)
You need the overwrite quick test results. Without this the other checks return already a result. With this, your comparison will need more time.
| Q: how to ignore lf,crlf difference in beyond compare folder compare? I have 2 same php file. one is download in win7, another is from linux.
I use folder compare function in beyond compare.
Beyond compare regards them as different file because one is PC, another one is UNIX.
Screenshot:
I would like to ignore this difference ,how to do ?
A: Can you check the session settings (In the menu under Settings -> Session Settings) if you compare also the line endings?
You find the flag on the botton of the options.
If you need a pre-check in folder compare you can use the following settings:
(See the different filesize 18 to 19 Byte - The difference is the LF)
You need the overwrite quick test results. Without this the other checks return already a result. With this, your comparison will need more time.
| stackoverflow | {
"language": "en",
"length": 145,
"provenance": "stackexchange_0000F.jsonl.gz:887632",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613147"
} |
295598fb0bb5008be199a2fe276173f739cf4dc8 | Stackoverflow Stackexchange
Q: React use of HTML5 video tag controlsList attribute Tried to return with React component this element: <video ... controls controlsList="nodownload" /> and download button still appears.
There isn't a way to pass this argument (controlsList) with React?
Tried htmlControlsList= too
Error log:
Unknown prop controlsList on tag. Remove this prop from the element. For details, see ....URL
A: Until the problem gets fixed in React, this how you can add the attribute
componentDidMount() {
this.video.setAttribute("controlsList","nodownload");
}
render() {
return (
<video
ref={(v)=>{this.video=v}}
src="myvideo.mp4"
controls
autoplay />
)
}
| Q: React use of HTML5 video tag controlsList attribute Tried to return with React component this element: <video ... controls controlsList="nodownload" /> and download button still appears.
There isn't a way to pass this argument (controlsList) with React?
Tried htmlControlsList= too
Error log:
Unknown prop controlsList on tag. Remove this prop from the element. For details, see ....URL
A: Until the problem gets fixed in React, this how you can add the attribute
componentDidMount() {
this.video.setAttribute("controlsList","nodownload");
}
render() {
return (
<video
ref={(v)=>{this.video=v}}
src="myvideo.mp4"
controls
autoplay />
)
}
A: Support for ControlsList API has been reported a couple of weeks ago and the related PR has been merged just 5 days ago.
It should work in one of the upcoming versions of React.
| stackoverflow | {
"language": "en",
"length": 124,
"provenance": "stackexchange_0000F.jsonl.gz:887633",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613150"
} |
c42594cab24cd9d0a8b78bf4f563801768b11db7 | Stackoverflow Stackexchange
Q: How to handle, when tkinter window gets focus I have this code:
from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
It prints hello world only once, and then it stops working. No more hello world Basically WM_TAKE_FOCUS does not work.
A: You can bind a function to the <FocusIn> event. When you bind to the root window the binding is applied to every widget in the root window, so if you only want to do something when the window as a whole gets focus you'll need to compare event.widget to the root window.
For example:
import Tkinter as tk
def handle_focus(event):
if event.widget == root:
print("I have gained the focus")
root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry1.pack()
entry2.pack()
root.bind("<FocusIn>", handle_focus)
root.mainloop()
| Q: How to handle, when tkinter window gets focus I have this code:
from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
It prints hello world only once, and then it stops working. No more hello world Basically WM_TAKE_FOCUS does not work.
A: You can bind a function to the <FocusIn> event. When you bind to the root window the binding is applied to every widget in the root window, so if you only want to do something when the window as a whole gets focus you'll need to compare event.widget to the root window.
For example:
import Tkinter as tk
def handle_focus(event):
if event.widget == root:
print("I have gained the focus")
root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry1.pack()
entry2.pack()
root.bind("<FocusIn>", handle_focus)
root.mainloop()
A: "Note that WM_SAVE_YOURSELF is deprecated, and Tk apps can't implement WM_TAKE_FOCUS or _NET_WM_PING correctly, so WM_DELETE_WINDOW is the only one that should be used".
Here's a link!
If you need to keep tkinter focus all the time:
w.wm_attributes("-topmost", 1)
does a pretty good job.
| stackoverflow | {
"language": "en",
"length": 173,
"provenance": "stackexchange_0000F.jsonl.gz:887647",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613191"
} |
eca4f02e395628a3a4262a33e03d6192dbca8af3 | Stackoverflow Stackexchange
Q: How do I get log files from an deployed iOS app that is not crashed? I know that it is possible to get crash reports from an appstore customer, either using xcode -> organizer -> crash, or telling the customer to go to settings -> privacy -> diagnostics.
However, the app did not crash (just hangs) and there is no crash report created. I would like to get the regular console output of the app to gather some more informations. Is there a way to force the creation of a log file, either by iphone settings or by changing my app?
A: Try using this ios_deploy You will get all logs from the deployed app on device.
| Q: How do I get log files from an deployed iOS app that is not crashed? I know that it is possible to get crash reports from an appstore customer, either using xcode -> organizer -> crash, or telling the customer to go to settings -> privacy -> diagnostics.
However, the app did not crash (just hangs) and there is no crash report created. I would like to get the regular console output of the app to gather some more informations. Is there a way to force the creation of a log file, either by iphone settings or by changing my app?
A: Try using this ios_deploy You will get all logs from the deployed app on device.
| stackoverflow | {
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:887665",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613233"
} |
3b313f526c543a077169fe1d53e3215b9f7081be | Stackoverflow Stackexchange
Q: Elixir - How to convert keyword list to string? I have a keyword list: [key1: "value", key2: "value2", key3: "value3"]
I want to convert it into a string: "key1:value1&key2:value2&key3:value3"
I was thinking to use Enum.reduce, but what will be the arguments to the function?
A: Since you want to add a separator between the values after mapping them, I'd suggest using Enum.map_join/3:
iex(1)> list = [key1: "value", key2: "value2", key3: "value3"]
[key1: "value", key2: "value2", key3: "value3"]
iex(2)> list |> Enum.map_join("&", fn {k, v} -> "#{k}:#{v}" end)
"key1:value&key2:value2&key3:value3"
This is how you can do it with Enum.reduce/3 (There's an extra & inserted at the start which is being removed using String.trim_leading/1):
iex(3)> list |> Enum.reduce("", fn {k, v}, acc -> "#{acc}&#{k}:#{v}" end) |> String.trim_leading("&")
"key1:value&key2:value2&key3:value3"
| Q: Elixir - How to convert keyword list to string? I have a keyword list: [key1: "value", key2: "value2", key3: "value3"]
I want to convert it into a string: "key1:value1&key2:value2&key3:value3"
I was thinking to use Enum.reduce, but what will be the arguments to the function?
A: Since you want to add a separator between the values after mapping them, I'd suggest using Enum.map_join/3:
iex(1)> list = [key1: "value", key2: "value2", key3: "value3"]
[key1: "value", key2: "value2", key3: "value3"]
iex(2)> list |> Enum.map_join("&", fn {k, v} -> "#{k}:#{v}" end)
"key1:value&key2:value2&key3:value3"
This is how you can do it with Enum.reduce/3 (There's an extra & inserted at the start which is being removed using String.trim_leading/1):
iex(3)> list |> Enum.reduce("", fn {k, v}, acc -> "#{acc}&#{k}:#{v}" end) |> String.trim_leading("&")
"key1:value&key2:value2&key3:value3"
| stackoverflow | {
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:887678",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613261"
} |
6f4640297de6070387a2a9a4de243ef1bffc2ce7 | Stackoverflow Stackexchange
Q: Multidimensional array for random.choice in NumPy I have a table and I need to use random.choice for probability calculation,
for example (taken from docs):
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
dtype='|S11')
If I have 3D array instead of aa_milne_arr, it doesn't let me proceed. I need to generate random things with the different probabilities for the 3 arrays, but the same for elements inside of them. For example,
>>> arr0 = ['red', 'green', 'blue']
>>> arr1 = ['light', 'wind', 'sky']
>>> arr3 = ['chicken', 'wolf', 'dog']
>>> p = [0.5, 0.1, 0.4]
And I want the same probs for elements in arr0 (0.5), arr1 (0.1) and arr3 (0.4) so as a result I will see with the probability of 0.5 any element from arr0 etc.
Is it any elegant way to do it?
A: Divide values of p by the lengths of arrays and then repeat by the same lengths.
Then choose from concatenated array with new probabilities
arr = [arr0, arr1, arr3]
lens = [len(a) for a in arr]
p = [.5, .1, .4]
new_arr = np.concatenate(arr)
new_p = np.repeat(np.divide(p, lens), lens)
np.random.choice(new_arr, p=new_p)
| Q: Multidimensional array for random.choice in NumPy I have a table and I need to use random.choice for probability calculation,
for example (taken from docs):
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
dtype='|S11')
If I have 3D array instead of aa_milne_arr, it doesn't let me proceed. I need to generate random things with the different probabilities for the 3 arrays, but the same for elements inside of them. For example,
>>> arr0 = ['red', 'green', 'blue']
>>> arr1 = ['light', 'wind', 'sky']
>>> arr3 = ['chicken', 'wolf', 'dog']
>>> p = [0.5, 0.1, 0.4]
And I want the same probs for elements in arr0 (0.5), arr1 (0.1) and arr3 (0.4) so as a result I will see with the probability of 0.5 any element from arr0 etc.
Is it any elegant way to do it?
A: Divide values of p by the lengths of arrays and then repeat by the same lengths.
Then choose from concatenated array with new probabilities
arr = [arr0, arr1, arr3]
lens = [len(a) for a in arr]
p = [.5, .1, .4]
new_arr = np.concatenate(arr)
new_p = np.repeat(np.divide(p, lens), lens)
np.random.choice(new_arr, p=new_p)
A: Here is what I came with.
It takes either a vector of probabilities, or a matrix where the weights are organized in columns. The weights will be normalized to sum to 1.
import numpy as np
def choice_vect(source,weights):
# Draw N choices, each picked among K options
# source: K x N ndarray
# weights: K x N ndarray or K vector of probabilities
weights = np.atleast_2d(weights)
source = np.atleast_2d(source)
N = source.shape[1]
if weights.shape[0] == 1:
weights = np.tile(weights.transpose(),(1,N))
cum_weights = weights.cumsum(axis=0) / np.sum(weights,axis=0)
unif_draws = np.random.rand(1,N)
choices = (unif_draws < cum_weights)
bool_indices = choices > np.vstack( (np.zeros((1,N),dtype='bool'),choices ))[0:-1,:]
return source[bool_indices]
It avoids using loops and is like a vectorized version of random.choice.
You can then use it like that:
source = [[1,2],[3,4],[5,6]]
weights = [0.5, 0.4, 0.1]
choice_vect(source,weights)
>> array([3, 2])
weights = [[0.5,0.1],[0.4,0.4],[0.1,0.5]]
choice_vect(source,weights)
>> array([1, 4])
| stackoverflow | {
"language": "en",
"length": 340,
"provenance": "stackexchange_0000F.jsonl.gz:887707",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613347"
} |
4c00dd1c54bd3a63a53e85e377d5a55b13df3bc7 | Stackoverflow Stackexchange
Q: Symfony: make CSRF token available to all twig templates My app has AJAX requests here and there, and I want to protect them with CSRF tokens. However, rather than generating and passing a CSRF token to the Twig renderer for use in the JavaScript, I'd like a CSRF token to be readily available in every html page that Twig renders.
I've seen that Laravel seems to put it in a meta tag, so I can easily grab it with JavaScript. But how to do this in Symfony? How can I insert this token in every page?
Or is this not good practice?
A: Of course this is a good practice!!
You have the built-in function csrf_token('key') in symfony/twig for that.
Example:
<a href="{{ path('product_remove', {id: product.id, csrf: csrf_token('product') }) }}"
class="btn btn-info">Remove</a>
From a controller, you just have to check it:
/**
* @Route("/product/remove/{csrf}/{id}", name="product_remove")
*/
public function removeProductAction($csrf, $id)
{
if ($csrf !== $this->get('security.csrf.token_manager')->getToken('product')->getValue()) {
throw new InvalidCsrfTokenException('Invalid CSRF token');
}
// delete $id
// cleans up url
return $this->redirectToRoute('product_list');
}
| Q: Symfony: make CSRF token available to all twig templates My app has AJAX requests here and there, and I want to protect them with CSRF tokens. However, rather than generating and passing a CSRF token to the Twig renderer for use in the JavaScript, I'd like a CSRF token to be readily available in every html page that Twig renders.
I've seen that Laravel seems to put it in a meta tag, so I can easily grab it with JavaScript. But how to do this in Symfony? How can I insert this token in every page?
Or is this not good practice?
A: Of course this is a good practice!!
You have the built-in function csrf_token('key') in symfony/twig for that.
Example:
<a href="{{ path('product_remove', {id: product.id, csrf: csrf_token('product') }) }}"
class="btn btn-info">Remove</a>
From a controller, you just have to check it:
/**
* @Route("/product/remove/{csrf}/{id}", name="product_remove")
*/
public function removeProductAction($csrf, $id)
{
if ($csrf !== $this->get('security.csrf.token_manager')->getToken('product')->getValue()) {
throw new InvalidCsrfTokenException('Invalid CSRF token');
}
// delete $id
// cleans up url
return $this->redirectToRoute('product_list');
}
A: The answer: insert it as a twig global variable and then use Javascript to bind it to all requests.
config.yml
twig:
## ...
globals:
csrfTokenManager: '@security.csrf.token_manager'
base.html.twig
<script>
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-csrf-token', '{{ csrfTokenManager.getToken('ajaxAuth') }}');
});
</script>
Receiving controller
public function receiveAction (Request $request)
{
$tokenManager = $this->get('security.csrf.token_manager');
$tokenId = 'ajaxAuth';
$token = new CsrfToken($tokenId, $request->headers->get('x-csrf-token'));
if (!$tokenManager->isTokenValid($token)) {
throw new HttpException(403, 'Go away h4x0r');
}
}
| stackoverflow | {
"language": "en",
"length": 242,
"provenance": "stackexchange_0000F.jsonl.gz:887778",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613585"
} |
61db7ed1db29aa22bb04564b7cd53b8f09f18e5b | Stackoverflow Stackexchange
Q: ionic 3 - show rounded image I'm trying to set a round image at the top of a page (like a profile page). The image is rectangular and about 300x200. I've tried these ways:
1) Using the Ion-Avatar Tag
2) Using Ion-Image tag, setting the border radius in the scss
None of these methods worked. The image just kept showing squared (and eventually shrinked) inside a grey circle:
Any suggestions?
A: you can try with css
.image {
height: 5vw;
width: 5vw;
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 5px gray;
display: inline-block;
margin-left: auto;
margin-right: auto;
}
.circle-pic{
width:50px;
height:50px;
-webkit-border-radius: 50%;
border-radius: 50%;
}
<div class="image">
</div>
<p>or if you want only image try this</p>
<img class="circle-pic"
src="http://autokadabra.ru/system/uploads/users/18/18340/small.png?1318432918" />
| Q: ionic 3 - show rounded image I'm trying to set a round image at the top of a page (like a profile page). The image is rectangular and about 300x200. I've tried these ways:
1) Using the Ion-Avatar Tag
2) Using Ion-Image tag, setting the border radius in the scss
None of these methods worked. The image just kept showing squared (and eventually shrinked) inside a grey circle:
Any suggestions?
A: you can try with css
.image {
height: 5vw;
width: 5vw;
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 5px gray;
display: inline-block;
margin-left: auto;
margin-right: auto;
}
.circle-pic{
width:50px;
height:50px;
-webkit-border-radius: 50%;
border-radius: 50%;
}
<div class="image">
</div>
<p>or if you want only image try this</p>
<img class="circle-pic"
src="http://autokadabra.ru/system/uploads/users/18/18340/small.png?1318432918" />
A: In ionic 3, you can do this...
<ion-avatar>
<img src="">
</ion-avatar>
That simple
In some cases, you may need to set the img height and width to the same value manually. But this is the standard ionic 3 method.
https://ionicframework.com/docs/components/#avatar-list
| stackoverflow | {
"language": "en",
"length": 165,
"provenance": "stackexchange_0000F.jsonl.gz:887823",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613748"
} |
e31cf82952e90f0b8fc73a708183dd569aefa560 | Stackoverflow Stackexchange
Q: Autoplay YouTube Video Background Tiles Fiddle: https://codepen.io/anon/pen/ZyLqPd
Fiddle with YTVideos: https://codepen.io/anon/pen/KqXavy?editors=0100
http://www.seanmccambridge.com/tubular/
https://pupunzi.com/#mb.components/mb.YTPlayer/YTPlayer.html
Are there are libraries out there that easily enable adding a background youtube video to a div?
I've searched over and over and couldn't find anything.
Essentially I want to play a YouTube video as the background for the divs with the images in this screenshot.
$('.canvas .box').YTPlayer({
fitToBackground: true,
videoId: '-JlcxL2ux_A'
});
A: in your mockup the videos have a normal 16:9 aspect ratio, so that's what i went with instead of the squares you initially had. here are the tweaks:
https://codepen.io/saetia/full/BZwWdx/
video boxes
<div class="ib box">
<div class="responsive"><iframe src="https://www.youtube.com/embed/8nH-49PgKdw?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=W0LHTWG-UmQ" frameborder="0" allowfullscreen></iframe></div>
</div>
styles
.canvas .box {
display: inline-block;
width: 25%;
pointer-events: none;
}
.canvas .box .responsive {
position: relative;
height: 0;
overflow: hidden;
padding-bottom: 56.25%;
}
.canvas .box iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
| Q: Autoplay YouTube Video Background Tiles Fiddle: https://codepen.io/anon/pen/ZyLqPd
Fiddle with YTVideos: https://codepen.io/anon/pen/KqXavy?editors=0100
http://www.seanmccambridge.com/tubular/
https://pupunzi.com/#mb.components/mb.YTPlayer/YTPlayer.html
Are there are libraries out there that easily enable adding a background youtube video to a div?
I've searched over and over and couldn't find anything.
Essentially I want to play a YouTube video as the background for the divs with the images in this screenshot.
$('.canvas .box').YTPlayer({
fitToBackground: true,
videoId: '-JlcxL2ux_A'
});
A: in your mockup the videos have a normal 16:9 aspect ratio, so that's what i went with instead of the squares you initially had. here are the tweaks:
https://codepen.io/saetia/full/BZwWdx/
video boxes
<div class="ib box">
<div class="responsive"><iframe src="https://www.youtube.com/embed/8nH-49PgKdw?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=W0LHTWG-UmQ" frameborder="0" allowfullscreen></iframe></div>
</div>
styles
.canvas .box {
display: inline-block;
width: 25%;
pointer-events: none;
}
.canvas .box .responsive {
position: relative;
height: 0;
overflow: hidden;
padding-bottom: 56.25%;
}
.canvas .box iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
| stackoverflow | {
"language": "en",
"length": 147,
"provenance": "stackexchange_0000F.jsonl.gz:887824",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613749"
} |
ff7d377a9a64b5152235576d9a92bf68dc2f26c2 | Stackoverflow Stackexchange
Q: How to change Android application name in Xamarin.Forms? I am working with Xamarin.Forms in Visual Studio For Mac and I have created a very basic Xamarin.Forms application.
I have checked Android and iOS targets. I got 3 projects:
*
*A common project
*An iOS specific project
*And a Droid specific project.
The Android specific application has a ".Droid" suffix in application name.
So I decided to right click on droid project, and to remove this suffix in "Assembly name" field.
I got an exception where I run the app (at startup). If I change Assembly name again to put the droid suffix, it does not work anymore.
You can try this with a blank project with the latest version of Xamarin.Forms.
I do not understand why?
A: The problem is that you are changing the assembly name of your application, not the name.
If you want to change the application name in Xamarin.Forms Android you have two options:
*
*Go to your MainActivity and change the Label property:
*
*Or remove the Label of the MainActivity and add the name in the Manifest.xml via UI or code:
On iOS you must change it in Info.plist.
| Q: How to change Android application name in Xamarin.Forms? I am working with Xamarin.Forms in Visual Studio For Mac and I have created a very basic Xamarin.Forms application.
I have checked Android and iOS targets. I got 3 projects:
*
*A common project
*An iOS specific project
*And a Droid specific project.
The Android specific application has a ".Droid" suffix in application name.
So I decided to right click on droid project, and to remove this suffix in "Assembly name" field.
I got an exception where I run the app (at startup). If I change Assembly name again to put the droid suffix, it does not work anymore.
You can try this with a blank project with the latest version of Xamarin.Forms.
I do not understand why?
A: The problem is that you are changing the assembly name of your application, not the name.
If you want to change the application name in Xamarin.Forms Android you have two options:
*
*Go to your MainActivity and change the Label property:
*
*Or remove the Label of the MainActivity and add the name in the Manifest.xml via UI or code:
On iOS you must change it in Info.plist.
A: For android
make the change in android folder, mainactivity.cs
[Activity(Label = "Myappname", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
Fos iOS
make the following in change in the info.plist
Bundle display name to Myappname
A: Other answer works fine.
But I am adding more details .
Application name is picked from AndroidManifest.xml file i.e. <application android:label=@string/app_name , which in turn refers to values>strings.xml file . Do not hard code app name here. Its good practice separate all strings used in strings.xml file.
strings.xml
<resources>
<string name="app_name">App Name</string>
</resources>
Label property overrides this and sets the app title , apk name to Label value set inside MainActivity.
Its preferable to delete Label value from MainActivity.cs's assembly directive [Activity (as it overrides this manifest value at debug time) change the value in strings.xml so that its global and consistent.
A: //Change the Xamarin Forms Android Application Name
[Activity(Label = "ApplicationName", Icon = "@mipmap/icon", Theme =
"@style/splashscreen", LaunchMode = LaunchMode.SingleTop, MainLauncher = true,
ScreenOrientation = ScreenOrientation.Portrait,ConfigurationChanges =
ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode |
ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
//In IOS , we can change the name of Application in info.plist
Double click in info.plist , change Application Name
| stackoverflow | {
"language": "en",
"length": 398,
"provenance": "stackexchange_0000F.jsonl.gz:887889",
"question_score": "29",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44613974"
} |
480f45415dbb1840cca3742bf3176371745483fe | Stackoverflow Stackexchange
Q: Amazon S3 Error: The specified bucket exists in another region I'm just setting up a simple splash page basic static HTML and I decided to put it on S3.
my bucket name is called the same as my domain
www.example.com.s3-website.eu-west-2.amazonaws.com/
And then I've got a CNAME set to the same thing.
the only problem is i'm getting a 400 error from Amazon S3
400 Bad Request
Code: IncorrectEndpoint
Message: The specified bucket exists in another region. Please direct
requests to the specified endpoint.
I've checked and my bucket is definitely EU West and this is the endpoint it's given me when serving a static site.
A: You can check your bucket location through the following command.
aws s3api get-bucket-location --bucket {bucketname}
Could it be, that your bucket is located in eu-west-1 instead of eu-west-2?
| Q: Amazon S3 Error: The specified bucket exists in another region I'm just setting up a simple splash page basic static HTML and I decided to put it on S3.
my bucket name is called the same as my domain
www.example.com.s3-website.eu-west-2.amazonaws.com/
And then I've got a CNAME set to the same thing.
the only problem is i'm getting a 400 error from Amazon S3
400 Bad Request
Code: IncorrectEndpoint
Message: The specified bucket exists in another region. Please direct
requests to the specified endpoint.
I've checked and my bucket is definitely EU West and this is the endpoint it's given me when serving a static site.
A: You can check your bucket location through the following command.
aws s3api get-bucket-location --bucket {bucketname}
Could it be, that your bucket is located in eu-west-1 instead of eu-west-2?
A: I didn't manage to solve the wrong region problem, however, I created a cloudfront distrubution and set a CNAME to that instead.
| stackoverflow | {
"language": "en",
"length": 158,
"provenance": "stackexchange_0000F.jsonl.gz:887900",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614009"
} |
a98d0f0e6430a72cf3ee4aa819d5fe9e6c8536c7 | Stackoverflow Stackexchange
Q: Use pre-trained word2vec in lstm language model? I used tensorflow to train LSTM language model, code is from here.
According to article here, it seems that if I use pre-trained word2vec, it works better.
Using word embeddings such as word2vec and GloVe is a popular method to improve the accuracy of your model. Instead of using one-hot vectors to represent our words, the low-dimensional vectors learned using word2vec or GloVe carry semantic meaning – similar words have similar vectors. Using these vectors is a form of pre-training.
So, I want to use word2vec to redo the training, but I am a little bit confused about how to do this.
The embedding code goes here:
with tf.device("/cpu:0"):
embedding = tf.get_variable(
"embedding", [vocab_size, size], dtype=data_type())
inputs = tf.nn.embedding_lookup(embedding, input_.input_data)
How can I change this code to use pre-trained word2vec?
| Q: Use pre-trained word2vec in lstm language model? I used tensorflow to train LSTM language model, code is from here.
According to article here, it seems that if I use pre-trained word2vec, it works better.
Using word embeddings such as word2vec and GloVe is a popular method to improve the accuracy of your model. Instead of using one-hot vectors to represent our words, the low-dimensional vectors learned using word2vec or GloVe carry semantic meaning – similar words have similar vectors. Using these vectors is a form of pre-training.
So, I want to use word2vec to redo the training, but I am a little bit confused about how to do this.
The embedding code goes here:
with tf.device("/cpu:0"):
embedding = tf.get_variable(
"embedding", [vocab_size, size], dtype=data_type())
inputs = tf.nn.embedding_lookup(embedding, input_.input_data)
How can I change this code to use pre-trained word2vec?
| stackoverflow | {
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:887930",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614097"
} |
3e7a1ac70b0d38fbfe69dc838241a3f89ac81d93 | Stackoverflow Stackexchange
Q: When does Angular trigger ngAfterContentChecked? According to the docs the AfterContentChecked lifecycle hook is triggered:
after Angular checks the content projected into the component
What does "Angular checks" in the documentation mean, exactly?
A: AfterContentChecked, component-only hook, is called after Angular checks the content projected into the component (it's data-bound properties).
When does Angular check the projected content?
*
*Initially, after the AfterContentInit hook finishes.
*Every time the change detection is run (application state change).
What causes the application state change?
*
*Events - click, submit, …
*Ajax calls - fetching data from a remote server
*Timers - setTimeout, setInterval
See also: Angular change detection explained.
| Q: When does Angular trigger ngAfterContentChecked? According to the docs the AfterContentChecked lifecycle hook is triggered:
after Angular checks the content projected into the component
What does "Angular checks" in the documentation mean, exactly?
A: AfterContentChecked, component-only hook, is called after Angular checks the content projected into the component (it's data-bound properties).
When does Angular check the projected content?
*
*Initially, after the AfterContentInit hook finishes.
*Every time the change detection is run (application state change).
What causes the application state change?
*
*Events - click, submit, …
*Ajax calls - fetching data from a remote server
*Timers - setTimeout, setInterval
See also: Angular change detection explained.
| stackoverflow | {
"language": "en",
"length": 107,
"provenance": "stackexchange_0000F.jsonl.gz:887937",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614108"
} |
246b1e6c6d3113da753d778aa15f21de45743156 | Stackoverflow Stackexchange
Q: log4net: Could not load type 'log4net.Appender.AdoNetAppender' I have a problem with the AdoNetAppender of log4net in my ASP.NET Core application (netcoreapp1.1).
If I want to use the AdoNetAppender, I get the following error:
System.TypeLoadException: Could not load type 'log4net.Appender.AdoNetAppender' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
Is there anybody who have the AdoNetAppender running under ASP.NET Core (netcoreapp1.1)? If not, is there a good alternative to log with log4net into a database? I also use Entity Framework Core.
A: The AdoNetAppender isn't supported at present on .NET Core 1.0 / .NET Standard 1.3: https://logging.apache.org/log4net/release/framework-support.html#Appenders
| Q: log4net: Could not load type 'log4net.Appender.AdoNetAppender' I have a problem with the AdoNetAppender of log4net in my ASP.NET Core application (netcoreapp1.1).
If I want to use the AdoNetAppender, I get the following error:
System.TypeLoadException: Could not load type 'log4net.Appender.AdoNetAppender' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
Is there anybody who have the AdoNetAppender running under ASP.NET Core (netcoreapp1.1)? If not, is there a good alternative to log with log4net into a database? I also use Entity Framework Core.
A: The AdoNetAppender isn't supported at present on .NET Core 1.0 / .NET Standard 1.3: https://logging.apache.org/log4net/release/framework-support.html#Appenders
A: For .Net Core you can use nuget.org/packages/MicroKnights.Log4NetAdoNetAppender . It has a bit differences in set up compare to AdoNetAppender, but is very straightforward too, to Find how to set it up here: github.com/microknights/Log4NetAdoNetAppender
Here an example that works for me
<appender name="AdoNetAppender" type="MicroKnights.Logging.AdoNetAppender, MicroKnights.Log4NetAdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection,System.Data.SqlClient,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<connectionStringName value="log4net" />
<connectionStringFile value="appsettings.json" />
<commandText value="INSERT INTO Log ....." />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
and in your appsettings.json
"ConnectionStrings": {
"log4net": "Data Source=.\\SQLEXPRESS;Initial Catalog=LogDB;User ID=user;Password=pass",
}
| stackoverflow | {
"language": "en",
"length": 263,
"provenance": "stackexchange_0000F.jsonl.gz:887961",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614188"
} |
5fb2d6aee1bda346a0476be35a54ac719617d2f7 | Stackoverflow Stackexchange
Q: How to make function that some parameters not required in when call it in iOS Swift 3? I wanna make function without some required parameters like this:
func myMethod(Name name:String,Age age:Int){
print(name)
}
//call
myMethod(Name:"Donald")
Is this can be?
A: You just have to make them nilable.
func myMethod(name name: String? = nil, age age: Int? = nil) {
print(name!)
}
Notice: when yo make parameters optional, you have to be careful about how to unwrap them. usually using if let syntax is helpful.
func myMethod(name name: String? = nil, age age: Int? = nil) {
if let name = name {
print(name)
}
}
you can also provide default value for them:
func myMethod(name name: String? = "Donald", age age: Int? = 10) {
print(name!)
}
| Q: How to make function that some parameters not required in when call it in iOS Swift 3? I wanna make function without some required parameters like this:
func myMethod(Name name:String,Age age:Int){
print(name)
}
//call
myMethod(Name:"Donald")
Is this can be?
A: You just have to make them nilable.
func myMethod(name name: String? = nil, age age: Int? = nil) {
print(name!)
}
Notice: when yo make parameters optional, you have to be careful about how to unwrap them. usually using if let syntax is helpful.
func myMethod(name name: String? = nil, age age: Int? = nil) {
if let name = name {
print(name)
}
}
you can also provide default value for them:
func myMethod(name name: String? = "Donald", age age: Int? = 10) {
print(name!)
}
| stackoverflow | {
"language": "en",
"length": 128,
"provenance": "stackexchange_0000F.jsonl.gz:887971",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614225"
} |
e0b35a8e99f6cdae30f6e8a34d808d06ae7ace21 | Stackoverflow Stackexchange
Q: Numpy, apply a list of functions along array dimension I have a list of functions of the type:
func_list = [lambda x: function1(input),
lambda x: function2(input),
lambda x: function3(input),
lambda x: x]
and an array of shape [4, 200, 200, 1] (a batch of images).
I want to apply the list of functions, in order, along the 0th axis.
EDIT: Rephrasing the problem. This is equivalent to the above. Say, instead of the array, I have a tuple of 4 identical arrays, of shape (200, 200, 1), and I want to apply function1 on the first element, function2 on the second element, etc. Can this be done without a for loop?
A: You can iterate over your function list using np.apply_along_axis:
import numpy as np
x = np.ranom.randn(100, 100)
for f in fun_list:
x = np.apply_along_axis(f, 0, x)
Based on OP's Update
Assuming your functions and batches are the same in size:
batch = ... # tuple of 4 images
batch_out = tuple([np.apply_along_axis(f, 0, x) for f, x in zip(fun_list, batch)])
| Q: Numpy, apply a list of functions along array dimension I have a list of functions of the type:
func_list = [lambda x: function1(input),
lambda x: function2(input),
lambda x: function3(input),
lambda x: x]
and an array of shape [4, 200, 200, 1] (a batch of images).
I want to apply the list of functions, in order, along the 0th axis.
EDIT: Rephrasing the problem. This is equivalent to the above. Say, instead of the array, I have a tuple of 4 identical arrays, of shape (200, 200, 1), and I want to apply function1 on the first element, function2 on the second element, etc. Can this be done without a for loop?
A: You can iterate over your function list using np.apply_along_axis:
import numpy as np
x = np.ranom.randn(100, 100)
for f in fun_list:
x = np.apply_along_axis(f, 0, x)
Based on OP's Update
Assuming your functions and batches are the same in size:
batch = ... # tuple of 4 images
batch_out = tuple([np.apply_along_axis(f, 0, x) for f, x in zip(fun_list, batch)])
A: I tried @Coldspeed's answer, and it does work (so I will accept it) but here is an alternative I found, without using for loops:
result = tuple(map(lambda x,y:x(y), functions, image_tuple))
Edit: forgot to add the tuple(), thanks @Coldspeed
| stackoverflow | {
"language": "en",
"length": 211,
"provenance": "stackexchange_0000F.jsonl.gz:887981",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614254"
} |
fd1fc4edc2ffd409640981487b3ce36d2c3be10c | Stackoverflow Stackexchange
Q: Implement a read receipt feature in Firebase group messaging app I'd like to implement a 'Seen' feature in my Firebase group messaging app. Can you kindly advise the best and most efficient approach to take (working code will be appreciated)? For example, the app would show "Seen by 6" or "Seen by 15" on a group message.
Here's my project: https://github.com/firebase/friendlychat/tree/master/android
Here's the MainActivity: https://github.com/firebase/friendlychat/blob/master/android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.java
A: Yeah it is possible, You can add a child seen_by to the message, whenever user views the message append the viewers userId to the seen_by , then by retrieving the userID and you can count the number of viewers and also you can see the list of viewed members too. The format should be
message:{
FirebaseKey:{
message:"hi",
timestamp:1498472455940,
seen_by:"abc,def,ghi" //users UID
}
}
| Q: Implement a read receipt feature in Firebase group messaging app I'd like to implement a 'Seen' feature in my Firebase group messaging app. Can you kindly advise the best and most efficient approach to take (working code will be appreciated)? For example, the app would show "Seen by 6" or "Seen by 15" on a group message.
Here's my project: https://github.com/firebase/friendlychat/tree/master/android
Here's the MainActivity: https://github.com/firebase/friendlychat/blob/master/android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.java
A: Yeah it is possible, You can add a child seen_by to the message, whenever user views the message append the viewers userId to the seen_by , then by retrieving the userID and you can count the number of viewers and also you can see the list of viewed members too. The format should be
message:{
FirebaseKey:{
message:"hi",
timestamp:1498472455940,
seen_by:"abc,def,ghi" //users UID
}
}
A: To achieve this, you need to add another node in your Firebase database named seenBy which must be nested under each messageId in meassage section. Your database should look like this:
Firebase-root
|
---- messages
|
---- messageId1
|
---- meessage: "Hello!"
|
---- timestamp: 1498472455940
|
---- seenBy
|
---- userUid1: John
|
---- userUid2: Mary
|
---- userUid3: George
Every time a new user opens a meesage, just add the uid and the name as explained above.
To implement Seen by 6 option, it's very easy. You just need to create a listener and use getChildrenCount() method like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference seenByRef = rootRef.child("messages").child(messageId).child("seenBy");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long seenBy = dataSnapshot.getChildrenCount();
Lod.d("TAG", "Seen by: " + seenBy);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
seenByRef.addListenerForSingleValueEvent(eventListener);
To know whether a message has been opened or not, you need to add another field to your user section in which you need to add a boolean with the default value of false. This new section should look like this:
Firebase-root
|
---- users
|
---- userId1
|
---- meessages
|
---- messageId1: false
|
---- messageId2: false
|
---- messageId3: false
When a users opens that message, just set the value of that particular message from false to true, which means that the particular message has been opened. This is the code:
DatabaseReference openedRef = rootRef.child("users").child(userId).child("meessages").child("messageId1");
openedRef.setValue(true);
When you create a message, use push() method on the reference like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messageRef = rootRef.child("meessages").push();
String messageKey = messageRef.getKey();
Having this key, you can use it in your DatabaseReference. In the same way you can use for the userId.
Hope it helps.
| stackoverflow | {
"language": "en",
"length": 418,
"provenance": "stackexchange_0000F.jsonl.gz:887996",
"question_score": "12",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614301"
} |
aa15bdb657fb66234944de289973ab9519f28724 | Stackoverflow Stackexchange
Q: Run Jest test and collect coverage from all files in a specific directory I am using the following code to run Jest test on specific file.
jest utils.spec.js --collectCoverageFrom=**/utils.js
If i want to test whole directory i use
jest someDirectory --collectCoverageFrom=**/someDirectory
But the code coverage does not work here why is so?
Thanks.
A: You need to add this pattern /**/*.js, that match all the files in all sub directories:
jest someDirectory --collectCoverageFrom=**/someDirectory/**/*.js
| Q: Run Jest test and collect coverage from all files in a specific directory I am using the following code to run Jest test on specific file.
jest utils.spec.js --collectCoverageFrom=**/utils.js
If i want to test whole directory i use
jest someDirectory --collectCoverageFrom=**/someDirectory
But the code coverage does not work here why is so?
Thanks.
A: You need to add this pattern /**/*.js, that match all the files in all sub directories:
jest someDirectory --collectCoverageFrom=**/someDirectory/**/*.js
| stackoverflow | {
"language": "en",
"length": 74,
"provenance": "stackexchange_0000F.jsonl.gz:888013",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614353"
} |
988e14ae7ef1f3a78480dcb901748bfdaffb7767 | Stackoverflow Stackexchange
Q: Take Panoramic photo in Ionic In Ionic 3.4.0 and am able to take a single photo with it being saved to the library on iOS. I would like to take Pano photos on iOS. How can I do that?
| Q: Take Panoramic photo in Ionic In Ionic 3.4.0 and am able to take a single photo with it being saved to the library on iOS. I would like to take Pano photos on iOS. How can I do that?
| stackoverflow | {
"language": "en",
"length": 40,
"provenance": "stackexchange_0000F.jsonl.gz:888016",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614370"
} |
dceb767fb6e57ea9095bd28f23c9ebed21134115 | Stackoverflow Stackexchange
Q: facebook api: event url lets say I know I have an event ID. I would like the event URL (to link users to it), but the graph API does not seem to have it (https://developers.facebook.com/docs/graph-api/reference/event/), for example if I use the command GET /v2.9/310917539364835 HTTP/1.1 the output is:
{
"description": "...",
"end_time": "2017-06-23T22:30:00+1000",
"name": "UQ Postgrad Masquerade Party (End of Semester)",
"place": {
"name": "Cloudland",
"location": {
"city": "Brisbane",
"country": "Australia",
"latitude": -27.45891,
"longitude": 153.0349699,
"state": "QLD",
"street": "641 Ann Street",
"zip": "4006"
},
"id": "103221159774910"
},
"start_time": "2017-06-23T19:30:00+1000",
"id": "310917539364835"
}
but there is not URL.
Thanks
A: after doing some searching, it turns out that the URL is:
facebook.com/ + ID
so in this example. facebook.com/310917539364835
| Q: facebook api: event url lets say I know I have an event ID. I would like the event URL (to link users to it), but the graph API does not seem to have it (https://developers.facebook.com/docs/graph-api/reference/event/), for example if I use the command GET /v2.9/310917539364835 HTTP/1.1 the output is:
{
"description": "...",
"end_time": "2017-06-23T22:30:00+1000",
"name": "UQ Postgrad Masquerade Party (End of Semester)",
"place": {
"name": "Cloudland",
"location": {
"city": "Brisbane",
"country": "Australia",
"latitude": -27.45891,
"longitude": 153.0349699,
"state": "QLD",
"street": "641 Ann Street",
"zip": "4006"
},
"id": "103221159774910"
},
"start_time": "2017-06-23T19:30:00+1000",
"id": "310917539364835"
}
but there is not URL.
Thanks
A: after doing some searching, it turns out that the URL is:
facebook.com/ + ID
so in this example. facebook.com/310917539364835
| stackoverflow | {
"language": "en",
"length": 119,
"provenance": "stackexchange_0000F.jsonl.gz:888017",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614371"
} |
b010250eec70d30c5a4c3fdeea25a695324e77ab | Stackoverflow Stackexchange
Q: How can I make bcrypt in php and jbcrypt in java compatible I want to make register page in php and make the password hashed with bcrypt and put in database.
I also want to make a login system in Java, and get the password in the same password, using jbcrypt.
How can I make jbcrypt and bcrypt in php compatible, with the same salt.
A: you can check out this:
https://github.com/ircmaxell/password_compat/issues/49
that's worked for me:
public static void main(String[] args) {
//Laravel bcrypt out
String hash_php = "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO".replaceFirst("2y", "2a");
System.out.println("hash php " + hash_php);
//String a_hash = BCrypt.hashpw("123456", BCrypt.gensalt());
//System.out.println("Encrypt " + a_hash);
if (BCrypt.checkpw("123456", hash_php)) {
System.out.println("It matches");
} else {
System.out.println("It does not match");
}
//mtPruebaRecuperarClave();
}
Console - OutPut
I hope that's help You.
| Q: How can I make bcrypt in php and jbcrypt in java compatible I want to make register page in php and make the password hashed with bcrypt and put in database.
I also want to make a login system in Java, and get the password in the same password, using jbcrypt.
How can I make jbcrypt and bcrypt in php compatible, with the same salt.
A: you can check out this:
https://github.com/ircmaxell/password_compat/issues/49
that's worked for me:
public static void main(String[] args) {
//Laravel bcrypt out
String hash_php = "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO".replaceFirst("2y", "2a");
System.out.println("hash php " + hash_php);
//String a_hash = BCrypt.hashpw("123456", BCrypt.gensalt());
//System.out.println("Encrypt " + a_hash);
if (BCrypt.checkpw("123456", hash_php)) {
System.out.println("It matches");
} else {
System.out.println("It does not match");
}
//mtPruebaRecuperarClave();
}
Console - OutPut
I hope that's help You.
A: The problem is that PHP with it's password_hash() has it's own version scheme due to the fact that previous implementations had breaking bugs and it should be possible to recognize the old hashes.
So the version used by OpenBSD is $2a$ (will be $2b$ in future releases) and password_hash() uses $2y$ (previously $2x$), so of course the has will not match e.g.
$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
vs
$2a$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
(see the wikipedia article about more info on the versions)
Currently jBcrypt (0.4) only supports $2a$.
There are 2 possibilities:
1. Replace the version identifier manually before passing it to jBcrypt (hack)
String hash_php = "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO".replaceFirst("$2y$", "$2a$");
2. Using a different implemention supporting custom version identifier
This is the reason I implemented a new library for bcrypt (based on jBcrypt). https://github.com/patrickfav/bcrypt
Just use it like this (it does not verify for version per default, you can use verifyStrict() in that case)
BCrypt.Result result = BCrypt.verifyer().verify(password.toCharArray(), "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO")
if(result.verified) {...}
If you want bcrypt to create $2y$ hashes:
String bcryptHash = BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(6, password.toCharArray());
// $2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
Full Disclaimer: Im the author of bcrypt
A: If you remove the first 7 chars from the hashes ($2y$10$ / $2a$10$) the rest should be the same regardless of the programming language you have used. The first characters of the generated hash is a prefix that tells more about the hash algorithm.
In your example, the $2y$ and $a2$ are defining the algorithm of the hash, and the 10$ is the "cost" of the hash generation (how many times the hash algorithm was repeatedly applied or something like this).
If you want to learn more about the prefixes in the bcrypt generated hashes, read this article.
| stackoverflow | {
"language": "en",
"length": 404,
"provenance": "stackexchange_0000F.jsonl.gz:888020",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614380"
} |
d6dc9a05dada05a804c5aa7a9dd0925a9b5bd35c | Stackoverflow Stackexchange
Q: Class incorrectly implements interface 'OnChanges'. Property 'ngOnChanges' is missing in type I basically started using angular 4 and and working with the ngChanges I'm getting this error
Class 'GalleryComponent' incorrectly implements interface
'OnChanges'.Property 'ngOnChanges' is missing in type
'GalleryComponent'.
I don't really know what to do, I know that a class can have multiples interfaces but event using just one it shows the same error
import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { ImageService } from '../image/shared/image.service';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit, OnChanges {
visibleImages: any[] = [];
constructor(private imageService: ImageService) {
this.visibleImages = this.imageService.getImages();
}
ngOnInit() {}
OnChanges(){}
}
I'll be so thankful if anybody can notice what I'm missing
thanks in advance
A: First issue is function name:
OnChanges(){}
To
ngOnChanges(changes: SimpleChanges){}
You need to add parameter in ngOnChanges function changes: SimpleChanges
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
Please read this :
https://angular.io/api/core/OnChanges
| Q: Class incorrectly implements interface 'OnChanges'. Property 'ngOnChanges' is missing in type I basically started using angular 4 and and working with the ngChanges I'm getting this error
Class 'GalleryComponent' incorrectly implements interface
'OnChanges'.Property 'ngOnChanges' is missing in type
'GalleryComponent'.
I don't really know what to do, I know that a class can have multiples interfaces but event using just one it shows the same error
import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { ImageService } from '../image/shared/image.service';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit, OnChanges {
visibleImages: any[] = [];
constructor(private imageService: ImageService) {
this.visibleImages = this.imageService.getImages();
}
ngOnInit() {}
OnChanges(){}
}
I'll be so thankful if anybody can notice what I'm missing
thanks in advance
A: First issue is function name:
OnChanges(){}
To
ngOnChanges(changes: SimpleChanges){}
You need to add parameter in ngOnChanges function changes: SimpleChanges
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
Please read this :
https://angular.io/api/core/OnChanges
| stackoverflow | {
"language": "en",
"length": 164,
"provenance": "stackexchange_0000F.jsonl.gz:888083",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614572"
} |
b302a0987cbee2ff925990cc62201ac807142b98 | Stackoverflow Stackexchange
Q: RDS: RemoteApp notifications icon is not visible I'm using Windows Server 2016 for Remote Desktop Services (RDS) the applications I've published are working fine. I've created a logon script so that my windows application starts when a user establishes RDS session. My problem is when a user logs in and my application runs automatically it doesn't show icon notification in system tray. I've gone through the below link and added the registry key which fixed the issue but it had also shown all unwanted application's icon as well.
https://social.technet.microsoft.com/Forums/lync/en-US/4122521f-7896-4098-a723-858077a243f1/remoteapp-notification-area-icons-not-visable?forum=winserverTS
Is there any way that I could programmatically dictate "rdpshell" to show only my application icon? or if there is any registry key specifically I could use for my application? or anything that I could use to show my application icon only?
Thanks.
| Q: RDS: RemoteApp notifications icon is not visible I'm using Windows Server 2016 for Remote Desktop Services (RDS) the applications I've published are working fine. I've created a logon script so that my windows application starts when a user establishes RDS session. My problem is when a user logs in and my application runs automatically it doesn't show icon notification in system tray. I've gone through the below link and added the registry key which fixed the issue but it had also shown all unwanted application's icon as well.
https://social.technet.microsoft.com/Forums/lync/en-US/4122521f-7896-4098-a723-858077a243f1/remoteapp-notification-area-icons-not-visable?forum=winserverTS
Is there any way that I could programmatically dictate "rdpshell" to show only my application icon? or if there is any registry key specifically I could use for my application? or anything that I could use to show my application icon only?
Thanks.
| stackoverflow | {
"language": "en",
"length": 133,
"provenance": "stackexchange_0000F.jsonl.gz:888091",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614600"
} |
2de2caf377d7198024ac2dbe592e567c7c074b1e | Stackoverflow Stackexchange
Q: What is the position embedding in the convolutional sequence to sequence learning model? I don't understand the position embedding in paper Convolutional Sequence to Sequence Learning, anyone can help me?
A: From what I understand, for each word to translate, the input contains both the word itself and its position in the input chain (say, 0, 1, ...m).
Now, encoding such a data with simply having a cell with value pos (in 0..m) would not perform very well (for the same reason we use one-hot vectors to encode words). So, basically, the position will be encoded in a number of input cells, with one-hot representation (or similar, I might think of a binary representation of the position being used).
Then, an embedding layer will be used (just as it is used for word encodings) to transform this sparse and discrete representation into a continuous one.
The representation used in the paper chose to have the same dimension for the word embedding and the position embedding and to simply sum up the two.
| Q: What is the position embedding in the convolutional sequence to sequence learning model? I don't understand the position embedding in paper Convolutional Sequence to Sequence Learning, anyone can help me?
A: From what I understand, for each word to translate, the input contains both the word itself and its position in the input chain (say, 0, 1, ...m).
Now, encoding such a data with simply having a cell with value pos (in 0..m) would not perform very well (for the same reason we use one-hot vectors to encode words). So, basically, the position will be encoded in a number of input cells, with one-hot representation (or similar, I might think of a binary representation of the position being used).
Then, an embedding layer will be used (just as it is used for word encodings) to transform this sparse and discrete representation into a continuous one.
The representation used in the paper chose to have the same dimension for the word embedding and the position embedding and to simply sum up the two.
A: From what I perceive, the position embedding is still the procedure of building a low dimension representation for the one-hot vectors. Whereas this time the dimension of the one-hot vector is the length of the sentence. BTY, I think whether placing the 'one hot' in position order really doesn't matter. It just gives the model a sense of 'position awareness'.
A: From what I have understood so far is for each word in the sentence they have 2 vectors:
*
*One hot encoding vector to encode the word.
*One hot encoding vector to encode the position of the word in the sentence.
Both of these vectors are now passed separately as input and they embed both the inputs into f dimensional space. Once they had activation values from both the inputs which ∈ R^f. They just add these activations to obtain a combined input element representation.
A: I think khaemuaset's answer is correct.
To reinforce: As I understand from the paper (I'm reading A Convolutional Encoder Model for Machine Translation) and the corresponding Facebook AI Research PyTorch source code, the position embedding is a typical embedding table, but for seq position one-hot vectors instead of vocab one-hot vectors. I verified this with the source code here. Notice the inheritance of nn.Embedding and the call to its forward method at line 32.
The class I linked to is used in the FConvEncoder here.
| stackoverflow | {
"language": "en",
"length": 406,
"provenance": "stackexchange_0000F.jsonl.gz:888093",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614603"
} |
1b6c21e5903115504c6c3457e4ce22e7de3688f3 | Stackoverflow Stackexchange
Q: YouTube artist charts api? Does YouTube expose it's artist charts via api or is there a way to get the charts data using the youtube api?
I'm talking about the charts data here https://artists.youtube.com/charts/videos
A: I don't think it's possible using the official Youtube API, if we look at https://artists.youtube.com/charts/videos, it uses YouTube Internal API (InnerTube) with a specific API key (registered to use youtubei API which is not available to developers)
Of course it's a hack just FYI
The API key has https://artists.youtube.com configured as referer, adding the custom header: x-referer:https://artists.youtube.com make it works :
curl -H 'Content-Type: application/json' \
-H "x-referer:https://artists.youtube.com" \
"https://content.googleapis.com/youtubei/v1/browse?alt=json&key=AIzaSyCzEW7JUJdSql0-2V4tHUb6laYm4iAE_dM" \
-d '{
"context": {
"client": {
"clientName": "WEB_MUSIC_ANALYTICS",
"clientVersion": "0.2",
"theme": "MUSIC",
"hl": "en",
"gl": "FR",
"experimentIds": []
},
"capabilities": {
},
"request": {
"internalExperimentFlags": []
}
},
"browseId": "FEmusic_analytics",
"query": "chart_params_type=WEEK&perspective=CHART&flags=viral_video_chart&selected_chart=VIRAL_VIDEOS"
}'
If it doesn't work, get the API key from the network log of https://artists.youtube.com
In the query field, you can modify the selected_chart parameter :
*
*all video :
selected_chart=VIDEOS
*viral videos chart :
selected_chart=VIRAL_VIDEOS
*artists :
selected_chart=ARTISTS
*tracks :
selected_chart=TRACKS
| Q: YouTube artist charts api? Does YouTube expose it's artist charts via api or is there a way to get the charts data using the youtube api?
I'm talking about the charts data here https://artists.youtube.com/charts/videos
A: I don't think it's possible using the official Youtube API, if we look at https://artists.youtube.com/charts/videos, it uses YouTube Internal API (InnerTube) with a specific API key (registered to use youtubei API which is not available to developers)
Of course it's a hack just FYI
The API key has https://artists.youtube.com configured as referer, adding the custom header: x-referer:https://artists.youtube.com make it works :
curl -H 'Content-Type: application/json' \
-H "x-referer:https://artists.youtube.com" \
"https://content.googleapis.com/youtubei/v1/browse?alt=json&key=AIzaSyCzEW7JUJdSql0-2V4tHUb6laYm4iAE_dM" \
-d '{
"context": {
"client": {
"clientName": "WEB_MUSIC_ANALYTICS",
"clientVersion": "0.2",
"theme": "MUSIC",
"hl": "en",
"gl": "FR",
"experimentIds": []
},
"capabilities": {
},
"request": {
"internalExperimentFlags": []
}
},
"browseId": "FEmusic_analytics",
"query": "chart_params_type=WEEK&perspective=CHART&flags=viral_video_chart&selected_chart=VIRAL_VIDEOS"
}'
If it doesn't work, get the API key from the network log of https://artists.youtube.com
In the query field, you can modify the selected_chart parameter :
*
*all video :
selected_chart=VIDEOS
*viral videos chart :
selected_chart=VIRAL_VIDEOS
*artists :
selected_chart=ARTISTS
*tracks :
selected_chart=TRACKS
| stackoverflow | {
"language": "en",
"length": 181,
"provenance": "stackexchange_0000F.jsonl.gz:888097",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614612"
} |
1dc861819906a35058abaf7dc0b40c0e554b8f60 | Stackoverflow Stackexchange
Q: Removing Specific Object In Array Based On Property? I have an array of drink toppings and want to remove the ones that aren't relevant to the drink, this is the code I have, but I can't figure out how to remove the topping from the array if it isn't within the criteria.
I can only remove at index path and this can change if we added more toppings etc so didn't seem accurate?
for toppings in self.toppings {
if self.selectedDrink.name == "Tea" {
if toppings.limit == "C" {
self.toppings.remove(at: toppings)
}
}
}
Essentially if the user selected Tea it looks for toppings limited for coffee and then I need to remove those ones that respond to the "C" property, but I can't see how?
Thanks for the help!
A: You can do in-place removal with a for loop, but it would be tricky, because you would need to iterate back to avoid disturbing indexes.
A simpler approach is to filter the array, and assign it back to the toppings property, like this:
toppings = toppings.filter {$0.limit != "C"}
| Q: Removing Specific Object In Array Based On Property? I have an array of drink toppings and want to remove the ones that aren't relevant to the drink, this is the code I have, but I can't figure out how to remove the topping from the array if it isn't within the criteria.
I can only remove at index path and this can change if we added more toppings etc so didn't seem accurate?
for toppings in self.toppings {
if self.selectedDrink.name == "Tea" {
if toppings.limit == "C" {
self.toppings.remove(at: toppings)
}
}
}
Essentially if the user selected Tea it looks for toppings limited for coffee and then I need to remove those ones that respond to the "C" property, but I can't see how?
Thanks for the help!
A: You can do in-place removal with a for loop, but it would be tricky, because you would need to iterate back to avoid disturbing indexes.
A simpler approach is to filter the array, and assign it back to the toppings property, like this:
toppings = toppings.filter {$0.limit != "C"}
| stackoverflow | {
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:888110",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614661"
} |
ecd700683cba5028c10ec636053cd8dad28bfa44 | Stackoverflow Stackexchange
Q: Logger service using logging package in Angular Dart There is a mention in the docs of using the logging package to create a proper logger service. Given the features in the logging package it would be nice to be able to get the angular component tree as the logger full name.
I tried to play a bit with the dependency injection system to get the injector tree, so that I could reconstruct the app structure for the loggers. But this proved to be too tricky.
Is there a way to do this, or alternatively, is there a canonical logger service that I could use? It seems to be a pretty basic feature so it must be available somewhere.
A: I'd look at the logging package for help here.
This is not Angular-specific, but it supports tested loggers.
| Q: Logger service using logging package in Angular Dart There is a mention in the docs of using the logging package to create a proper logger service. Given the features in the logging package it would be nice to be able to get the angular component tree as the logger full name.
I tried to play a bit with the dependency injection system to get the injector tree, so that I could reconstruct the app structure for the loggers. But this proved to be too tricky.
Is there a way to do this, or alternatively, is there a canonical logger service that I could use? It seems to be a pretty basic feature so it must be available somewhere.
A: I'd look at the logging package for help here.
This is not Angular-specific, but it supports tested loggers.
| stackoverflow | {
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:888126",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614717"
} |
a2fa2a2e8ed490445a653ff52ab5d8606c4817e1 | Stackoverflow Stackexchange
Q: Modifying mongoose document on pre hook of findOneAndUpdate() I have a mongoose schema as such
var schema = new Schema({
id:Number
updated_at:Date
});
I am using findOneAndUpdate() to update this model as such
model.findOneAndUpdate(
{ id: json.id },
json,
{
upsert: true,
runValidators: true
})
.then(() => {
recordsUpdated++;
})
.catch((err) => {
this.emit('error', err);
});
The value being passed in json is not correct and I need to make some modifications to it. I am looking for a pre hook to do the modification. I have tried
faction.pre('findOneAndUpdate', function (next) {
this.update({ $set: { updated_at: this.getUpdate().updated_at * 1000 } });
next();
});
In short I want to convert the timestamp which is in seconds to milliseconds before updating the database, but this doesn't work.
A: After blindly throwing stones all around, what worked for me was
schema.pre('findOneAndUpdate', function (next) {
this._update.updated_at *= 1000;
next();
});
In short one needs to modify the document present in the _update property.
| Q: Modifying mongoose document on pre hook of findOneAndUpdate() I have a mongoose schema as such
var schema = new Schema({
id:Number
updated_at:Date
});
I am using findOneAndUpdate() to update this model as such
model.findOneAndUpdate(
{ id: json.id },
json,
{
upsert: true,
runValidators: true
})
.then(() => {
recordsUpdated++;
})
.catch((err) => {
this.emit('error', err);
});
The value being passed in json is not correct and I need to make some modifications to it. I am looking for a pre hook to do the modification. I have tried
faction.pre('findOneAndUpdate', function (next) {
this.update({ $set: { updated_at: this.getUpdate().updated_at * 1000 } });
next();
});
In short I want to convert the timestamp which is in seconds to milliseconds before updating the database, but this doesn't work.
A: After blindly throwing stones all around, what worked for me was
schema.pre('findOneAndUpdate', function (next) {
this._update.updated_at *= 1000;
next();
});
In short one needs to modify the document present in the _update property.
A: Better solution is like this:
schema.pre('findOneAndUpdate', function (this, next) {
this.update().updated_at *= 1000;
next();
});
A: Update "mongoose": "^6.4.0"
Thanks to the above top-rated solution, what worked for me was
this._update.$set.updated_at = new Date();
In my case, I wanted to save the currency key as uppercase if it is available in the requested object.
schema.pre('findOneAndUpdate', async function (next) {
const currency = this?._update?.$set?.currency;
if (currency) {
this.set({ currency: currency.toUpperCase() });
}
next();
});
| stackoverflow | {
"language": "en",
"length": 234,
"provenance": "stackexchange_0000F.jsonl.gz:888132",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614734"
} |
ef29810a9a3a103e52bcda8dd4b86ec495309cbf | Stackoverflow Stackexchange
Q: Why pm2 NodeJS app starts but not accessible on EC2 I have a Nodejs app running on AWS EC2. My package.json has the following instructions:
"scripts": {
"build": "babel src -s -D -d dist --presets es2015,stage-0",
"start": "node dist/index.js",
"prestart": "npm run build",
..
So when connected to EC2 I (after install and cd to proj folder) I do PORT=8080 npm start The app starts fine - but messages in the console and is acessinble via my EC2 addres :8080. Also if I run PORT=8080 node dist/index.js
- also good.
But since I would like to use monitoring, restarting of the script by pm2 I try do following:
pm2 start dist/index.js -- PORT=8080
or
PORT=8080 pm2 start dist/index.js
I see that pm2 has the app started,
but it's not acessible on AWS address :8080
What do I do wrong?
| Q: Why pm2 NodeJS app starts but not accessible on EC2 I have a Nodejs app running on AWS EC2. My package.json has the following instructions:
"scripts": {
"build": "babel src -s -D -d dist --presets es2015,stage-0",
"start": "node dist/index.js",
"prestart": "npm run build",
..
So when connected to EC2 I (after install and cd to proj folder) I do PORT=8080 npm start The app starts fine - but messages in the console and is acessinble via my EC2 addres :8080. Also if I run PORT=8080 node dist/index.js
- also good.
But since I would like to use monitoring, restarting of the script by pm2 I try do following:
pm2 start dist/index.js -- PORT=8080
or
PORT=8080 pm2 start dist/index.js
I see that pm2 has the app started,
but it's not acessible on AWS address :8080
What do I do wrong?
| stackoverflow | {
"language": "en",
"length": 140,
"provenance": "stackexchange_0000F.jsonl.gz:888170",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614839"
} |
392fb88e7e93920608a8c83ef3e526c31b6a0f32 | Stackoverflow Stackexchange
Q: VS Code - how to document an object using JSDoc I have a variable storage, that stores all elements of type Person. So basically it is a dictionary with key URL and value PersonInstance:
let storage = {}
storage["localhost.com/person/1"] = new Person("John Wick");
Actually I could do it by writing:
/**
* @type {Object.<string, Person>}
*/
But VS Code Intellisense does not work in such case. Is there other way to document such object with unlimited number of keys in VS Code?
A: VScode's javascript intellisense is powered by TypeScript which unfortunatly does not currently support the Object.<string, Person> type syntax. Here's the bug tracking this.
You can work around this by using typescript syntax for the map:
/**
* @type {{ [key: string]: Person }}
*/
const storage = {}
which will improve the intellisense in vscode but is not a standard or widely supported jsdoc type.
| Q: VS Code - how to document an object using JSDoc I have a variable storage, that stores all elements of type Person. So basically it is a dictionary with key URL and value PersonInstance:
let storage = {}
storage["localhost.com/person/1"] = new Person("John Wick");
Actually I could do it by writing:
/**
* @type {Object.<string, Person>}
*/
But VS Code Intellisense does not work in such case. Is there other way to document such object with unlimited number of keys in VS Code?
A: VScode's javascript intellisense is powered by TypeScript which unfortunatly does not currently support the Object.<string, Person> type syntax. Here's the bug tracking this.
You can work around this by using typescript syntax for the map:
/**
* @type {{ [key: string]: Person }}
*/
const storage = {}
which will improve the intellisense in vscode but is not a standard or widely supported jsdoc type.
A: Missing support for Object<string, T> has been added. However, be aware that casing matters!
Works
Object<string, T> where string is the index and T is the value type.
Does NOT work
object<string, T> - object MUST start with upper case: Object
Object<String, T> - String MUST be all lower case: string
A: I found that it is better to use Map instead of object. So basically you can write something like this
/**
* @type {Map<string, Person>}
*/
let bsStorage = new Map();
NOTE: And if you concern about older browsers, that do not support ES6, you can transpile using Babel.
| stackoverflow | {
"language": "en",
"length": 251,
"provenance": "stackexchange_0000F.jsonl.gz:888175",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614847"
} |
3d2e9dc74375be607acbe2a3ba99826eacb58f95 | Stackoverflow Stackexchange
Q: Download file button with JS I need to generate the link and then download the link in one move. I have a button for generation and download and once is clicked i have to call the api to generate the download link for the pdf and then make the browser open the pop up with save item.
<button type="button" class="btn btn-success btn-block" ng-click="generateAndDownloadPdf()"><i
class="fa fa-plus"></i>Generate and download invoice</span></button>
and my js controller function looks like :
$scope.generateAndDownloadPdf = function(){
//getting download url from api
api.events.invoice.download($stateParams.eventId, $stateParams.speakerId).then(function(data){
console.log(data)
//give url to user
});
}
I know that once I have the download url I can use this html code, but was wondering if I can do all in one click for the user.
<a
target="_self"
href="download.url"
download="file.pdf">
<button type="button" class="btn btn-success btn-block" ng-click=""><i
class="fa fa-plus"></i>Download Invoice</span></button>
</a>
Thank you all!
A: you can force the download with this way in yout method "generateAndDownloadPdf",
var anchor = document.createElement('a');
anchor.href = data.downloadUrl;
anchor.target = '_blank';
anchor.download = data.fileName;
anchor.click();
| Q: Download file button with JS I need to generate the link and then download the link in one move. I have a button for generation and download and once is clicked i have to call the api to generate the download link for the pdf and then make the browser open the pop up with save item.
<button type="button" class="btn btn-success btn-block" ng-click="generateAndDownloadPdf()"><i
class="fa fa-plus"></i>Generate and download invoice</span></button>
and my js controller function looks like :
$scope.generateAndDownloadPdf = function(){
//getting download url from api
api.events.invoice.download($stateParams.eventId, $stateParams.speakerId).then(function(data){
console.log(data)
//give url to user
});
}
I know that once I have the download url I can use this html code, but was wondering if I can do all in one click for the user.
<a
target="_self"
href="download.url"
download="file.pdf">
<button type="button" class="btn btn-success btn-block" ng-click=""><i
class="fa fa-plus"></i>Download Invoice</span></button>
</a>
Thank you all!
A: you can force the download with this way in yout method "generateAndDownloadPdf",
var anchor = document.createElement('a');
anchor.href = data.downloadUrl;
anchor.target = '_blank';
anchor.download = data.fileName;
anchor.click();
A: You can do using
window.location.href= url_to_download;
| stackoverflow | {
"language": "en",
"length": 174,
"provenance": "stackexchange_0000F.jsonl.gz:888185",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614867"
} |
5da2586c4d11cbfac7886212c04df9d7ecdea7da | Stackoverflow Stackexchange
Q: Woo 3.0.8 Ajax fragments NOT updating Cart Menu We are using WP Cart Menu Pro and on our shop page we have Ajax add to cart, which is working fine but its not updating the Items in the Cart Menu.
This has only started to happen with auto update to WooCommerce 3.0.8. I have done some research and added the below code to our functions.php page:
function my_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?><a class="wpmenucart-contents" href="https://www.springbokbbq.co.uk/cart/" title="View your shopping cart">
<i class="wpmenucart-icon-shopping-cart-5"></i>
<span class="cartcontents"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span>
</a><?php
$fragments['a.wpmenucart-contents'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );
Did anybody else come across this issue with the Woo update?
EDIT:
I have checked the chrome console: when I click Add to Cart I get this error:
Uncaught TypeError: a(...).addClass(...).fadeTo(...).block is not a function
at String.<anonymous> (add-to-cart.min.js?ver=3.0.8:4)
at Function.each (jquery.js?ver=1.12.4:2)
at HTMLDocument.b.updateFragments (add-to-cart.min.js?ver=3.0.8:4)
at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)
at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)
at Object.trigger (jquery.js?ver=1.12.4:3)
at Object.a.event.trigger (jquery-migrate.min.js?ver=1.4.1:2)
at HTMLBodyElement.<anonymous> (jquery.js?ver=1.12.4:3)
at Function.each (jquery.js?ver=1.12.4:2)
at a.fn.init.each (jquery.js?ver=1.12.4:2)
I Don't get this error when removing items from the cart and it updates the menu Cart Items on cart page.
| Q: Woo 3.0.8 Ajax fragments NOT updating Cart Menu We are using WP Cart Menu Pro and on our shop page we have Ajax add to cart, which is working fine but its not updating the Items in the Cart Menu.
This has only started to happen with auto update to WooCommerce 3.0.8. I have done some research and added the below code to our functions.php page:
function my_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?><a class="wpmenucart-contents" href="https://www.springbokbbq.co.uk/cart/" title="View your shopping cart">
<i class="wpmenucart-icon-shopping-cart-5"></i>
<span class="cartcontents"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span>
</a><?php
$fragments['a.wpmenucart-contents'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );
Did anybody else come across this issue with the Woo update?
EDIT:
I have checked the chrome console: when I click Add to Cart I get this error:
Uncaught TypeError: a(...).addClass(...).fadeTo(...).block is not a function
at String.<anonymous> (add-to-cart.min.js?ver=3.0.8:4)
at Function.each (jquery.js?ver=1.12.4:2)
at HTMLDocument.b.updateFragments (add-to-cart.min.js?ver=3.0.8:4)
at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)
at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)
at Object.trigger (jquery.js?ver=1.12.4:3)
at Object.a.event.trigger (jquery-migrate.min.js?ver=1.4.1:2)
at HTMLBodyElement.<anonymous> (jquery.js?ver=1.12.4:3)
at Function.each (jquery.js?ver=1.12.4:2)
at a.fn.init.each (jquery.js?ver=1.12.4:2)
I Don't get this error when removing items from the cart and it updates the menu Cart Items on cart page.
| stackoverflow | {
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:888205",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614938"
} |
8848c2c9194d663d7b4c74239e17158dc0121555 | Stackoverflow Stackexchange
Q: why can't lodash find the max value from an array? I have below code and I tried to use lodash to find the max value from an array object;
var a = [ { type: 'exam', score: 47.67196715489599 },
{ type: 'quiz', score: 41.55743490493954 },
{ type: 'homework', score: 70.4612811769744 },
{ type: 'homework', score: 48.60803337116214 } ];
var _ = require("lodash")
var b = _.max(a, function(o){return o.score;})
console.log(b);
the output is 47.67196715489599 which is not the maximum value. What is wrong with my code?
A: Lodash's _.max() doesn't accept an iteratee (callback). Use _.maxBy() instead:
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
console.log(_.maxBy(a, function(o) {
return o.score;
}));
// or using `_.property` iteratee shorthand
console.log(_.maxBy(a, 'score'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
| Q: why can't lodash find the max value from an array? I have below code and I tried to use lodash to find the max value from an array object;
var a = [ { type: 'exam', score: 47.67196715489599 },
{ type: 'quiz', score: 41.55743490493954 },
{ type: 'homework', score: 70.4612811769744 },
{ type: 'homework', score: 48.60803337116214 } ];
var _ = require("lodash")
var b = _.max(a, function(o){return o.score;})
console.log(b);
the output is 47.67196715489599 which is not the maximum value. What is wrong with my code?
A: Lodash's _.max() doesn't accept an iteratee (callback). Use _.maxBy() instead:
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
console.log(_.maxBy(a, function(o) {
return o.score;
}));
// or using `_.property` iteratee shorthand
console.log(_.maxBy(a, 'score'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
A: Or even shorter:
var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
const b = _.maxBy(a, 'score');
console.log(b);
This uses the _.property iteratee shorthand.
| stackoverflow | {
"language": "en",
"length": 137,
"provenance": "stackexchange_0000F.jsonl.gz:888213",
"question_score": "28",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44614973"
} |
ea9da48ecc85fd9cb2d7521214836b2d5de5a7cf | Stackoverflow Stackexchange
Q: How to use tf.contrib.keras.optimizers.Adamax ? I use the tf.AdamOptimizer in tensorflow 1.2:
train_opt = tf.train.AdamOptimizer(learning_rate=0.0004).minimize(error)
now I want to replace it with the new tf.contrib.keras.optimizers:
train_opt = tf.contrib.keras.optimizers.Adamax(lr=0.0004)
But how can I minimize the error?? ( adding .minimize(error) does not work)
A: Use :
train_opt =
tf.contrib.keras.optimizers.Adamax().get_updates(loss=cost,constraints=[], params=train_params)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))
train_params = network.all_params
| Q: How to use tf.contrib.keras.optimizers.Adamax ? I use the tf.AdamOptimizer in tensorflow 1.2:
train_opt = tf.train.AdamOptimizer(learning_rate=0.0004).minimize(error)
now I want to replace it with the new tf.contrib.keras.optimizers:
train_opt = tf.contrib.keras.optimizers.Adamax(lr=0.0004)
But how can I minimize the error?? ( adding .minimize(error) does not work)
A: Use :
train_opt =
tf.contrib.keras.optimizers.Adamax().get_updates(loss=cost,constraints=[], params=train_params)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))
train_params = network.all_params
| stackoverflow | {
"language": "en",
"length": 60,
"provenance": "stackexchange_0000F.jsonl.gz:888249",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615085"
} |
d68fc09db4926563d016acadb50075e7a263579e | Stackoverflow Stackexchange
Q: C# Casting Generic Child Type to Parent Let's say we have these types:
class A {}
class B : A {}
class X<T> {}
Why we can't do this?
X<A> var = new X<B>();
Is there any workaround available?
[Edit]
I tried to use covariance but it failed because I want to access a property inside X that is of type T and C# does not allow using type T in the interface:
interface IX<out T> {
T sth {set; get;}
}
class X<T>: IX<T> {
T sth { set; get; }
}
[Edit 2]
I also tried this but it failed:
class X<T> where T : A
{
public T sth { set; get; }
public static implicit operator X<T>(X<B> v)
{
return new X<T>
{
sth = v.sth,
};
}
}
It's strange that C# does not allow to the casting for 'sth'.
A: The problem is that classes does not support Covariance and Contravariance, only interfaces:
class A { }
class B : A { }
class X<T> : P<T> { }
interface P<out T>
{
}
...
P<A> var = new X<B>();
Covariance and Contravariance FAQ
| Q: C# Casting Generic Child Type to Parent Let's say we have these types:
class A {}
class B : A {}
class X<T> {}
Why we can't do this?
X<A> var = new X<B>();
Is there any workaround available?
[Edit]
I tried to use covariance but it failed because I want to access a property inside X that is of type T and C# does not allow using type T in the interface:
interface IX<out T> {
T sth {set; get;}
}
class X<T>: IX<T> {
T sth { set; get; }
}
[Edit 2]
I also tried this but it failed:
class X<T> where T : A
{
public T sth { set; get; }
public static implicit operator X<T>(X<B> v)
{
return new X<T>
{
sth = v.sth,
};
}
}
It's strange that C# does not allow to the casting for 'sth'.
A: The problem is that classes does not support Covariance and Contravariance, only interfaces:
class A { }
class B : A { }
class X<T> : P<T> { }
interface P<out T>
{
}
...
P<A> var = new X<B>();
Covariance and Contravariance FAQ
A: You need covariance (mark the type parameter T with the word out):
interface IX<out T> {}
This is only allowed with interface types (and delegate types). And the type B must be a reference type (class like here is OK).
Then this is fine:
IX<B> ixb = ...;
IX<A> ok = new IX<B>();
| stackoverflow | {
"language": "en",
"length": 245,
"provenance": "stackexchange_0000F.jsonl.gz:888266",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615138"
} |
331a6d0d46aba567e26e7effca48515aa32fd2db | Stackoverflow Stackexchange
Q: Django constance - on save method Is there any way to call django command after changing constance value? I need to call:
python manage.py installtasks
for my kronos cron jobs. I don't have any idea how can I set this. In constance docs I found:
from constance.signals import config_updated
@receiver(config_updated)
def constance_updated(sender, key, old_value, new_value, **kwargs):
print(sender, key, old_value, new_value)
but I don't know what is receiver (I get "NameError: name 'receiver' is not defined") and where should I put this code. Any help?
A: You could import the decorator,
from django.dispatch import receiver
| Q: Django constance - on save method Is there any way to call django command after changing constance value? I need to call:
python manage.py installtasks
for my kronos cron jobs. I don't have any idea how can I set this. In constance docs I found:
from constance.signals import config_updated
@receiver(config_updated)
def constance_updated(sender, key, old_value, new_value, **kwargs):
print(sender, key, old_value, new_value)
but I don't know what is receiver (I get "NameError: name 'receiver' is not defined") and where should I put this code. Any help?
A: You could import the decorator,
from django.dispatch import receiver
| stackoverflow | {
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:888286",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615198"
} |
7cbc4eb7a5c4931b4176afab63b16685a8eecb66 | Stackoverflow Stackexchange
Q: AttributeError: 'module' object has no attribute 'audio_fadein' I have used cx_freeze to build a python project into a single folder with an .exe and it's dependencies, but when I run the .exe I get the error:
AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein'
I have read the docs for MoviePy but cannot find out why this is happening. My Python program runs perfectly from within the IDE (PyCharm) but after compiling, I am getting the MoviePy error. I have used the recommended from moviepy.editor import *
I don't actually use the audio_fadein directly in my script, so it must be being called by MoviePy when I show my video. Here is the code:
def cherrybyte():
pygame.display.set_caption('©2017 CherryByte™ Software')
pygame.mouse.set_visible(False)
logo = VideoFileClip('CherryByte Logo.mp4')
logo.preview()
pygame.mouse.set_visible(True)
EDIT: I have now also tried changing the import statement to from moviepy.editor import VideoFileClip but with exactly the same error.
A: I had same error while I was using the pyinstaller to build the .exe file.
However, I changed the import statement to from moviepy.video.io.VideoFileClip import VideoFileClip
and it worked.
| Q: AttributeError: 'module' object has no attribute 'audio_fadein' I have used cx_freeze to build a python project into a single folder with an .exe and it's dependencies, but when I run the .exe I get the error:
AttributeError: module 'moviepy.audio.fx.all' has no attribute 'audio_fadein'
I have read the docs for MoviePy but cannot find out why this is happening. My Python program runs perfectly from within the IDE (PyCharm) but after compiling, I am getting the MoviePy error. I have used the recommended from moviepy.editor import *
I don't actually use the audio_fadein directly in my script, so it must be being called by MoviePy when I show my video. Here is the code:
def cherrybyte():
pygame.display.set_caption('©2017 CherryByte™ Software')
pygame.mouse.set_visible(False)
logo = VideoFileClip('CherryByte Logo.mp4')
logo.preview()
pygame.mouse.set_visible(True)
EDIT: I have now also tried changing the import statement to from moviepy.editor import VideoFileClip but with exactly the same error.
A: I had same error while I was using the pyinstaller to build the .exe file.
However, I changed the import statement to from moviepy.video.io.VideoFileClip import VideoFileClip
and it worked.
A: For everyone that has the same issue i solved it by modifying the selected init file shown in the picture below:
File Location
Inside it there is a piece of code that import every function inside the fx folder:
__all__ = [name for _, name, _ in pkgutil.iter_modules(
fx.__path__) if name != "all"]
for name in __all__:
exec("from ..%s import %s" % (name, name))
Comment this block and import manually every function needed, like so:
from moviepy.video.fx.accel_decel import accel_decel
from moviepy.video.fx.blackwhite import blackwhite
from moviepy.video.fx.blink import blink
from moviepy.video.fx.crop import crop
from moviepy.video.fx.even_size import even_size
from moviepy.video.fx.fadein import fadein
from moviepy.video.fx.fadeout import fadeout
from moviepy.video.fx.mirror_x import mirror_x
from moviepy.video.fx.mirror_y import mirror_y
from moviepy.video.fx.resize import resize
#etc.
Do the same with the init placed in moviepy.audio.fx.all
A: Actual code in __init__.py:
__all__ = [name for _, name, _ in pkgutil.iter_modules(
fx.__path__) if name != "all"]
Just put square brackets around [fx.__path__]:
__all__ = [name for _, name, _ in pkgutil.iter_modules(
[fx.__path__]) if name != "all"]
A: I solved the errror the same way HunterDev did.
Here is the complete code for:
Python 3.8.6\Lib\site-packages\moviepy\video\fx\all_init_.py
from moviepy.video.fx.accel_decel import accel_decel
from moviepy.video.fx.blackwhite import blackwhite
from moviepy.video.fx.blink import blink
from moviepy.video.fx.colorx import colorx
from moviepy.video.fx.crop import crop
from moviepy.video.fx.even_size import even_size
from moviepy.video.fx.fadein import fadein
from moviepy.video.fx.fadeout import fadeout
from moviepy.video.fx.freeze import freeze
from moviepy.video.fx.freeze_region import freeze_region
from moviepy.video.fx.gamma_corr import gamma_corr
from moviepy.video.fx.headblur import headblur
from moviepy.video.fx.invert_colors import invert_colors
from moviepy.video.fx.loop import loop
from moviepy.video.fx.lum_contrast import lum_contrast
from moviepy.video.fx.make_loopable import make_loopable
from moviepy.video.fx.margin import margin
from moviepy.video.fx.mask_and import mask_and
from moviepy.video.fx.mask_color import mask_color
from moviepy.video.fx.mask_or import mask_or
from moviepy.video.fx.mirror_x import mirror_x
from moviepy.video.fx.mirror_y import mirror_y
from moviepy.video.fx.painting import painting
from moviepy.video.fx.resize import resize
from moviepy.video.fx.rotate import rotate
from moviepy.video.fx.scroll import scroll
from moviepy.video.fx.speedx import speedx
from moviepy.video.fx.supersample import supersample
from moviepy.video.fx.time_mirror import time_mirror
from moviepy.video.fx.time_symmetrize import time_symmetrize
Python 3.8.6\Lib\site-packages\moviepy\audio\fx\all_init_.py
from moviepy.audio.fx.audio_fadein import audio_fadein
from moviepy.audio.fx.audio_fadeout import audio_fadeout
from moviepy.audio.fx.audio_left_right import audio_left_right
from moviepy.audio.fx.audio_loop import audio_loop
from moviepy.audio.fx.audio_normalize import audio_normalize
from moviepy.audio.fx.volumex import volumex
For more info check:https://github.com/Zulko/moviepy/issues/591
| stackoverflow | {
"language": "en",
"length": 510,
"provenance": "stackexchange_0000F.jsonl.gz:888305",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615249"
} |
7a8a1e411da45654eedbf947cb191a883461b7d9 | Stackoverflow Stackexchange
Q: Combining multiple Observables I have these 2 observables:
this.areasService.getSelectAreas({})
.subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
.subscribe((result) => this.stationsSelect = result.json().data.stations);
that fills these 2 variables (async) this.areasSelect & this.stationsSelect.
I also have a 3rd observable that I need to have these values to continue:
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
How can I combine these 3 observables?
A: All you need to do is to use forkJoin , it will call both of your first async calls and only returns data on both completion , so no need to worry
After that on subscribe you will get result in array of sequence you called the urls or apis.
const combined = Observable.forkJoin(
this.areasService.getSelectAreas({}).map((res) => res.json().data.areas),
this.stationsService.getSelectStations({}).map((res) => res.json().data.stations)
)
combined.subscribe(latestValues => {
this.areasSelect = latestValues[0];
this.stationsSelect = latestValues[1];
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
});
| Q: Combining multiple Observables I have these 2 observables:
this.areasService.getSelectAreas({})
.subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
.subscribe((result) => this.stationsSelect = result.json().data.stations);
that fills these 2 variables (async) this.areasSelect & this.stationsSelect.
I also have a 3rd observable that I need to have these values to continue:
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
How can I combine these 3 observables?
A: All you need to do is to use forkJoin , it will call both of your first async calls and only returns data on both completion , so no need to worry
After that on subscribe you will get result in array of sequence you called the urls or apis.
const combined = Observable.forkJoin(
this.areasService.getSelectAreas({}).map((res) => res.json().data.areas),
this.stationsService.getSelectStations({}).map((res) => res.json().data.stations)
)
combined.subscribe(latestValues => {
this.areasSelect = latestValues[0];
this.stationsSelect = latestValues[1];
this.transportsService.getTransport().subscribe((res) => {
console.log(this.areasSelect)
console.log(this.stationsSelect)
})
});
A: You could use forkJoin:
import { forkJoin } from 'rxjs/observable/forkJoin';
let areaSelect$ = this.areasService.getSelectAreas({})
.map(res => res.json().data.areas)
.do(val => this.areaSelect = val);
let stationSelect$ = this.stationsService.getSelectStations({})
.map(res => res.json().data.stations)
.do(val => this.stationSelect = val);
forkJoin(areaSelect$,stationSelect$)
.mergeMap(data=>{
//data is an array with 2 positions which contain the results of the 2 requests. data[0] is the vale of this.areaSelect for example
return this.transportsService.getTransport(data[0],data[1]);
}).subscrite(res => {
// res is the response value of getTransport
})
| stackoverflow | {
"language": "en",
"length": 210,
"provenance": "stackexchange_0000F.jsonl.gz:888324",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615298"
} |
9e7eb65964d5385442d9a8a76c18a8cf88ff555d | Stackoverflow Stackexchange
Q: Gui viewer for RocksDb sst files I'm working with Kafka that save the data into rocksdb.
Now I want to have a look at the db keys and values that created by Kafka.
I downloaded FastNoSQL and tried but failed.
The folder contains:
*
*.sst files
*.log files
*CURRENT file
*IDENTITY file
*LOCK file
*LOG files
*MANIFEST files
*OPTIONS files
How can I watch the values?
A: It looks like the reason you have data stored in RocksDB files is because you are using Apache Kafka's Streams API. If so, then you can use Kafka's interactive queries feature to look into your data.
If, however, you want to interact directly with the local RocksDB files, you need to use other tools. I don't have experience with any GUIs for RocksDB, but perhaps answers from other SO folks can cover those.
| Q: Gui viewer for RocksDb sst files I'm working with Kafka that save the data into rocksdb.
Now I want to have a look at the db keys and values that created by Kafka.
I downloaded FastNoSQL and tried but failed.
The folder contains:
*
*.sst files
*.log files
*CURRENT file
*IDENTITY file
*LOCK file
*LOG files
*MANIFEST files
*OPTIONS files
How can I watch the values?
A: It looks like the reason you have data stored in RocksDB files is because you are using Apache Kafka's Streams API. If so, then you can use Kafka's interactive queries feature to look into your data.
If, however, you want to interact directly with the local RocksDB files, you need to use other tools. I don't have experience with any GUIs for RocksDB, but perhaps answers from other SO folks can cover those.
| stackoverflow | {
"language": "en",
"length": 141,
"provenance": "stackexchange_0000F.jsonl.gz:888348",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615389"
} |
9356a804f5dfa77bb5403bb46430aebcc57d0e25 | Stackoverflow Stackexchange
Q: Can't find variable: webpackJsonp I'm occasional getting this error and can't work out why. My vendor bundle is before my main bundle so there is no reason for this error to occur and I can't ever get the error.
The only thing I've thought of is my site uses http2 so could this cause script to be loaded out of order?
| Q: Can't find variable: webpackJsonp I'm occasional getting this error and can't work out why. My vendor bundle is before my main bundle so there is no reason for this error to occur and I can't ever get the error.
The only thing I've thought of is my site uses http2 so could this cause script to be loaded out of order?
| stackoverflow | {
"language": "en",
"length": 62,
"provenance": "stackexchange_0000F.jsonl.gz:888358",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615412"
} |
6582476350d7083cf0609a6e34031ed8ad64ffab | Stackoverflow Stackexchange
Q: MongoDB c# driver - How to save class by reference without modifying the object class? I have 2 classes:
public class Store
{
public Guid ID;
public List<Product> Products;
}
public class Product
{
public Guid ID;
public string Name;
}
I want to save "Store" in my MongoDB but I don't want the collection of Stores to include the content of "Product" (to save space \ duplication).
I want to create another colleciton of Product, and use some kind of ID reference to the matched document.
Does MongoDB 2.4.4 c# driver support this without changing my models? (I can't modify them - used in an API calls). How can I implement it?
A: Using [BsonIgnore] would do the trick if I understand you right.
MongoDB C# Driver: Ignore Property on Insert
| Q: MongoDB c# driver - How to save class by reference without modifying the object class? I have 2 classes:
public class Store
{
public Guid ID;
public List<Product> Products;
}
public class Product
{
public Guid ID;
public string Name;
}
I want to save "Store" in my MongoDB but I don't want the collection of Stores to include the content of "Product" (to save space \ duplication).
I want to create another colleciton of Product, and use some kind of ID reference to the matched document.
Does MongoDB 2.4.4 c# driver support this without changing my models? (I can't modify them - used in an API calls). How can I implement it?
A: Using [BsonIgnore] would do the trick if I understand you right.
MongoDB C# Driver: Ignore Property on Insert
| stackoverflow | {
"language": "en",
"length": 133,
"provenance": "stackexchange_0000F.jsonl.gz:888376",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615458"
} |
5b7c5d54555a3ad5c8e90ec6300cfede183d9c81 | Stackoverflow Stackexchange
Q: Firebase analytics in China I recently added Firebase analytics to my iOS app and I was wondering if Firebase analytics can track app usage in China? The thing is, we get a lot of downloads from China and tracking app usage in China is pretty important.
Some context, I initially wanted to add Google Analytics but the Google Analytics page for iOS apps redirected me to Firebase and hence I ended up adding Firebase analytics to my app.
A: I finally have a theory that I am satisfied with and I have written a blogpost that I hope can save others some time. The post details my analysis of the situation the includes how the GFW in China works, the OPT-IN nature of App Analytics in iTunes and why some data for Firebase analytics comes through. Yes and the reason we may see some analytics data in Firebase is not because of VPN, it's in part in the nature of how GFW works.
| Q: Firebase analytics in China I recently added Firebase analytics to my iOS app and I was wondering if Firebase analytics can track app usage in China? The thing is, we get a lot of downloads from China and tracking app usage in China is pretty important.
Some context, I initially wanted to add Google Analytics but the Google Analytics page for iOS apps redirected me to Firebase and hence I ended up adding Firebase analytics to my app.
A: I finally have a theory that I am satisfied with and I have written a blogpost that I hope can save others some time. The post details my analysis of the situation the includes how the GFW in China works, the OPT-IN nature of App Analytics in iTunes and why some data for Firebase analytics comes through. Yes and the reason we may see some analytics data in Firebase is not because of VPN, it's in part in the nature of how GFW works.
A: Firebase Analytics should work in China.
| stackoverflow | {
"language": "en",
"length": 171,
"provenance": "stackexchange_0000F.jsonl.gz:888386",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615485"
} |
d2b60a4a94ac3ce0c347313748603c3c9beb6fb2 | Stackoverflow Stackexchange
Q: Android Studio Logcat Search I am facing a strange problem with android studio. In logcat monitor, there is not much space for search box. I am not able to find out any option to make it larger.
is there any way to make this larger?
A: Actually the problem is with the device name, which is too long and due to this it squeezes the Logcat search. So to the solution I got for this name issue is to change the device name (whether its Genymotion or AVD). So to change your device name follow below steps :
For AVD : Go to Tools --> Android --> AVD Manager --> Select your device and then change the device name to shorter one.
For Genymotion : Open you VirtualBox --> Select your device and then Click on Settings --> Change the name to shorter one.
And other option is Right click on Logcat tab and then enable Floating mode. Then just resize the floating window so that the Logcat search can expand.
Edit: You can also use CTRL+F to filter logcat. It will open new search bar and then you can try on that.
| Q: Android Studio Logcat Search I am facing a strange problem with android studio. In logcat monitor, there is not much space for search box. I am not able to find out any option to make it larger.
is there any way to make this larger?
A: Actually the problem is with the device name, which is too long and due to this it squeezes the Logcat search. So to the solution I got for this name issue is to change the device name (whether its Genymotion or AVD). So to change your device name follow below steps :
For AVD : Go to Tools --> Android --> AVD Manager --> Select your device and then change the device name to shorter one.
For Genymotion : Open you VirtualBox --> Select your device and then Click on Settings --> Change the name to shorter one.
And other option is Right click on Logcat tab and then enable Floating mode. Then just resize the floating window so that the Logcat search can expand.
Edit: You can also use CTRL+F to filter logcat. It will open new search bar and then you can try on that.
A: For quickly search, use universal key combination CTRL+F.
| stackoverflow | {
"language": "en",
"length": 203,
"provenance": "stackexchange_0000F.jsonl.gz:888410",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615551"
} |
e21666635296fd3eb21ffc0773cbf18dc4784481 | Stackoverflow Stackexchange
Q: Angular 2\4 hash url keep index.html Background: Angular 4, ng cli, RouterModule, useHash: true.
when I browse to my app using http://server/index.html it resolves to http://server/#/ (index.html is omitted from the url) additionally every routing navigation also omits the index.html from the url.
This is problematic for how my app is hosted, I need to keep index.html in the url. How can I configure angular to keep it?
A: You can try:
ng build --prod --base-href /app/index.html
but it might affect relative path to your assets.
| Q: Angular 2\4 hash url keep index.html Background: Angular 4, ng cli, RouterModule, useHash: true.
when I browse to my app using http://server/index.html it resolves to http://server/#/ (index.html is omitted from the url) additionally every routing navigation also omits the index.html from the url.
This is problematic for how my app is hosted, I need to keep index.html in the url. How can I configure angular to keep it?
A: You can try:
ng build --prod --base-href /app/index.html
but it might affect relative path to your assets.
A: index.html is not a known route by the Angular router. Once it is loaded into memory it redirects unknowns to the default route which is usually '\' and wipes out the index.html and any additional path or query parameters.
Something like this should do the trick ...
[
{ path: 'index.html', component: AppComponent},
{ path: '', redirectTo: 'index.html', pathMatch: 'full' },
{ path: '**', redirectTo: 'index.html', pathMatch: 'full' }
]
Also answered here: How to preserve index.html and query params in URL in Angular 6?
| stackoverflow | {
"language": "en",
"length": 173,
"provenance": "stackexchange_0000F.jsonl.gz:888446",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615646"
} |
10b9cfba3245f943a761491decac81d06d9dcf32 | Stackoverflow Stackexchange
Q: How to read a file as a list / dict? I have a file which has the same structure as python list / dictionaries, i.e.
[
{
"key1" : "value1",
"key2" : "value2",
...
},
{
"key1" : "value3",
"key2" : "value4",
...
},
...
]
Is there some easy way how to read this file and convert it into a list of dictionaries?
A: if the file is a json file, then
import json
with open('file_url') as data_file:
data = json.load(data_file)
print(data[0]['key1'])
print(data[0]['key2'])
| Q: How to read a file as a list / dict? I have a file which has the same structure as python list / dictionaries, i.e.
[
{
"key1" : "value1",
"key2" : "value2",
...
},
{
"key1" : "value3",
"key2" : "value4",
...
},
...
]
Is there some easy way how to read this file and convert it into a list of dictionaries?
A: if the file is a json file, then
import json
with open('file_url') as data_file:
data = json.load(data_file)
print(data[0]['key1'])
print(data[0]['key2'])
A: with open('your_file', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
A: I think you want to look into the JSON module. If that is the format of your file, of course. If not, you can write your own text parser. It'd be helpful to have more information about your use case, where the file comes from, and that kind of stuff.
| stackoverflow | {
"language": "en",
"length": 145,
"provenance": "stackexchange_0000F.jsonl.gz:888447",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615648"
} |
722c4be5f17710a639fc17bd62b8c03dc6056bb9 | Stackoverflow Stackexchange
Q: Sphinx warning : targets for x source files that are out of date I have a Sphinx based website using Sphinx bootstrap theme. Whenever I add an RST file in it and run by typing make html, it always gives this warning:
building [html]: targets for 6 source files that are out of date
The build is succesful, but I want to prevent this warning appear all the time. It counts the number of RST files I add. By the way, I use :orphan: at the top of my RST files to customize the navbar of my website and don't include them on index.rst. I first thought that may be due to that, but when I also delete the orphan and add my RST files to the TOC tree, it still gives this warning. Any way to remove this warning ?
A: That is not really a warning; it is more of a log message. You can suppress it and other similar messages by running sphinx-build with the -q (or -Q) option.
See http://www.sphinx-doc.org/en/stable/invocation.html#cmdoption-sphinx-build-q.
| Q: Sphinx warning : targets for x source files that are out of date I have a Sphinx based website using Sphinx bootstrap theme. Whenever I add an RST file in it and run by typing make html, it always gives this warning:
building [html]: targets for 6 source files that are out of date
The build is succesful, but I want to prevent this warning appear all the time. It counts the number of RST files I add. By the way, I use :orphan: at the top of my RST files to customize the navbar of my website and don't include them on index.rst. I first thought that may be due to that, but when I also delete the orphan and add my RST files to the TOC tree, it still gives this warning. Any way to remove this warning ?
A: That is not really a warning; it is more of a log message. You can suppress it and other similar messages by running sphinx-build with the -q (or -Q) option.
See http://www.sphinx-doc.org/en/stable/invocation.html#cmdoption-sphinx-build-q.
| stackoverflow | {
"language": "en",
"length": 175,
"provenance": "stackexchange_0000F.jsonl.gz:888475",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615749"
} |
ab98f7dfda7c0aa45b0b55f2e4e31df2a0a927e3 | Stackoverflow Stackexchange
Q: Remove double quotes in Pandas I have the following file:
"j"; "x"; y
"0"; "1"; 5
"1"; "2"; 6
"2"; "3"; 7
"3"; "4"; 8
"4"; "5"; 3
"5"; "5"; 4
Which I read by:
df = pd.read_csv('test.csv', delimiter='; ', engine='python')
Then I print print df and see:
"j" "x" y
0 "0" "1" 5
1 "1" "2" 6
2 "2" "3" 7
3 "3" "4" 8
4 "4" "5" 3
5 "5" "5" 4
Instead, I would like to see:
j x y
0 0 1 5
1 1 2 6
2 2 3 7
3 3 4 8
4 4 5 3
5 5 5 4
How to remove the double quotes?
A: I did it with:
rm_quote = lambda x: x.replace('"', '')
df = pd.read_csv('test.csv', delimiter='; ', engine='python',
converters={'\"j\"': rm_quote,
'\"x\"': rm_quote})
df = df.rename(columns=rm_quote)
| Q: Remove double quotes in Pandas I have the following file:
"j"; "x"; y
"0"; "1"; 5
"1"; "2"; 6
"2"; "3"; 7
"3"; "4"; 8
"4"; "5"; 3
"5"; "5"; 4
Which I read by:
df = pd.read_csv('test.csv', delimiter='; ', engine='python')
Then I print print df and see:
"j" "x" y
0 "0" "1" 5
1 "1" "2" 6
2 "2" "3" 7
3 "3" "4" 8
4 "4" "5" 3
5 "5" "5" 4
Instead, I would like to see:
j x y
0 0 1 5
1 1 2 6
2 2 3 7
3 3 4 8
4 4 5 3
5 5 5 4
How to remove the double quotes?
A: I did it with:
rm_quote = lambda x: x.replace('"', '')
df = pd.read_csv('test.csv', delimiter='; ', engine='python',
converters={'\"j\"': rm_quote,
'\"x\"': rm_quote})
df = df.rename(columns=rm_quote)
A: You can pass the type as an argument to the read_csv function.
pd.read_csv('test.csv', delimiter='; ', engine='python', dtype=np.float32)
You can read more in read_csv
Also, you can use to_numeric function.
df = df.apply(pd.to_numeric)
A: There are various ways one might do that, such as using: str.replace or str.strip.
Considering that one wants to update the column of the following DataFrame
And let's say that you want to remove the double quotes from the first column.
With str.replace one can do
df[0] = df[0].str.replace(r"[\"]", '')
Or
df[0] = df[0].str.replace('"', "")
This last one will also remove quotation marks if they appear along the element. If for example one has "236"76", it will turn into 23676.
With str.strip, to remove quotes from the ends of the strings, one can do
df[0] = df[0].str.strip('"')
Here is the final result
A: A slightly more generic solution that was useful in my case:
def remove_quotes(datum: object) -> object | str:
if type(datum) is str:
return datum.replace('"', '')
else:
return datum
# Define the column names.
names = ['j', 'x', 'y']
df = pd.read_csv(
'test.csv',
delimiter=';\s',
engine='python',
header=0, # Ignore header.
names=names, # Rename the columns at reading time.
converters={name: remove_quotes for name in names},
)
| stackoverflow | {
"language": "en",
"length": 339,
"provenance": "stackexchange_0000F.jsonl.gz:888491",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615807"
} |
6fb21f17bef336731b8a75cdf83e369e300da8d1 | Stackoverflow Stackexchange
Q: Flutter: Define custom TextStyles for use throughout the app How can I define a small set of custom TextStyles that can then be reused throughout my app. The custom TextStyles should be based on the TextStyles defined in the Theme.
I know how to create the individual TextStyles (e.g.)
Theme.of(context).textTheme.title.copyWith(fontWeight: FontWeight.bold,)
A: Or simply define a such a class and use it in Text()
class AppTextStyle {
static Function sofiaProRegular = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w400);
static Function sofiaProMedium = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w500);
static Function sofiaProBold = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w700);
static Function latoRegular = ({Color color, @required double size}) =>
_lato(color, size, FontWeight.w400);
static TextStyle _sofiaPro(Color color, double size, FontWeight fontWeight) {
return _textStyle("SofiaPro", color, size, fontWeight);
}}
static TextStyle _textStyle(
String fontFamily, Color color, double size, FontWeight fontWeight) {
return TextStyle(
fontFamily: fontFamily,
color: color,
fontSize: size,
fontWeight: fontWeight);
}
| Q: Flutter: Define custom TextStyles for use throughout the app How can I define a small set of custom TextStyles that can then be reused throughout my app. The custom TextStyles should be based on the TextStyles defined in the Theme.
I know how to create the individual TextStyles (e.g.)
Theme.of(context).textTheme.title.copyWith(fontWeight: FontWeight.bold,)
A: Or simply define a such a class and use it in Text()
class AppTextStyle {
static Function sofiaProRegular = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w400);
static Function sofiaProMedium = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w500);
static Function sofiaProBold = ({Color color, @required double size}) =>
_sofiaPro(color, size, FontWeight.w700);
static Function latoRegular = ({Color color, @required double size}) =>
_lato(color, size, FontWeight.w400);
static TextStyle _sofiaPro(Color color, double size, FontWeight fontWeight) {
return _textStyle("SofiaPro", color, size, fontWeight);
}}
static TextStyle _textStyle(
String fontFamily, Color color, double size, FontWeight fontWeight) {
return TextStyle(
fontFamily: fontFamily,
color: color,
fontSize: size,
fontWeight: fontWeight);
}
A: import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Basic Class TextStyle'),
),
body: Center(
child: const Text('Size Text Test', style: myTextStyleBase.size_A
),
);
}
class myTextStyleBase {
static const size_A = TextStyle(fontSize: 10);
static const size_B = TextStyle(fontSize: 30);
}
You can call myTextStyleBase, if there is a similar style. if you change it, just change the style in myTextStyleBase. everything that implements will change too.
https://fluttercrashcourse.com/blog/04-text-style
A: You could make a class that provides methods to obtain the font styles.
Here's an example that declares a CustomTextStyle class that exposes a display5 method for really large text.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomePage(),
);
}
}
class CustomTextStyle {
static TextStyle display5(BuildContext context) {
return Theme.of(context).textTheme.display4.copyWith(fontSize: 192.0);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) => new Scaffold(
appBar: new AppBar(
title: new Text('Custom Font Example'),
),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
new Card(
child: new Container(
child: new Text(
'Wow',
style: CustomTextStyle.display5(context),
),
),
),
],
),
);
}
A: you can use dart extension:
extension TextExtension on Text {
Text setStyle(TextStyle style) => copyWith(style: style);
Text setFontFamily(String fontFamily) =>
copyWith(style: TextStyle(fontFamily: fontFamily));
Text copyWith(
{Key key,
StrutStyle strutStyle,
TextAlign textAlign,
TextDirection textDirection = TextDirection.ltr,
Locale locale,
bool softWrap,
TextOverflow overflow,
double textScaleFactor,
int maxLines,
String semanticsLabel,
TextWidthBasis textWidthBasis,
TextStyle style}) {
return Text(this.data,
key: key ?? this.key,
strutStyle: strutStyle ?? this.strutStyle,
textAlign: textAlign ?? this.textAlign,
textDirection: textDirection ?? this.textDirection,
locale: locale ?? this.locale,
softWrap: softWrap ?? this.softWrap,
overflow: overflow ?? this.overflow,
textScaleFactor: textScaleFactor ?? this.textScaleFactor,
maxLines: maxLines ?? this.maxLines,
semanticsLabel: semanticsLabel ?? this.semanticsLabel,
textWidthBasis: textWidthBasis ?? this.textWidthBasis,
style: style != null ? this.style?.merge(style) ?? style : this.style);
}
}
for example:
Text('MY TEXT').setStyle(...).setFontFamily(...),
A: Like Collin Jackson mentioned above,
class CustomTextStyle {
static TextStyle display5(BuildContext context) {
return Theme.of(context).textTheme.display4.copyWith(fontSize: 192.0);
}
}
this works, but dart linter will complain about it. However, try this
TextStyle display5(BuildContext context) {
return Theme.of(context).textTheme.display4!.copyWith(fontSize: 192.0);
}
You can do this in your code to use it
new Card(
child: new Container(
child: new Text(
'Wow',
style: display5(context),
),
),
),
| stackoverflow | {
"language": "en",
"length": 536,
"provenance": "stackexchange_0000F.jsonl.gz:888527",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615933"
} |
0df9eac7641d99a2abb37629fc503eab273c691b | Stackoverflow Stackexchange
Q: React Native ScrollView is cut off from the bottom on iOS I've just encountered a weird issue that I didn't know why it was happening. For some reason, I can't scroll to the bottom of my <ScrollView>.
Here's my code: https://repl.it/Iqcx/0
Thanks!
A: In my case the issue wasn't flex: 1 or flexGrow: 1, but using padding on ScrollView styles.
So instead of doing this:
<ScrollView style={{padding: 40}}>
{/* MY CONTENT HERE */}
</ScrollView>
I did this:
<ScrollView>
<View style={{padding: 40}}>
{/* MY CONTENT HERE */}
</View>
</ScrollView>
And the problem was fixed.
So if you want to add padding to your ScrollView, create a View inside it and apply padding to it instead.
| Q: React Native ScrollView is cut off from the bottom on iOS I've just encountered a weird issue that I didn't know why it was happening. For some reason, I can't scroll to the bottom of my <ScrollView>.
Here's my code: https://repl.it/Iqcx/0
Thanks!
A: In my case the issue wasn't flex: 1 or flexGrow: 1, but using padding on ScrollView styles.
So instead of doing this:
<ScrollView style={{padding: 40}}>
{/* MY CONTENT HERE */}
</ScrollView>
I did this:
<ScrollView>
<View style={{padding: 40}}>
{/* MY CONTENT HERE */}
</View>
</ScrollView>
And the problem was fixed.
So if you want to add padding to your ScrollView, create a View inside it and apply padding to it instead.
A: Adding flexGrow:1 to the <ScrollView> component contentContainerStyle prop worked for me (adding flex:1 to the outside <View> or to the <ScrollView> was NOT working for me).
<View>
<ScrollView contentContainerStyle={{flexGrow:1}}>
(...content here...)
</ScrollView>
</View>
A:
flex:1 to the outer parent
<View> //Parent
<Header/>
<ScrollView/>
</View>
if ScrollView is cutting off, assign parent <View> flex:1
<View style={{flex:1}}> //Parent
<Header/>
<ScrollView/>
</View>
A: Problem: Your nav bar is pushing your ScrollView down.
Solution: Make the wrapper around your ScrollView fill the entire screen. This change in line 8 does the magic: <View style={StyleSheet.absoluteFill}>
I also changed your code minimally to make it useful for people who don't have your image and to better see what's happening I named the values differently. Here's the working version: https://repl.it/Iqcx/2
Simplified code:
import { View, ScrollView, StyleSheet } from "react-native";
<View style={StyleSheet.absoluteFill}>
<ScrollView />
</View>
A: In my View of the element that was cut off, I had a value height = 100%
Removing this did the job for me.
A: In my case the problem was that my main content was set to position: absolute so the correct height was not calculated.
A: Each of the items in my ScrollView had its aspectRatio set to 1. When I removed that, I was able to scroll to the bottom of the ScrollView.
A: In my ScrollView component I could scroll to the bottom and see all the content, except there was always an overlay at the bottom while I scroll. I solved this by wrapping the ScrollView in a View component by doing this I did not see the overlay no more. Hope that this helps somebody.
| stackoverflow | {
"language": "en",
"length": 386,
"provenance": "stackexchange_0000F.jsonl.gz:888529",
"question_score": "21",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615936"
} |
044c9bf9e684716a4320cb9fd8c1388d030f8a58 | Stackoverflow Stackexchange
Q: How to Compare a String with a Char Guys how do i compare a String with a char?
heres my code :
private String s;
private char c;
public K(String string, char cc){
setS(string);
setC(cc);
}
public void setS(String string){
this.s = string;
}
public void setC(char cc){
this.c = cc;
}
public boolean equals(K other){
return s.equals(c);
}
public boolean try(){
return s.equals(c);
}
if i call my method try, it always returns me false even if i set
both s = "s" and c = 's'.
A: The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.
Secondly think that there are a few things which you need to consider in your method.
If you compare things of two different types they will never be the same.
A String can be null.
How long the string is.
The first char.
I would write the method like :
public boolean isSame() {
if (s != null && s.length() == 1 {
return s.charAt(0) == c;
}
return false;
}
| Q: How to Compare a String with a Char Guys how do i compare a String with a char?
heres my code :
private String s;
private char c;
public K(String string, char cc){
setS(string);
setC(cc);
}
public void setS(String string){
this.s = string;
}
public void setC(char cc){
this.c = cc;
}
public boolean equals(K other){
return s.equals(c);
}
public boolean try(){
return s.equals(c);
}
if i call my method try, it always returns me false even if i set
both s = "s" and c = 's'.
A: The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.
Secondly think that there are a few things which you need to consider in your method.
If you compare things of two different types they will never be the same.
A String can be null.
How long the string is.
The first char.
I would write the method like :
public boolean isSame() {
if (s != null && s.length() == 1 {
return s.charAt(0) == c;
}
return false;
}
A: Either use char comparison (assuming s will always be of length 1):
return c == s.charAt(0);
Or use String comparison:
return s.equals(new String(new char[]{c}));
| stackoverflow | {
"language": "en",
"length": 217,
"provenance": "stackexchange_0000F.jsonl.gz:888548",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615987"
} |
74b76e4acf0556c00518396e9ed33bd75fcbae92 | Stackoverflow Stackexchange
Q: how convert ogg file to telegram voice format? I'm trying to send a voice message through SendVoice method in telegram bot, but it sends the voice as a document file (not play).
ogg file by ffmpeg converted to opus encoding.
https://api.telegram.org/bot<token>/sendVoice?chat_id=x&voice=http://music-farsi.ir/ogg/voice.ogg
What is the difference between the my ogg file and telegram voice message?
My ogg file: ogg file
A: The MIME-Type for the sendVoice method must be set to audio/ogg. Your sample is set to video/ogg.
More infos on the sendVoice method with an url can be found here
| Q: how convert ogg file to telegram voice format? I'm trying to send a voice message through SendVoice method in telegram bot, but it sends the voice as a document file (not play).
ogg file by ffmpeg converted to opus encoding.
https://api.telegram.org/bot<token>/sendVoice?chat_id=x&voice=http://music-farsi.ir/ogg/voice.ogg
What is the difference between the my ogg file and telegram voice message?
My ogg file: ogg file
A: The MIME-Type for the sendVoice method must be set to audio/ogg. Your sample is set to video/ogg.
More infos on the sendVoice method with an url can be found here
A: Thanks to YoilyL I'm able to send voice messages with the spectrogram.
Here's my python script which converts my .wav file to .ogg:
import os
import requests
import subprocess
token = YYYYYYY
chat_id = XXXXXXXX
upload_audio_url = "https://api.telegram.org/bot%s/sendAudio?chat_id=%s" % (token, chat_id)
audio_path_wav = '/Users/me/some-file.wav'
# Convert the file from wav to ogg
filename = os.path.splitext(audio_path_wav)[0]
audio_path_ogg = filename + '.ogg'
subprocess.run(["ffmpeg", '-i', audio_path_wav, '-acodec', 'libopus', audio_path_ogg, '-y'])
with open(audio_path_ogg, 'rb') as f:
data = f.read()
# An arbitrary .ogg filename has to be present so that the spectogram is shown
file = {'audio': ('Message.ogg', data)}
result = requests.post(upload_audio_url, files=file)
This results in the following rendering of the voice message:
You'll need to install ffmpeg using the package manager of your choice.
A: if you want it to display the audio spectrogram, make sure the ogg is encoded with opus codec
A: Telegram has two APIs for sending Audio files: sendVoice
and sendAudio
To have spectrogram, you need to use the sendVoice API.
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
Also, note the other limitations thats mentioned in the docs:
To use sendVoice, the file must have the type audio/ogg and be no more than 1MB in size. 1-20MB voice notes will be sent as files.
Therefore, if you send a ogg file in opus format that is less than 1MB in size, you will get spectogram. If the ogg file is larger than 1MB, it will be still uploaded as a voice however with no spectogram bars.
You can use ffmpeg in linux with a low bitrate to reduce the size of your file:
ffmpeg -i input.mp3 -vn -acodec libopus -b:a 16k audio.ogg
Here is a sample python code that uses to send a sample ogg file to a channel using sendVoice
import os, sys
import requests
# Bot token
token = ''
if len(sys.argv) <=1:
print("Usage: send_voice.py destchannelid filename")
print("\te.g.")
print("\tsend_voice.py -10011111111 audio.ogg")
print("Convert audio files to ogg using the following command")
print("ffmpeg -i input.mp3 -vn -acodec libopus -b:a 16k audio.ogg")
exit()
upload_audio_url = "https://api.telegram.org/bot{}/sendVoice?chat_id={}".format(token,chat_id)
audio_path_ogg = os.getcwd() + "/" + sys.argv[2]
with open(audio_path_ogg, 'rb') as f:
data = f.read()
file = {'voice': ('Message.ogg', data)}
result = requests.post(upload_audio_url, files=file)
print(result.content)
| stackoverflow | {
"language": "en",
"length": 519,
"provenance": "stackexchange_0000F.jsonl.gz:888550",
"question_score": "14",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615991"
} |
4c5f81f180e3060978cfbd7493cac0bb46aa901a | Stackoverflow Stackexchange
Q: How to make git checkout files permission mode are 777? I use root to run git,the files permission mode changed to root 644 each time when I checkout, which means apache cannot delete,modify.
Then I decide to make GIT to checkout files with permission 777. I know set umask 000(default is 022) can do that, but I don't want to change my centos setting.
How to do it?
A: With Git 2.9 or more, you can do
git add --chmod=+x -- afile
git commit -m "Executable!"
Then, on the next clone or checkout, the file will be executable.
Sidenote: a proper umask would be 022 (for 755) or 002 for 775. 777 is generally not recommended.
Note 777 (even with git update-index) does not make sense, as Git itself does not record write: only 644 or 755, spelled 100644 and 100755, with the 100 part meaning "regular file".
| Q: How to make git checkout files permission mode are 777? I use root to run git,the files permission mode changed to root 644 each time when I checkout, which means apache cannot delete,modify.
Then I decide to make GIT to checkout files with permission 777. I know set umask 000(default is 022) can do that, but I don't want to change my centos setting.
How to do it?
A: With Git 2.9 or more, you can do
git add --chmod=+x -- afile
git commit -m "Executable!"
Then, on the next clone or checkout, the file will be executable.
Sidenote: a proper umask would be 022 (for 755) or 002 for 775. 777 is generally not recommended.
Note 777 (even with git update-index) does not make sense, as Git itself does not record write: only 644 or 755, spelled 100644 and 100755, with the 100 part meaning "regular file".
A: git config core.sharedRepository 0664. See git help config.
PS. I use mode 664 because it's more secure than wide-open 666. Git adds executable bit (thus making the mode 775 or 777) for directories automatically.
A: find . -type f -not -name '.git*' | xargs chmod 777
find . -type d -not -name '.git*' | xargs chmod 666
I use this in post-checkout hooks and seemed without any problem till now.
| stackoverflow | {
"language": "en",
"length": 220,
"provenance": "stackexchange_0000F.jsonl.gz:888551",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44615992"
} |
02579bafb74698f39caa06de78280089a626452c | Stackoverflow Stackexchange
Q: How to print the content of the generator? N = [1, 2, 3]
print(n for n in N)
Results:
<generator object <genexpr> at 0x000000000108E780>
Why didn't it print?:
1
2
3
However the code:
sum(n for n in N)
Will sum up all the number in N.
Could you please tell me why sum() worked but print() failed?
A: You are literally printing a generator object representation
If you want on one line, try printing a list
print([n for n in N])
Which is just print(N)
If you want a line separated string, print that
print("\n".join(map(str, N)))
Or write a regular loop and don't micro optimize the lines of code
| Q: How to print the content of the generator? N = [1, 2, 3]
print(n for n in N)
Results:
<generator object <genexpr> at 0x000000000108E780>
Why didn't it print?:
1
2
3
However the code:
sum(n for n in N)
Will sum up all the number in N.
Could you please tell me why sum() worked but print() failed?
A: You are literally printing a generator object representation
If you want on one line, try printing a list
print([n for n in N])
Which is just print(N)
If you want a line separated string, print that
print("\n".join(map(str, N)))
Or write a regular loop and don't micro optimize the lines of code
A: If you don't want to cast it as a list, you can try:
print(*(n for n in N))
See: https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments
A: It's because you passed a generator to a function and that's what __repr__ method of this generator returns. If you want to print what it would generate, you can use:
print(*N, sep='\n') # * will unpack the generator
or
print('\n'.join(map(str, N)))
Note that once you retrieve the generator's output to print it, the generator is exhausted - trying to iterate over it again will produce no items.
A: Generator …
def genfun():
yield ‘A’
yield ‘B’
yield ‘C’
g=genfun()
print(next(g))= it will print 0th index .
print(next(g))= it will print 1st index.
print(next(g))= it will print 2nd index.
print(next(g))= it will print 3rd index But here in this case it will give Error as 3rd element is not there
So , prevent from this error we will use for loop as below .
for i in g :
print(i)
| stackoverflow | {
"language": "en",
"length": 272,
"provenance": "stackexchange_0000F.jsonl.gz:888558",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616012"
} |
bb412693b101cd51ca1d8f9a23025f7593ad7678 | Stackoverflow Stackexchange
Q: In list component, how to implement a component to change the number of results displayed I was thinking about making a simple component with a Select and the list of results that should be displayed.
After reading the code, that seems impossible, because if I change the url, then update is triggered by componentWillReceiveProps, and this method does not check for a change of perPage
Change the prop perPage of the List component does not work either because the List use this prop only if the query does not already contains perPage
Here is an example of what I want to do :
import { List } from "admin-on-rest";
class SourceList extends Component {
constructor(props) {
super(props);
this.state = {
perPage: 10
};
}
render() {
return (
<div>
<Button
onClick={() => {
this.setState({ perPage: 50 });
}}
/>
<List {...props} perPage={this.state.perPage}>
... Here would be the content of the list
</List>
</div>
);
}
}
| Q: In list component, how to implement a component to change the number of results displayed I was thinking about making a simple component with a Select and the list of results that should be displayed.
After reading the code, that seems impossible, because if I change the url, then update is triggered by componentWillReceiveProps, and this method does not check for a change of perPage
Change the prop perPage of the List component does not work either because the List use this prop only if the query does not already contains perPage
Here is an example of what I want to do :
import { List } from "admin-on-rest";
class SourceList extends Component {
constructor(props) {
super(props);
this.state = {
perPage: 10
};
}
render() {
return (
<div>
<Button
onClick={() => {
this.setState({ perPage: 50 });
}}
/>
<List {...props} perPage={this.state.perPage}>
... Here would be the content of the list
</List>
</div>
);
}
}
| stackoverflow | {
"language": "en",
"length": 157,
"provenance": "stackexchange_0000F.jsonl.gz:888560",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616016"
} |
5851128c9bfdd4df6ba7f593285c4f4ae75e7585 | Stackoverflow Stackexchange
Q: How to give more weight to Proper Nouns in scikit TfidfVectorizer I am using sci-kit's TdidfVectorizer to extract keywords from a list of scientific articles. There is an argument for stop_words, but I was wondering if I could give more weight/score to proper nouns such as "Bohr" or "Japan".
Will I have to implement my own custom tfidf vectorizer or can I still use this built in one?
tf = TfidfVectorizer(strip_accents='ascii',
analyzer='word',
ngram_range=(1,1),
min_df = 0,
stop_words = stopwords,
lowercase = True)
A: You can make your own postrpocessing to the TfIdf matrix for it.
At first you need to look through all the words indexes to find indexes for all the Proper Nouns, after that look through the matrix and increase weight for those indexes.
| Q: How to give more weight to Proper Nouns in scikit TfidfVectorizer I am using sci-kit's TdidfVectorizer to extract keywords from a list of scientific articles. There is an argument for stop_words, but I was wondering if I could give more weight/score to proper nouns such as "Bohr" or "Japan".
Will I have to implement my own custom tfidf vectorizer or can I still use this built in one?
tf = TfidfVectorizer(strip_accents='ascii',
analyzer='word',
ngram_range=(1,1),
min_df = 0,
stop_words = stopwords,
lowercase = True)
A: You can make your own postrpocessing to the TfIdf matrix for it.
At first you need to look through all the words indexes to find indexes for all the Proper Nouns, after that look through the matrix and increase weight for those indexes.
| stackoverflow | {
"language": "en",
"length": 127,
"provenance": "stackexchange_0000F.jsonl.gz:888570",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616045"
} |
90e5d5f5180fd8def13d5368bf030895b2f2a7cf | Stackoverflow Stackexchange
Q: Regex validation for Hungarian names I have made my regex name validation like this (for Hungarian names):
/^([A-Z]{1}[a-z áéúőóüö.]{1,}){2,}$/
My only problem that is that it accepts more than just 1 space, which I shouldn't allow.
Any idea how could i fix this?
A: Remove space out of character class and add it outside
because [a-z áéúőóüö.]{1,} mean match one or more characters represented inside [] which will also match any number of spaces as well
you can use ^([A-Z]([a-záéúőóüö.]{1,}\s?)){2,}$ to allow only one space.
Improvement for readability : [A-Z]{1} is equal to [A-Z] so remove unnecessary {1} and {1,} can simply be +
so a concise solution would be ^([A-Z]([a-záéúőóüö.]+\s?)){2,}$
| Q: Regex validation for Hungarian names I have made my regex name validation like this (for Hungarian names):
/^([A-Z]{1}[a-z áéúőóüö.]{1,}){2,}$/
My only problem that is that it accepts more than just 1 space, which I shouldn't allow.
Any idea how could i fix this?
A: Remove space out of character class and add it outside
because [a-z áéúőóüö.]{1,} mean match one or more characters represented inside [] which will also match any number of spaces as well
you can use ^([A-Z]([a-záéúőóüö.]{1,}\s?)){2,}$ to allow only one space.
Improvement for readability : [A-Z]{1} is equal to [A-Z] so remove unnecessary {1} and {1,} can simply be +
so a concise solution would be ^([A-Z]([a-záéúőóüö.]+\s?)){2,}$
A: I lost my right to comment because I threw away my rep as bounty, for science, so I I'll post as answer for now and delete it later :D
small side-note:
There are Hungarian names like Ágnes, Ági, Ákos, Árpád, Ödön, Örs, etc.
Your [A-Z] doesn't cover their first letter, so maybe include the uppercase variants of the Hungarian letters in there as well :)
| stackoverflow | {
"language": "en",
"length": 178,
"provenance": "stackexchange_0000F.jsonl.gz:888576",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616070"
} |
120b2172972c2b02289b7c5045af27e6ab799455 | Stackoverflow Stackexchange
Q: Add syntax highlighting to certain file extensions for VIM or GVIM by default In my Linux machine files with the .sv extension opens up by default with the verilog syntax highlighting scheme, however extension with .vor .vs don't.
I have to manually in gvim do a :set syntax=verilog every time I open one of these files.
How do I make those file extensions .v or .vs open up in a verilog syntax highlighting by default ?
Thanks
A: Add an auto-command to your .vimrc to do that for you:
autocmd BufNewFile,BufRead *.v,*.vs set syntax=verilog
| Q: Add syntax highlighting to certain file extensions for VIM or GVIM by default In my Linux machine files with the .sv extension opens up by default with the verilog syntax highlighting scheme, however extension with .vor .vs don't.
I have to manually in gvim do a :set syntax=verilog every time I open one of these files.
How do I make those file extensions .v or .vs open up in a verilog syntax highlighting by default ?
Thanks
A: Add an auto-command to your .vimrc to do that for you:
autocmd BufNewFile,BufRead *.v,*.vs set syntax=verilog
| stackoverflow | {
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:888577",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616072"
} |
6a499f9c3b98a998dccbb4a0db5a34fe8455da93 | Stackoverflow Stackexchange
Q: When to use QString{...}, tr(...) and +=/append? The information about what QString can do is wide spread in the extensive Qt documentation. But from information overflow I am not sure when I should use what tool best.
For a simple report generator from a form I now have this code, mainly relying on tr and arg to create the QString for the final QMessageBox:
void Dialog::analyseDialog() {
QString str{};
if( ui.lineEdit->text().isEmpty()) {
str += tr("Name: keine Angaben\n");
} else {
str += tr("Name: %1\n").arg(ui.lineEdit->text());
}
if( ui.spinBox->cleanText().isEmpty()) {
str += tr("Geburtsdatum: keine Angaben\n");
} else {
str += tr("Geburtsdatum: %1\n").arg(ui.spinBox->cleanText());
}
if( ui.radioButton->isChecked()) {
str += tr("Geschlecht: weiblich\n");
} else {
str += tr("Geschlecht: männlich\n");
}
QMessageBox::information(0, tr("Die Auswertung"), str);
}
But I am not sure if this is correctly used:
*
*Is using tr() appropriate if I don't expect localization?
*or should I use QString{...}-c'tor instead?
*Is += (or .append) efficient with Qt? It is supposed to use QStringBuffer internally. Sometimes... err... what?
*Or is there a much better approach?
A: Q:Is += (or .append) efficient with Qt? It is supposed to use QStringBuffer internally. Sometimes... err... what? | Q: When to use QString{...}, tr(...) and +=/append? The information about what QString can do is wide spread in the extensive Qt documentation. But from information overflow I am not sure when I should use what tool best.
For a simple report generator from a form I now have this code, mainly relying on tr and arg to create the QString for the final QMessageBox:
void Dialog::analyseDialog() {
QString str{};
if( ui.lineEdit->text().isEmpty()) {
str += tr("Name: keine Angaben\n");
} else {
str += tr("Name: %1\n").arg(ui.lineEdit->text());
}
if( ui.spinBox->cleanText().isEmpty()) {
str += tr("Geburtsdatum: keine Angaben\n");
} else {
str += tr("Geburtsdatum: %1\n").arg(ui.spinBox->cleanText());
}
if( ui.radioButton->isChecked()) {
str += tr("Geschlecht: weiblich\n");
} else {
str += tr("Geschlecht: männlich\n");
}
QMessageBox::information(0, tr("Die Auswertung"), str);
}
But I am not sure if this is correctly used:
*
*Is using tr() appropriate if I don't expect localization?
*or should I use QString{...}-c'tor instead?
*Is += (or .append) efficient with Qt? It is supposed to use QStringBuffer internally. Sometimes... err... what?
*Or is there a much better approach?
A: Q:Is += (or .append) efficient with Qt? It is supposed to use QStringBuffer internally. Sometimes... err... what?
A: You may have java experience, in java, a String is not modifiable, you concatenate it by making a new String, That's why java recommends using StringBuffer, in C++, std::string or QString is a vector-like object,
something like StringBuffer in java, so += or append is efficient
| stackoverflow | {
"language": "en",
"length": 237,
"provenance": "stackexchange_0000F.jsonl.gz:888613",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616177"
} |
967af799b8ca4349c33151e4e74cc71081807781 | Stackoverflow Stackexchange
Q: mongodb wildcard match all values for specific key I am trying to figure out how to match a key and return all the values for that key. Is it possible to give the value as a wildcard? I want to return everything for that specific key using wildcard on the value.
db.collection.find({"key" :"*"})
Also I was hoping this would return the entire collection as well that had the key with the wildcard value match as well.
A: You may be looking for something like this:
db.collection.find({"key": {$exists: true}})
This will return all documents in the collection where the key "key" is present. The entire document is returned.
| Q: mongodb wildcard match all values for specific key I am trying to figure out how to match a key and return all the values for that key. Is it possible to give the value as a wildcard? I want to return everything for that specific key using wildcard on the value.
db.collection.find({"key" :"*"})
Also I was hoping this would return the entire collection as well that had the key with the wildcard value match as well.
A: You may be looking for something like this:
db.collection.find({"key": {$exists: true}})
This will return all documents in the collection where the key "key" is present. The entire document is returned.
A: Yes:
db.collection.distinct("key")
| stackoverflow | {
"language": "en",
"length": 111,
"provenance": "stackexchange_0000F.jsonl.gz:888641",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616276"
} |
280494a76984d67812ffd2c803847e30efece9b1 | Stackoverflow Stackexchange
Q: Declarations in extensions cannot override yet error in Swift 4 I have an extension:
public extension UIWindow {
override public func topMostController()->UIViewController? { ... }
}
but for my topMostController I get the next error:
Declarations in extensions cannot override yet error
It works well for Swift 3.1, but for Swift 4 I get this error. How can it be fixed? What did they change in Swift 4?
A: It will work if you make the base implementation @objc. See Hamish's answer for a detailed explanation about the internals.
Overriding methods declared in extensions is a bit tricky to do correctly. Objective-C supports it, but it's not absolutely safe. Swift aims to do it better. The proposal is not completed yet.
Current version of the proposal available here.
| Q: Declarations in extensions cannot override yet error in Swift 4 I have an extension:
public extension UIWindow {
override public func topMostController()->UIViewController? { ... }
}
but for my topMostController I get the next error:
Declarations in extensions cannot override yet error
It works well for Swift 3.1, but for Swift 4 I get this error. How can it be fixed? What did they change in Swift 4?
A: It will work if you make the base implementation @objc. See Hamish's answer for a detailed explanation about the internals.
Overriding methods declared in extensions is a bit tricky to do correctly. Objective-C supports it, but it's not absolutely safe. Swift aims to do it better. The proposal is not completed yet.
Current version of the proposal available here.
A: Swift 5
Actually there are few problems in OP code:
*
*UIView (which is superclass of UIWindow) doesn't have method topMostController(), that why you can't override it.
*Apple doesn't encourage override func inside extension:
Extensions can add new functionality to a type, but they cannot
override existing functionality.
*Incase you still want to override function in extension, there are 2 ways:
[A] Mark your function with @objc dynamic func in parent class:
class Vehicle {
@objc dynamic func run() { /* do something */ }
}
class Car: Vehicle { }
extension Car {
override func run() { /* do another thing */ }
}
[B] Override function from build-in classes, which is descendant of NSObject.
extension UIWindow {
// UIWindow is a descendant of NSObject, and its superclass UIView has this function then you can override
override open func becomeFirstResponder() -> Bool {
...
return super.becomeFirstResponder()
}
}
A: Extensions can add new functionality to a type, but they cannot override existing functionality.
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).
Extensions in Swift can:
*
*Add computed instance properties and computed type properties
*Define instance methods and type methods
*Provide new initializers
*Define subscripts
*Define and use new nested types
*Make an existing type conform to a protocol
Apple Developer Guide
You are trying to do is similar to what done by this code:
class MyClass: UIWindow {
func myFunc() {}
}
extension MyClass {
override func myFunc() {}
}
NOTE: If you want to override topMostController() then make subclass of UIWindow
| stackoverflow | {
"language": "en",
"length": 412,
"provenance": "stackexchange_0000F.jsonl.gz:888674",
"question_score": "64",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616409"
} |
b32a556bd73e49350578b34c0d3b13e39dbd3462 | Stackoverflow Stackexchange
Q: Custom object passed in a method in DAO class Room persistence I am trying to replace my database with Room persistence I've a method which accept a Custom Object and return the id of that row is in database
/**
* This method return -1 if there is not any classInfo other wise return
* the id of the classInfo
*
* @param ClassInfo
* @return
*/
public int getClassIdByInfo(ClassInfo classInfo) {
Cursor c = db.query(DB_CLASS_INFO, new String[]{CL_ID}, CL_BRANCH
+ "=? AND " + CL_SEM + "=? AND " + CL_SECTION + "=?",
new String[]{classInfo.branch, classInfo.sem, classInfo.section}, null, null, null);
if (c.getCount() > 0) {
c.moveToFirst();
return c.getInt(0);
} else {
return -1;
}
I want to replace this method with Room persistence DAO method
@Dao
public interface StudentClassDao {
@Query("SELECT id FROM class_info....") //what will be the query?
int getClassIdByInfo(ClassInfo classInfo);
}
What will be the query for that scenario?
| Q: Custom object passed in a method in DAO class Room persistence I am trying to replace my database with Room persistence I've a method which accept a Custom Object and return the id of that row is in database
/**
* This method return -1 if there is not any classInfo other wise return
* the id of the classInfo
*
* @param ClassInfo
* @return
*/
public int getClassIdByInfo(ClassInfo classInfo) {
Cursor c = db.query(DB_CLASS_INFO, new String[]{CL_ID}, CL_BRANCH
+ "=? AND " + CL_SEM + "=? AND " + CL_SECTION + "=?",
new String[]{classInfo.branch, classInfo.sem, classInfo.section}, null, null, null);
if (c.getCount() > 0) {
c.moveToFirst();
return c.getInt(0);
} else {
return -1;
}
I want to replace this method with Room persistence DAO method
@Dao
public interface StudentClassDao {
@Query("SELECT id FROM class_info....") //what will be the query?
int getClassIdByInfo(ClassInfo classInfo);
}
What will be the query for that scenario?
| stackoverflow | {
"language": "en",
"length": 152,
"provenance": "stackexchange_0000F.jsonl.gz:888676",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616413"
} |
8f4e5073d0c0e444b6eaaef1653863662bb18100 | Stackoverflow Stackexchange
Q: How I know which contacts have iMessage? I have iPhone 6.
Is there any app on apple app store that can show me which of my contacts have IOS iMessage? There is some information on google but for checking one by one contact. I want to check all contacts in one shot
A: It's old but anyway ....
*
*Launch the Messages app in iOS.
*Tap the Compose button in the upper right corner to start a new message.
*Type the contacts name, or just put the first letter of their name and have a list populate.
*iMessage users will show a blue iMessage icon alongside their name.
| Q: How I know which contacts have iMessage? I have iPhone 6.
Is there any app on apple app store that can show me which of my contacts have IOS iMessage? There is some information on google but for checking one by one contact. I want to check all contacts in one shot
A: It's old but anyway ....
*
*Launch the Messages app in iOS.
*Tap the Compose button in the upper right corner to start a new message.
*Type the contacts name, or just put the first letter of their name and have a list populate.
*iMessage users will show a blue iMessage icon alongside their name.
| stackoverflow | {
"language": "en",
"length": 109,
"provenance": "stackexchange_0000F.jsonl.gz:888689",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616446"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.