qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
58,395,576
Given an application converting csv to parquet (from and to S3) with little transformation: ``` for table in tables: df_table = spark.read.format('csv') \ .option("header", "true") \ .option("escape", "\"") \ .load(path) df_one_seven_thirty_days = df_table \ .filter( (df_table['date'] == fn.to_date(fn.lit(one_day))) \ | (df_table['date'] == fn.to_date(fn.lit(seven_days))) \ | (df_table['date'] == fn.to_date(fn.lit(thirty_days))) ) for i in df_one_seven_thirty_days.schema.names: df_one_seven_thirty_days = df_one_seven_thirty_days.withColumnRenamed(i, colrename(i).lower()) df_one_seven_thirty_days.createOrReplaceTempView(table) df_sql = spark.sql("SELECT * FROM "+table) df_sql.write \ .mode("overwrite").format('parquet') \ .partitionBy("customer_id", "date") \ .option("path", path) \ .saveAsTable(adwords_table) ``` I'm facing a difficulty with spark EMR. On local with spark submit, this has no difficulties running (140MB of data) and quite fast. But on EMR, it's another story. the first "adwords\_table" will be converted without problems but the second one stays idle. I've gone through the spark jobs UI provided by EMR and I noticed that once this task is done: > > Listing leaf files and directories for 187 paths: > > > Spark kills all executors: [![enter image description here](https://i.stack.imgur.com/FAL2c.png)](https://i.stack.imgur.com/FAL2c.png) and 20min later nothing more happens. All the tasks are on "Completed" and no new ones are starting. I'm waiting for the saveAsTable to start. My local machine is 8 cores 15GB and the cluster is made of 10 nodes r3.4xlarge: 32 vCore, 122 GiB memory, 320 SSD GB storage EBS Storage:200 GiB The configuration is using `maximizeResourceAllocation` true and I've only change the --num-executors / --executor-cores to 5 Does any know why the cluster goes into "idle" and don't finishes the task? (it'll eventually crashes without errors 3 hours later) **EDIT:** I made few progress by removing all glue catalogue connections + downgrading hadoop to use: hadoop-aws:2.7.3 Now the saveAsTable is working just fine, but once it finishes, I see the executors being removed and the cluster is idle, the step doesn't finish. Thus my problem is still the same.
2019/10/15
[ "https://Stackoverflow.com/questions/58395576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599698/" ]
I would recommend: ``` select r1.* from R1 where exists (select 1 from r2 where r1.a = r2.val) or exists (select 1 from r2 where r1.b = r2.val); ``` Then, you want an index on `r2(val)`. If `r2` is *really* small and `r1` is *really* big and there are separate indexes on `r1(a)` and `r1(b)`, then this might be faster: ``` select r1.* from r1 join r2 on r1.a = r2.val union select r1.* from r1 join r2 on r1.b = r2.val; ```
Use a [`CTE`](https://www.postgresql.org/docs/current/queries-with.html) that returns all the `VAL`s from `R2` (so you scan `R2` only once). But maybe this is not needed if the optimizer does it already for `select VAL from R2`. Then use `CASE` to check the 2 separate cases, so the 2nd case (`WHEN b IN (SELECT VAL FROM cte)`) will be evaluated only when the 1st case (`WHEN a IN (SELECT VAL FROM cte)`) fails. ``` WITH cte AS (SELECT VAL FROM R2) SELECT * FROM R1 WHERE 1 = CASE WHEN a IN (SELECT VAL FROM cte) THEN 1 WHEN b IN (SELECT VAL FROM cte) THEN 1 ELSE 0 END ```
58,395,576
Given an application converting csv to parquet (from and to S3) with little transformation: ``` for table in tables: df_table = spark.read.format('csv') \ .option("header", "true") \ .option("escape", "\"") \ .load(path) df_one_seven_thirty_days = df_table \ .filter( (df_table['date'] == fn.to_date(fn.lit(one_day))) \ | (df_table['date'] == fn.to_date(fn.lit(seven_days))) \ | (df_table['date'] == fn.to_date(fn.lit(thirty_days))) ) for i in df_one_seven_thirty_days.schema.names: df_one_seven_thirty_days = df_one_seven_thirty_days.withColumnRenamed(i, colrename(i).lower()) df_one_seven_thirty_days.createOrReplaceTempView(table) df_sql = spark.sql("SELECT * FROM "+table) df_sql.write \ .mode("overwrite").format('parquet') \ .partitionBy("customer_id", "date") \ .option("path", path) \ .saveAsTable(adwords_table) ``` I'm facing a difficulty with spark EMR. On local with spark submit, this has no difficulties running (140MB of data) and quite fast. But on EMR, it's another story. the first "adwords\_table" will be converted without problems but the second one stays idle. I've gone through the spark jobs UI provided by EMR and I noticed that once this task is done: > > Listing leaf files and directories for 187 paths: > > > Spark kills all executors: [![enter image description here](https://i.stack.imgur.com/FAL2c.png)](https://i.stack.imgur.com/FAL2c.png) and 20min later nothing more happens. All the tasks are on "Completed" and no new ones are starting. I'm waiting for the saveAsTable to start. My local machine is 8 cores 15GB and the cluster is made of 10 nodes r3.4xlarge: 32 vCore, 122 GiB memory, 320 SSD GB storage EBS Storage:200 GiB The configuration is using `maximizeResourceAllocation` true and I've only change the --num-executors / --executor-cores to 5 Does any know why the cluster goes into "idle" and don't finishes the task? (it'll eventually crashes without errors 3 hours later) **EDIT:** I made few progress by removing all glue catalogue connections + downgrading hadoop to use: hadoop-aws:2.7.3 Now the saveAsTable is working just fine, but once it finishes, I see the executors being removed and the cluster is idle, the step doesn't finish. Thus my problem is still the same.
2019/10/15
[ "https://Stackoverflow.com/questions/58395576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2599698/" ]
It seems like in this specific case the first query I suggested in my main comment provides the best performance : ``` select * from R1 where R1.a in (select VAL from R2) or R1.b in (select VAL from R2); ``` @klin prepared a dbfiddle with all the execution plans if someone want to have a look : <https://dbfiddle.uk/?rdbms=postgres_9.5&fiddle=5b50f605262e406c0bab13710ec121d5>
Use a [`CTE`](https://www.postgresql.org/docs/current/queries-with.html) that returns all the `VAL`s from `R2` (so you scan `R2` only once). But maybe this is not needed if the optimizer does it already for `select VAL from R2`. Then use `CASE` to check the 2 separate cases, so the 2nd case (`WHEN b IN (SELECT VAL FROM cte)`) will be evaluated only when the 1st case (`WHEN a IN (SELECT VAL FROM cte)`) fails. ``` WITH cte AS (SELECT VAL FROM R2) SELECT * FROM R1 WHERE 1 = CASE WHEN a IN (SELECT VAL FROM cte) THEN 1 WHEN b IN (SELECT VAL FROM cte) THEN 1 ELSE 0 END ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
> > This function is working properly in devices before Android N > > > It works for very few `Uri` values, may not have a result (e.g., for things that are indexed by `MediaStore` that are not local files), and may not have a usable result (e.g., for files on removable storage). > > So please help. > > > Use a `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. Ideally, just use that stream directly, for whatever it is that you are trying to do. Or, use that `InputStream` and some `FileOutputStream` on a file that you control to make a copy of the content, then use that file.
@Redturbo I can't write a comment, I write here ``` IOUtils.copyStream(inputStream, outputStream); ``` TEMP\_DIR\_PATH - any your directory path, something like this ``` File rootDataDir = context.getFilesDir(); File copyFile = new File( rootDataDir + File.separator + fileName + ".jpg"); ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
> > This function is working properly in devices before Android N > > > It works for very few `Uri` values, may not have a result (e.g., for things that are indexed by `MediaStore` that are not local files), and may not have a usable result (e.g., for files on removable storage). > > So please help. > > > Use a `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. Ideally, just use that stream directly, for whatever it is that you are trying to do. Or, use that `InputStream` and some `FileOutputStream` on a file that you control to make a copy of the content, then use that file.
//The following code is working in Android N: ``` private static String getFilePathForN(Uri uri, Context context) { Uri returnUri = uri; Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File file = new File(context.getFilesDir(), name); try { InputStream inputStream = context.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; int maxBufferSize = 1 * 1024 * 1024; int bytesAvailable = inputStream.available(); //int bufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } Log.e("File Size", "Size " + file.length()); inputStream.close(); outputStream.close(); Log.e("File Path", "Path " + file.getPath()); Log.e("File Size", "Size " + file.length()); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return file.getPath(); } ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
> > This function is working properly in devices before Android N > > > It works for very few `Uri` values, may not have a result (e.g., for things that are indexed by `MediaStore` that are not local files), and may not have a usable result (e.g., for files on removable storage). > > So please help. > > > Use a `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. Ideally, just use that stream directly, for whatever it is that you are trying to do. Or, use that `InputStream` and some `FileOutputStream` on a file that you control to make a copy of the content, then use that file.
Further adding to Vidha's answer as per Android R storage framework guide and if you do not want to permanently save the copied file to storage: ``` public static String getFilePathFromURI(Context context, Uri contentUri) { File folder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { folder = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+ "yourAppFolderName" ); } else { folder = new File(Environment.getExternalStorageDirectory() + "/"+ "yourAppFolderName"); } // if you want to save the copied image temporarily for further process use .TEMP folder otherwise use your app folder where you want to save String TEMP_DIR_PATH = folder.getAbsolutePath() + "/.TEMP_CAMERA.xxx"; //copy file and send new file path String fileName = getFilename(); if (!TextUtils.isEmpty(fileName)) { File dir = new File(TEMP_DIR_PATH); dir.mkdirs(); File copyFile = new File(dir, fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static String getFilename() { // if file is not to be saved, this format can be used otherwise current fileName from Vidha's answer can be used String ts = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date()); return ".TEMP_" + ts + ".xxx"; } ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
As per given answer by CommonsWare, the solution code is : ``` public static String getFilePathFromURI(Context context, Uri contentUri) { //copy file and send new file path String fileName = getFileName(contentUri); if (!TextUtils.isEmpty(fileName)) { File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static String getFileName(Uri uri) { if (uri == null) return null; String fileName = null; String path = uri.getPath(); int cut = path.lastIndexOf('/'); if (cut != -1) { fileName = path.substring(cut + 1); } return fileName; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` I hope this helps you. The origin of IOUtils.copy is from this site : <https://www.developerfeed.com/copy-bytes-inputstream-outputstream-android/> (May need to change a bit the exception but it works as needed)
@Redturbo I can't write a comment, I write here ``` IOUtils.copyStream(inputStream, outputStream); ``` TEMP\_DIR\_PATH - any your directory path, something like this ``` File rootDataDir = context.getFilesDir(); File copyFile = new File( rootDataDir + File.separator + fileName + ".jpg"); ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
As per given answer by CommonsWare, the solution code is : ``` public static String getFilePathFromURI(Context context, Uri contentUri) { //copy file and send new file path String fileName = getFileName(contentUri); if (!TextUtils.isEmpty(fileName)) { File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static String getFileName(Uri uri) { if (uri == null) return null; String fileName = null; String path = uri.getPath(); int cut = path.lastIndexOf('/'); if (cut != -1) { fileName = path.substring(cut + 1); } return fileName; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` I hope this helps you. The origin of IOUtils.copy is from this site : <https://www.developerfeed.com/copy-bytes-inputstream-outputstream-android/> (May need to change a bit the exception but it works as needed)
//The following code is working in Android N: ``` private static String getFilePathForN(Uri uri, Context context) { Uri returnUri = uri; Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File file = new File(context.getFilesDir(), name); try { InputStream inputStream = context.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; int maxBufferSize = 1 * 1024 * 1024; int bytesAvailable = inputStream.available(); //int bufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } Log.e("File Size", "Size " + file.length()); inputStream.close(); outputStream.close(); Log.e("File Path", "Path " + file.getPath()); Log.e("File Size", "Size " + file.length()); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return file.getPath(); } ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
As per given answer by CommonsWare, the solution code is : ``` public static String getFilePathFromURI(Context context, Uri contentUri) { //copy file and send new file path String fileName = getFileName(contentUri); if (!TextUtils.isEmpty(fileName)) { File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static String getFileName(Uri uri) { if (uri == null) return null; String fileName = null; String path = uri.getPath(); int cut = path.lastIndexOf('/'); if (cut != -1) { fileName = path.substring(cut + 1); } return fileName; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` I hope this helps you. The origin of IOUtils.copy is from this site : <https://www.developerfeed.com/copy-bytes-inputstream-outputstream-android/> (May need to change a bit the exception but it works as needed)
Further adding to Vidha's answer as per Android R storage framework guide and if you do not want to permanently save the copied file to storage: ``` public static String getFilePathFromURI(Context context, Uri contentUri) { File folder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { folder = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+ "yourAppFolderName" ); } else { folder = new File(Environment.getExternalStorageDirectory() + "/"+ "yourAppFolderName"); } // if you want to save the copied image temporarily for further process use .TEMP folder otherwise use your app folder where you want to save String TEMP_DIR_PATH = folder.getAbsolutePath() + "/.TEMP_CAMERA.xxx"; //copy file and send new file path String fileName = getFilename(); if (!TextUtils.isEmpty(fileName)) { File dir = new File(TEMP_DIR_PATH); dir.mkdirs(); File copyFile = new File(dir, fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static String getFilename() { // if file is not to be saved, this format can be used otherwise current fileName from Vidha's answer can be used String ts = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date()); return ".TEMP_" + ts + ".xxx"; } ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
//The following code is working in Android N: ``` private static String getFilePathForN(Uri uri, Context context) { Uri returnUri = uri; Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File file = new File(context.getFilesDir(), name); try { InputStream inputStream = context.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; int maxBufferSize = 1 * 1024 * 1024; int bytesAvailable = inputStream.available(); //int bufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } Log.e("File Size", "Size " + file.length()); inputStream.close(); outputStream.close(); Log.e("File Path", "Path " + file.getPath()); Log.e("File Size", "Size " + file.length()); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return file.getPath(); } ```
@Redturbo I can't write a comment, I write here ``` IOUtils.copyStream(inputStream, outputStream); ``` TEMP\_DIR\_PATH - any your directory path, something like this ``` File rootDataDir = context.getFilesDir(); File copyFile = new File( rootDataDir + File.separator + fileName + ".jpg"); ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
@Redturbo I can't write a comment, I write here ``` IOUtils.copyStream(inputStream, outputStream); ``` TEMP\_DIR\_PATH - any your directory path, something like this ``` File rootDataDir = context.getFilesDir(); File copyFile = new File( rootDataDir + File.separator + fileName + ".jpg"); ```
Further adding to Vidha's answer as per Android R storage framework guide and if you do not want to permanently save the copied file to storage: ``` public static String getFilePathFromURI(Context context, Uri contentUri) { File folder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { folder = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+ "yourAppFolderName" ); } else { folder = new File(Environment.getExternalStorageDirectory() + "/"+ "yourAppFolderName"); } // if you want to save the copied image temporarily for further process use .TEMP folder otherwise use your app folder where you want to save String TEMP_DIR_PATH = folder.getAbsolutePath() + "/.TEMP_CAMERA.xxx"; //copy file and send new file path String fileName = getFilename(); if (!TextUtils.isEmpty(fileName)) { File dir = new File(TEMP_DIR_PATH); dir.mkdirs(); File copyFile = new File(dir, fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static String getFilename() { // if file is not to be saved, this format can be used otherwise current fileName from Vidha's answer can be used String ts = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date()); return ".TEMP_" + ts + ".xxx"; } ```
42,508,383
In Nougat, this function is not working. ``` String path = getRealPathFromURI(this, getIntent().getParcelableExtra(Intent.EXTRA_STREAM)); ``` ``` public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) return contentUri.getPath(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } ``` Crash log: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{class path}: java.lang.IllegalArgumentException: column '_data' does not exist at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by java.lang.IllegalArgumentException: column '_data' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:333) at android.database.CursorWrapper.getColumnIndexOrThrow(CursorWrapper.java:87) at com.package.SaveImageActivity.getRealPathFromURI() at com.package.SaveImageActivity.onCreate() at android.app.Activity.performCreate(Activity.java:6672) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) ``` This function is working properly in devices before Android N. I read the article [file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)](https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en). But couldn't find any solution. So please help.
2017/02/28
[ "https://Stackoverflow.com/questions/42508383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4150706/" ]
//The following code is working in Android N: ``` private static String getFilePathForN(Uri uri, Context context) { Uri returnUri = uri; Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null); /* * Get the column indexes of the data in the Cursor, * * move to the first row in the Cursor, get the data, * * and display it. * */ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); returnCursor.moveToFirst(); String name = (returnCursor.getString(nameIndex)); String size = (Long.toString(returnCursor.getLong(sizeIndex))); File file = new File(context.getFilesDir(), name); try { InputStream inputStream = context.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; int maxBufferSize = 1 * 1024 * 1024; int bytesAvailable = inputStream.available(); //int bufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); final byte[] buffers = new byte[bufferSize]; while ((read = inputStream.read(buffers)) != -1) { outputStream.write(buffers, 0, read); } Log.e("File Size", "Size " + file.length()); inputStream.close(); outputStream.close(); Log.e("File Path", "Path " + file.getPath()); Log.e("File Size", "Size " + file.length()); } catch (Exception e) { Log.e("Exception", e.getMessage()); } return file.getPath(); } ```
Further adding to Vidha's answer as per Android R storage framework guide and if you do not want to permanently save the copied file to storage: ``` public static String getFilePathFromURI(Context context, Uri contentUri) { File folder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { folder = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+ "yourAppFolderName" ); } else { folder = new File(Environment.getExternalStorageDirectory() + "/"+ "yourAppFolderName"); } // if you want to save the copied image temporarily for further process use .TEMP folder otherwise use your app folder where you want to save String TEMP_DIR_PATH = folder.getAbsolutePath() + "/.TEMP_CAMERA.xxx"; //copy file and send new file path String fileName = getFilename(); if (!TextUtils.isEmpty(fileName)) { File dir = new File(TEMP_DIR_PATH); dir.mkdirs(); File copyFile = new File(dir, fileName); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static String getFilename() { // if file is not to be saved, this format can be used otherwise current fileName from Vidha's answer can be used String ts = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date()); return ".TEMP_" + ts + ".xxx"; } ```
7,326,572
So I'm building an application in Rails 3 using Devise as my authentication mechanism. I have all my controllers and views working. Our web site is humming along. Now we'd like to export our routes to 3rd party developers. The problem is how. Here's the list of things I think I need to figure out. 1. Third party authentication. I am trying to get it straight in my head what I need to do. We have an existing user base and tokens have been generated for all of them with the Devise authentication model. Now I need to provide some kind of security. My current line of thinking is to set up an OAuth Provider to manage private keys and then somehow set up our web app as one of the applications the 3rd party developer can gain access to. Is that the correct line of thinking or am I over-engineering it? 2. Generate public facing documentation for our REST endpoints. While the rake routes is nice for internal developers, I really think we need something more along the lines of swagger-ui. the problem is rails doesn't generate the appropriate json/xml calls for swagger-ui. Which as I understand it are required in a true REST service. Such as resource listing, and operations listing on a resource. Thanks in advance for any direction you can give me in these arena's!
2011/09/06
[ "https://Stackoverflow.com/questions/7326572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195351/" ]
I'm biased about Swagger (I work on it at Wordnik) and will point out that we'll add ruby server support to automatically generate the description layer like we do with Scala.
I would definitely recommend OAuth if there is a security element for your users. That is, you want someone to be able to edit multiple users details via their service then used 3-legged OAuth (Provider, User, Client). Otherwise go for the 2-legged OAuth (Provider, Client.) If you want to implement a 3-legged OAuth API then I wrote a tutorial which is available [here](https://github.com/Gazler/Oauth2-Tutorial). It uses Devise and Oauth2. As for the documentation, I would go as far as to write custom documentation instead of relying on tools. Twitter have a very well documented API, I use that as a basis for the RESTful APIs I write.
40,713,757
I need to add string in between of filename where a pattern is matched. Sample filenames: ``` file_1_my001 file_11_my0012 file_65_my_012 ``` I would like to rename them as: ``` file_1_my_copied_001 file_11_my_copied_0012 file_65_my_copied_012 ``` Pattern is `<any string>0<any string>` My logic was to first fetch the numerical format starting with 0, store in variable as pattern, then search for the variable and replace it by `_copied_<variable>`. I tried fetching numbers as: ``` ls | sed -e s/[^0-9]//g ``` but above command is fetching all numbers in filename eg. `1001, 110012, 65012` I am unable to make it search for numerical format starting with 0. Please guide.
2016/11/21
[ "https://Stackoverflow.com/questions/40713757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173763/" ]
with `perl` based `rename` command: ``` $ touch file_1_my001 file_11_my0012 file_65_my_012 $ rename -n 's/_?(?=0)/_copied_/' file_* rename(file_11_my0012, file_11_my_copied_0012) rename(file_1_my001, file_1_my_copied_001) rename(file_65_my_012, file_65_my_copied_012) ``` * `_?(?=0)` zero or one instance of `_` followed by `0` * `-n` option is for dry run, after it looks good, remove the option for actual renaming If `perl` based `rename` is not available, try: ``` $ for file in file_* ; do echo mv "$file" $(echo "$file" | sed 's/_\?0/_copied_0/'); done mv file_11_my0012 file_11_my_copied_0012 mv file_1_my001 file_1_my_copied_001 mv file_65_my_012 file_65_my_copied_012 ``` If it is okay, change `echo mv` to `mv` for actual renaming If optional `_` before `0` is not present, it is easier to use [parameter expansion](http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion) ``` $ touch file_1_my001 file_11_my0012 file_65_my012 $ for file in file_* ; do echo mv "$file" "${file/0/_copied_0}"; done mv file_11_my0012 file_11_my_copied_0012 mv file_1_my001 file_1_my_copied_001 mv file_65_my012 file_65_my_copied_012 ```
``` ls | sed -e 's/\([_]*0\)/_copied_0/' ```
40,713,757
I need to add string in between of filename where a pattern is matched. Sample filenames: ``` file_1_my001 file_11_my0012 file_65_my_012 ``` I would like to rename them as: ``` file_1_my_copied_001 file_11_my_copied_0012 file_65_my_copied_012 ``` Pattern is `<any string>0<any string>` My logic was to first fetch the numerical format starting with 0, store in variable as pattern, then search for the variable and replace it by `_copied_<variable>`. I tried fetching numbers as: ``` ls | sed -e s/[^0-9]//g ``` but above command is fetching all numbers in filename eg. `1001, 110012, 65012` I am unable to make it search for numerical format starting with 0. Please guide.
2016/11/21
[ "https://Stackoverflow.com/questions/40713757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173763/" ]
with `perl` based `rename` command: ``` $ touch file_1_my001 file_11_my0012 file_65_my_012 $ rename -n 's/_?(?=0)/_copied_/' file_* rename(file_11_my0012, file_11_my_copied_0012) rename(file_1_my001, file_1_my_copied_001) rename(file_65_my_012, file_65_my_copied_012) ``` * `_?(?=0)` zero or one instance of `_` followed by `0` * `-n` option is for dry run, after it looks good, remove the option for actual renaming If `perl` based `rename` is not available, try: ``` $ for file in file_* ; do echo mv "$file" $(echo "$file" | sed 's/_\?0/_copied_0/'); done mv file_11_my0012 file_11_my_copied_0012 mv file_1_my001 file_1_my_copied_001 mv file_65_my_012 file_65_my_copied_012 ``` If it is okay, change `echo mv` to `mv` for actual renaming If optional `_` before `0` is not present, it is easier to use [parameter expansion](http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion) ``` $ touch file_1_my001 file_11_my0012 file_65_my012 $ for file in file_* ; do echo mv "$file" "${file/0/_copied_0}"; done mv file_11_my0012 file_11_my_copied_0012 mv file_1_my001 file_1_my_copied_001 mv file_65_my012 file_65_my_copied_012 ```
Something like, ``` $ sed -E "s/(.*[^0-9]+)(0[0-9]*)/\1_copied_\2/" ```
825,944
I have connected to nic adapters a standard vSwitch, and have enable 'Route based on an IP hash' on the vSwitch. For the physical switch we are using a cisco switch and have enabled LACP with nic teaming on two ports. Now when we connect, the host stops responding. To bring it back I need to change the port on the physical switch. What could we be doing wrong.
2017/01/12
[ "https://serverfault.com/questions/825944", "https://serverfault.com", "https://serverfault.com/users/75464/" ]
Using LACP on the ESXi end requires that the uplinks be attached to a Distributed switch, as Standard switches don't have those options. You can still get teaming with standard switches, but need to enable a static team on the switch end, then use 'Route based on an IP hash' on your vSwitch.
The management interface overrides the settings of the vswitch. Set the settings of the management interface of the ESXi accordingly, especially the hashing algorithm.
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
I don't know whether you can use any random integer function library or not. However, I am giving you a simple pseudo code based on that: ``` 1) Generate a Random Number I from 1 to 10. 2) For J = 0 to I byte array[j] = (byte) Generate a Random Number from 0 to 128. 3) For J = 0 to I String st = st + (char) byte array[j] ``` String will be a random word. Simple. But, I don't know whether acceptable or not.
**Nudge served:** Yes, it is possible. You run single for-loop and then convert every counter value to base 26. Then every digit in your new number will code one letter. Please see [here](http://rachel5nj.tripod.com/NOTC/convertingbases.html) on how to convert numbers to arbitrary base. (Sorry for ads overrun page)
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
If you are looking for creating a single random word, then follow the next steps: 1. Populate an array of chars: `char[] arr = { 'a', 'b', ... , 'z'}` 2. get a random integer that denotes the size of the string. 3. initialize an empty string `s` 4. iterate from 0 to the drawed length, draw a number in range `[0,arr.length)` let it be `x`, and append `arr[x]` to the string `s`. If you are looking for all possibilities, you are looking for all [combinations](http://en.wikipedia.org/wiki/Combination), and the simplest way to do it in my opinion is using recursion. The idea is to "guess" the first char, and run the recursion on the suffix of the string - repeat this for all first possibilities of first char, and you get all combinations. Pseudo code: ``` getCombinations(set,idx,length,current): if (idx == length): set.add(copy(current)) return for each char c: current[idx] = c //setting the next char getCombinations(set,idx+1,length,current) //invoking recursively on smaller range ``` invoke with `getCombinations([],0,length,arr)` where `[]` is an empty set which will hold the results, `length` is the length of the combinations generated, and `arr` is an empty array. To get combinations smaller then `length` you can either add also substrings during the process or to invoke with smaller `length`. Note that the number of combinations is exponential in the length of the word, so it will consume a lot of time.
Lets suppose that you know the length of the list and the 'words' are again of random length and of totally random. You can then do something like the following (it prints the words, you can write them on a file instead): ``` import java.util.Random; ... String alphabet = "qwertyuioplkjhgfdsazxcvbnm"; Random r = new Random(); for(int i = 0; i < list_length; i++) { int word_size = r.nextInt(word_max_length); String word = ""; for(int j = 0; j < word_size; j++) { word += alphabet.charAt(r.nextInt(alphabet.length())); } System.out.println(word); } ```
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
Create a function that maps integers to character sequences. ie: ``` 0 -> a 1 -> b ... 26 -> aa ``` etc. You can use that to create a specific word or a list of words iteratively. Inside your algorithm you will be using modulus `%26` a lot…
Lets suppose that you know the length of the list and the 'words' are again of random length and of totally random. You can then do something like the following (it prints the words, you can write them on a file instead): ``` import java.util.Random; ... String alphabet = "qwertyuioplkjhgfdsazxcvbnm"; Random r = new Random(); for(int i = 0; i < list_length; i++) { int word_size = r.nextInt(word_max_length); String word = ""; for(int j = 0; j < word_size; j++) { word += alphabet.charAt(r.nextInt(alphabet.length())); } System.out.println(word); } ```
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
If you are looking for creating a single random word, then follow the next steps: 1. Populate an array of chars: `char[] arr = { 'a', 'b', ... , 'z'}` 2. get a random integer that denotes the size of the string. 3. initialize an empty string `s` 4. iterate from 0 to the drawed length, draw a number in range `[0,arr.length)` let it be `x`, and append `arr[x]` to the string `s`. If you are looking for all possibilities, you are looking for all [combinations](http://en.wikipedia.org/wiki/Combination), and the simplest way to do it in my opinion is using recursion. The idea is to "guess" the first char, and run the recursion on the suffix of the string - repeat this for all first possibilities of first char, and you get all combinations. Pseudo code: ``` getCombinations(set,idx,length,current): if (idx == length): set.add(copy(current)) return for each char c: current[idx] = c //setting the next char getCombinations(set,idx+1,length,current) //invoking recursively on smaller range ``` invoke with `getCombinations([],0,length,arr)` where `[]` is an empty set which will hold the results, `length` is the length of the combinations generated, and `arr` is an empty array. To get combinations smaller then `length` you can either add also substrings during the process or to invoke with smaller `length`. Note that the number of combinations is exponential in the length of the word, so it will consume a lot of time.
Create a function that maps integers to character sequences. ie: ``` 0 -> a 1 -> b ... 26 -> aa ``` etc. You can use that to create a specific word or a list of words iteratively. Inside your algorithm you will be using modulus `%26` a lot…
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
Create a function that maps integers to character sequences. ie: ``` 0 -> a 1 -> b ... 26 -> aa ``` etc. You can use that to create a specific word or a list of words iteratively. Inside your algorithm you will be using modulus `%26` a lot…
``` final char[] tabC = "abcdefghijklmnopqrstuvwxyz".toCharArray(); for (final char c1 : tabC) { System.out.println(c1 + "\t" + c1); for (final char c2 : tabC) { System.out.println(Character.toString(c1) + Character.toString(c2) + "\t" + (c1 + (c2 << 6))); } } ``` Just verify if <<6 is sufficient to avoid collision(have to Strings for one numbe) output ``` a 97 aa 6305 ab 6369 ac 6433 . . . ar 7393 as 7457 az 7905 b 98 ba 6306 bb 6370 bc 6434 bd 6498 . . . rz 7922 s 115 sa 6323 sb 6387 sc 6451 sd 6515 se 6579 ```
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
Create a function that maps integers to character sequences. ie: ``` 0 -> a 1 -> b ... 26 -> aa ``` etc. You can use that to create a specific word or a list of words iteratively. Inside your algorithm you will be using modulus `%26` a lot…
I would do this: Input n - number of words you want to generate, [I,J] - the range for the words length. The algorithm: * Do n times: + i <- random number between I and J. + Do i times: (0 <= j <= i-1) - Word[j] = random char between 'a' and 'z' + Add Word to result * Return result
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
If you are looking for creating a single random word, then follow the next steps: 1. Populate an array of chars: `char[] arr = { 'a', 'b', ... , 'z'}` 2. get a random integer that denotes the size of the string. 3. initialize an empty string `s` 4. iterate from 0 to the drawed length, draw a number in range `[0,arr.length)` let it be `x`, and append `arr[x]` to the string `s`. If you are looking for all possibilities, you are looking for all [combinations](http://en.wikipedia.org/wiki/Combination), and the simplest way to do it in my opinion is using recursion. The idea is to "guess" the first char, and run the recursion on the suffix of the string - repeat this for all first possibilities of first char, and you get all combinations. Pseudo code: ``` getCombinations(set,idx,length,current): if (idx == length): set.add(copy(current)) return for each char c: current[idx] = c //setting the next char getCombinations(set,idx+1,length,current) //invoking recursively on smaller range ``` invoke with `getCombinations([],0,length,arr)` where `[]` is an empty set which will hold the results, `length` is the length of the combinations generated, and `arr` is an empty array. To get combinations smaller then `length` you can either add also substrings during the process or to invoke with smaller `length`. Note that the number of combinations is exponential in the length of the word, so it will consume a lot of time.
**Nudge served:** Yes, it is possible. You run single for-loop and then convert every counter value to base 26. Then every digit in your new number will code one letter. Please see [here](http://rachel5nj.tripod.com/NOTC/convertingbases.html) on how to convert numbers to arbitrary base. (Sorry for ads overrun page)
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
If you are looking for creating a single random word, then follow the next steps: 1. Populate an array of chars: `char[] arr = { 'a', 'b', ... , 'z'}` 2. get a random integer that denotes the size of the string. 3. initialize an empty string `s` 4. iterate from 0 to the drawed length, draw a number in range `[0,arr.length)` let it be `x`, and append `arr[x]` to the string `s`. If you are looking for all possibilities, you are looking for all [combinations](http://en.wikipedia.org/wiki/Combination), and the simplest way to do it in my opinion is using recursion. The idea is to "guess" the first char, and run the recursion on the suffix of the string - repeat this for all first possibilities of first char, and you get all combinations. Pseudo code: ``` getCombinations(set,idx,length,current): if (idx == length): set.add(copy(current)) return for each char c: current[idx] = c //setting the next char getCombinations(set,idx+1,length,current) //invoking recursively on smaller range ``` invoke with `getCombinations([],0,length,arr)` where `[]` is an empty set which will hold the results, `length` is the length of the combinations generated, and `arr` is an empty array. To get combinations smaller then `length` you can either add also substrings during the process or to invoke with smaller `length`. Note that the number of combinations is exponential in the length of the word, so it will consume a lot of time.
I don't know whether you can use any random integer function library or not. However, I am giving you a simple pseudo code based on that: ``` 1) Generate a Random Number I from 1 to 10. 2) For J = 0 to I byte array[j] = (byte) Generate a Random Number from 0 to 128. 3) For J = 0 to I String st = st + (char) byte array[j] ``` String will be a random word. Simple. But, I don't know whether acceptable or not.
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
If you are looking for creating a single random word, then follow the next steps: 1. Populate an array of chars: `char[] arr = { 'a', 'b', ... , 'z'}` 2. get a random integer that denotes the size of the string. 3. initialize an empty string `s` 4. iterate from 0 to the drawed length, draw a number in range `[0,arr.length)` let it be `x`, and append `arr[x]` to the string `s`. If you are looking for all possibilities, you are looking for all [combinations](http://en.wikipedia.org/wiki/Combination), and the simplest way to do it in my opinion is using recursion. The idea is to "guess" the first char, and run the recursion on the suffix of the string - repeat this for all first possibilities of first char, and you get all combinations. Pseudo code: ``` getCombinations(set,idx,length,current): if (idx == length): set.add(copy(current)) return for each char c: current[idx] = c //setting the next char getCombinations(set,idx+1,length,current) //invoking recursively on smaller range ``` invoke with `getCombinations([],0,length,arr)` where `[]` is an empty set which will hold the results, `length` is the length of the combinations generated, and `arr` is an empty array. To get combinations smaller then `length` you can either add also substrings during the process or to invoke with smaller `length`. Note that the number of combinations is exponential in the length of the word, so it will consume a lot of time.
I would do this: Input n - number of words you want to generate, [I,J] - the range for the words length. The algorithm: * Do n times: + i <- random number between I and J. + Do i times: (0 <= j <= i-1) - Word[j] = random char between 'a' and 'z' + Add Word to result * Return result
11,826,267
I want to create a word generator, but in a way it almost seems like a numerical system. Hex goes from `0` to `f`, this algorithm should go from `a` to `z`. So the word that is created goes like this (every `-` means a new word): ``` a - b - c - d - ... - z - aa - ab - ac - ad - ... - ba - bb - bc - ... ``` Each word is for example stored in a file, so the file would read: ``` a b c d ... z aa ab ac ... ``` I think this is possible with a lot of nested `for` loops and `if`s, but is there a simpler way to do this? You don't have to tell me the whole algorithm, but a nudge in the right direction is much appreciated.
2012/08/06
[ "https://Stackoverflow.com/questions/11826267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290498/" ]
I don't know whether you can use any random integer function library or not. However, I am giving you a simple pseudo code based on that: ``` 1) Generate a Random Number I from 1 to 10. 2) For J = 0 to I byte array[j] = (byte) Generate a Random Number from 0 to 128. 3) For J = 0 to I String st = st + (char) byte array[j] ``` String will be a random word. Simple. But, I don't know whether acceptable or not.
You need to define how long are your words, otherwise this would be infinitve. This is called Combinatorics in math, take a look [here](http://www.martinbroadhurst.com/combinatorial-algorithms.html) you can choose which algorthm suits your needs.
42,019,358
I have three tables : ``` CREATE TABLE workflow_roles ( role_id NUMBER PRIMARY KEY, role_desc VARCHAR2(20) ); CREATE TABLE tbl_workflow ( workflow_id VARCHAR2(5) PRIMARY KEY, workflow_desc VARCHAR2(20) ); CREATE TABLE workflow_detail ( role_id NUMBER REFERENCES workflow_roles( role_id ), workflow_id VARCHAR2(5) REFERENCES tbl_workflow( workflow_id ) ); ``` Let say the data is: ``` INSERT INTO workflow_roles SELECT 1, 'Role 1' FROM DUAL UNION ALL SELECT 2, 'Role 2' FROM DUAL; INSERT INTO tbl_workflow SELECT 'A', 'Work A' FROM DUAL UNION ALL SELECT 'B', 'Work B' FROM DUAL UNION ALL SELECT 'C', 'Work C' FROM DUAL UNION ALL SELECT 'D', 'Work D' FROM DUAL UNION ALL INSERT INTO workflow_detail SELECT 1, 'A' FROM DUAL UNION ALL SELECT 1, 'B' FROM DUAL UNION ALL SELECT 2, 'B' FROM DUAL UNION ALL SELECT 2, 'C' FROM DUAL; ``` **Role "B" exists in both workflows** I want to get the common roles who exists in selected workflows i.e. **it should return Role B only** . I've tried the following : ``` select * from workflow_roles where role_id in ( select role_id from workflow_detail where workflow_id in (1,2) ); ``` But it is returning all roles assigned to the given workflows. How can I do this ?
2017/02/03
[ "https://Stackoverflow.com/questions/42019358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554359/" ]
A solution using a User-Defined Aggregation function to get the intersection of multiple collections: **Oracle Setup**: First, define a collection to hold the workflows: ``` CREATE OR REPLACE TYPE VARCHAR2s_Table IS TABLE OF VARCHAR2(4000); / ``` Secondly, define an object to use in the aggregation process: ``` CREATE OR REPLACE TYPE Varchar2sTableIntersection AS OBJECT( intersection VARCHAR2s_Table, STATIC FUNCTION ODCIAggregateInitialize( ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateIterate( self IN OUT Varchar2sTableIntersection, value IN VARCHAR2s_Table ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateTerminate( self IN OUT Varchar2sTableIntersection, returnValue OUT VARCHAR2s_Table, flags IN NUMBER ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateMerge( self IN OUT Varchar2sTableIntersection, ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER ); / CREATE OR REPLACE TYPE BODY Varchar2sTableIntersection IS STATIC FUNCTION ODCIAggregateInitialize( ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER IS BEGIN ctx := Varchar2sTableIntersection( NULL ); RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateIterate( self IN OUT Varchar2sTableIntersection, value IN VARCHAR2s_Table ) RETURN NUMBER IS BEGIN IF value IS NULL THEN NULL; ELSIF self.intersection IS NULL THEN self.intersection := value; ELSE self.intersection := self.intersection MULTISET INTERSECT value; END IF; RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateTerminate( self IN OUT Varchar2sTableIntersection, returnValue OUT VARCHAR2s_Table, flags IN NUMBER ) RETURN NUMBER IS BEGIN returnValue := self.intersection; RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateMerge( self IN OUT Varchar2sTableIntersection, ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER IS BEGIN IF self.intersection IS NULL THEN self.intersection := ctx.intersection; ELSIF ctx.intersection IS NULL THEN NULL; ELSE self.intersection := self.intersection MULTISET INTERSECT ctx.intersection; END IF; RETURN ODCIConst.SUCCESS; END; END; / ``` Thirdly, create a user-defined aggregation function: ``` CREATE FUNCTION MULTISET_INTERSECT( collection VARCHAR2s_Table ) RETURN VARCHAR2s_Table PARALLEL_ENABLE AGGREGATE USING Varchar2sTableIntersection; / ``` **Query 1 - Output as a collection**: ``` SELECT MULTISET_INTERSECT( workflows ) AS common_workflows FROM ( SELECT role_id, CAST( COLLECT( workflow_id ) AS VARCHAR2s_Table ) AS workflows FROM workflow_detail GROUP BY role_id ); ``` **Output**: ``` COMMON_WORKFLOWS ---------------------- VARCHAR2S_TABLE( 'B' ) ``` **Query 2 - Output as rows**: ``` SELECT t.COLUMN_VALUE AS common_workflows FROM ( SELECT MULTISET_INTERSECT( workflows ) AS common FROM ( SELECT role_id, CAST( COLLECT( workflow_id ) AS VARCHAR2s_Table ) AS workflows FROM workflow_detail GROUP BY role_id ) ) cw CROSS JOIN TABLE( cw.common ) t; ``` **Output**: ``` COMMON_WORKFLOWS ---------------- B ```
I this way you have all the rols with number they are used ``` select wr.role_desc role_desc, count(*) role_nums from workflow_detail wd inner join workflow_roles wr on wr.role_id = wd.role_id inner join tbl_workflow tw on tw.workflow_id = wd.workflow_id group by wr.role_desc order by role_nums desc ``` else If you need the role that are common between two workflow you could filter for distinct role having conut = 2 ``` select wr.role_desc role_desc, count(disctinct wd.role_id) role_nums from workflow_detail wd inner join workflow_roles wr on wr.role_id = wd.role_id inner join tbl_workflow tw on tw.workflow_id = wd.workflow_id where wd.workflow_id in (1,2) group by wr.role_desc having role_nums = 2 order by role_nums desc ```
42,019,358
I have three tables : ``` CREATE TABLE workflow_roles ( role_id NUMBER PRIMARY KEY, role_desc VARCHAR2(20) ); CREATE TABLE tbl_workflow ( workflow_id VARCHAR2(5) PRIMARY KEY, workflow_desc VARCHAR2(20) ); CREATE TABLE workflow_detail ( role_id NUMBER REFERENCES workflow_roles( role_id ), workflow_id VARCHAR2(5) REFERENCES tbl_workflow( workflow_id ) ); ``` Let say the data is: ``` INSERT INTO workflow_roles SELECT 1, 'Role 1' FROM DUAL UNION ALL SELECT 2, 'Role 2' FROM DUAL; INSERT INTO tbl_workflow SELECT 'A', 'Work A' FROM DUAL UNION ALL SELECT 'B', 'Work B' FROM DUAL UNION ALL SELECT 'C', 'Work C' FROM DUAL UNION ALL SELECT 'D', 'Work D' FROM DUAL UNION ALL INSERT INTO workflow_detail SELECT 1, 'A' FROM DUAL UNION ALL SELECT 1, 'B' FROM DUAL UNION ALL SELECT 2, 'B' FROM DUAL UNION ALL SELECT 2, 'C' FROM DUAL; ``` **Role "B" exists in both workflows** I want to get the common roles who exists in selected workflows i.e. **it should return Role B only** . I've tried the following : ``` select * from workflow_roles where role_id in ( select role_id from workflow_detail where workflow_id in (1,2) ); ``` But it is returning all roles assigned to the given workflows. How can I do this ?
2017/02/03
[ "https://Stackoverflow.com/questions/42019358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554359/" ]
A solution using a User-Defined Aggregation function to get the intersection of multiple collections: **Oracle Setup**: First, define a collection to hold the workflows: ``` CREATE OR REPLACE TYPE VARCHAR2s_Table IS TABLE OF VARCHAR2(4000); / ``` Secondly, define an object to use in the aggregation process: ``` CREATE OR REPLACE TYPE Varchar2sTableIntersection AS OBJECT( intersection VARCHAR2s_Table, STATIC FUNCTION ODCIAggregateInitialize( ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateIterate( self IN OUT Varchar2sTableIntersection, value IN VARCHAR2s_Table ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateTerminate( self IN OUT Varchar2sTableIntersection, returnValue OUT VARCHAR2s_Table, flags IN NUMBER ) RETURN NUMBER, MEMBER FUNCTION ODCIAggregateMerge( self IN OUT Varchar2sTableIntersection, ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER ); / CREATE OR REPLACE TYPE BODY Varchar2sTableIntersection IS STATIC FUNCTION ODCIAggregateInitialize( ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER IS BEGIN ctx := Varchar2sTableIntersection( NULL ); RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateIterate( self IN OUT Varchar2sTableIntersection, value IN VARCHAR2s_Table ) RETURN NUMBER IS BEGIN IF value IS NULL THEN NULL; ELSIF self.intersection IS NULL THEN self.intersection := value; ELSE self.intersection := self.intersection MULTISET INTERSECT value; END IF; RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateTerminate( self IN OUT Varchar2sTableIntersection, returnValue OUT VARCHAR2s_Table, flags IN NUMBER ) RETURN NUMBER IS BEGIN returnValue := self.intersection; RETURN ODCIConst.SUCCESS; END; MEMBER FUNCTION ODCIAggregateMerge( self IN OUT Varchar2sTableIntersection, ctx IN OUT Varchar2sTableIntersection ) RETURN NUMBER IS BEGIN IF self.intersection IS NULL THEN self.intersection := ctx.intersection; ELSIF ctx.intersection IS NULL THEN NULL; ELSE self.intersection := self.intersection MULTISET INTERSECT ctx.intersection; END IF; RETURN ODCIConst.SUCCESS; END; END; / ``` Thirdly, create a user-defined aggregation function: ``` CREATE FUNCTION MULTISET_INTERSECT( collection VARCHAR2s_Table ) RETURN VARCHAR2s_Table PARALLEL_ENABLE AGGREGATE USING Varchar2sTableIntersection; / ``` **Query 1 - Output as a collection**: ``` SELECT MULTISET_INTERSECT( workflows ) AS common_workflows FROM ( SELECT role_id, CAST( COLLECT( workflow_id ) AS VARCHAR2s_Table ) AS workflows FROM workflow_detail GROUP BY role_id ); ``` **Output**: ``` COMMON_WORKFLOWS ---------------------- VARCHAR2S_TABLE( 'B' ) ``` **Query 2 - Output as rows**: ``` SELECT t.COLUMN_VALUE AS common_workflows FROM ( SELECT MULTISET_INTERSECT( workflows ) AS common FROM ( SELECT role_id, CAST( COLLECT( workflow_id ) AS VARCHAR2s_Table ) AS workflows FROM workflow_detail GROUP BY role_id ) ) cw CROSS JOIN TABLE( cw.common ) t; ``` **Output**: ``` COMMON_WORKFLOWS ---------------- B ```
One simple solution: you want the role to be in two sets, so query *two* sets with `IN`: ``` select * from workflow_roles where role_id in (select role_id from workflow_detail where workflow_id = 1) and role_id in (select role_id from workflow_detail where workflow_id = 2); ``` Another option is to count matches in workflow\_detail. You are looking for two workflow\_ids, so check whether you find the two for a role: ``` select * from workflow_roles where role_id in ( select role_id from workflow_detail where workflow_id in (1,2) group by role_id having count(distinct workflow_id) = 2 ); ```
20,359,781
file.data has the following values to fit with Weibull distribution, ``` x y 2.53 0.00 0.70 0.99 0.60 2.45 0.49 5.36 0.40 9.31 0.31 18.53 0.22 30.24 0.11 42.23 ``` Following the Weibull distribution function `f(x)=1.0-exp(-lambda*x**n)`, it is giving error: ``` fit f(x) 'data.dat' via lambda, n ``` and finally plotting f(x) and xy graph have large discrepancy. Any feedback would be highly appreciated. Thanks!
2013/12/03
[ "https://Stackoverflow.com/questions/20359781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618021/" ]
Several things: 1. You must skip the first line (if it really is `x y`). 2. You must use the correct function (the pdf and not the CDF, see <http://en.wikipedia.org/wiki/Weibull_distribution>, like you did in <https://stackoverflow.com/q/20336051/2604213>) 3. You must use an additional scaling parameter, because your data are not normalized 4. You must select adequate initial values for the fitting. The following works fine: ``` f(x) = (x < 0 ? 0 : a*(x/lambda)**(n-1)*exp(-(x/lambda)**n)) n = 0.5 a = 100 lambda = 0.15 fit f(x) 'data.dat' every ::1 via lambda, n, a set encoding utf8 plot f(x) title sprintf('λ = %.2f, n = %.2f', lambda, n), 'data.dat' every ::1 ``` That gives (with 4.6.4): ![enter image description here](https://i.stack.imgur.com/Ks4S4.png)
If that's the actual command you provided to gnuplot, it won't work because you haven't yet defined f(x).
81,196
Would a "panel antenna" used for RFID (probably microstrip-based; e.g. <http://www.joymax.com.tw/index.php?_Page=product&mode=show&cid=2387&pid=364>) work for satellite communication, assuming a positive link margin? I can't see any reason why not: there is circular polarisation, directivity, gain, am I missing anything? (Assume the carrier frequency of interest is within the antenna's bandwidth)
2013/09/04
[ "https://electronics.stackexchange.com/questions/81196", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/18133/" ]
Which satellite frequency band were you expecting to work on the antenna you linked? > > assume the frequency of interest is within the antenna's bandwidth > > > What is the bandwidth of the signal to be received? > > Narrowband (< 1 MHz) > > > If the receiver frequency is in the frequency range of the antenna AND it doesn't have components that exceed the bandwidth of the antenna, providing the signal is strong enough and there isn't too much interference than it has a good chance of working. If my crap android phone can receive satellite info with its crap antenna then a better antenna is going to improve things but it's all down to what your expectations are as well.
I would suppose you're dealing with completely different frequency ranges and you will never get the required gain for the frequencies you need.
81,196
Would a "panel antenna" used for RFID (probably microstrip-based; e.g. <http://www.joymax.com.tw/index.php?_Page=product&mode=show&cid=2387&pid=364>) work for satellite communication, assuming a positive link margin? I can't see any reason why not: there is circular polarisation, directivity, gain, am I missing anything? (Assume the carrier frequency of interest is within the antenna's bandwidth)
2013/09/04
[ "https://electronics.stackexchange.com/questions/81196", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/18133/" ]
Which satellite frequency band were you expecting to work on the antenna you linked? > > assume the frequency of interest is within the antenna's bandwidth > > > What is the bandwidth of the signal to be received? > > Narrowband (< 1 MHz) > > > If the receiver frequency is in the frequency range of the antenna AND it doesn't have components that exceed the bandwidth of the antenna, providing the signal is strong enough and there isn't too much interference than it has a good chance of working. If my crap android phone can receive satellite info with its crap antenna then a better antenna is going to improve things but it's all down to what your expectations are as well.
Given the criteria you specify, and absent any hidden unspecified gotchas, quite possibly yes. BUT achieving your criteria seems unlikely. The RFID patch antenna will have a low gain and you may need to use * a MBS (Main Battle Star) MASER as the downlink tx and * liquid (or solid) Hydrogen cooled downlink (space end) RX, and even then * may need to drive the RFID tag hard enough to make it glow in the dark (and in the light) to obtain your 'Positive Link Margin'
41,039,458
I'm trying to insert CSV file into MySql but I'm getting an error. > > Warning: mysql\_real\_escape\_string() expects parameter 1 to be string, > > > My database table is: ``` :s_no :name :id : :1 :Lim :678 : :2 :Mary :623 : :3 :Mimi :4124 : ``` The **number** is AUTO\_INCREMENT, I wanted instead the Name And ID only. ``` <?php $connect = mysql_connect("localhost","root","","skpj"); if(isset($_POST["submit"])) { if($_FILES['file']['name']) { $filename = explode('.',$_FILES['file']['name']); if ($filename[1] == 'csv') { $handle = fopen($_FILES['file']['tmp_name'], "r"); while ($data = fgetcsv($handle)) { $item1 = mysql_real_escape_string($connect, $data[0]); $item2 = mysql_real_escape_string($connect, $data[1]); $sql="INSERT into student( s_no, name, id) value ('','$item1','$item2')"; mysql_query($connect, $sql); } fclose($handle); print "Done"; } } } ?> <html> <head></head> <body> <form method="post" enctype="multipart/form-data"> <div> <p>Upload CSV: <input type="file" name="file" /></p> <p><input type="submit" name="submit" value="Import" /></p> </div> </form> </body> </html> ```
2016/12/08
[ "https://Stackoverflow.com/questions/41039458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7267483/" ]
The connection is the second parameter. ``` mysql_real_escape_string( $data[0], $connect); ``` Also remember it is a deprecated function <http://php.net/manual/en/function.mysql-real-escape-string.php>
try this ``` mysql_real_escape_string("string") ``` means ``` mysql_real_escape_string($data[0]); ```
41,039,458
I'm trying to insert CSV file into MySql but I'm getting an error. > > Warning: mysql\_real\_escape\_string() expects parameter 1 to be string, > > > My database table is: ``` :s_no :name :id : :1 :Lim :678 : :2 :Mary :623 : :3 :Mimi :4124 : ``` The **number** is AUTO\_INCREMENT, I wanted instead the Name And ID only. ``` <?php $connect = mysql_connect("localhost","root","","skpj"); if(isset($_POST["submit"])) { if($_FILES['file']['name']) { $filename = explode('.',$_FILES['file']['name']); if ($filename[1] == 'csv') { $handle = fopen($_FILES['file']['tmp_name'], "r"); while ($data = fgetcsv($handle)) { $item1 = mysql_real_escape_string($connect, $data[0]); $item2 = mysql_real_escape_string($connect, $data[1]); $sql="INSERT into student( s_no, name, id) value ('','$item1','$item2')"; mysql_query($connect, $sql); } fclose($handle); print "Done"; } } } ?> <html> <head></head> <body> <form method="post" enctype="multipart/form-data"> <div> <p>Upload CSV: <input type="file" name="file" /></p> <p><input type="submit" name="submit" value="Import" /></p> </div> </form> </body> </html> ```
2016/12/08
[ "https://Stackoverflow.com/questions/41039458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7267483/" ]
The connection is the second parameter. ``` mysql_real_escape_string( $data[0], $connect); ``` Also remember it is a deprecated function <http://php.net/manual/en/function.mysql-real-escape-string.php>
if you are using **mysqli** then ``` mysqli_real_escape_string($connect,$data[0]); ``` if you are use **mysql** ``` mysql_real_escape_string( $data[0]); ```
29,248,323
I am implementing chosen dropdown in my project. But I have some problem which I want to solve. Before proceeding, let me give you the jQuery fiddle: <http://jsfiddle.net/jHvmg/278/> Now I have a dropdown like this ``` <select id="drp_menu"> <option value="Option 1">Option 1</option> <option value="Option 2">Option 2</option> <option value="Option 3">Option 3</option> <option value="Option 4">Option 4</option> <option value="Option 5">Option 5</option> </select> ``` As you can see in the fiddle: 1) If I write `"Opt"` in the searchbox then the list is filtered showing all the options. 2) If I write `" 1"` it shows `"Option 1"` 3) If I write `"1"` it shows `"Option 1"` 4) If I write `"ptio"` then it states `"No results"` 5) If I write `"tio"` then it states `"No result"` I want to results if words typed in the searchbox matches.
2015/03/25
[ "https://Stackoverflow.com/questions/29248323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1170507/" ]
add `{ search_contains: true }` and Enjoy :) JS Code: -------- ``` $(document).ready(function() { $('#drp_menu').chosen({ search_contains: true }); }); ``` [Demo](http://jsfiddle.net/jHvmg/279/)
Replace ``` $('#drp_menu').chosen(); ``` with ``` $('#drp_menu').chosen({search_contains:true}); ``` [Here is a fiddle](http://jsfiddle.net/jHvmg/282/) Just look for the [documentation](http://harvesthq.github.io/chosen/options.html) for `configuration options` like this
50,446,738
I’m using *AWS Cognito to perform login authentication*. When login is successful we get below request body : *Request body:* ``` > {"UserContextData":{"EncodedData":"eyJ..9”},”ClientMetadata":{"cognito:deviceName":"MacBookPro12-01","cognito:bundleShortV":"1.0.0", > "cognito:idForVendor":"A6FD46FBB205","cognito:bundleVersion":"207", > "cognito:bundleId":"com.abc.Project-Dev","cognito:model":"iPhone", "cognito:systemName":"iOS","cognito:iOSVersion":"11.3"}, > "AuthParameters":{"SRP_A":"a6..627","SECRET_HASH":"vr..Oo=", "USERNAME":"jay.dubey@abc.com”},**”AuthFlow":"USER_SRP_AUTH"**, > "ClientId”:”123”} ``` Now, there is a scenario wherein I’ve to **set “AuthFlow” value to “USER\_PASSWORD\_AUTH”.** How can this be done? The headache with this is that **all these values are set in Pods.** Below code prints the request body that is added above : ``` passwordAuthenticationCompletion?.set(result: AWSCognitoIdentityPasswordAuthenticationDetails(username: username, password: password)) ```
2018/05/21
[ "https://Stackoverflow.com/questions/50446738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753005/" ]
Unfortunately you can't just pass a string directly as the credentials argument (although perhaps we should make it where you can), you should do this instead: ``` from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file('service_acc_key.json') client = vision.ImageAnnotatorClient(credentials=credentials) ```
Add the following lines before calling the client > > os.environ["GOOGLE\_APPLICATION\_CREDENTIALS"] = path/to/service-account.json/file > > >
6,846,969
I am writing a website and want a user to be able to click post to Facebook and have it open a window already filled out with a custom post. I do not want to have to authenticate them with my site or anything like that just send them to a Facebook url with the post already filled in. Twitter has something like this that I am using. For instance click this <http://twitter.com/home?status=This%20is%20a%20custom%20post> Is there a way to do this same thing for Facebook? If so does anyone know the URL? Thanks
2011/07/27
[ "https://Stackoverflow.com/questions/6846969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509967/" ]
I found the solution I was looking for. To post to a Facebook wall without actually managing tokens you must make a call to the url below with the parameters specified below. "http://www.facebook.com/dialog/feed?app\_id=YOU\_APP\_ID&link=A\_LINK\_HERE&picture=PATH\_TO\_A\_PICTURE&name=SOME\_NAME&caption=SOME\_CAPTION&description=SOME\_DESCRIPTION&message=MESSAGE\_TO\_POST\_ON\_WALL&redirect\_uri=REDIRECT\_URL\_AFTER\_POST" This will redirect back to the url that was specified in redirect parameter after the post. It will have the parameter post\_id with the id of the new post or no params if they did not post. You can find documentation here <http://developers.facebook.com/docs/reference/dialogs/feed/>.
The Like and Send buttons provide this functionality: <http://developers.facebook.com/docs/reference/plugins/like/> You include meta tags on your page and the Like / Send button pick this up for sharing to a user's wall.
6,846,969
I am writing a website and want a user to be able to click post to Facebook and have it open a window already filled out with a custom post. I do not want to have to authenticate them with my site or anything like that just send them to a Facebook url with the post already filled in. Twitter has something like this that I am using. For instance click this <http://twitter.com/home?status=This%20is%20a%20custom%20post> Is there a way to do this same thing for Facebook? If so does anyone know the URL? Thanks
2011/07/27
[ "https://Stackoverflow.com/questions/6846969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509967/" ]
I found the solution I was looking for. To post to a Facebook wall without actually managing tokens you must make a call to the url below with the parameters specified below. "http://www.facebook.com/dialog/feed?app\_id=YOU\_APP\_ID&link=A\_LINK\_HERE&picture=PATH\_TO\_A\_PICTURE&name=SOME\_NAME&caption=SOME\_CAPTION&description=SOME\_DESCRIPTION&message=MESSAGE\_TO\_POST\_ON\_WALL&redirect\_uri=REDIRECT\_URL\_AFTER\_POST" This will redirect back to the url that was specified in redirect parameter after the post. It will have the parameter post\_id with the id of the new post or no params if they did not post. You can find documentation here <http://developers.facebook.com/docs/reference/dialogs/feed/>.
You can't prefill story text, it's against FB policies. Twitter is cool with that, but on Facebook it's a no-no. See: <http://developers.facebook.com/docs/guides/policy/examples_and_explanations/stream_stories/> Scroll down a bit to 'Platform Policy IV.2' You can put suggestions of what to say on the screen, but you can't prefill the comment box.
14,145,303
I'd like to have a helper that works just like link\_to except that it merges in a data attribute (in this case for ease of creating tabs using bootstrap: <http://twitter.github.com/bootstrap/javascript.html#tabs>) So I can call it like this: ``` link_to_tab("Name", @obj) ``` and get ``` <a href='/path' data-toggle='tab'>Name</a> ``` I've come up with this which seems to work: ``` def link_to_tab(*args, &block) toggle_hash = {'data-toggle' => 'tab'} last_arg = args.pop # if link_to was given a hash of html_options, merge with it if last_arg.is_a? Hash link_to(*args, last_arg.merge(toggle_hash), &block) else link_to(*args, last_arg, toggle_hash, &block) end end ``` Is there a cleaner, more idiomatic way to support all of the styles of calling link\_to?
2013/01/03
[ "https://Stackoverflow.com/questions/14145303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/625365/" ]
Not really. You could try this... ``` def link_to_tab(*args, &block) toggle_hash = {'data-toggle' => 'tab'} if args.last.is_a? Hash args.last.merge!(toggle_hash) else args << toggle_hash end link_to(*args, &block) end ``` Not that different though...
> > I'd like to have a helper that works just like link\_to except that it merges in a data attribute > > > I might be missing something, but why not just pass a custom data argument to the link\_to helper? ``` = link_to "foo tab", {}, "data-toggle" => "tab" ``` Outputs: ``` <a data-toggle="tab" href="/">foo tab</a> ``` **Edit** If you're planning on using it a lot you can do: ``` def link_to_tab(*args, &block) if args.last.is_a? Hash link_to *(args.take args.size - 1), args.last.merge("data-tab" => "tab"), &block else link_to *args, "data-tab" => "tab", &block end end ```
57,158,475
Is there a way to disable "search wrapping" in VS code? I.e. prevent the search from starting back at the top again after reaching the last occurrence of the search term in the file?
2019/07/23
[ "https://Stackoverflow.com/questions/57158475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930462/" ]
**UPDATE** !! A setting is being added to v1.45 to disable "search wrapping". See <https://github.com/microsoft/vscode/pull/92243> > > Editor > Find: Loop > > > default is enabled, it will loop or wrap. --- ---------------- old answer: No, apparently not. See this issue: [disable search wrap](https://github.com/Microsoft/vscode/issues/46504). That issue was closed due to lack of interest in 2018.
In Preferences > Settings > Open Settings (Json) Add: ``` "editor.find.loop": false ```
51,064,103
I need to form several subqueries with sets of dates including only sundays between two set points, for example between 01.04.2018 and 30.06.2018. The first thing which comes into mind is something like this: ``` SELECT '01.04.2018' STARTDATE FROM DUAL UNION ALL SELECT '08.04.2018' STARTDATE FROM DUAL ... ``` But it doesn't look very elegant. Is there an easier way to achieve what I need?
2018/06/27
[ "https://Stackoverflow.com/questions/51064103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9003662/" ]
You can use: [SQL Fiddle](http://sqlfiddle.com/#!4/ae2cc8/473) **Query 1**: ``` SELECT NEXT_DAY( DATE '2018-04-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 AS startdate FROM DUAL CONNECT BY NEXT_DAY( DATE '2018-04-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 <= DATE '2018-06-30' ``` **[Results](http://sqlfiddle.com/#!4/ae2cc8/473/0)**: ``` | STARTDATE | |----------------------| | 2018-04-01T00:00:00Z | | 2018-04-08T00:00:00Z | | 2018-04-15T00:00:00Z | | 2018-04-22T00:00:00Z | | 2018-04-29T00:00:00Z | | 2018-05-06T00:00:00Z | | 2018-05-13T00:00:00Z | | 2018-05-20T00:00:00Z | | 2018-05-27T00:00:00Z | | 2018-06-03T00:00:00Z | | 2018-06-10T00:00:00Z | | 2018-06-17T00:00:00Z | | 2018-06-24T00:00:00Z | ``` > > Does this construction always return at least one row? If I add an additional condition that `NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7` should be less than `SYSDATE` it still returns the first row which is larger than `SYSDATE`. > > > Yes, a hierarchical query will always return one row if the filtering is just performed in the `CONNECT BY` clause (since it will only check it when it tries to connect one row to its parent and needs to have generated at least one parent first to do this): ``` SELECT NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 AS startdate FROM DUAL CONNECT BY NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 <= LEAST( SYSDATE, -- DATE '2018-06-29' DATE '2018-07-30' ) ``` **Results**: ``` | STARTDATE | |----------------------| | 2018-07-01T00:00:00Z | -- Greater than SYSDATE ``` But if you add a `WHERE` clause (rather than filtering in the `CONNECT BY` clause) then it can return zero rows: ``` SELECT NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 AS startdate FROM DUAL WHERE NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 <= SYSDATE CONNECT BY NEXT_DAY( DATE '2018-07-01' - 1, 'SUNDAY' ) + ( LEVEL - 1 ) * 7 <= DATE '2018-07-30' ``` **Results**: ``` No data found. ```
The brute force approach would be to just generate the entire date range and then filter it to leave only Sundays: ``` WITH cte AS ( SELECT TRUNC (date '2018-06-30' - ROWNUM) dt FROM DUAL CONNECT BY ROWNUM < 100 ) SELECT * FROM cte WHERE TO_CHAR(dt, 'DAY') = 'SUN' ```
11,391,088
I need to draw a string over a Infragistics toolbar, and I cannot use a label since it's background will not be actually transparent (see in image). I've managed to overlay the text as desired using DrawString method, but the problem is that the text does not resemble a label. it's thicker, aliased and for some reason black. What should i change im my code to replicate a label's looks using the DrawString method (same font, size, forecolor) ? ![enter image description here](https://i.stack.imgur.com/EIHG6.png) And the code: ``` FontFamily fontFamily = new FontFamily("Microsoft Sans Serif"); Font font = new Font( fontFamily, 17, FontStyle.Regular, GraphicsUnit.Pixel); SolidBrush solidBrush = new SolidBrush(SystemColors.ControlText); drawParams.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias; drawParams.Graphics.DrawString("String Drawn with DrawString method", font, solidBrush, textEditorLoc.X, textEditorLoc.Y + 25); ```
2012/07/09
[ "https://Stackoverflow.com/questions/11391088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1887900/" ]
Try using [`TextRenderer`](http://msdn.microsoft.com/en-us/library/system.windows.forms.textrenderer.aspx) class: ``` TextRenderer.DrawString( drawParams.Graphics, "String Drawn with TextRenderer (GDI) method", font, new Point(textEditorLoc.X, textEditorLoc.Y + 25), SystemColors.ControlText); ``` Also leave `TextRenderingHint` as `SystemDefault` and use the same font size as for label.
The standard text size of a label is 8,25 points, or approximately 11 pixels. Your size of 17 pixels results in a text size of 13 pt. Try using this ``` FontFamily fontFamily = new FontFamily("Microsoft Sans Serif"); Font font = new Font( fontFamily, 8.25f, FontStyle.Regular, GraphicsUnit.Point); SolidBrush solidBrush = new SolidBrush(SystemColors.ControlText); e.Graphics.DrawString("String Drawn with DrawString", font, solidBrush, textEditorLoc.X, textEditorLoc.Y + 25); ```
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
DI.fm allows you to download as `.pls`. As for Sky.fm, you will have to manually download the files by entering this URL: `listen.sky.fm/public3/STATIONNAME.pls`. For example: `listen.sky.fm/public3/dreamscapes.pls`
You can download all the .pls files. After that you open this files in a text editor like notepad++. You´ll discover the true url for the station. Add these url in a streaming audio grabber. You´ll download in real time as the music plays. I recomend StremRipper for winamp (you really don´t need winamp to use it) Open the program, press rightclick and paste the true url from the station like inside the PLS files (listen.sky.fm/public3/STATIONNAME.pls) Dont forget to configure the output folder.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
DI.fm allows you to download as `.pls`. As for Sky.fm, you will have to manually download the files by entering this URL: `listen.sky.fm/public3/STATIONNAME.pls`. For example: `listen.sky.fm/public3/dreamscapes.pls`
My answer was initially the same as above, except I give the link to the di fm radio and not sky radio. The link would be something like this: ``` http://listen.di.fm/public3/insert_radio_name.pls ``` And you get radio name by clicking on any of the radios, it will be `http://www.di.fm/insert_radio_name` so this is the manual way to do it, and not all at once. And I'm not sure if it works for all stations. It's not 5 clicks per station, it's just 1 hover and 1 click, but even if that sounds like a lot, you can right click on the Stations button and do an Inspect element and expand the submenu and the lists divs. There you can find the names of the stations and you're 1 copy paste away. Ooor, without expanding any further, copy the ul elements, paste them in a txt file and start doing find/replace to turn for instance: ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key="00sclubhits" data-channel-id="324"></li> ``` into ``` http://listen.di.fm/public3/00sclubhits.pls ``` How? First part is easy, notepad is enough, just replace this ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key=" ``` with ``` http://listen.di.fm/public3/ ``` And for the 2nd part you can google "notepad++ regex" and install notepad++ and come up with: ``` " data-channel-id="(\d)*"></li> ``` being replaced with ``` .pls ``` Then trim out the ul elements or replace them with empty string. In the end you will have em all in 1 file, like this: `http://pastebin.com/V0mPewCq`. If you want this done in 1 go, I suggest you pick up Java and do a crawler for the main page in case they change them and you don't want to go through this again. I have yet to know how to get them all in a playlist or save them all at once from such a file. Either save each manually (you can use this `http://www.urlopener.com/home.html` if you don't want to paste each in a tab, but you still have to click Save As... ) or again automated with some script (I also found this but idk how trustworthy it is: `http://helpdeskgeek.com/free-tools-review/download-multiple-files-at-once-in-windows/`), or add each Location manually and save them all into 1 big playlist. It's all a 2 step because the .pls that they give you contains the true links.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
DI.fm allows you to download as `.pls`. As for Sky.fm, you will have to manually download the files by entering this URL: `listen.sky.fm/public3/STATIONNAME.pls`. For example: `listen.sky.fm/public3/dreamscapes.pls`
This solution uses command line programs: `curl` - cURL tool to transfer data from or to a server `grep` - Grep a command-line utility that can search and filter text *Linux users should find these either already installed or simply use their distro's package manager to install. Windows users can install [Cygwin](https://www.cygwin.com/) or a lighter weight toolset [Gnu on Windows](https://github.com/bmatzelle/gow/wiki).* Solution: The webpage <http://listen.di.fm/public3/> is a json list. We only need to get the page using cURL search for the .pls links using grep. Type this in a command terminal: `curl -s "http://listen.di.fm/public3/" | grep -Po 'http://listen.*?pls'` A subset of the output should be: ``` http://listen.di.fm/public3/trance.pls http://listen.di.fm/public3/vocaltrance.pls http://listen.di.fm/public3/chillout.pls http://listen.di.fm/public3/house.pls http://listen.di.fm/public3/harddance.pls http://listen.di.fm/public3/eurodance.pls http://listen.di.fm/public3/progressive.pls http://listen.di.fm/public3/goapsy.pls ... etc. ```
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
1. Save the following text in a .pls file. 2. Edit with notepad to replace the text YOUR\_KEY by your premium key or delete it if you are not premium. 3. Open the pls file in your favorite player :) > > [playlist] > > NumberOfEntries=70 > > File1=http://listen.di.fm/premium\_high/trance.pls?YOUR\_KEY > > Title1=Digitally Imported - trance > > Length1=-1 > > File2=http://listen.di.fm/premium\_high/vocaltrance.pls?YOUR\_KEY > > Title2=Digitally Imported - vocaltrance > > Length2=-1 > > File3=http://listen.di.fm/premium\_high/ambient.pls?YOUR\_KEY > > Title3=Digitally Imported - ambient > > Length3=-1 > > File4=http://listen.di.fm/premium\_high/bigroomhouse.pls?YOUR\_KEY > > Title4=Digitally Imported - bigroomhouse > > Length4=-1 > > File5=http://listen.di.fm/premium\_high/breaks.pls?YOUR\_KEY > > Title5=Digitally Imported - breaks > > Length5=-1 > > File6=http://listen.di.fm/premium\_high/chillhop.pls?YOUR\_KEY > > Title6=Digitally Imported - chillhop > > Length6=-1 > > File7=http://listen.di.fm/premium\_high/chillout.pls?YOUR\_KEY > > Title7=Digitally Imported - chillout > > Length7=-1 > > File8=http://listen.di.fm/premium\_high/chilloutdreams.pls?YOUR\_KEY > > Title8=Digitally Imported - chilloutdreams > > Length8=-1 > > File9=http://listen.di.fm/premium\_high/chillstep.pls?YOUR\_KEY > > Title9=Digitally Imported - chillstep > > Length9=-1 > > File10=http://listen.di.fm/premium\_high/chiptunes.pls?YOUR\_KEY > > Title10=Digitally Imported - chiptunes > > Length10=-1 > > File11=http://listen.di.fm/premium\_high/classiceurodance.pls?YOUR\_KEY > > Title11=Digitally Imported - classiceurodance > > Length11=-1 > > File12=http://listen.di.fm/premium\_high/classiceurodisco.pls?YOUR\_KEY > > Title12=Digitally Imported - classiceurodisco > > Length12=-1 > > File13=http://listen.di.fm/premium\_high/classictrance.pls?YOUR\_KEY > > Title13=Digitally Imported - classictrance > > Length13=-1 > > File14=http://listen.di.fm/premium\_high/classicvocaltrance.pls?YOUR\_KEY > > Title14=Digitally Imported - classicvocaltrance > > Length14=-1 > > File15=http://listen.di.fm/premium\_high/clubdubstep.pls?YOUR\_KEY > > Title15=Digitally Imported - clubdubstep > > Length15=-1 > > File16=http://listen.di.fm/premium\_high/club.pls?YOUR\_KEY > > Title16=Digitally Imported - club > > Length16=-1 > > File17=http://listen.di.fm/premium\_high/cosmicdowntempo.pls?YOUR\_KEY > > Title17=Digitally Imported - cosmicdowntempo > > Length17=-1 > > File18=http://listen.di.fm/premium\_high/djmixes.pls?YOUR\_KEY > > Title18=Digitally Imported - djmixes > > Length18=-1 > > File19=http://listen.di.fm/premium\_high/darkdnb.pls?YOUR\_KEY > > Title19=Digitally Imported - darkdnb > > Length19=-1 > > File20=http://listen.di.fm/premium\_high/deephouse.pls?YOUR\_KEY > > Title20=Digitally Imported - deephouse > > Length20=-1 > > File21=http://listen.di.fm/premium\_high/deepnudisco.pls?YOUR\_KEY > > Title21=Digitally Imported - deepnudisco > > Length21=-1 > > File22=http://listen.di.fm/premium\_high/deeptech.pls?YOUR\_KEY > > Title22=Digitally Imported - deeptech > > Length22=-1 > > File23=http://listen.di.fm/premium\_high/discohouse.pls?YOUR\_KEY > > Title23=Digitally Imported - discohouse > > Length23=-1 > > File24=http://listen.di.fm/premium\_high/downtempolounge.pls?YOUR\_KEY > > Title24=Digitally Imported - downtempolounge > > Length24=-1 > > File25=http://listen.di.fm/premium\_high/drumandbass.pls?YOUR\_KEY > > Title25=Digitally Imported - drumandbass > > Length25=-1 > > File26=http://listen.di.fm/premium\_high/dubstep.pls?YOUR\_KEY > > Title26=Digitally Imported - dubstep > > Length26=-1 > > File27=http://listen.di.fm/premium\_high/eclectronica.pls?YOUR\_KEY > > Title27=Digitally Imported - eclectronica > > Length27=-1 > > File28=http://listen.di.fm/premium\_high/electro.pls?YOUR\_KEY > > Title28=Digitally Imported - electro > > Length28=-1 > > File29=http://listen.di.fm/premium\_high/electronicpioneers.pls?YOUR\_KEY > > Title29=Digitally Imported - electronicpioneers > > Length29=-1 > > File30=http://listen.di.fm/premium\_high/electropop.pls?YOUR\_KEY > > Title30=Digitally Imported - electropop > > Length30=-1 > > File31=http://listen.di.fm/premium\_high/epictrance.pls?YOUR\_KEY > > Title31=Digitally Imported - epictrance > > Length31=-1 > > File32=http://listen.di.fm/premium\_high/eurodance.pls?YOUR\_KEY > > Title32=Digitally Imported - eurodance > > Length32=-1 > > File33=http://listen.di.fm/premium\_high/funkyhouse.pls?YOUR\_KEY > > Title33=Digitally Imported - funkyhouse > > Length33=-1 > > File34=http://listen.di.fm/premium\_high/futuresynthpop.pls?YOUR\_KEY > > Title34=Digitally Imported - futuresynthpop > > Length34=-1 > > File35=http://listen.di.fm/premium\_high/gabber.pls?YOUR\_KEY > > Title35=Digitally Imported - gabber > > Length35=-1 > > File36=http://listen.di.fm/premium\_high/glitchhop.pls?YOUR\_KEY > > Title36=Digitally Imported - glitchhop > > Length36=-1 > > File37=http://listen.di.fm/premium\_high/goapsy.pls?YOUR\_KEY > > Title37=Digitally Imported - goapsy > > Length37=-1 > > File38=http://listen.di.fm/premium\_high/handsup.pls?YOUR\_KEY > > Title38=Digitally Imported - handsup > > Length38=-1 > > File39=http://listen.di.fm/premium\_high/harddance.pls?YOUR\_KEY > > Title39=Digitally Imported - harddance > > Length39=-1 > > File40=http://listen.di.fm/premium\_high/hardtechno.pls?YOUR\_KEY > > Title40=Digitally Imported - hardtechno > > Length40=-1 > > File41=http://listen.di.fm/premium\_high/hardcore.pls?YOUR\_KEY > > Title41=Digitally Imported - hardcore > > Length41=-1 > > File42=http://listen.di.fm/premium\_high/hardstyle.pls?YOUR\_KEY > > Title42=Digitally Imported - hardstyle > > Length42=-1 > > File43=http://listen.di.fm/premium\_high/house.pls?YOUR\_KEY > > Title43=Digitally Imported - house > > Length43=-1 > > File44=http://listen.di.fm/premium\_high/latinhouse.pls?YOUR\_KEY > > Title44=Digitally Imported - latinhouse > > Length44=-1 > > File45=http://listen.di.fm/premium\_high/liquiddnb.pls?YOUR\_KEY > > Title45=Digitally Imported - liquiddnb > > Length45=-1 > > File46=http://listen.di.fm/premium\_high/liquiddubstep.pls?YOUR\_KEY > > Title46=Digitally Imported - liquiddubstep > > Length46=-1 > > File47=http://listen.di.fm/premium\_high/lounge.pls?YOUR\_KEY > > Title47=Digitally Imported - lounge > > Length47=-1 > > File48=http://listen.di.fm/premium\_high/mainstage.pls?YOUR\_KEY > > Title48=Digitally Imported - mainstage > > Length48=-1 > > File49=http://listen.di.fm/premium\_high/minimal.pls?YOUR\_KEY > > Title49=Digitally Imported - minimal > > Length49=-1 > > File50=http://listen.di.fm/premium\_high/moombahton.pls?YOUR\_KEY > > Title50=Digitally Imported - moombahton > > Length50=-1 > > File51=http://listen.di.fm/premium\_high/oldschoolacid.pls?YOUR\_KEY > > Title51=Digitally Imported - oldschoolacid > > Length51=-1 > > File52=http://listen.di.fm/premium\_high/classictechno.pls?YOUR\_KEY > > Title52=Digitally Imported - classictechno > > Length52=-1 > > File53=http://listen.di.fm/premium\_high/progressive.pls?YOUR\_KEY > > Title53=Digitally Imported - progressive > > Length53=-1 > > File54=http://listen.di.fm/premium\_high/progressivepsy.pls?YOUR\_KEY > > Title54=Digitally Imported - progressivepsy > > Length54=-1 > > File55=http://listen.di.fm/premium\_high/psychill.pls?YOUR\_KEY > > Title55=Digitally Imported - psychill > > Length55=-1 > > File56=http://listen.di.fm/premium\_high/psybient.pls?YOUR\_KEY > > Title56=Digitally Imported - psybient > > Length56=-1 > > File57=http://listen.di.fm/premium\_high/russianclubhits.pls?YOUR\_KEY > > Title57=Digitally Imported - russianclubhits > > Length57=-1 > > File58=http://listen.di.fm/premium\_high/sankeys.pls?YOUR\_KEY > > Title58=Digitally Imported - sankeys > > Length58=-1 > > File59=http://listen.di.fm/premium\_high/scousehouse.pls?YOUR\_KEY > > Title59=Digitally Imported - scousehouse > > Length59=-1 > > File60=http://listen.di.fm/premium\_high/soulfulhouse.pls?YOUR\_KEY > > Title60=Digitally Imported - soulfulhouse > > Length60=-1 > > File61=http://listen.di.fm/premium\_high/spacemusic.pls?YOUR\_KEY > > Title61=Digitally Imported - spacemusic > > Length61=-1 > > File62=http://listen.di.fm/premium\_high/techhouse.pls?YOUR\_KEY > > Title62=Digitally Imported - techhouse > > Length62=-1 > > File63=http://listen.di.fm/premium\_high/techno.pls?YOUR\_KEY > > Title63=Digitally Imported - techno > > Length63=-1 > > File64=http://listen.di.fm/premium\_high/trap.pls?YOUR\_KEY > > Title64=Digitally Imported - trap > > Length64=-1 > > File65=http://listen.di.fm/premium\_high/tribalhouse.pls?YOUR\_KEY > > Title65=Digitally Imported - tribalhouse > > Length65=-1 > > File66=http://listen.di.fm/premium\_high/ukgarage.pls?YOUR\_KEY > > Title66=Digitally Imported - ukgarage > > Length66=-1 > > File67=http://listen.di.fm/premium\_high/umfradio.pls?YOUR\_KEY > > Title67=Digitally Imported - umfradio > > Length67=-1 > > File68=http://listen.di.fm/premium\_high/undergroundtechno.pls?YOUR\_KEY > > Title68=Digitally Imported - undergroundtechno > > Length68=-1 > > File69=http://listen.di.fm/premium\_high/vocalchillout.pls?YOUR\_KEY > > Title69=Digitally Imported - vocalchillout > > Length69=-1 > > File70=http://listen.di.fm/premium\_high/vocallounge.pls?YOUR\_KEY > > Title70=Digitally Imported - vocallounge > > Length70=-1 > > version=2 > > > >
You can download all the .pls files. After that you open this files in a text editor like notepad++. You´ll discover the true url for the station. Add these url in a streaming audio grabber. You´ll download in real time as the music plays. I recomend StremRipper for winamp (you really don´t need winamp to use it) Open the program, press rightclick and paste the true url from the station like inside the PLS files (listen.sky.fm/public3/STATIONNAME.pls) Dont forget to configure the output folder.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
My answer was initially the same as above, except I give the link to the di fm radio and not sky radio. The link would be something like this: ``` http://listen.di.fm/public3/insert_radio_name.pls ``` And you get radio name by clicking on any of the radios, it will be `http://www.di.fm/insert_radio_name` so this is the manual way to do it, and not all at once. And I'm not sure if it works for all stations. It's not 5 clicks per station, it's just 1 hover and 1 click, but even if that sounds like a lot, you can right click on the Stations button and do an Inspect element and expand the submenu and the lists divs. There you can find the names of the stations and you're 1 copy paste away. Ooor, without expanding any further, copy the ul elements, paste them in a txt file and start doing find/replace to turn for instance: ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key="00sclubhits" data-channel-id="324"></li> ``` into ``` http://listen.di.fm/public3/00sclubhits.pls ``` How? First part is easy, notepad is enough, just replace this ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key=" ``` with ``` http://listen.di.fm/public3/ ``` And for the 2nd part you can google "notepad++ regex" and install notepad++ and come up with: ``` " data-channel-id="(\d)*"></li> ``` being replaced with ``` .pls ``` Then trim out the ul elements or replace them with empty string. In the end you will have em all in 1 file, like this: `http://pastebin.com/V0mPewCq`. If you want this done in 1 go, I suggest you pick up Java and do a crawler for the main page in case they change them and you don't want to go through this again. I have yet to know how to get them all in a playlist or save them all at once from such a file. Either save each manually (you can use this `http://www.urlopener.com/home.html` if you don't want to paste each in a tab, but you still have to click Save As... ) or again automated with some script (I also found this but idk how trustworthy it is: `http://helpdeskgeek.com/free-tools-review/download-multiple-files-at-once-in-windows/`), or add each Location manually and save them all into 1 big playlist. It's all a 2 step because the .pls that they give you contains the true links.
You can download all the .pls files. After that you open this files in a text editor like notepad++. You´ll discover the true url for the station. Add these url in a streaming audio grabber. You´ll download in real time as the music plays. I recomend StremRipper for winamp (you really don´t need winamp to use it) Open the program, press rightclick and paste the true url from the station like inside the PLS files (listen.sky.fm/public3/STATIONNAME.pls) Dont forget to configure the output folder.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
This solution uses command line programs: `curl` - cURL tool to transfer data from or to a server `grep` - Grep a command-line utility that can search and filter text *Linux users should find these either already installed or simply use their distro's package manager to install. Windows users can install [Cygwin](https://www.cygwin.com/) or a lighter weight toolset [Gnu on Windows](https://github.com/bmatzelle/gow/wiki).* Solution: The webpage <http://listen.di.fm/public3/> is a json list. We only need to get the page using cURL search for the .pls links using grep. Type this in a command terminal: `curl -s "http://listen.di.fm/public3/" | grep -Po 'http://listen.*?pls'` A subset of the output should be: ``` http://listen.di.fm/public3/trance.pls http://listen.di.fm/public3/vocaltrance.pls http://listen.di.fm/public3/chillout.pls http://listen.di.fm/public3/house.pls http://listen.di.fm/public3/harddance.pls http://listen.di.fm/public3/eurodance.pls http://listen.di.fm/public3/progressive.pls http://listen.di.fm/public3/goapsy.pls ... etc. ```
You can download all the .pls files. After that you open this files in a text editor like notepad++. You´ll discover the true url for the station. Add these url in a streaming audio grabber. You´ll download in real time as the music plays. I recomend StremRipper for winamp (you really don´t need winamp to use it) Open the program, press rightclick and paste the true url from the station like inside the PLS files (listen.sky.fm/public3/STATIONNAME.pls) Dont forget to configure the output folder.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
1. Save the following text in a .pls file. 2. Edit with notepad to replace the text YOUR\_KEY by your premium key or delete it if you are not premium. 3. Open the pls file in your favorite player :) > > [playlist] > > NumberOfEntries=70 > > File1=http://listen.di.fm/premium\_high/trance.pls?YOUR\_KEY > > Title1=Digitally Imported - trance > > Length1=-1 > > File2=http://listen.di.fm/premium\_high/vocaltrance.pls?YOUR\_KEY > > Title2=Digitally Imported - vocaltrance > > Length2=-1 > > File3=http://listen.di.fm/premium\_high/ambient.pls?YOUR\_KEY > > Title3=Digitally Imported - ambient > > Length3=-1 > > File4=http://listen.di.fm/premium\_high/bigroomhouse.pls?YOUR\_KEY > > Title4=Digitally Imported - bigroomhouse > > Length4=-1 > > File5=http://listen.di.fm/premium\_high/breaks.pls?YOUR\_KEY > > Title5=Digitally Imported - breaks > > Length5=-1 > > File6=http://listen.di.fm/premium\_high/chillhop.pls?YOUR\_KEY > > Title6=Digitally Imported - chillhop > > Length6=-1 > > File7=http://listen.di.fm/premium\_high/chillout.pls?YOUR\_KEY > > Title7=Digitally Imported - chillout > > Length7=-1 > > File8=http://listen.di.fm/premium\_high/chilloutdreams.pls?YOUR\_KEY > > Title8=Digitally Imported - chilloutdreams > > Length8=-1 > > File9=http://listen.di.fm/premium\_high/chillstep.pls?YOUR\_KEY > > Title9=Digitally Imported - chillstep > > Length9=-1 > > File10=http://listen.di.fm/premium\_high/chiptunes.pls?YOUR\_KEY > > Title10=Digitally Imported - chiptunes > > Length10=-1 > > File11=http://listen.di.fm/premium\_high/classiceurodance.pls?YOUR\_KEY > > Title11=Digitally Imported - classiceurodance > > Length11=-1 > > File12=http://listen.di.fm/premium\_high/classiceurodisco.pls?YOUR\_KEY > > Title12=Digitally Imported - classiceurodisco > > Length12=-1 > > File13=http://listen.di.fm/premium\_high/classictrance.pls?YOUR\_KEY > > Title13=Digitally Imported - classictrance > > Length13=-1 > > File14=http://listen.di.fm/premium\_high/classicvocaltrance.pls?YOUR\_KEY > > Title14=Digitally Imported - classicvocaltrance > > Length14=-1 > > File15=http://listen.di.fm/premium\_high/clubdubstep.pls?YOUR\_KEY > > Title15=Digitally Imported - clubdubstep > > Length15=-1 > > File16=http://listen.di.fm/premium\_high/club.pls?YOUR\_KEY > > Title16=Digitally Imported - club > > Length16=-1 > > File17=http://listen.di.fm/premium\_high/cosmicdowntempo.pls?YOUR\_KEY > > Title17=Digitally Imported - cosmicdowntempo > > Length17=-1 > > File18=http://listen.di.fm/premium\_high/djmixes.pls?YOUR\_KEY > > Title18=Digitally Imported - djmixes > > Length18=-1 > > File19=http://listen.di.fm/premium\_high/darkdnb.pls?YOUR\_KEY > > Title19=Digitally Imported - darkdnb > > Length19=-1 > > File20=http://listen.di.fm/premium\_high/deephouse.pls?YOUR\_KEY > > Title20=Digitally Imported - deephouse > > Length20=-1 > > File21=http://listen.di.fm/premium\_high/deepnudisco.pls?YOUR\_KEY > > Title21=Digitally Imported - deepnudisco > > Length21=-1 > > File22=http://listen.di.fm/premium\_high/deeptech.pls?YOUR\_KEY > > Title22=Digitally Imported - deeptech > > Length22=-1 > > File23=http://listen.di.fm/premium\_high/discohouse.pls?YOUR\_KEY > > Title23=Digitally Imported - discohouse > > Length23=-1 > > File24=http://listen.di.fm/premium\_high/downtempolounge.pls?YOUR\_KEY > > Title24=Digitally Imported - downtempolounge > > Length24=-1 > > File25=http://listen.di.fm/premium\_high/drumandbass.pls?YOUR\_KEY > > Title25=Digitally Imported - drumandbass > > Length25=-1 > > File26=http://listen.di.fm/premium\_high/dubstep.pls?YOUR\_KEY > > Title26=Digitally Imported - dubstep > > Length26=-1 > > File27=http://listen.di.fm/premium\_high/eclectronica.pls?YOUR\_KEY > > Title27=Digitally Imported - eclectronica > > Length27=-1 > > File28=http://listen.di.fm/premium\_high/electro.pls?YOUR\_KEY > > Title28=Digitally Imported - electro > > Length28=-1 > > File29=http://listen.di.fm/premium\_high/electronicpioneers.pls?YOUR\_KEY > > Title29=Digitally Imported - electronicpioneers > > Length29=-1 > > File30=http://listen.di.fm/premium\_high/electropop.pls?YOUR\_KEY > > Title30=Digitally Imported - electropop > > Length30=-1 > > File31=http://listen.di.fm/premium\_high/epictrance.pls?YOUR\_KEY > > Title31=Digitally Imported - epictrance > > Length31=-1 > > File32=http://listen.di.fm/premium\_high/eurodance.pls?YOUR\_KEY > > Title32=Digitally Imported - eurodance > > Length32=-1 > > File33=http://listen.di.fm/premium\_high/funkyhouse.pls?YOUR\_KEY > > Title33=Digitally Imported - funkyhouse > > Length33=-1 > > File34=http://listen.di.fm/premium\_high/futuresynthpop.pls?YOUR\_KEY > > Title34=Digitally Imported - futuresynthpop > > Length34=-1 > > File35=http://listen.di.fm/premium\_high/gabber.pls?YOUR\_KEY > > Title35=Digitally Imported - gabber > > Length35=-1 > > File36=http://listen.di.fm/premium\_high/glitchhop.pls?YOUR\_KEY > > Title36=Digitally Imported - glitchhop > > Length36=-1 > > File37=http://listen.di.fm/premium\_high/goapsy.pls?YOUR\_KEY > > Title37=Digitally Imported - goapsy > > Length37=-1 > > File38=http://listen.di.fm/premium\_high/handsup.pls?YOUR\_KEY > > Title38=Digitally Imported - handsup > > Length38=-1 > > File39=http://listen.di.fm/premium\_high/harddance.pls?YOUR\_KEY > > Title39=Digitally Imported - harddance > > Length39=-1 > > File40=http://listen.di.fm/premium\_high/hardtechno.pls?YOUR\_KEY > > Title40=Digitally Imported - hardtechno > > Length40=-1 > > File41=http://listen.di.fm/premium\_high/hardcore.pls?YOUR\_KEY > > Title41=Digitally Imported - hardcore > > Length41=-1 > > File42=http://listen.di.fm/premium\_high/hardstyle.pls?YOUR\_KEY > > Title42=Digitally Imported - hardstyle > > Length42=-1 > > File43=http://listen.di.fm/premium\_high/house.pls?YOUR\_KEY > > Title43=Digitally Imported - house > > Length43=-1 > > File44=http://listen.di.fm/premium\_high/latinhouse.pls?YOUR\_KEY > > Title44=Digitally Imported - latinhouse > > Length44=-1 > > File45=http://listen.di.fm/premium\_high/liquiddnb.pls?YOUR\_KEY > > Title45=Digitally Imported - liquiddnb > > Length45=-1 > > File46=http://listen.di.fm/premium\_high/liquiddubstep.pls?YOUR\_KEY > > Title46=Digitally Imported - liquiddubstep > > Length46=-1 > > File47=http://listen.di.fm/premium\_high/lounge.pls?YOUR\_KEY > > Title47=Digitally Imported - lounge > > Length47=-1 > > File48=http://listen.di.fm/premium\_high/mainstage.pls?YOUR\_KEY > > Title48=Digitally Imported - mainstage > > Length48=-1 > > File49=http://listen.di.fm/premium\_high/minimal.pls?YOUR\_KEY > > Title49=Digitally Imported - minimal > > Length49=-1 > > File50=http://listen.di.fm/premium\_high/moombahton.pls?YOUR\_KEY > > Title50=Digitally Imported - moombahton > > Length50=-1 > > File51=http://listen.di.fm/premium\_high/oldschoolacid.pls?YOUR\_KEY > > Title51=Digitally Imported - oldschoolacid > > Length51=-1 > > File52=http://listen.di.fm/premium\_high/classictechno.pls?YOUR\_KEY > > Title52=Digitally Imported - classictechno > > Length52=-1 > > File53=http://listen.di.fm/premium\_high/progressive.pls?YOUR\_KEY > > Title53=Digitally Imported - progressive > > Length53=-1 > > File54=http://listen.di.fm/premium\_high/progressivepsy.pls?YOUR\_KEY > > Title54=Digitally Imported - progressivepsy > > Length54=-1 > > File55=http://listen.di.fm/premium\_high/psychill.pls?YOUR\_KEY > > Title55=Digitally Imported - psychill > > Length55=-1 > > File56=http://listen.di.fm/premium\_high/psybient.pls?YOUR\_KEY > > Title56=Digitally Imported - psybient > > Length56=-1 > > File57=http://listen.di.fm/premium\_high/russianclubhits.pls?YOUR\_KEY > > Title57=Digitally Imported - russianclubhits > > Length57=-1 > > File58=http://listen.di.fm/premium\_high/sankeys.pls?YOUR\_KEY > > Title58=Digitally Imported - sankeys > > Length58=-1 > > File59=http://listen.di.fm/premium\_high/scousehouse.pls?YOUR\_KEY > > Title59=Digitally Imported - scousehouse > > Length59=-1 > > File60=http://listen.di.fm/premium\_high/soulfulhouse.pls?YOUR\_KEY > > Title60=Digitally Imported - soulfulhouse > > Length60=-1 > > File61=http://listen.di.fm/premium\_high/spacemusic.pls?YOUR\_KEY > > Title61=Digitally Imported - spacemusic > > Length61=-1 > > File62=http://listen.di.fm/premium\_high/techhouse.pls?YOUR\_KEY > > Title62=Digitally Imported - techhouse > > Length62=-1 > > File63=http://listen.di.fm/premium\_high/techno.pls?YOUR\_KEY > > Title63=Digitally Imported - techno > > Length63=-1 > > File64=http://listen.di.fm/premium\_high/trap.pls?YOUR\_KEY > > Title64=Digitally Imported - trap > > Length64=-1 > > File65=http://listen.di.fm/premium\_high/tribalhouse.pls?YOUR\_KEY > > Title65=Digitally Imported - tribalhouse > > Length65=-1 > > File66=http://listen.di.fm/premium\_high/ukgarage.pls?YOUR\_KEY > > Title66=Digitally Imported - ukgarage > > Length66=-1 > > File67=http://listen.di.fm/premium\_high/umfradio.pls?YOUR\_KEY > > Title67=Digitally Imported - umfradio > > Length67=-1 > > File68=http://listen.di.fm/premium\_high/undergroundtechno.pls?YOUR\_KEY > > Title68=Digitally Imported - undergroundtechno > > Length68=-1 > > File69=http://listen.di.fm/premium\_high/vocalchillout.pls?YOUR\_KEY > > Title69=Digitally Imported - vocalchillout > > Length69=-1 > > File70=http://listen.di.fm/premium\_high/vocallounge.pls?YOUR\_KEY > > Title70=Digitally Imported - vocallounge > > Length70=-1 > > version=2 > > > >
My answer was initially the same as above, except I give the link to the di fm radio and not sky radio. The link would be something like this: ``` http://listen.di.fm/public3/insert_radio_name.pls ``` And you get radio name by clicking on any of the radios, it will be `http://www.di.fm/insert_radio_name` so this is the manual way to do it, and not all at once. And I'm not sure if it works for all stations. It's not 5 clicks per station, it's just 1 hover and 1 click, but even if that sounds like a lot, you can right click on the Stations button and do an Inspect element and expand the submenu and the lists divs. There you can find the names of the stations and you're 1 copy paste away. Ooor, without expanding any further, copy the ul elements, paste them in a txt file and start doing find/replace to turn for instance: ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key="00sclubhits" data-channel-id="324"></li> ``` into ``` http://listen.di.fm/public3/00sclubhits.pls ``` How? First part is easy, notepad is enough, just replace this ``` <li data-ga-event="MainNav,channel-dropdown-click,@data-channel-key" data-channel-key=" ``` with ``` http://listen.di.fm/public3/ ``` And for the 2nd part you can google "notepad++ regex" and install notepad++ and come up with: ``` " data-channel-id="(\d)*"></li> ``` being replaced with ``` .pls ``` Then trim out the ul elements or replace them with empty string. In the end you will have em all in 1 file, like this: `http://pastebin.com/V0mPewCq`. If you want this done in 1 go, I suggest you pick up Java and do a crawler for the main page in case they change them and you don't want to go through this again. I have yet to know how to get them all in a playlist or save them all at once from such a file. Either save each manually (you can use this `http://www.urlopener.com/home.html` if you don't want to paste each in a tab, but you still have to click Save As... ) or again automated with some script (I also found this but idk how trustworthy it is: `http://helpdeskgeek.com/free-tools-review/download-multiple-files-at-once-in-windows/`), or add each Location manually and save them all into 1 big playlist. It's all a 2 step because the .pls that they give you contains the true links.
21,798
I would like to download the radio station playlists available for free (LQ) by www.di.fm and www.sky.fm, because they offer no web/desktop app! But I don't always use my iPhone or Android tablet and their website navigation is way too cumbersome. Is there a quick way to download **all** their stations \*.pls? I want to add them to my internet radio playlist (foobar). The only solution I found is [**this "hack"**](http://mpd.wikia.com/wiki/Hack:di.fm-playlists), but I don't even understand what it says, i.e. where I place those scripts so that they do what they are intended to do. I would highly appreciate your help in using the above scripts or find another way. Maybe someone of you already made himself the work and can upload the playlist file here. (It doesn't matter for me if sky.fm and di.fm are separated or in one file.)
2011/12/08
[ "https://webapps.stackexchange.com/questions/21798", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/9898/" ]
1. Save the following text in a .pls file. 2. Edit with notepad to replace the text YOUR\_KEY by your premium key or delete it if you are not premium. 3. Open the pls file in your favorite player :) > > [playlist] > > NumberOfEntries=70 > > File1=http://listen.di.fm/premium\_high/trance.pls?YOUR\_KEY > > Title1=Digitally Imported - trance > > Length1=-1 > > File2=http://listen.di.fm/premium\_high/vocaltrance.pls?YOUR\_KEY > > Title2=Digitally Imported - vocaltrance > > Length2=-1 > > File3=http://listen.di.fm/premium\_high/ambient.pls?YOUR\_KEY > > Title3=Digitally Imported - ambient > > Length3=-1 > > File4=http://listen.di.fm/premium\_high/bigroomhouse.pls?YOUR\_KEY > > Title4=Digitally Imported - bigroomhouse > > Length4=-1 > > File5=http://listen.di.fm/premium\_high/breaks.pls?YOUR\_KEY > > Title5=Digitally Imported - breaks > > Length5=-1 > > File6=http://listen.di.fm/premium\_high/chillhop.pls?YOUR\_KEY > > Title6=Digitally Imported - chillhop > > Length6=-1 > > File7=http://listen.di.fm/premium\_high/chillout.pls?YOUR\_KEY > > Title7=Digitally Imported - chillout > > Length7=-1 > > File8=http://listen.di.fm/premium\_high/chilloutdreams.pls?YOUR\_KEY > > Title8=Digitally Imported - chilloutdreams > > Length8=-1 > > File9=http://listen.di.fm/premium\_high/chillstep.pls?YOUR\_KEY > > Title9=Digitally Imported - chillstep > > Length9=-1 > > File10=http://listen.di.fm/premium\_high/chiptunes.pls?YOUR\_KEY > > Title10=Digitally Imported - chiptunes > > Length10=-1 > > File11=http://listen.di.fm/premium\_high/classiceurodance.pls?YOUR\_KEY > > Title11=Digitally Imported - classiceurodance > > Length11=-1 > > File12=http://listen.di.fm/premium\_high/classiceurodisco.pls?YOUR\_KEY > > Title12=Digitally Imported - classiceurodisco > > Length12=-1 > > File13=http://listen.di.fm/premium\_high/classictrance.pls?YOUR\_KEY > > Title13=Digitally Imported - classictrance > > Length13=-1 > > File14=http://listen.di.fm/premium\_high/classicvocaltrance.pls?YOUR\_KEY > > Title14=Digitally Imported - classicvocaltrance > > Length14=-1 > > File15=http://listen.di.fm/premium\_high/clubdubstep.pls?YOUR\_KEY > > Title15=Digitally Imported - clubdubstep > > Length15=-1 > > File16=http://listen.di.fm/premium\_high/club.pls?YOUR\_KEY > > Title16=Digitally Imported - club > > Length16=-1 > > File17=http://listen.di.fm/premium\_high/cosmicdowntempo.pls?YOUR\_KEY > > Title17=Digitally Imported - cosmicdowntempo > > Length17=-1 > > File18=http://listen.di.fm/premium\_high/djmixes.pls?YOUR\_KEY > > Title18=Digitally Imported - djmixes > > Length18=-1 > > File19=http://listen.di.fm/premium\_high/darkdnb.pls?YOUR\_KEY > > Title19=Digitally Imported - darkdnb > > Length19=-1 > > File20=http://listen.di.fm/premium\_high/deephouse.pls?YOUR\_KEY > > Title20=Digitally Imported - deephouse > > Length20=-1 > > File21=http://listen.di.fm/premium\_high/deepnudisco.pls?YOUR\_KEY > > Title21=Digitally Imported - deepnudisco > > Length21=-1 > > File22=http://listen.di.fm/premium\_high/deeptech.pls?YOUR\_KEY > > Title22=Digitally Imported - deeptech > > Length22=-1 > > File23=http://listen.di.fm/premium\_high/discohouse.pls?YOUR\_KEY > > Title23=Digitally Imported - discohouse > > Length23=-1 > > File24=http://listen.di.fm/premium\_high/downtempolounge.pls?YOUR\_KEY > > Title24=Digitally Imported - downtempolounge > > Length24=-1 > > File25=http://listen.di.fm/premium\_high/drumandbass.pls?YOUR\_KEY > > Title25=Digitally Imported - drumandbass > > Length25=-1 > > File26=http://listen.di.fm/premium\_high/dubstep.pls?YOUR\_KEY > > Title26=Digitally Imported - dubstep > > Length26=-1 > > File27=http://listen.di.fm/premium\_high/eclectronica.pls?YOUR\_KEY > > Title27=Digitally Imported - eclectronica > > Length27=-1 > > File28=http://listen.di.fm/premium\_high/electro.pls?YOUR\_KEY > > Title28=Digitally Imported - electro > > Length28=-1 > > File29=http://listen.di.fm/premium\_high/electronicpioneers.pls?YOUR\_KEY > > Title29=Digitally Imported - electronicpioneers > > Length29=-1 > > File30=http://listen.di.fm/premium\_high/electropop.pls?YOUR\_KEY > > Title30=Digitally Imported - electropop > > Length30=-1 > > File31=http://listen.di.fm/premium\_high/epictrance.pls?YOUR\_KEY > > Title31=Digitally Imported - epictrance > > Length31=-1 > > File32=http://listen.di.fm/premium\_high/eurodance.pls?YOUR\_KEY > > Title32=Digitally Imported - eurodance > > Length32=-1 > > File33=http://listen.di.fm/premium\_high/funkyhouse.pls?YOUR\_KEY > > Title33=Digitally Imported - funkyhouse > > Length33=-1 > > File34=http://listen.di.fm/premium\_high/futuresynthpop.pls?YOUR\_KEY > > Title34=Digitally Imported - futuresynthpop > > Length34=-1 > > File35=http://listen.di.fm/premium\_high/gabber.pls?YOUR\_KEY > > Title35=Digitally Imported - gabber > > Length35=-1 > > File36=http://listen.di.fm/premium\_high/glitchhop.pls?YOUR\_KEY > > Title36=Digitally Imported - glitchhop > > Length36=-1 > > File37=http://listen.di.fm/premium\_high/goapsy.pls?YOUR\_KEY > > Title37=Digitally Imported - goapsy > > Length37=-1 > > File38=http://listen.di.fm/premium\_high/handsup.pls?YOUR\_KEY > > Title38=Digitally Imported - handsup > > Length38=-1 > > File39=http://listen.di.fm/premium\_high/harddance.pls?YOUR\_KEY > > Title39=Digitally Imported - harddance > > Length39=-1 > > File40=http://listen.di.fm/premium\_high/hardtechno.pls?YOUR\_KEY > > Title40=Digitally Imported - hardtechno > > Length40=-1 > > File41=http://listen.di.fm/premium\_high/hardcore.pls?YOUR\_KEY > > Title41=Digitally Imported - hardcore > > Length41=-1 > > File42=http://listen.di.fm/premium\_high/hardstyle.pls?YOUR\_KEY > > Title42=Digitally Imported - hardstyle > > Length42=-1 > > File43=http://listen.di.fm/premium\_high/house.pls?YOUR\_KEY > > Title43=Digitally Imported - house > > Length43=-1 > > File44=http://listen.di.fm/premium\_high/latinhouse.pls?YOUR\_KEY > > Title44=Digitally Imported - latinhouse > > Length44=-1 > > File45=http://listen.di.fm/premium\_high/liquiddnb.pls?YOUR\_KEY > > Title45=Digitally Imported - liquiddnb > > Length45=-1 > > File46=http://listen.di.fm/premium\_high/liquiddubstep.pls?YOUR\_KEY > > Title46=Digitally Imported - liquiddubstep > > Length46=-1 > > File47=http://listen.di.fm/premium\_high/lounge.pls?YOUR\_KEY > > Title47=Digitally Imported - lounge > > Length47=-1 > > File48=http://listen.di.fm/premium\_high/mainstage.pls?YOUR\_KEY > > Title48=Digitally Imported - mainstage > > Length48=-1 > > File49=http://listen.di.fm/premium\_high/minimal.pls?YOUR\_KEY > > Title49=Digitally Imported - minimal > > Length49=-1 > > File50=http://listen.di.fm/premium\_high/moombahton.pls?YOUR\_KEY > > Title50=Digitally Imported - moombahton > > Length50=-1 > > File51=http://listen.di.fm/premium\_high/oldschoolacid.pls?YOUR\_KEY > > Title51=Digitally Imported - oldschoolacid > > Length51=-1 > > File52=http://listen.di.fm/premium\_high/classictechno.pls?YOUR\_KEY > > Title52=Digitally Imported - classictechno > > Length52=-1 > > File53=http://listen.di.fm/premium\_high/progressive.pls?YOUR\_KEY > > Title53=Digitally Imported - progressive > > Length53=-1 > > File54=http://listen.di.fm/premium\_high/progressivepsy.pls?YOUR\_KEY > > Title54=Digitally Imported - progressivepsy > > Length54=-1 > > File55=http://listen.di.fm/premium\_high/psychill.pls?YOUR\_KEY > > Title55=Digitally Imported - psychill > > Length55=-1 > > File56=http://listen.di.fm/premium\_high/psybient.pls?YOUR\_KEY > > Title56=Digitally Imported - psybient > > Length56=-1 > > File57=http://listen.di.fm/premium\_high/russianclubhits.pls?YOUR\_KEY > > Title57=Digitally Imported - russianclubhits > > Length57=-1 > > File58=http://listen.di.fm/premium\_high/sankeys.pls?YOUR\_KEY > > Title58=Digitally Imported - sankeys > > Length58=-1 > > File59=http://listen.di.fm/premium\_high/scousehouse.pls?YOUR\_KEY > > Title59=Digitally Imported - scousehouse > > Length59=-1 > > File60=http://listen.di.fm/premium\_high/soulfulhouse.pls?YOUR\_KEY > > Title60=Digitally Imported - soulfulhouse > > Length60=-1 > > File61=http://listen.di.fm/premium\_high/spacemusic.pls?YOUR\_KEY > > Title61=Digitally Imported - spacemusic > > Length61=-1 > > File62=http://listen.di.fm/premium\_high/techhouse.pls?YOUR\_KEY > > Title62=Digitally Imported - techhouse > > Length62=-1 > > File63=http://listen.di.fm/premium\_high/techno.pls?YOUR\_KEY > > Title63=Digitally Imported - techno > > Length63=-1 > > File64=http://listen.di.fm/premium\_high/trap.pls?YOUR\_KEY > > Title64=Digitally Imported - trap > > Length64=-1 > > File65=http://listen.di.fm/premium\_high/tribalhouse.pls?YOUR\_KEY > > Title65=Digitally Imported - tribalhouse > > Length65=-1 > > File66=http://listen.di.fm/premium\_high/ukgarage.pls?YOUR\_KEY > > Title66=Digitally Imported - ukgarage > > Length66=-1 > > File67=http://listen.di.fm/premium\_high/umfradio.pls?YOUR\_KEY > > Title67=Digitally Imported - umfradio > > Length67=-1 > > File68=http://listen.di.fm/premium\_high/undergroundtechno.pls?YOUR\_KEY > > Title68=Digitally Imported - undergroundtechno > > Length68=-1 > > File69=http://listen.di.fm/premium\_high/vocalchillout.pls?YOUR\_KEY > > Title69=Digitally Imported - vocalchillout > > Length69=-1 > > File70=http://listen.di.fm/premium\_high/vocallounge.pls?YOUR\_KEY > > Title70=Digitally Imported - vocallounge > > Length70=-1 > > version=2 > > > >
This solution uses command line programs: `curl` - cURL tool to transfer data from or to a server `grep` - Grep a command-line utility that can search and filter text *Linux users should find these either already installed or simply use their distro's package manager to install. Windows users can install [Cygwin](https://www.cygwin.com/) or a lighter weight toolset [Gnu on Windows](https://github.com/bmatzelle/gow/wiki).* Solution: The webpage <http://listen.di.fm/public3/> is a json list. We only need to get the page using cURL search for the .pls links using grep. Type this in a command terminal: `curl -s "http://listen.di.fm/public3/" | grep -Po 'http://listen.*?pls'` A subset of the output should be: ``` http://listen.di.fm/public3/trance.pls http://listen.di.fm/public3/vocaltrance.pls http://listen.di.fm/public3/chillout.pls http://listen.di.fm/public3/house.pls http://listen.di.fm/public3/harddance.pls http://listen.di.fm/public3/eurodance.pls http://listen.di.fm/public3/progressive.pls http://listen.di.fm/public3/goapsy.pls ... etc. ```
64,774,158
I am looking for a way to use grep on a linux server to find duplicate json records, is it possible to have a grep to search for duplicate id's in the example below ? so the grep would return: 01 ``` { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "02", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "03", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "04", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } ```
2020/11/10
[ "https://Stackoverflow.com/questions/64774158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312005/" ]
use `grep` along with `uniq`. ``` grep '"id":' filename | sort | uniq -d ``` The `-d` option only prints duplicates. However, this depends on the JSON being laid out neatly. To handle more general formatting, I recommend you use the `jq` utility.
Use a Perl one-liner to extract the numeric ids, then `sort | uniq -d` to print only the duplicates (as in the answer by *Barmar*): This assumes that the id key/value pair is on the same line, but disregards whitespace (or lack of whitespace) anywhere on the line (leading, trailing, and in between): ``` perl -lne 'print for /"id":\s*"(\d+)"/' in.json | sort | uniq -d ``` This makes no assumptions (disregards whitespace and newlines). Note that it reads the entire json file into memory (using the `-0777` command line switch): ``` perl -0777 -nE 'say for /"id":\s*"(\d+)"/g' in.json | sort | uniq -d ``` The Perl one-liner uses these command line flags: `-e` : Tells Perl to look for code in-line, instead of in a file. `-E` : Tells Perl to look for code in-line, instead of in a file. Also enables all optional features. Here, enables `say`. `-n` : Loop over the input one line at a time, assigning it to `$_` by default. `-l` : Strip the input line separator (`"\n"` on \*NIX by default) before executing the code in-line, and append it when printing. `-0777` : Slurp files whole. The regex uses this modifier: `/g` : Multiple matches. **SEE ALSO:** [`perldoc perlrun`: how to execute the Perl interpreter: command line switches](https://perldoc.perl.org/perlrun.html#Command-Switches) [`perldoc perlre`: Perl regular expressions (regexes)](https://perldoc.perl.org/perlre.html) [`perldoc perlre`: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups](https://perldoc.perl.org/perlre.html#Regular-Expressions) [`perldoc perlrequick`: Perl regular expressions quick start](https://perldoc.perl.org/perlrequick)
64,774,158
I am looking for a way to use grep on a linux server to find duplicate json records, is it possible to have a grep to search for duplicate id's in the example below ? so the grep would return: 01 ``` { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "02", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "03", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "04", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } ```
2020/11/10
[ "https://Stackoverflow.com/questions/64774158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312005/" ]
OK, discarding any whitespace from the JSON strings I can offer this if `awk` is acceptable - `hutch` being the formatted chunk of JSON above in a file. I use `tr` to remove any whitespace, use `,` as a field separator in awk; iterate over the one long lines elements with a for-loop, do some pattern-matching in awk to isolate ID fields and increment an array for each matched ID. At the end of processing I iterate over the array and print ID's that have more than one match. Here your data: ``` $ cat hutch { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "02", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "03", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "04", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } ``` And here the finding of dupes: ``` $ tr -d '[:space:]' <hutch | awk -F, '{for(i=1;i<=NF;i++){if($i~/"id":/){a[gensub(/^.*"id":"([0-9]+)"$/, "\\1","1",$i)]++}}}END{for(i in a){if(a[i]>1){print i}}}' 01 ```
Use a Perl one-liner to extract the numeric ids, then `sort | uniq -d` to print only the duplicates (as in the answer by *Barmar*): This assumes that the id key/value pair is on the same line, but disregards whitespace (or lack of whitespace) anywhere on the line (leading, trailing, and in between): ``` perl -lne 'print for /"id":\s*"(\d+)"/' in.json | sort | uniq -d ``` This makes no assumptions (disregards whitespace and newlines). Note that it reads the entire json file into memory (using the `-0777` command line switch): ``` perl -0777 -nE 'say for /"id":\s*"(\d+)"/g' in.json | sort | uniq -d ``` The Perl one-liner uses these command line flags: `-e` : Tells Perl to look for code in-line, instead of in a file. `-E` : Tells Perl to look for code in-line, instead of in a file. Also enables all optional features. Here, enables `say`. `-n` : Loop over the input one line at a time, assigning it to `$_` by default. `-l` : Strip the input line separator (`"\n"` on \*NIX by default) before executing the code in-line, and append it when printing. `-0777` : Slurp files whole. The regex uses this modifier: `/g` : Multiple matches. **SEE ALSO:** [`perldoc perlrun`: how to execute the Perl interpreter: command line switches](https://perldoc.perl.org/perlrun.html#Command-Switches) [`perldoc perlre`: Perl regular expressions (regexes)](https://perldoc.perl.org/perlre.html) [`perldoc perlre`: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups](https://perldoc.perl.org/perlre.html#Regular-Expressions) [`perldoc perlrequick`: Perl regular expressions quick start](https://perldoc.perl.org/perlrequick)
64,774,158
I am looking for a way to use grep on a linux server to find duplicate json records, is it possible to have a grep to search for duplicate id's in the example below ? so the grep would return: 01 ``` { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "02", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "03", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "04", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } ```
2020/11/10
[ "https://Stackoverflow.com/questions/64774158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312005/" ]
A `jq`-based approach: ```sh jq -r '.book[].id' < in.json | sort | uniq -d 01 ``` This should work even for minified JSON files with no newlines.
Use a Perl one-liner to extract the numeric ids, then `sort | uniq -d` to print only the duplicates (as in the answer by *Barmar*): This assumes that the id key/value pair is on the same line, but disregards whitespace (or lack of whitespace) anywhere on the line (leading, trailing, and in between): ``` perl -lne 'print for /"id":\s*"(\d+)"/' in.json | sort | uniq -d ``` This makes no assumptions (disregards whitespace and newlines). Note that it reads the entire json file into memory (using the `-0777` command line switch): ``` perl -0777 -nE 'say for /"id":\s*"(\d+)"/g' in.json | sort | uniq -d ``` The Perl one-liner uses these command line flags: `-e` : Tells Perl to look for code in-line, instead of in a file. `-E` : Tells Perl to look for code in-line, instead of in a file. Also enables all optional features. Here, enables `say`. `-n` : Loop over the input one line at a time, assigning it to `$_` by default. `-l` : Strip the input line separator (`"\n"` on \*NIX by default) before executing the code in-line, and append it when printing. `-0777` : Slurp files whole. The regex uses this modifier: `/g` : Multiple matches. **SEE ALSO:** [`perldoc perlrun`: how to execute the Perl interpreter: command line switches](https://perldoc.perl.org/perlrun.html#Command-Switches) [`perldoc perlre`: Perl regular expressions (regexes)](https://perldoc.perl.org/perlre.html) [`perldoc perlre`: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups](https://perldoc.perl.org/perlre.html#Regular-Expressions) [`perldoc perlrequick`: Perl regular expressions quick start](https://perldoc.perl.org/perlrequick)
19,868,734
I'm writing a jQuery plugin using a typical `$.extend` scenario for merging user settings with the defaults, as in: ``` var settings = $.extend({ title: '', padding: [0,0,0,0] }, options); ``` Is there a swift way to ensure that `padding` always be a 4-member array of integers, honouring user's proper parameters, but ignoring/sanitizing bad type parameters?
2013/11/08
[ "https://Stackoverflow.com/questions/19868734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/776686/" ]
No, you have to check validity of `options` before extending the defaults. so no 'swift way' there. I would however go for four separate properties to make the code more readable (which index is which padding; top, left, right, bottom?) and solve your problem... ``` var settings = $.extend({ title: '', paddingLeft: 0, paddingTop: 0, paddingRight: 0, paddingBottom: 0, }, options); ```
I ended up with the following code, which so far has worked just fine: ``` if (options.padding && $.isArray(options.padding)) { var pd = options.padding; // Parsing shortcuts. switch (pd.length) { case 0: options.padding = [0,0,0,0]; break; case 1: options.padding = [pd[0], pd[0], pd[0], pd[0]]; break; case 2: options.padding = [pd[0], pd[1], pd[0], pd[1]]; break; case 3: options.padding = [pd[0], pd[1], pd[2], pd[1]]; break; default: options.padding = pd.splice(0, 4); } // Sanitizing values. for (var i = 0; i < 4; i++) { var pv = options.padding[i]; switch (typeof pv) { case 'number': options.padding[i] = Math.floor(pv); break; default: options.padding[i] = 0; break; } } } else { delete options.padding; } ```
721,880
I am trying to combine these 2 Nginx location definitions into 1 ``` location /v1/login { proxy_pass http://upstream/v1/login; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } location /v1/logout { proxy_pass http://upstream/v1/logout; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } ``` So I figured something like this should do the job ``` location ^~ /v1/(login|logout) { rewrite ^/v1/(.*)$ /v1/$1 break; proxy_pass http://upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ``` But for the life of me I can't get it to work. What am I doing wrong here? I have tried every possible combination of rewrite regexes.
2015/09/12
[ "https://serverfault.com/questions/721880", "https://serverfault.com", "https://serverfault.com/users/40672/" ]
What's wrong with this simple one? ``` location /v1/ { proxy_pass http://upstream/v1/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ```
You are not passing the complete URL to `proxy_pass`. Try something like this: ``` location ~ ^/v1/(login|logout) { proxy_pass http://upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ```
721,880
I am trying to combine these 2 Nginx location definitions into 1 ``` location /v1/login { proxy_pass http://upstream/v1/login; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } location /v1/logout { proxy_pass http://upstream/v1/logout; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } ``` So I figured something like this should do the job ``` location ^~ /v1/(login|logout) { rewrite ^/v1/(.*)$ /v1/$1 break; proxy_pass http://upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ``` But for the life of me I can't get it to work. What am I doing wrong here? I have tried every possible combination of rewrite regexes.
2015/09/12
[ "https://serverfault.com/questions/721880", "https://serverfault.com", "https://serverfault.com/users/40672/" ]
Have you tried this one? ``` location ~ ^/v1/(login|logout) { proxy_pass http://upstream/v1/$1; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ``` ***Edit:*** You may also add the following directive along with your `proxy_pass_header Authorization;` directive: ``` proxy_set_header Authorization $http_authorization; ```
You are not passing the complete URL to `proxy_pass`. Try something like this: ``` location ~ ^/v1/(login|logout) { proxy_pass http://upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ```
721,880
I am trying to combine these 2 Nginx location definitions into 1 ``` location /v1/login { proxy_pass http://upstream/v1/login; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } location /v1/logout { proxy_pass http://upstream/v1/logout; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_header Authorization; } ``` So I figured something like this should do the job ``` location ^~ /v1/(login|logout) { rewrite ^/v1/(.*)$ /v1/$1 break; proxy_pass http://upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ``` But for the life of me I can't get it to work. What am I doing wrong here? I have tried every possible combination of rewrite regexes.
2015/09/12
[ "https://serverfault.com/questions/721880", "https://serverfault.com", "https://serverfault.com/users/40672/" ]
Have you tried this one? ``` location ~ ^/v1/(login|logout) { proxy_pass http://upstream/v1/$1; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ``` ***Edit:*** You may also add the following directive along with your `proxy_pass_header Authorization;` directive: ``` proxy_set_header Authorization $http_authorization; ```
What's wrong with this simple one? ``` location /v1/ { proxy_pass http://upstream/v1/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
### Scope and Context are not the same The way variable `x` is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context. You could have a look at [this article](http://ryanmorr.com/understanding-scope-and-context-in-javascript/). The behaviour is not particular to `eval`, it is the same with other functions: ```js "use strict"; var obj = { x : 3}; var y = 4; function test() { console.log(this.x); // 3 console.log(typeof x); // undefined } test.call(obj); function test2() { console.log(this.y); // 4 console.log(typeof y); // number } test2.call(window); ```
whilst I recommend the answer provided by @trincot and in particular the great link. I am posting here my solution to the problem I faced ``` function evalInContext(scr, context) { // execute script in private context return (new Function( "with(this) { return " + scr + "}")).call(context); } ``` The `with(this)` expression allows the member variables of the `context` object to be present in the execution scope of the expression `scr`. Credit to [this answer](https://stackoverflow.com/a/543820/1972493) to a similar question
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
### Scope and Context are not the same The way variable `x` is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context. You could have a look at [this article](http://ryanmorr.com/understanding-scope-and-context-in-javascript/). The behaviour is not particular to `eval`, it is the same with other functions: ```js "use strict"; var obj = { x : 3}; var y = 4; function test() { console.log(this.x); // 3 console.log(typeof x); // undefined } test.call(obj); function test2() { console.log(this.y); // 4 console.log(typeof y); // number } test2.call(window); ```
This is an alternative method (written in ES6): ``` (new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context)); ``` Credits to Jonas Wilms for the answer. Here is my explanation, since I did not initially understand how it worked: ``` let example = new Function('a', 'b', 'return a+ b') ``` is the same as creating the function and assigning it to `example`: ``` function(a,b) { return a + b } ``` After that, you can call `example` like this: `example(2,6)` which returns 8. But let's say you don't want to assign the function created by `new Function` to a variable and you want to immediately call it instead. Then you can just do this: ``` new Function('a', 'b', 'return a+ b')(2,6) ``` The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the `context` object like this: `new Function(key1, key2, key3... lastkey, codeYouWantToExecute)`. It then calls the newly created function and passes the values that correspond to each key with the spread operator. Lastly, here is the answer compiled to ES5: ``` (new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context)); ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
### Scope and Context are not the same The way variable `x` is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context. You could have a look at [this article](http://ryanmorr.com/understanding-scope-and-context-in-javascript/). The behaviour is not particular to `eval`, it is the same with other functions: ```js "use strict"; var obj = { x : 3}; var y = 4; function test() { console.log(this.x); // 3 console.log(typeof x); // undefined } test.call(obj); function test2() { console.log(this.y); // 4 console.log(typeof y); // number } test2.call(window); ```
This evaluates expressions in a given context without the need to prefix vars with 'this'. Has caveats but works fine. Can also incorporate custom functions in the expression. Just call an 'evaluate' function, passing in your expression, context and an optional function. The context must be a flat structure (no nested elements) and the function must be referred to as 'fn' inside the string expression. Answer prints 11 in this case: ```js var expression = "fn((a+b)*c,2)"; var context = { a: 1, b: 2, c: 3 }; var func = function(x,y){return x+y;}; function evaluate(ex, ctx, fn) { return eval("var "+JSON.stringify(ctx).replace(/["{}]/gi, "").replace(/:/gi, "=")+", fn="+fn.toString()+";"+ex); } var answer = evaluate(expression, context, func); console.log(answer); ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
### Scope and Context are not the same The way variable `x` is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context. You could have a look at [this article](http://ryanmorr.com/understanding-scope-and-context-in-javascript/). The behaviour is not particular to `eval`, it is the same with other functions: ```js "use strict"; var obj = { x : 3}; var y = 4; function test() { console.log(this.x); // 3 console.log(typeof x); // undefined } test.call(obj); function test2() { console.log(this.y); // 4 console.log(typeof y); // number } test2.call(window); ```
cannot comment so i post, Joe's answer is great but if the string holds multiple statements (like `x++; y++; x+y;`) the `y++` part would never be executed because it returns at first statement. with this modification all statements will be executed and the last statement will be the return value. > > > ``` > function evalInScopeAndContext(scr, scopeAndContext) > { > // execute script in private context > return (new Function( "with(this) { return eval('" + scr + "'); }")).call(scopeAndContext); > } > > ``` > > i also changed the parameter name because that parameter is used both as scope and context, and they are different things. Warning 1: When using this function `this.x` will equal to `x` and cannot be changed, because the `this` property of the scope will be shadowed if present. if you execute `evalInScopeAndContext('this', {a:1, b:2, this:3})` the answer will be `{a:1, b:2, this:3}` instead of `3`. To access the property `this`, you have to write `this.this` instead, i don't think it can be fixed. Warning 2: Outer scope (From the caller of this function up to `window`) can be accessed and modified unless shadowed by the scope object. So if you plan to execute something like `location = 'house';` but forget to insert the `location` key inside the scope object, you will execute `window.location = 'house'` and might cause damage. Instead `this.location = 'house';` is always safe because `this` always exists and will just add the `location` key to the scope object provided, so you might want to always use `this.` as a prefix
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
whilst I recommend the answer provided by @trincot and in particular the great link. I am posting here my solution to the problem I faced ``` function evalInContext(scr, context) { // execute script in private context return (new Function( "with(this) { return " + scr + "}")).call(context); } ``` The `with(this)` expression allows the member variables of the `context` object to be present in the execution scope of the expression `scr`. Credit to [this answer](https://stackoverflow.com/a/543820/1972493) to a similar question
This is an alternative method (written in ES6): ``` (new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context)); ``` Credits to Jonas Wilms for the answer. Here is my explanation, since I did not initially understand how it worked: ``` let example = new Function('a', 'b', 'return a+ b') ``` is the same as creating the function and assigning it to `example`: ``` function(a,b) { return a + b } ``` After that, you can call `example` like this: `example(2,6)` which returns 8. But let's say you don't want to assign the function created by `new Function` to a variable and you want to immediately call it instead. Then you can just do this: ``` new Function('a', 'b', 'return a+ b')(2,6) ``` The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the `context` object like this: `new Function(key1, key2, key3... lastkey, codeYouWantToExecute)`. It then calls the newly created function and passes the values that correspond to each key with the spread operator. Lastly, here is the answer compiled to ES5: ``` (new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context)); ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
whilst I recommend the answer provided by @trincot and in particular the great link. I am posting here my solution to the problem I faced ``` function evalInContext(scr, context) { // execute script in private context return (new Function( "with(this) { return " + scr + "}")).call(context); } ``` The `with(this)` expression allows the member variables of the `context` object to be present in the execution scope of the expression `scr`. Credit to [this answer](https://stackoverflow.com/a/543820/1972493) to a similar question
This evaluates expressions in a given context without the need to prefix vars with 'this'. Has caveats but works fine. Can also incorporate custom functions in the expression. Just call an 'evaluate' function, passing in your expression, context and an optional function. The context must be a flat structure (no nested elements) and the function must be referred to as 'fn' inside the string expression. Answer prints 11 in this case: ```js var expression = "fn((a+b)*c,2)"; var context = { a: 1, b: 2, c: 3 }; var func = function(x,y){return x+y;}; function evaluate(ex, ctx, fn) { return eval("var "+JSON.stringify(ctx).replace(/["{}]/gi, "").replace(/:/gi, "=")+", fn="+fn.toString()+";"+ex); } var answer = evaluate(expression, context, func); console.log(answer); ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
whilst I recommend the answer provided by @trincot and in particular the great link. I am posting here my solution to the problem I faced ``` function evalInContext(scr, context) { // execute script in private context return (new Function( "with(this) { return " + scr + "}")).call(context); } ``` The `with(this)` expression allows the member variables of the `context` object to be present in the execution scope of the expression `scr`. Credit to [this answer](https://stackoverflow.com/a/543820/1972493) to a similar question
cannot comment so i post, Joe's answer is great but if the string holds multiple statements (like `x++; y++; x+y;`) the `y++` part would never be executed because it returns at first statement. with this modification all statements will be executed and the last statement will be the return value. > > > ``` > function evalInScopeAndContext(scr, scopeAndContext) > { > // execute script in private context > return (new Function( "with(this) { return eval('" + scr + "'); }")).call(scopeAndContext); > } > > ``` > > i also changed the parameter name because that parameter is used both as scope and context, and they are different things. Warning 1: When using this function `this.x` will equal to `x` and cannot be changed, because the `this` property of the scope will be shadowed if present. if you execute `evalInScopeAndContext('this', {a:1, b:2, this:3})` the answer will be `{a:1, b:2, this:3}` instead of `3`. To access the property `this`, you have to write `this.this` instead, i don't think it can be fixed. Warning 2: Outer scope (From the caller of this function up to `window`) can be accessed and modified unless shadowed by the scope object. So if you plan to execute something like `location = 'house';` but forget to insert the `location` key inside the scope object, you will execute `window.location = 'house'` and might cause damage. Instead `this.location = 'house';` is always safe because `this` always exists and will just add the `location` key to the scope object provided, so you might want to always use `this.` as a prefix
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
This is an alternative method (written in ES6): ``` (new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context)); ``` Credits to Jonas Wilms for the answer. Here is my explanation, since I did not initially understand how it worked: ``` let example = new Function('a', 'b', 'return a+ b') ``` is the same as creating the function and assigning it to `example`: ``` function(a,b) { return a + b } ``` After that, you can call `example` like this: `example(2,6)` which returns 8. But let's say you don't want to assign the function created by `new Function` to a variable and you want to immediately call it instead. Then you can just do this: ``` new Function('a', 'b', 'return a+ b')(2,6) ``` The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the `context` object like this: `new Function(key1, key2, key3... lastkey, codeYouWantToExecute)`. It then calls the newly created function and passes the values that correspond to each key with the spread operator. Lastly, here is the answer compiled to ES5: ``` (new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context)); ```
This evaluates expressions in a given context without the need to prefix vars with 'this'. Has caveats but works fine. Can also incorporate custom functions in the expression. Just call an 'evaluate' function, passing in your expression, context and an optional function. The context must be a flat structure (no nested elements) and the function must be referred to as 'fn' inside the string expression. Answer prints 11 in this case: ```js var expression = "fn((a+b)*c,2)"; var context = { a: 1, b: 2, c: 3 }; var func = function(x,y){return x+y;}; function evaluate(ex, ctx, fn) { return eval("var "+JSON.stringify(ctx).replace(/["{}]/gi, "").replace(/:/gi, "=")+", fn="+fn.toString()+";"+ex); } var answer = evaluate(expression, context, func); console.log(answer); ```
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
This is an alternative method (written in ES6): ``` (new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context)); ``` Credits to Jonas Wilms for the answer. Here is my explanation, since I did not initially understand how it worked: ``` let example = new Function('a', 'b', 'return a+ b') ``` is the same as creating the function and assigning it to `example`: ``` function(a,b) { return a + b } ``` After that, you can call `example` like this: `example(2,6)` which returns 8. But let's say you don't want to assign the function created by `new Function` to a variable and you want to immediately call it instead. Then you can just do this: ``` new Function('a', 'b', 'return a+ b')(2,6) ``` The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the `context` object like this: `new Function(key1, key2, key3... lastkey, codeYouWantToExecute)`. It then calls the newly created function and passes the values that correspond to each key with the spread operator. Lastly, here is the answer compiled to ES5: ``` (new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context)); ```
cannot comment so i post, Joe's answer is great but if the string holds multiple statements (like `x++; y++; x+y;`) the `y++` part would never be executed because it returns at first statement. with this modification all statements will be executed and the last statement will be the return value. > > > ``` > function evalInScopeAndContext(scr, scopeAndContext) > { > // execute script in private context > return (new Function( "with(this) { return eval('" + scr + "'); }")).call(scopeAndContext); > } > > ``` > > i also changed the parameter name because that parameter is used both as scope and context, and they are different things. Warning 1: When using this function `this.x` will equal to `x` and cannot be changed, because the `this` property of the scope will be shadowed if present. if you execute `evalInScopeAndContext('this', {a:1, b:2, this:3})` the answer will be `{a:1, b:2, this:3}` instead of `3`. To access the property `this`, you have to write `this.this` instead, i don't think it can be fixed. Warning 2: Outer scope (From the caller of this function up to `window`) can be accessed and modified unless shadowed by the scope object. So if you plan to execute something like `location = 'house';` but forget to insert the `location` key inside the scope object, you will execute `window.location = 'house'` and might cause damage. Instead `this.location = 'house';` is always safe because `this` always exists and will just add the `location` key to the scope object provided, so you might want to always use `this.` as a prefix
40,107,919
I am trying to execute eval within a particular context. I have found the answer [here](https://stackoverflow.com/a/25859853/1972493) useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following: ``` function evalInContext(js, context) { return function() { return eval(js); }.call(context); } console.log(evalInContext('x==3', { x : 3})) // Throws console.log(evalInContext('this.x==3', { x : 3})) // OK ``` However I expected the first call to `evalInContext` not to throw. Any ideas why this might be happening?
2016/10/18
[ "https://Stackoverflow.com/questions/40107919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972493/" ]
This evaluates expressions in a given context without the need to prefix vars with 'this'. Has caveats but works fine. Can also incorporate custom functions in the expression. Just call an 'evaluate' function, passing in your expression, context and an optional function. The context must be a flat structure (no nested elements) and the function must be referred to as 'fn' inside the string expression. Answer prints 11 in this case: ```js var expression = "fn((a+b)*c,2)"; var context = { a: 1, b: 2, c: 3 }; var func = function(x,y){return x+y;}; function evaluate(ex, ctx, fn) { return eval("var "+JSON.stringify(ctx).replace(/["{}]/gi, "").replace(/:/gi, "=")+", fn="+fn.toString()+";"+ex); } var answer = evaluate(expression, context, func); console.log(answer); ```
cannot comment so i post, Joe's answer is great but if the string holds multiple statements (like `x++; y++; x+y;`) the `y++` part would never be executed because it returns at first statement. with this modification all statements will be executed and the last statement will be the return value. > > > ``` > function evalInScopeAndContext(scr, scopeAndContext) > { > // execute script in private context > return (new Function( "with(this) { return eval('" + scr + "'); }")).call(scopeAndContext); > } > > ``` > > i also changed the parameter name because that parameter is used both as scope and context, and they are different things. Warning 1: When using this function `this.x` will equal to `x` and cannot be changed, because the `this` property of the scope will be shadowed if present. if you execute `evalInScopeAndContext('this', {a:1, b:2, this:3})` the answer will be `{a:1, b:2, this:3}` instead of `3`. To access the property `this`, you have to write `this.this` instead, i don't think it can be fixed. Warning 2: Outer scope (From the caller of this function up to `window`) can be accessed and modified unless shadowed by the scope object. So if you plan to execute something like `location = 'house';` but forget to insert the `location` key inside the scope object, you will execute `window.location = 'house'` and might cause damage. Instead `this.location = 'house';` is always safe because `this` always exists and will just add the `location` key to the scope object provided, so you might want to always use `this.` as a prefix
45,033,943
I am trying to compile the following code (simplified from actual use) using g++: ``` namespace A { class B; } A::B operator+(A::B a, A::B b); namespace A { class B { private: int i; public: B() : i(0) {} B(int j) : i(j) {} friend B ::operator+(B a, B b); }; } A::B operator+(A::B a, A::B b) { return A::B(a.i + b.i); } int main() { A::B a(1), b(2); A::B c = a+b; return 0; } ``` To the best of my understanding, the friend declaration in class B is correct, and the :: global scope declaration is needed otherwise the compiler assumes that A::operator+(B a, B b) is meant. However, on compiling this, gcc gives the error message ``` ISO C++ forbids declaration of ‘operator+’ with no type ``` I have no idea how to fix this. The error messages after it give the impression that gcc is ignoring the space between B and :: in that line, instead interpreting this as a friend declaration of a member function of B. How can I tell it what I want?
2017/07/11
[ "https://Stackoverflow.com/questions/45033943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148502/" ]
Based on my understanding, you are talking about Azure SQL database. I assumed that you could [Export your Azure SQL database to a BACPAC file](https://learn.microsoft.com/en-us/azure/sql-database/sql-database-export). > > I try to do an export of an Azure DB, but I can't find how to do that in C#. > > > According to your description, I checked [Microsoft Azure Management Libraries](https://www.nuget.org/packages/Microsoft.WindowsAzure.Management.Libraries/) and found you could refer to the following code snippet for exporting your azure sql database into the azure blob storage: ``` CertificateCloudCredentials credential = new CertificateCloudCredentials("{subscriptionId}","{managementCertificate}"); var sqlManagement = new SqlManagementClient(credential); var result = sqlManagement.Dac.Export("{serverName}", new DacExportParameters() { BlobCredentials = new DacExportParameters.BlobCredentialsParameter() { StorageAccessKey = "{storage-account-accesskey}", Uri = new Uri("https://{storage-accountname}.blob.core.windows.net/{container-name}") }, ConnectionInfo = new DacExportParameters.ConnectionInfoParameter() { DatabaseName = "{dbname}", ServerName = "{serverName}.database.windows.net", UserName = "{username}", Password = "{password}" } }); ``` And you could use `sqlManagement.Dac.GetStatus` for retrieving the status of the export operation. Additionally, the Microsoft Azure Management Libraries uses [Export Database (classic)](https://msdn.microsoft.com/en-us/library/azure/dn781282.aspx), for newer resource manager based REST API, you could refer to [here](https://learn.microsoft.com/en-us/rest/api/sql/databases%20-%20import%20export#Databases_Export). Moreover, you could refer to [create a storage account](https://learn.microsoft.com/en-us/azure/storage/storage-create-storage-account#create-a-storage-account) and leverage [Microsoft Azure Storage Explorer](http://storageexplorer.com/) for a simple way to manage your storage resources, for more details, you could refer to [here](https://learn.microsoft.com/en-us/azure/vs-azure-tools-storage-explorer-blobs).
I've found the solution of my problem: I had to update my Microsoft.Azure.Management.Sql library. Now, I can use this export method: > > public static ImportExportResponse Export(this IDatabasesOperations > operations, string resourceGroupName, string serverName, string > databaseName, ExportRequest parameters); > > >
13,389,583
I have UIDatePicker and I want to draw time in UIDatePicker for example in gray color I need this, if in my graphic is draw some interval, so in datePicker user can't select this time ![enter image description here](https://i.stack.imgur.com/5LDwF.png)
2012/11/15
[ "https://Stackoverflow.com/questions/13389583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304878/" ]
You can enclose your strings with `NULLIF()` You use it like this: ``` NULLIF('test','') --> returns 'test' NULLIF('' ,'') --> returns NULL ```
Alternatively to NULLIF you could set the default to NULL and just not pass empty fields along.
70,800,272
I have a flutter app and its working fine in debug mode but when i run flutter build apk command for android apk it shows the following error. The error is cannot run with sound null safety. **Error:** ``` C:\Users\RAILO\flutter\bin\flutter.bat --no-color build apk Building with sound null safety Running Gradle task 'assembleRelease'... Error: Cannot run with sound null safety, because the following dependencies don't support null safety: - package:flutter_swiper - package:flutter_page_indicator - package:transformer_page_view For solutions, see https://dart.dev/go/unsound-null-safety FAILURE: Build failed with an exception. ```
2022/01/21
[ "https://Stackoverflow.com/questions/70800272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12752433/" ]
You can use `Series.str.get` to extract values from an `object` column with dictionaries in it. ``` df['idx'] = df['a'].str.get('word') indices = df['idx'].to_list() ```
Another option is to convert the column to a list, cast it to a DataFrame constructor. This creates a DataFrame where the columns correspond to dictionary keys and values correspond to dict values. Then simply select the relevant column/key and convert the values to list: ``` idx = pd.DataFrame(df['a'].tolist())['word'].tolist() ``` Output: ``` ['3', '1', '0'] ```
70,800,272
I have a flutter app and its working fine in debug mode but when i run flutter build apk command for android apk it shows the following error. The error is cannot run with sound null safety. **Error:** ``` C:\Users\RAILO\flutter\bin\flutter.bat --no-color build apk Building with sound null safety Running Gradle task 'assembleRelease'... Error: Cannot run with sound null safety, because the following dependencies don't support null safety: - package:flutter_swiper - package:flutter_page_indicator - package:transformer_page_view For solutions, see https://dart.dev/go/unsound-null-safety FAILURE: Build failed with an exception. ```
2022/01/21
[ "https://Stackoverflow.com/questions/70800272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12752433/" ]
You can use `Series.str.get` to extract values from an `object` column with dictionaries in it. ``` df['idx'] = df['a'].str.get('word') indices = df['idx'].to_list() ```
**Hi, you could just use a join**: ``` listElement = [''.join(i[1].values()) for i in df['a'].items()] ``` **Output:** ``` ['3', '1', '0'] ```
70,800,272
I have a flutter app and its working fine in debug mode but when i run flutter build apk command for android apk it shows the following error. The error is cannot run with sound null safety. **Error:** ``` C:\Users\RAILO\flutter\bin\flutter.bat --no-color build apk Building with sound null safety Running Gradle task 'assembleRelease'... Error: Cannot run with sound null safety, because the following dependencies don't support null safety: - package:flutter_swiper - package:flutter_page_indicator - package:transformer_page_view For solutions, see https://dart.dev/go/unsound-null-safety FAILURE: Build failed with an exception. ```
2022/01/21
[ "https://Stackoverflow.com/questions/70800272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12752433/" ]
Another option is to convert the column to a list, cast it to a DataFrame constructor. This creates a DataFrame where the columns correspond to dictionary keys and values correspond to dict values. Then simply select the relevant column/key and convert the values to list: ``` idx = pd.DataFrame(df['a'].tolist())['word'].tolist() ``` Output: ``` ['3', '1', '0'] ```
**Hi, you could just use a join**: ``` listElement = [''.join(i[1].values()) for i in df['a'].items()] ``` **Output:** ``` ['3', '1', '0'] ```
8,383,680
have a problem with object setters in a class. I have the class GEOImage, where things like description, title etc. will be saved according to an image. ``` @interface GEOImage : UIImage { NSString *title; NSString *imgDescription; NSString *latitude; NSString *longitude; NSDictionary *editInfo; } @property (nonatomic, copy) NSString *title, *imgDescription, *latitude, *longitude; @property (nonatomic, copy) NSDictionary *editInfo; @end ``` Now i try to store a description out of another class: ``` self.chosenImage.imgDescription = @"description"; ``` where chosenImage is of type GEOImage. But i get the error: > > -[UIImage setTitle:]: unrecognized selector sent to instance 0x939d220 > 2011-12-05 10:59:40.621 GeoPG[511:17c03] *\** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage setTitle:]: unrecognized selector sent to instance 0x939d220' > > > If I'm looking in the debugger, the chosenImage is not NULL, and its been displayed correct in an image view. Greets s4lfish
2011/12/05
[ "https://Stackoverflow.com/questions/8383680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1055851/" ]
We can safely infer that `chosenImage` is not `nil`; if it were `nil`, sending it a message would simply do nothing, not crash. (Also, I'm assuming that you meant `title` rather than `imgDescription` in your usage sample, or that you implemented `setImgDescription:` to set the `title` in turn.) There are two possibilities: ### Dead object You created the image you stored to `chosenImage` as a GEOImage, but then it died while you were holding on to it. Subsequently, a UIImage (as identified in the exception message) was created at the same address, so the pointer you still hold now points to a UIImage. You sent a message to it that only works on GEOImages, but it's only a UIImage, so it doesn't respond to the message, which is the exception. The cause of an object dying while you're holding it is that either you didn't retain it somewhere where you should have, or you released it somewhere where you shouldn't have. Or possibly both. Run your app under Instruments with the Zombies template. It will raise a flag when you hit this crash, and you can then investigate by clicking the button in that flag. Look at all of the Release and Autorelease events, starting from the end, to find the one that shouldn't be there; then, if the release itself is unwarranted, take it out, or if it should be balanced by a previous retain, put one of those in. One possible cause of the crash is that you declared the `chosenImage` property as `assign`, but you should have declared it as `retain`/`strong`. If this is the problem, your Instruments findings will support it. Long-term, you should convert to ARC, which eliminates 90% of the cases where this problem could happen. ### You never created a GEOImage in the first place Just because you declared that `chosenImage` will hold a pointer to a GEOImage doesn't mean it does. You can assign any object pointer there, and in many cases, the compiler doesn't know if it isn't actually a GEOImage. (They introduced a feature called “related result types” in a future version of Clang that should make this much less likely.) At a guess, I'd say you're doing something like this: ``` self.chosenImage = [GEOImage imageNamed:@"blah blah blah"]; ``` or this: ``` self.chosenImage = [imagePicker takePicture]; ``` There is no reason to expect `takePicture` to return a GEOImage (how should it know that's what you want?), and it's likely that `+[UIImage imageNamed:]` (assuming you simply inherit it) won't, either. Unless you create a GEOImage instance yourself, using `alloc` and an initializer, you cannot assume that any UIImage you get will be a GEOImage. The solution is to make it easy to create a GEOImage from a UIImage (which will involve wrapping [this method](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html#//apple_ref/occ/instm/UIImage/initWithCGImage%3ascale%3aorientation%3a)), and then do that. --- Once you have a live (not dead) GEOImage (not UIImage) in your `chosenImage` property, it will work.
In fact, it was like Peter said: I never created an GEOImage. I now I create the GEOImage like this: ``` - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info valueForKey:@"UIImagePickerControllerOriginalImage"]; NSURL *imgURL = [info valueForKey:@"UIImagePickerControllerMediaURL"]; CGImageRef imageRef = [image CGImage]; [self createGEOImage:imageRef info:info imageURL:imgURL]; } ``` And the method called with the imageRef: ``` - (void)createGEOImage:(CGImageRef*)imageRef info:(NSDictionary*)info imageURL:(NSURL*)imgURL{ GEOImage *geoImage = [[GEOImage alloc]initWithCGImage:imageRef]; geoImage = info; geoImage = imgURL; } ``` Thanks for your help!
41,676,391
I am writing a web server, in which I recieve the data from a client through a `WinSock` socket, and parse the data into parts. Then, according to the method found and the resource requested, I want to build a new packet which I will send back to the client. I have this function, used to build the packet to send nack to client: (`BUFFER_SIZE=2048`) ``` char* build_packet(char *ver, char *code, char *content, long length, long *p_length) { char *packet = (char *)malloc(BUFFER_SIZE); char *len_str = malloc(BUFF_64); _itoa(length, len_str, 10); char *content_len = "Content-length: "; char *content_type = "Content-Type: "; long len = strlen(ver) + 1; len += strlen(code) + strlen(HTTP_DELIM); len += strlen(content_len) + strlen(len_str) + strlen(HTTP_DELIM); len += strlen(content_type) + strlen(HTTP_HTML_TYPE_TEXT) +strlen(HTTP_DELIM); len += strlen(content); *p_length = len; // This is where problems start... // ############################################################## strncat(ver, packet, BUFFER_SIZE - 1); // Trouble starts here strncat(" ", packet, BUFFER_SIZE - 1); strncat(code, packet, BUFFER_SIZE - 1); strncat(HTTP_DELIM, packet, BUFFER_SIZE - 1); strncat(content_len, packet, BUFFER_SIZE - 1); strncat(len_str, packet, BUFFER_SIZE - 1); strncat(HTTP_DELIM, packet, BUFFER_SIZE - 1); strncat(content_type, packet, BUFFER_SIZE - 1); strncat(HTTP_HTML_TYPE_TEXT, packet, BUFFER_SIZE - 1); strncat(HTTP_DELIM, packet, BUFFER_SIZE - 1); strncat(content, packet, BUFFER_SIZE - 1); return packet; } ``` (Of course I should (and I will) add validation to the strncat so that it will eventually send all data) **My question is:** why is the first `strncat` call not working and raises a Access Violation error? What am I doing wrong?
2017/01/16
[ "https://Stackoverflow.com/questions/41676391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6451874/" ]
Not such a good idea, but you can use jquery to select the radio by the value of the `value` attribute and disable the relevant radio (using the `prop` method): ```js $('input[type="radio"][value=" Afternoon (1 PM - 5 PM)"]').prop('disabled', true); $('input[type="radio"][value=" Evening (5 PM - 9 PM)"]').prop('disabled', true); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="fieldset"> <div class="radio"> <label > <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value="Morning (8 AM - 1 PM)"> <span class="disable">Morning (8 AM - 1 PM)</span> </label> </div> <div class="radio"> <label> <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value=" Afternoon (1 PM - 5 PM)" aria-invalid="false"> <span> Afternoon (1 PM - 5 PM)</span> </label> </div> <div class="radio"> <label> <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value=" Evening (5 PM - 9 PM)"> <span> Evening (5 PM - 9 PM)</span> </label> </div> </div> ```
```js $(document).ready(function(){ var testString="Afternoon (1 PM - 5 PM)";//show only this text control and hide other control $.each($('input[type=radio]'),function(i,v){ if($.trim($(v).val())!=testString)// any condtion you can put here { $(v).addClass("disable").next().addClass("disable"); } }); }); ``` ```css .disable { display : none; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="fieldset"> <div class="radio"> <label > <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value="Morning (8 AM - 1 PM)"> <span class="">Morning (8 AM - 1 PM)</span> </label> </div> <div class="radio"> <label> <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value=" Afternoon (1 PM - 5 PM)" aria-invalid="false"> <span> Afternoon (1 PM - 5 PM)</span> </label> </div> <div class="radio"> <label> <input id="wffmd4800a78bba44322993e9ef2a91e0ea0_Sections_9__Fields_3__Value" name="wffmd4800a78bba44322993e9ef2a91e0ea0.Sections[9].Fields[3].Value" type="radio" value=" Evening (5 PM - 9 PM)"> <span> Evening (5 PM - 9 PM)</span> </label> </div> </div> </div> ```
20,113,895
In my Android app I add `SearchBar` in headerview of `TableView`. Problem is that when I scroll my `TableView` to load more data then my `SearchBar` automatically focus and table scroll to top. I want to stop this auto focus. How do I do that?
2013/11/21
[ "https://Stackoverflow.com/questions/20113895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2621383/" ]
You can use your queries as derived tables and join on `ShowDate`. ``` SELECT T1.TotalShows, T1.ScreenCapacity, T1.ShowDate, T2.TotalTicketsSold, T2.Nett FROM ( SELECT COUNT(showtimeId) AS TotalShows, sum(sc.Capacity) AS ScreenCapacity, ShowDate ------For all screens FROM Shows s JOIN Screens sc ON sc.ScreenID = s.ScreenID WHERE s.ShowDate < @dateNew -- someDate AND s.MovieID = 34 AND s.IsDeleted = 0 GROUP BY ShowDate ) AS T1 INNER JOIN ( SELECT s.ShowDate, COUNT(ut.UserTicketID) AS TotalTicketsSold, SUM(ISNULL((Price+ConvinienceCharge-DiscountAmount)/(EntertainmentTax+BoxOfficeTax+1), 0)) AS Nett FROM Shows s LEFT OUTER JOIN UserTickets ut ON s.ShowID = ut.ShowID WHERE ut.ShowID IN ( SELECT ShowID FROM Shows WHERE ShowDate < @dateNew -- someDate AND MovieID = 34 AND IsDeleted = 0 GROUP BY ShowID ) GROUP BY s.ShowDate ) AS T2 ON T1.ShowDate = T2.ShowDate ```
Mybe this will work ? ``` SELECT COUNT(showtimeId) AS TotalShows, SUM(sc.Capacity) AS ScreenCapacity, ShowDate ------For all screens, ,COUNT(ut.UserTicketID) AS TotalTicketsSold, SUM(ISNULL((Price+ConvinienceCharge-DiscountAmount)/ (EntertainmentTax+BoxOfficeTax+1), 0)) AS Nett FROM Shows s JOIN Screens sc ON sc.ScreenID = s.ScreenID LEFT OUTER JOIN UserTickets ut ON s.ShowID = ut.ShowID WHERE s.ShowDate < @dateNew -- someDate AND s.MovieID = 34 AND s.IsDeleted = 0 GROUP BY ShowDate ```
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
The answer to "How do we feel temperature" is "you define temperature in a way that is different from how physicists define it." [This video](https://www.youtube.com/watch?v=vqDbMEdLiCs) does an excellent job of showing the issue off. In science, temperature is defined to be a measure of the energy of highly disorganized motion of atoms in a material. In everything around you there is motion of this sort -- quite a lot of it in fact. You can't see it because its all disorganized. If one molecule in the key of your keyboard is vibrating towards you, its highly likely that the molecule next to it is vibrating away, so you don't notice the motion. However, everything is moving in this way. We observe that if you put two objects together, they can transfer energy in this way. This transfer of thermal energy from a "hot" object to a "cold" object is called "heat" (another word which has a very specific meaning to physicists which is more picky than our day-to-day-usage). Two objects are defined to be of the same temperature if, when you put them together, no thermal energy transfers from one to the other. If we want to look at how fast that heat transfer occurs, we need to look at more than just the temperature of the object. Temperature does play the expected part (large temperature differences mean you transfer more heat!), but the material properties also matter. Metals, for instance, are very good conductors of heat. If you have a warm piece of metal and you touch it, it transfers heat very quicky. On the other hand, if you have an insulator of heat (such as a down jacket), it will transfer that heat slower. Rest assured, though, by the laws of thermodynamics, both materials will *eventually* reach the same temperature as their surroundings, but the metals will do it faster. We do actually measure temperatures, and rates of change in tmperature, but we measure them within our skin, and those temperatures measured are not just a simple measurement of the object, but are a complex balance between our body's internal temperature and the object. For example, typically the body's core is 98.6F, but the skin is typically closer to 91F. Why? It's because we're constantly emitting heat into the air (which is colder). If we touch a piece of metal at the same temperature as the air, however, we feel as though it is "colder." Why? Because the metal can pull heat away from the body faster than the air, so the skin temperature will be lower than it was in the air. The metal will feel colder, even though it, in fact, has the same temperature as the air! Because of this dynamic effect, it's typically more precise to say that we sense heat transfer to/from an object more than we sense its actual temperature. The sensations you and I grew up to think of as "hot" and "cold" are really more "fast influx of heat" and "fast outflow of heat." As for how we actually sense that temperature, that is a question for Biology.SE. However, there's a few pieces worth mentioning: * We have proteins that deform slightly at a given temperature. These are used to tell us if an object is hot or cold (and by that I mean tell us that the skin has been made hotter or colder). TrpV1, for instance, deforms to let ions pass through it at 43C/109F. Capsaicin, the active ingredient in spicy food and pepper spray, also deforms TrpV1, which is why you feel like your mouth is burning. * Our brains are *amazing* signal processors, so its easy to get the illusion that they are measuring something they aren't. For example, the sensation of burning is currently believed to come from measuring heat-transfer by watching the signals from the different layers of skin and effectively calculating a heat flux from that. This is why you still feel burning after your fingers have left the hot object. * Our slowest moving temperature sensors are used in homeostasis. There, we contrast reactions which move at different speeds at different temperatures to figure out what our actual temperature is.
We are able to measure temperature because of the differences a temperature has upon the resultant bodies it affects. The temperature a body has is dependent upon its molecular structure and the vibration of its molecular construction. and and it is measurable, because of this difference between the two we are calculate its relative temperature or energy between the two . But hopefully in more natural arrangements it results in fewer calculations
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
The answer to "How do we feel temperature" is "you define temperature in a way that is different from how physicists define it." [This video](https://www.youtube.com/watch?v=vqDbMEdLiCs) does an excellent job of showing the issue off. In science, temperature is defined to be a measure of the energy of highly disorganized motion of atoms in a material. In everything around you there is motion of this sort -- quite a lot of it in fact. You can't see it because its all disorganized. If one molecule in the key of your keyboard is vibrating towards you, its highly likely that the molecule next to it is vibrating away, so you don't notice the motion. However, everything is moving in this way. We observe that if you put two objects together, they can transfer energy in this way. This transfer of thermal energy from a "hot" object to a "cold" object is called "heat" (another word which has a very specific meaning to physicists which is more picky than our day-to-day-usage). Two objects are defined to be of the same temperature if, when you put them together, no thermal energy transfers from one to the other. If we want to look at how fast that heat transfer occurs, we need to look at more than just the temperature of the object. Temperature does play the expected part (large temperature differences mean you transfer more heat!), but the material properties also matter. Metals, for instance, are very good conductors of heat. If you have a warm piece of metal and you touch it, it transfers heat very quicky. On the other hand, if you have an insulator of heat (such as a down jacket), it will transfer that heat slower. Rest assured, though, by the laws of thermodynamics, both materials will *eventually* reach the same temperature as their surroundings, but the metals will do it faster. We do actually measure temperatures, and rates of change in tmperature, but we measure them within our skin, and those temperatures measured are not just a simple measurement of the object, but are a complex balance between our body's internal temperature and the object. For example, typically the body's core is 98.6F, but the skin is typically closer to 91F. Why? It's because we're constantly emitting heat into the air (which is colder). If we touch a piece of metal at the same temperature as the air, however, we feel as though it is "colder." Why? Because the metal can pull heat away from the body faster than the air, so the skin temperature will be lower than it was in the air. The metal will feel colder, even though it, in fact, has the same temperature as the air! Because of this dynamic effect, it's typically more precise to say that we sense heat transfer to/from an object more than we sense its actual temperature. The sensations you and I grew up to think of as "hot" and "cold" are really more "fast influx of heat" and "fast outflow of heat." As for how we actually sense that temperature, that is a question for Biology.SE. However, there's a few pieces worth mentioning: * We have proteins that deform slightly at a given temperature. These are used to tell us if an object is hot or cold (and by that I mean tell us that the skin has been made hotter or colder). TrpV1, for instance, deforms to let ions pass through it at 43C/109F. Capsaicin, the active ingredient in spicy food and pepper spray, also deforms TrpV1, which is why you feel like your mouth is burning. * Our brains are *amazing* signal processors, so its easy to get the illusion that they are measuring something they aren't. For example, the sensation of burning is currently believed to come from measuring heat-transfer by watching the signals from the different layers of skin and effectively calculating a heat flux from that. This is why you still feel burning after your fingers have left the hot object. * Our slowest moving temperature sensors are used in homeostasis. There, we contrast reactions which move at different speeds at different temperatures to figure out what our actual temperature is.
In a few words, temperature is a macroscopic property related to the kinetic energy of molecules. What it **really is**, is a tricky question, because we don't know what **mass** is or what **force** is, but we know how to measure and relate each other and how to intuitively understand. Based on that, we can infer some key properties about temperature. First of all, it is important to understand the difference between **heat** and **temperature**. Heat is energy, and when we are dealing with thermal systems, heat depends on the amount of mass that contains that energy. We call that an extensive property. ([more about that](https://en.wikipedia.org/wiki/Intensive_and_extensive_properties)). You would imagine that heating a house would take a lot more energy than to heat a can of water, for example. Temperature, on the other side, is an intensive property, i.e. it does not depends on the size of things. A 30ºC house wouldn't be hotter than a 30ºC water in a can. So, temperature is kind of an index, it is a metrics associated with each point in space. Heat transfer is related to heat flux. And heat flux as the name says, measures how much **heat** is flowing from one place to another. When we are dealing with steady-state systems (<https://en.wikipedia.org/wiki/Steady_state>), we can assume that: $$\Delta T=\dot{Q}\frac{L}{kA}$$ Explaining this equation: If we have a wall with two sides, the difference of temperature $\Delta T$ between the two sides will be proportional to how much of heat is coming in and out ($\dot{Q}$) and to the thickness of the wall ($L$) and inversely proportional to the conductivity ($k$) and area of the wall($A$). We often think the term $\frac{L}{kA}$ as *thermal resistance* as it is analogous to the equation in electricity: $$V=RI$$ If you are familiar, $V$ is the difference of potential (analogous to $\Delta T$), $I$ is the current (analogous to how much comes in and out, $\dot{Q}$) and $R$ would be the resistance, as I pointed. As in electricity, $V$ is a point property (it depends on two points) and $I$ is the flow of electrons. These points were just to make clear the distinction between these properties. But then, what is really temperature all about? Well, temperature is an useful measure to know thermal characteristics of a system. * We know that the dilation is proportional to temperature. Based on that, we have built thermometers, which use the principle of dilation. * We know that two bodies in contact with each other will empirically have the same temperature at infinite time. * We understand that thermal equilibrium, i.e. when two bodies exchange no energy, occurs when the temperature of both are the same. * In the perfect gas model, empirically discovered, we know that $PV=mRT$, i.e. four measurable properties (pressure, volume, mass and temperature) have a relation within a range of values.
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
The answer to "How do we feel temperature" is "you define temperature in a way that is different from how physicists define it." [This video](https://www.youtube.com/watch?v=vqDbMEdLiCs) does an excellent job of showing the issue off. In science, temperature is defined to be a measure of the energy of highly disorganized motion of atoms in a material. In everything around you there is motion of this sort -- quite a lot of it in fact. You can't see it because its all disorganized. If one molecule in the key of your keyboard is vibrating towards you, its highly likely that the molecule next to it is vibrating away, so you don't notice the motion. However, everything is moving in this way. We observe that if you put two objects together, they can transfer energy in this way. This transfer of thermal energy from a "hot" object to a "cold" object is called "heat" (another word which has a very specific meaning to physicists which is more picky than our day-to-day-usage). Two objects are defined to be of the same temperature if, when you put them together, no thermal energy transfers from one to the other. If we want to look at how fast that heat transfer occurs, we need to look at more than just the temperature of the object. Temperature does play the expected part (large temperature differences mean you transfer more heat!), but the material properties also matter. Metals, for instance, are very good conductors of heat. If you have a warm piece of metal and you touch it, it transfers heat very quicky. On the other hand, if you have an insulator of heat (such as a down jacket), it will transfer that heat slower. Rest assured, though, by the laws of thermodynamics, both materials will *eventually* reach the same temperature as their surroundings, but the metals will do it faster. We do actually measure temperatures, and rates of change in tmperature, but we measure them within our skin, and those temperatures measured are not just a simple measurement of the object, but are a complex balance between our body's internal temperature and the object. For example, typically the body's core is 98.6F, but the skin is typically closer to 91F. Why? It's because we're constantly emitting heat into the air (which is colder). If we touch a piece of metal at the same temperature as the air, however, we feel as though it is "colder." Why? Because the metal can pull heat away from the body faster than the air, so the skin temperature will be lower than it was in the air. The metal will feel colder, even though it, in fact, has the same temperature as the air! Because of this dynamic effect, it's typically more precise to say that we sense heat transfer to/from an object more than we sense its actual temperature. The sensations you and I grew up to think of as "hot" and "cold" are really more "fast influx of heat" and "fast outflow of heat." As for how we actually sense that temperature, that is a question for Biology.SE. However, there's a few pieces worth mentioning: * We have proteins that deform slightly at a given temperature. These are used to tell us if an object is hot or cold (and by that I mean tell us that the skin has been made hotter or colder). TrpV1, for instance, deforms to let ions pass through it at 43C/109F. Capsaicin, the active ingredient in spicy food and pepper spray, also deforms TrpV1, which is why you feel like your mouth is burning. * Our brains are *amazing* signal processors, so its easy to get the illusion that they are measuring something they aren't. For example, the sensation of burning is currently believed to come from measuring heat-transfer by watching the signals from the different layers of skin and effectively calculating a heat flux from that. This is why you still feel burning after your fingers have left the hot object. * Our slowest moving temperature sensors are used in homeostasis. There, we contrast reactions which move at different speeds at different temperatures to figure out what our actual temperature is.
In short: * **Temperature** is a measure of thermal energy. * **Heat** (and **heat transfer**) is the *transfer* of thermal energy. **Heat** is like **work**; work is energy and heat is energy, yes, but you cannot "have" work. You can *do* work. In the same way you can't "have" heat. Work is more correctly a *transfer* of energy (kinetic, potential...), just like heat is a transfer of energy (thermal). *What thermal energy is, is a different question, which the other answers take good care of.*
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
In a few words, temperature is a macroscopic property related to the kinetic energy of molecules. What it **really is**, is a tricky question, because we don't know what **mass** is or what **force** is, but we know how to measure and relate each other and how to intuitively understand. Based on that, we can infer some key properties about temperature. First of all, it is important to understand the difference between **heat** and **temperature**. Heat is energy, and when we are dealing with thermal systems, heat depends on the amount of mass that contains that energy. We call that an extensive property. ([more about that](https://en.wikipedia.org/wiki/Intensive_and_extensive_properties)). You would imagine that heating a house would take a lot more energy than to heat a can of water, for example. Temperature, on the other side, is an intensive property, i.e. it does not depends on the size of things. A 30ºC house wouldn't be hotter than a 30ºC water in a can. So, temperature is kind of an index, it is a metrics associated with each point in space. Heat transfer is related to heat flux. And heat flux as the name says, measures how much **heat** is flowing from one place to another. When we are dealing with steady-state systems (<https://en.wikipedia.org/wiki/Steady_state>), we can assume that: $$\Delta T=\dot{Q}\frac{L}{kA}$$ Explaining this equation: If we have a wall with two sides, the difference of temperature $\Delta T$ between the two sides will be proportional to how much of heat is coming in and out ($\dot{Q}$) and to the thickness of the wall ($L$) and inversely proportional to the conductivity ($k$) and area of the wall($A$). We often think the term $\frac{L}{kA}$ as *thermal resistance* as it is analogous to the equation in electricity: $$V=RI$$ If you are familiar, $V$ is the difference of potential (analogous to $\Delta T$), $I$ is the current (analogous to how much comes in and out, $\dot{Q}$) and $R$ would be the resistance, as I pointed. As in electricity, $V$ is a point property (it depends on two points) and $I$ is the flow of electrons. These points were just to make clear the distinction between these properties. But then, what is really temperature all about? Well, temperature is an useful measure to know thermal characteristics of a system. * We know that the dilation is proportional to temperature. Based on that, we have built thermometers, which use the principle of dilation. * We know that two bodies in contact with each other will empirically have the same temperature at infinite time. * We understand that thermal equilibrium, i.e. when two bodies exchange no energy, occurs when the temperature of both are the same. * In the perfect gas model, empirically discovered, we know that $PV=mRT$, i.e. four measurable properties (pressure, volume, mass and temperature) have a relation within a range of values.
We are able to measure temperature because of the differences a temperature has upon the resultant bodies it affects. The temperature a body has is dependent upon its molecular structure and the vibration of its molecular construction. and and it is measurable, because of this difference between the two we are calculate its relative temperature or energy between the two . But hopefully in more natural arrangements it results in fewer calculations
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
In short: * **Temperature** is a measure of thermal energy. * **Heat** (and **heat transfer**) is the *transfer* of thermal energy. **Heat** is like **work**; work is energy and heat is energy, yes, but you cannot "have" work. You can *do* work. In the same way you can't "have" heat. Work is more correctly a *transfer* of energy (kinetic, potential...), just like heat is a transfer of energy (thermal). *What thermal energy is, is a different question, which the other answers take good care of.*
We are able to measure temperature because of the differences a temperature has upon the resultant bodies it affects. The temperature a body has is dependent upon its molecular structure and the vibration of its molecular construction. and and it is measurable, because of this difference between the two we are calculate its relative temperature or energy between the two . But hopefully in more natural arrangements it results in fewer calculations
326,627
Recently I watched a Youtube Video by [Veritasium](https://www.youtube.com/watch?v=vqDbMEdLiCs) He said we are actually feeling the rate of heat transfer, not the temperature. But how do we feel temperature? How is temperature different from heat and heat tranfer?
2017/04/14
[ "https://physics.stackexchange.com/questions/326627", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/122455/" ]
In a few words, temperature is a macroscopic property related to the kinetic energy of molecules. What it **really is**, is a tricky question, because we don't know what **mass** is or what **force** is, but we know how to measure and relate each other and how to intuitively understand. Based on that, we can infer some key properties about temperature. First of all, it is important to understand the difference between **heat** and **temperature**. Heat is energy, and when we are dealing with thermal systems, heat depends on the amount of mass that contains that energy. We call that an extensive property. ([more about that](https://en.wikipedia.org/wiki/Intensive_and_extensive_properties)). You would imagine that heating a house would take a lot more energy than to heat a can of water, for example. Temperature, on the other side, is an intensive property, i.e. it does not depends on the size of things. A 30ºC house wouldn't be hotter than a 30ºC water in a can. So, temperature is kind of an index, it is a metrics associated with each point in space. Heat transfer is related to heat flux. And heat flux as the name says, measures how much **heat** is flowing from one place to another. When we are dealing with steady-state systems (<https://en.wikipedia.org/wiki/Steady_state>), we can assume that: $$\Delta T=\dot{Q}\frac{L}{kA}$$ Explaining this equation: If we have a wall with two sides, the difference of temperature $\Delta T$ between the two sides will be proportional to how much of heat is coming in and out ($\dot{Q}$) and to the thickness of the wall ($L$) and inversely proportional to the conductivity ($k$) and area of the wall($A$). We often think the term $\frac{L}{kA}$ as *thermal resistance* as it is analogous to the equation in electricity: $$V=RI$$ If you are familiar, $V$ is the difference of potential (analogous to $\Delta T$), $I$ is the current (analogous to how much comes in and out, $\dot{Q}$) and $R$ would be the resistance, as I pointed. As in electricity, $V$ is a point property (it depends on two points) and $I$ is the flow of electrons. These points were just to make clear the distinction between these properties. But then, what is really temperature all about? Well, temperature is an useful measure to know thermal characteristics of a system. * We know that the dilation is proportional to temperature. Based on that, we have built thermometers, which use the principle of dilation. * We know that two bodies in contact with each other will empirically have the same temperature at infinite time. * We understand that thermal equilibrium, i.e. when two bodies exchange no energy, occurs when the temperature of both are the same. * In the perfect gas model, empirically discovered, we know that $PV=mRT$, i.e. four measurable properties (pressure, volume, mass and temperature) have a relation within a range of values.
In short: * **Temperature** is a measure of thermal energy. * **Heat** (and **heat transfer**) is the *transfer* of thermal energy. **Heat** is like **work**; work is energy and heat is energy, yes, but you cannot "have" work. You can *do* work. In the same way you can't "have" heat. Work is more correctly a *transfer* of energy (kinetic, potential...), just like heat is a transfer of energy (thermal). *What thermal energy is, is a different question, which the other answers take good care of.*
63,255,407
Edit: This question has gotten quite old and is no longer useful. Prestissimo isn't really useful any more now that Composer 2 is out. The way to use composer 2 in DDEV-Local v1.16 is `ddev config --composer-version=2`. In DDEV-Local v1.17 Composer 2 will be the default. Original question: I'd like to use [hirak/prestissimo](https://github.com/hirak/prestissimo) to speed up the downloads for my DDEV-Local composer builds on all my projects, but I don't know how to install it globally. How can I install it?
2020/08/04
[ "https://Stackoverflow.com/questions/63255407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215713/" ]
In DDEV-Local v1.15+ you can globally put anything you want in the web container home directory using the [homeadditions feature](https://ddev.readthedocs.io/en/stable/users/extend/in-container-configuration/#in-container-home-directory-configuration), and in the web container the composer global configuration is in ~/.composer. So the simple way to create the files you need (and hirak/prestissimo is just an example) is to ```sh ddev composer global require hirak/prestissimo # This installs prestissimo into global composer (home directory) docker cp ddev-<your-project-name>-web:/home/$(id -un)/.composer ~/.ddev/homeadditions/ ddev start ``` Of course, you can also do this on the project level instead of the global level using your project's .ddev/homeadditions directory instead of the ~/.ddev/homeadditions directory.
In addition to what rfay said, and based on his solution here is another approach. In your `.ddev/web-build/Dockerfile` add `RUN composer global require hirak/prestissimo`. This will install `hirak/prestissimo` in the `/root/.composer` directory. Then, in the `.ddev/homeadditions/.bash_aliases` add the following: ``` sync_global_composer() { sudo rsync -a /root/.composer/ /home/$(id -un)/.composer sudo chown -R 1000:1000 /home/$(id -un)/.composer } sync_global_composer ``` The first time you execute `ddev ssh` will take a bit longer because of the rsync, but the followings are quick. The reason of this approach is not having prestissimo (and in my case some others global libraries) in git, and the idea is to have this transparent for the rest of the dev team. PD: I'm still thinking in how to improve it.
63,255,407
Edit: This question has gotten quite old and is no longer useful. Prestissimo isn't really useful any more now that Composer 2 is out. The way to use composer 2 in DDEV-Local v1.16 is `ddev config --composer-version=2`. In DDEV-Local v1.17 Composer 2 will be the default. Original question: I'd like to use [hirak/prestissimo](https://github.com/hirak/prestissimo) to speed up the downloads for my DDEV-Local composer builds on all my projects, but I don't know how to install it globally. How can I install it?
2020/08/04
[ "https://Stackoverflow.com/questions/63255407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215713/" ]
In DDEV-Local v1.15+ you can globally put anything you want in the web container home directory using the [homeadditions feature](https://ddev.readthedocs.io/en/stable/users/extend/in-container-configuration/#in-container-home-directory-configuration), and in the web container the composer global configuration is in ~/.composer. So the simple way to create the files you need (and hirak/prestissimo is just an example) is to ```sh ddev composer global require hirak/prestissimo # This installs prestissimo into global composer (home directory) docker cp ddev-<your-project-name>-web:/home/$(id -un)/.composer ~/.ddev/homeadditions/ ddev start ``` Of course, you can also do this on the project level instead of the global level using your project's .ddev/homeadditions directory instead of the ~/.ddev/homeadditions directory.
You can also update to composer 2 since it is fast enough to not need hirak. Update using `composer self-update --2` and then remove `hirak/prestissimo` with `composer global remove hirak/prestissimo` resources: * <https://github.com/hirak/prestissimo> * <https://blog.packagist.com/composer-2-0-is-now-available/> - speed increases
63,255,407
Edit: This question has gotten quite old and is no longer useful. Prestissimo isn't really useful any more now that Composer 2 is out. The way to use composer 2 in DDEV-Local v1.16 is `ddev config --composer-version=2`. In DDEV-Local v1.17 Composer 2 will be the default. Original question: I'd like to use [hirak/prestissimo](https://github.com/hirak/prestissimo) to speed up the downloads for my DDEV-Local composer builds on all my projects, but I don't know how to install it globally. How can I install it?
2020/08/04
[ "https://Stackoverflow.com/questions/63255407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215713/" ]
In addition to what rfay said, and based on his solution here is another approach. In your `.ddev/web-build/Dockerfile` add `RUN composer global require hirak/prestissimo`. This will install `hirak/prestissimo` in the `/root/.composer` directory. Then, in the `.ddev/homeadditions/.bash_aliases` add the following: ``` sync_global_composer() { sudo rsync -a /root/.composer/ /home/$(id -un)/.composer sudo chown -R 1000:1000 /home/$(id -un)/.composer } sync_global_composer ``` The first time you execute `ddev ssh` will take a bit longer because of the rsync, but the followings are quick. The reason of this approach is not having prestissimo (and in my case some others global libraries) in git, and the idea is to have this transparent for the rest of the dev team. PD: I'm still thinking in how to improve it.
You can also update to composer 2 since it is fast enough to not need hirak. Update using `composer self-update --2` and then remove `hirak/prestissimo` with `composer global remove hirak/prestissimo` resources: * <https://github.com/hirak/prestissimo> * <https://blog.packagist.com/composer-2-0-is-now-available/> - speed increases
58,411,520
After writing a file with the snippet below ``` with open("temp.trig", "wb") as f: f.write(data) ``` I use `curl` to load it into the server ``` curl -X POST -F file=@"temp.trig" -H "Accept: application/json" http://localhost:8081/demo/upload ``` which works fine. I am trying to replace the `curl` with python requests, as follows: ``` with open("temp.trig", "rb") as f: result = requests.post("http://localhost:8081/demo/upload", files={'file': f}, headers = {"Accept": "application/json"}) ``` which attempted to follow the `curl` as closely as possible. This code results in an error 500 from the server. I suspect it must be something related to the request, because the same server is ok via `curl. Any ideas?
2019/10/16
[ "https://Stackoverflow.com/questions/58411520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2302244/" ]
Modern task manager uses internal private Windows functionality for its stay on top behaviour. The system does not make this available to user windows. The functionality that task manager uses simply isn't available to you. Related question: [Is Task Manager a special kind of 'Always on Top' window for windows 10?](https://stackoverflow.com/questions/39246590/is-task-manager-a-special-kind-of-always-on-top-window-for-windows-10)
Just use the **Object Inspector** at design time to set the form's `FormStyle` property to `fsStayOnTop`.
58,411,520
After writing a file with the snippet below ``` with open("temp.trig", "wb") as f: f.write(data) ``` I use `curl` to load it into the server ``` curl -X POST -F file=@"temp.trig" -H "Accept: application/json" http://localhost:8081/demo/upload ``` which works fine. I am trying to replace the `curl` with python requests, as follows: ``` with open("temp.trig", "rb") as f: result = requests.post("http://localhost:8081/demo/upload", files={'file': f}, headers = {"Accept": "application/json"}) ``` which attempted to follow the `curl` as closely as possible. This code results in an error 500 from the server. I suspect it must be something related to the request, because the same server is ok via `curl. Any ideas?
2019/10/16
[ "https://Stackoverflow.com/questions/58411520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2302244/" ]
Modern task manager uses internal private Windows functionality for its stay on top behaviour. The system does not make this available to user windows. The functionality that task manager uses simply isn't available to you. Related question: [Is Task Manager a special kind of 'Always on Top' window for windows 10?](https://stackoverflow.com/questions/39246590/is-task-manager-a-special-kind-of-always-on-top-window-for-windows-10)
The code from the original post might work on a main form, but will not work on a secondary form. fsStayOnTop is only part of the solution for a secondary form. Below is an easy solution for making a secondary form stay on top while the main form is obscured by other applications - without resorting to showmodal or form creation hacks. Put this in the "Form B" OnCreate event: **FormStyle:= fsStayOnTop;** but that alone won't do the trick... Drag a **TApplicationEvents** onto your "Form B" In the **OnDeactivate** event for **ApplicationEvents1**, add the following: **SetForegroundWindow(Handle);** I keep an eye on a small status window while my main form is crunching data out of site. Works beautifully!
56,398,716
I have an angular application that call my back-end written in Asp.net c#. The back-end works correctly (already used by a mobile application) but one entry point does not behave correctly while being hit by the angular Application. I Serialize a tupple array of and send it to the API, but when API entry point gets hit, it seems like the data of the tuple array is not being received. I've already looked to my tuple array, the data is correctly serialized to json client-side but not received server-side. Here is the entry point definition in my c# API : ``` public HttpResponseMessage Xamarin_UpdateStatut([FromRoute] int idEvent, [System.Web.Http.FromBody] List<Tuple<int, bool>> listUsersStatut) { } ``` And here is the tuple sended client-side (get via chrome console) : "[[2102,false],[1096,false],[73,false]]" Here is the code used to serialized the tuple array to Json (client-side) : ``` var listUpdate = new Array<[number, boolean]>(); arr.forEach(re => { let el: [number, boolean] = [re.userId, re.wasThere]; listUpdate.push(el); }); let body = JSON.stringify(listUpdate); ``` I debugged a few times server side, the list length is 0. I tried to change the type received from List to Tuple array (server side, in the method definition) but it didn't change anything. It seems to me like the json output is correct so I don't understand why it does not work. A little help would be very much appreciated :) Have a nice day and thanks in advance, Lio
2019/05/31
[ "https://Stackoverflow.com/questions/56398716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9414420/" ]
Tuples in C# are treated like classes, whereas you're setting up your client-side model as if they're arrays. Try something like this: ``` var listUpdate = new Array<{item1: number, item2: boolean}>(); arr.forEach(re => { let el: {item1: number, item2: boolean} = {item1: re.userId, item2: re.wasThere}; listUpdate.push(el); }); ``` I'd personally suggest using a strongly-typed class instead of tuples, so you have more meaningful property names than `Item1` and `Item2`. You might also consider posting an object that has the list as one of its properties rather than posting the list itself: this will give you the flexibility to add more data to the object in the future, should the need arise, without needing to change as much code.
Binding happens by name. From [Model Binding](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2): "MVC will try to bind request data to the action parameters by name. MVC will look for values for each parameter using the parameter name and the names of its public settable properties." In order for binding to be successful, the names in your JSON must match the names of the C# parameters, including the names of the properties of each parameter.
549,779
I have an AZURE virtual machine with a MySQL server installed on it running ubuntu 13.04. I am trying to remote connect to the MySQL server however get the simple error "Can't connect to MySQL server on {IP}" I have already done the follow: ``` * commented out the bind-address within the /etc/mysql/my.cnf * commented out skip-external-locking within the same my.cnf * "ufw allow mysql" * "iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT" * setup an AZURE endpoint for mysql * "sudo netstat -lpn | grep 3306" does indeed show mysql LISTENING * "GRANT ALL ON *.* TO remote@'%' IDENTIFIED BY 'password'; * "GRANT ALL ON *.* TO remote@'localhost' IDENTIFIED BY 'password'; * "/etc/init.d/mysql restart" * I can connect via SSH tunneling, but not without it * I have spun up an identical ubuntu 13.04 server on rackspace and SUCCESSFULLY connected using the same procedures outlined here. ``` NONE of the above works on my azure server however. I thought the creation of an endpoint would work, but no luck. Any help please? Is there something I'm missing entirely? ![enter image description here](https://i.stack.imgur.com/9AOlY.png)
2013/10/31
[ "https://serverfault.com/questions/549779", "https://serverfault.com", "https://serverfault.com/users/110586/" ]
The 'official manual' quoted above didnt work for me and seems to set up a ssh tunnel to accomplish this... even after following the guide it still didnt work. Heres my working solution For a Ubuntu Azure VM see: <https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-create-lamp-stack/> Specifically the section "Allow remote access to MySQL" Comment out: ``` bind-address = 127.0.0.1 ``` located at /etc/mysql/my.cnf run ``` sudo service mysql restart ``` and my remote connections worked --- just make sure port 3306 is open in the azure server portal for your vm!
Check your firewall uring sudo ufw status.
549,779
I have an AZURE virtual machine with a MySQL server installed on it running ubuntu 13.04. I am trying to remote connect to the MySQL server however get the simple error "Can't connect to MySQL server on {IP}" I have already done the follow: ``` * commented out the bind-address within the /etc/mysql/my.cnf * commented out skip-external-locking within the same my.cnf * "ufw allow mysql" * "iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT" * setup an AZURE endpoint for mysql * "sudo netstat -lpn | grep 3306" does indeed show mysql LISTENING * "GRANT ALL ON *.* TO remote@'%' IDENTIFIED BY 'password'; * "GRANT ALL ON *.* TO remote@'localhost' IDENTIFIED BY 'password'; * "/etc/init.d/mysql restart" * I can connect via SSH tunneling, but not without it * I have spun up an identical ubuntu 13.04 server on rackspace and SUCCESSFULLY connected using the same procedures outlined here. ``` NONE of the above works on my azure server however. I thought the creation of an endpoint would work, but no luck. Any help please? Is there something I'm missing entirely? ![enter image description here](https://i.stack.imgur.com/9AOlY.png)
2013/10/31
[ "https://serverfault.com/questions/549779", "https://serverfault.com", "https://serverfault.com/users/110586/" ]
The 'official manual' quoted above didnt work for me and seems to set up a ssh tunnel to accomplish this... even after following the guide it still didnt work. Heres my working solution For a Ubuntu Azure VM see: <https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-create-lamp-stack/> Specifically the section "Allow remote access to MySQL" Comment out: ``` bind-address = 127.0.0.1 ``` located at /etc/mysql/my.cnf run ``` sudo service mysql restart ``` and my remote connections worked --- just make sure port 3306 is open in the azure server portal for your vm!
[This](https://azure.microsoft.com/en-us/blog/create-your-own-dedicated-mysql-server-for-your-azure-websites/) succinct guide was useful for me to get mine to work. While there are other essential steps [that I had already done] there, the one I was missing was this: 3306 port is not opened by default, hence you need to first open this port so a remote client can connect to your MySQL Server. Run the following command to open TCP port 3306: ``` iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT ``` check if the port 3306 is open by running this command: ``` sudo netstat -anltp|grep :3306 ```
549,779
I have an AZURE virtual machine with a MySQL server installed on it running ubuntu 13.04. I am trying to remote connect to the MySQL server however get the simple error "Can't connect to MySQL server on {IP}" I have already done the follow: ``` * commented out the bind-address within the /etc/mysql/my.cnf * commented out skip-external-locking within the same my.cnf * "ufw allow mysql" * "iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT" * setup an AZURE endpoint for mysql * "sudo netstat -lpn | grep 3306" does indeed show mysql LISTENING * "GRANT ALL ON *.* TO remote@'%' IDENTIFIED BY 'password'; * "GRANT ALL ON *.* TO remote@'localhost' IDENTIFIED BY 'password'; * "/etc/init.d/mysql restart" * I can connect via SSH tunneling, but not without it * I have spun up an identical ubuntu 13.04 server on rackspace and SUCCESSFULLY connected using the same procedures outlined here. ``` NONE of the above works on my azure server however. I thought the creation of an endpoint would work, but no luck. Any help please? Is there something I'm missing entirely? ![enter image description here](https://i.stack.imgur.com/9AOlY.png)
2013/10/31
[ "https://serverfault.com/questions/549779", "https://serverfault.com", "https://serverfault.com/users/110586/" ]
[This](https://azure.microsoft.com/en-us/blog/create-your-own-dedicated-mysql-server-for-your-azure-websites/) succinct guide was useful for me to get mine to work. While there are other essential steps [that I had already done] there, the one I was missing was this: 3306 port is not opened by default, hence you need to first open this port so a remote client can connect to your MySQL Server. Run the following command to open TCP port 3306: ``` iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT ``` check if the port 3306 is open by running this command: ``` sudo netstat -anltp|grep :3306 ```
Check your firewall uring sudo ufw status.
52,461,392
I'm trying to create code that will take a given integer, then output a set of integers, all of which are rotations of digits of the input integer. Thus, if I inputted '197', the output should be '197', '971', and '791'. However, when I try: ``` def rotation(n): rotations = set() for i in range( len( str(n) ) ): n = int( str(n)[i:] + str(n)[:i] ) rotations.add(n) ``` with the input '197', it only returns '197', '971', yet NOT '791'. Why is this happening?
2018/09/22
[ "https://Stackoverflow.com/questions/52461392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10240052/" ]
You're almost there. Except you're erasing the input n at each iteration. Use another variable name. ``` def rotation(n): rotations = set() for i in range( len( str(n) ) ): m = int( str(n)[i:] + str(n)[:i] ) rotations.add(m) return rotations print(rotation(197)) ``` I would write it more like this, using a set comprehension: ``` def rotation(number): str_number = str(number) return { int( str_number[i:] + str_number[:i] ) for i in range(len(str_number)) } ``` Solution 2 by @Henry Woody is nice too. Rather than rotate input string by `i` at each iteration, rotate by `1` from last iteration.
The way you have your code structured does duplicate rotation because you reassign `n` on each step of the loop and use the iteration variable `i` in your slices. So the process in the loop from your example is: * `i = 0` + You have `n = 197` and the rotation logic does nothing with `i = 0` so you add `197` to rotations * `i = 1` + Again you have `n = 197`, and rotation logic makes `n = 971` and you add that to `rotations`. * `i = 2` + Now `n = 971`, and the rotation logic slices from index `2`, but `n` has already been rotated so we have `n = 197` again, which is added to `rotations` (and removed since `rotations` is a set). Basically `n` has already been rotated forward, and now it is being rotated forward 2 steps (back to the initial value and skipping over `n = 719`) To fix this you can either: **1.** Keep `n` at its initial value and on each step rotate `n` the full amount (`i`) and add that to `rotation` without modifying `n`. Like so: ``` def rotation(n): rotations = set() for i in range( len( str(n) ) ): rotations.add(int( str(n)[i:] + str(n)[:i] )) return rotations ``` **2.** Rotate `n` forward on each step, but only rotate it forward one position each time. Like so: ``` def rotation(n): rotations = set() for i in range( len( str(n) ) ): n = int( str(n)[1:] + str(n)[:1] ) rotations.add(n) return rotations ```
61,090,282
How would I add user input validation to the following code? not sure whether to use try and catch or if there is some other way that would be great, cheers :) ``` private static int ReadInteger(string prompt) { Console.Write(prompt + ": > "); return Convert.ToInt32(Console.ReadLine()); } private static string ReadString(string prompt) { Console.WriteLine(prompt + ": > "); return Console.ReadLine(); } private static double ReadDouble(string prompt) { Console.WriteLine(prompt + ": > "); return Convert.ToDouble(Console.ReadLine()); } private static DateTime ReadDate(string prompt) { Console.WriteLine(prompt + ": > "); return Convert.ToDateTime(Console.ReadLine()); } ```
2020/04/07
[ "https://Stackoverflow.com/questions/61090282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13253690/" ]
Without calculating the largest text size, you can simply use a `BoxConstraints` with a `minWidth` and `maxWidth` properties like this : ``` ToggleButtons( children: [Text('long text'), Text('text')], constraints: BoxConstraints(minWidth: 70, maxWidth: 70, minHeight: kMinInteractiveDimension), isSelected: [true, false], ) ``` Larger text on ToggleButtons will be wrapped I hope this will be helpful to you
I had the similar issue today when I had to create custom toggle buttons, where toggle button items where loading from a list of various options of various text sizes and client was ok to wrap the longer text options. With in built toggle button, it would just fix the size for all items. So when I created the custom toggle buttons,it calculates the size of each button based on the longest word in that item using getWidth() method. ``` return Center( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 15.0, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ for (int i = 0; i < responses.length; i++) InkWell( onTap: (() { setState(() { for (int j = 0; j < isSelected[index]!.length; j++) { isSelected[index]![j] = j == i; surveys[0]["feedbackQuestion"][index]["answer"] = i.toString(); } }); print(isSelected[index]![i]); print(color.toString()); }), child: SizedBox( width: getWidth( responses[i], GoogleFonts.roboto( fontWeight: FontWeight.bold, fontSize: 12.0, color: color)), child: Text(responses[i], style: GoogleFonts.roboto( fontWeight: FontWeight.bold, fontSize: 12.0, color: isSelected[index]![i] ? Colors.green : Colors.orange)), ), ), ``` getWidth method ``` getWidth(String response, TextStyle textStyle) { String result = ""; if (response.contains(" ")) { var values = <String>[]; values = response.split(" "); for (String value in values) { if (value.length > result.length) { result = value; } } } else { result = response; } final Size size = (TextPainter( text: TextSpan(text: result, style: textStyle), maxLines: 1, textScaleFactor: MediaQuery.of(context).textScaleFactor, textDirection: TextDirection.ltr) ..layout()) .size; return size.width + 5; //Extra 5 for padding } ``` isSelected is a Map of `<int, List<bool>?>` to contain bool values for all buttons. isSelected should be loaded outside the buttons loading method, preferrably at class level to to avoid being reset with each set of buttons load. Result(Green being the selected color): [![Green being the selected color](https://i.stack.imgur.com/c4FbY.png)](https://i.stack.imgur.com/c4FbY.png)
61,090,282
How would I add user input validation to the following code? not sure whether to use try and catch or if there is some other way that would be great, cheers :) ``` private static int ReadInteger(string prompt) { Console.Write(prompt + ": > "); return Convert.ToInt32(Console.ReadLine()); } private static string ReadString(string prompt) { Console.WriteLine(prompt + ": > "); return Console.ReadLine(); } private static double ReadDouble(string prompt) { Console.WriteLine(prompt + ": > "); return Convert.ToDouble(Console.ReadLine()); } private static DateTime ReadDate(string prompt) { Console.WriteLine(prompt + ": > "); return Convert.ToDateTime(Console.ReadLine()); } ```
2020/04/07
[ "https://Stackoverflow.com/questions/61090282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13253690/" ]
Without calculating the largest text size, you can simply use a `BoxConstraints` with a `minWidth` and `maxWidth` properties like this : ``` ToggleButtons( children: [Text('long text'), Text('text')], constraints: BoxConstraints(minWidth: 70, maxWidth: 70, minHeight: kMinInteractiveDimension), isSelected: [true, false], ) ``` Larger text on ToggleButtons will be wrapped I hope this will be helpful to you
This is difficult to do without some custom layout code and re-implementing the toggle button, here I am using the [boxy](https://pub.dev/packages/boxy) package to make each button the same size: [![](https://i.stack.imgur.com/DSIMn.png)](https://i.stack.imgur.com/DSIMn.png) ```dart class MyWidget extends StatefulWidget { const MyWidget({Key? key}) : super(key: key); @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { final isSelected = <bool>[false, false, false]; @override Widget build(BuildContext context) { return EvenSizedToggleButtons( onPressed: (i) { setState(() { isSelected[i] = !isSelected[i]; }); }, isSelected: isSelected, children: const [ Text('Smol'), Text('Longer'), Text('__Longest__'), ], ); } } class EvenSizedToggleButtons extends StatefulWidget { const EvenSizedToggleButtons({ Key? key, required this.onPressed, required this.isSelected, required this.children, }) : super(key: key); final void Function(int index) onPressed; final List<bool> isSelected; final List<Widget> children; @override State<EvenSizedToggleButtons> createState() => _EvenSizedToggleButtonsState(); } class _EvenSizedToggleButtonsState extends State<EvenSizedToggleButtons> { @override Widget build(BuildContext context) { return EvenSized( children: [ for (var i = 0; i < widget.children.length; i++) ToggleButton( selected: widget.isSelected[i], onPressed: () => widget.onPressed(i), child: widget.children[i], isFirst: i == 0, ), ], ); } } class ToggleButton extends StatelessWidget { const ToggleButton({ Key? key, required this.onPressed, required this.selected, required this.child, required this.isFirst, }) : super(key: key); final VoidCallback onPressed; final bool selected; final Widget child; final bool isFirst; @override Widget build(BuildContext context) { final theme = Theme.of(context); final colorScheme = theme.colorScheme; final borderSide = BorderSide( color: colorScheme.onSurface.withOpacity(0.12), width: 1, ); return Container( decoration: BoxDecoration( border: Border( left: isFirst ? borderSide : BorderSide.none, top: borderSide, right: borderSide, bottom: borderSide, ), ), constraints: const BoxConstraints( minWidth: 50, minHeight: 50, ), child: TextButton( onPressed: onPressed, style: ButtonStyle( backgroundColor: MaterialStatePropertyAll(selected ? colorScheme.primary.withOpacity(0.12) : Colors.transparent), shape: const MaterialStatePropertyAll(RoundedRectangleBorder()), textStyle: const MaterialStatePropertyAll(TextStyle()), foregroundColor: MaterialStatePropertyAll(selected ? colorScheme.primary : theme.textTheme.bodyMedium!.color), ), child: child, ), ); } } class EvenSized extends StatelessWidget { const EvenSized({ Key? key, required this.children, }) : super(key: key); final List<Widget> children; @override Widget build(BuildContext context) { return CustomBoxy( delegate: EvenSizedBoxy(), children: children, ); } } class EvenSizedBoxy extends BoxyDelegate { @override Size layout() { // Find the max intrinsic width of each child // // Intrinsics are a little scary but `getMaxIntrinsicWidth(double.infinity)` // just calculates the width of the child as if its maximum height is // infinite var childWidth = 0.0; for (final child in children) { childWidth = max( childWidth, child.render.getMaxIntrinsicWidth(double.infinity), ); } // Clamp the width so children don't overflow childWidth = min(childWidth, constraints.maxWidth / children.length); // Find the max intrinsic height // // We calculate childHeight after childWidth because the height of text // depends on its width (i.e. wrapping), `getMinIntrinsicHeight(childWidth)` // calculates what the child's height would be if it's width is childWidth. var childHeight = 0.0; for (final child in children) { childHeight = max( childHeight, child.render.getMinIntrinsicHeight(childWidth), ); } // Force each child to be the same size final childConstraints = BoxConstraints.tight( Size(childWidth, childHeight), ); var x = 0.0; for (final child in children) { child.layout(childConstraints); // Space them out evenly child.position(Offset(x, 0)); x += childWidth; } return Size(childWidth * children.length, childHeight); } } ``` An interactive example can be found at <https://dartpad.boxy.wiki/?id=1e1239c8e412750081a053e9f14f6d8d>
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
Use colons to separate hours, minutes and seconds: "05-MAY-09 03:55:50"
That constructor is deprecated (since jdk 1.1). It not even valid in java5 <http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Date.html> You should ``` SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Date date = sdf.parse("05-MAY-09 03:55:50"); ```
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That [Date constructor is deprecated](http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date(java.lang.String)) for a reason. You should be using a [DateFormat](http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html) / [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) instead to create Date instances from a String representation. ``` DateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss"); Date myDate = df.parse("05-05-MAY-09 03.55.50"); ``` This way, you can parse dates that are in just about any format you could conceivably want.
Use colons to separate hours, minutes and seconds: "05-MAY-09 03:55:50"
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
Other than the fact that you are using a deprecated method (you should be using [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) instead), this should work: ``` new Date("05-MAY-09 03:55:50"); ``` Also check out [Joda Time](http://joda-time.sourceforge.net/)
Use colons to separate hours, minutes and seconds: "05-MAY-09 03:55:50"
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That [Date constructor is deprecated](http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date(java.lang.String)) for a reason. You should be using a [DateFormat](http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html) / [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) instead to create Date instances from a String representation. ``` DateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss"); Date myDate = df.parse("05-05-MAY-09 03.55.50"); ``` This way, you can parse dates that are in just about any format you could conceivably want.
That constructor is deprecated (since jdk 1.1). It not even valid in java5 <http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Date.html> You should ``` SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Date date = sdf.parse("05-MAY-09 03:55:50"); ```
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
Other than the fact that you are using a deprecated method (you should be using [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) instead), this should work: ``` new Date("05-MAY-09 03:55:50"); ``` Also check out [Joda Time](http://joda-time.sourceforge.net/)
That constructor is deprecated (since jdk 1.1). It not even valid in java5 <http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Date.html> You should ``` SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Date date = sdf.parse("05-MAY-09 03:55:50"); ```
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
Don't use this method, as it has been deprecated for years (and years). Use DateFormat.parse() in which you can easily define the format you want to parse.
That constructor is deprecated (since jdk 1.1). It not even valid in java5 <http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Date.html> You should ``` SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Date date = sdf.parse("05-MAY-09 03:55:50"); ```
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That [Date constructor is deprecated](http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date(java.lang.String)) for a reason. You should be using a [DateFormat](http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html) / [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) instead to create Date instances from a String representation. ``` DateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss"); Date myDate = df.parse("05-05-MAY-09 03.55.50"); ``` This way, you can parse dates that are in just about any format you could conceivably want.
Other than the fact that you are using a deprecated method (you should be using [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) instead), this should work: ``` new Date("05-MAY-09 03:55:50"); ``` Also check out [Joda Time](http://joda-time.sourceforge.net/)
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That [Date constructor is deprecated](http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date(java.lang.String)) for a reason. You should be using a [DateFormat](http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html) / [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) instead to create Date instances from a String representation. ``` DateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss"); Date myDate = df.parse("05-05-MAY-09 03.55.50"); ``` This way, you can parse dates that are in just about any format you could conceivably want.
Don't use this method, as it has been deprecated for years (and years). Use DateFormat.parse() in which you can easily define the format you want to parse.
852,887
``` new Date("05-MAY-09 03.55.50") ``` is any thing wrong with this ? i am getting illegalArgumentException
2009/05/12
[ "https://Stackoverflow.com/questions/852887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
Other than the fact that you are using a deprecated method (you should be using [SimpleDateFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html) instead), this should work: ``` new Date("05-MAY-09 03:55:50"); ``` Also check out [Joda Time](http://joda-time.sourceforge.net/)
Don't use this method, as it has been deprecated for years (and years). Use DateFormat.parse() in which you can easily define the format you want to parse.