Q: R data.table to calculate new columns from existing columns bases in certain conditions Let's say I have the following data table:
dta <- data.table(
  criteria = c('A', 'A', 'B', 'A', 'A', 'B'),
  phase = list('block3', c('block1', 'block2'), 'block2', 'block2', 'block3', 'block1'),
  start_val = c(12.0, 1.0, 7.0, 7.0, 12.0, 1.0),
  end_val = c(15.0, 11.0, 11.0, 11.0, 15.0, 6.0),
  max_val = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0)
)

from which I need the resulting table with two additional column's, cor_start and cor_end
dtb <- data.table(
  criteria = c('A', 'A', 'B', 'A', 'A', 'B'),
  phase = list('block3', c('block1', 'block2'), 'block2', 'block2', 'block3', 'block1'),
  start_val = c(12.0, 1.0, 7.0, 7.0, 12.0, 1.0),
  end_val = c(15.0, 11.0, 11.0, 11.0, 15.0, 6.0),
  max_val = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0),
  cor_start = c(12.0, 1.0, 8.0, 9.5, 13.0, 6.0),
  cor_end = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0)
)

the new columns need to be calculated with reference to phases column by checking if there is any previous row with the current matching phase value.
For better understanding, in this example:

*

*row 3 has a matching phase of block2 in row 2

*row 4 has a matching phase of block2 in row 3

*row 5 has a matching phase of block3 in row 1

*row 6 has a matching phase of block1 in row 2

however row 1 and row 2 have no previous matching phase rows. Note that the phase is of type list.
So, when there is a previous matching row, below are the conditions:
if (max_val in previous matching row is < end_val in current row)
  cor_start = previous matching row max_val
  cor_end = current row end_val

if (max_val in previous matching row is > end_val in current row)
  cor_start = current row end_val
  cor_end = current row end_val

and when there is no previous matching row, below are the conditions:
  cor_start = current row start_val
  cor_end = current row max_val

I looked into shift(), but could not figure out on how to set the above conditions ? Thanks!

A: Something like:
dta_transformed <- dta[,.(rn = .I, phase = unlist(phase)), by = setdiff(names(dta), 'phase')][
  , shifted_max := shift(max_val), by = phase][
    shifted_max < end_val, `:=` (cor_start = shifted_max, cor_end = end_val), by = phase][
      shifted_max > end_val, `:=` (cor_start = end_val, cor_end = end_val), by = phase][
        is.na(cor_start), `:=` (cor_start = start_val, cor_end = max_val), by = phase][
          , phase := paste(phase, collapse = ","), by = rn][!duplicated(rn),][
            , c("rn", "shifted_max") := NULL]

However, the output I get is:
   criteria         phase start_val end_val max_val cor_start cor_end
1:        A        block3        12      15    13.0      12.0      13
2:        A block1,block2         1      11     8.0       1.0       8
3:        B        block2         7      11     9.5       8.0      11
4:        A        block2         7      11    11.0       9.5      11
5:        A        block3        12      15    15.0      13.0      15
6:        B        block1         1       6     6.0       6.0       6

Could it be that in row number 3 the cor_end should be 11 in your desired output? As the previous matching row (2) has lower max_val, therefore the current end_val (11) should be taken?
Also the tidyverse approach, slightly more readable:
library(tidyverse)

dta %>% mutate(rn = row_number()) %>%
  unnest(phase) %>%
  group_by(phase) %>%
  mutate(
    cor_start = case_when(
      lag(max_val) < end_val ~ lag(max_val),
      lag(max_val) > end_val ~ end_val,
      TRUE ~ start_val
    ),
    cor_end = if_else(!is.na(lag(max_val)), end_val, max_val)
  ) %>% group_by(rn) %>%
  mutate(
    phase = paste(phase, collapse = ",")
  ) %>% ungroup() %>% select(-rn) %>% distinct()

A: Here is a different approach which uses pmin() instead of ifelse() and utilises the fill parameter of the shift() function. Furthermore, it reduces the number of grouping operations:
library(data.table)
dta[, rn := .I]
dta[dta[, .(phase2 = unlist(phase)), by = rn], on = "rn"][
  , `:=`(cor_start = pmin(shift(max_val, fill = start_val[1]), end_val),
         cor_end = max_val), by = phase2][
    , .SD[1], by = rn][
      , c("rn", "phase2") := NULL][]

  criteria         phase start_val end_val max_val cor_start cor_end
1:        A        block3        12      15    13.0      12.0    13.0
2:        A block1,block2         1      11     8.0       1.0     8.0
3:        B        block2         7      11     9.5       8.0     9.5
4:        A        block2         7      11    11.0       9.5    11.0
5:        A        block3        12      15    15.0      13.0    15.0
6:        B        block1         1       6     6.0       6.0     6.0


Q: How to download files from Folders inside Azure Blob storage? I would like to know how to download files from folders that are created inside azure blob. A schematic diagram is shown below:
MyContainer (Container) --> HomeFolder--> Sample.txt (Blob)
If There is no folder and only sample.txt file is there, then I am able to download the file, but not when the file is inside a folder.
On stackeoverflow, I see most of issues are related to file directly under container. Could any one guide me on above request?
2) Another question is I want to do it via latest azure sdk [Azure.Storage.Blobs], but it would be fine if someone is using [Microsoft.Azure.Storage.Blob] dll.
Below code that I am currently writing with [Microsoft.Azure.Storage.Blob] class.
class Program
{
    static void Main(string[] args)
    {
        string storageAccount_connectionString = "DefaultEndpointsProtocol=https;AccountName=<account key>;EndpointSuffix=core.windows.net";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = blobClient.GetContainerReference("lbdemocontainers");
        string blobPrefix = null;
        bool useFlatBlobListing = false;
        var listOfFileNames = new List<string>();
        var blobs = container.ListBlobs(blobPrefix, useFlatBlobListing, BlobListingDetails.None);
        //var folders = blobs.Where(b => b as CloudBlobDirectory != null).ToList();
        //foreach (var folder in blobs)
        //{
        //    var blob = (CloudBlockBlob)folder;
        //    blob.FetchAttributes();
        //    listOfFileNames.Add(blob.Name);
        //}
        //var downloads = blobs.Select(blob => blob.Uri.Segments.Last()).ToList();
        var blobNames = blobs.OfType<CloudBlockBlob>().Select(b => b.Name).ToList();
        Console.ReadLine();

    }
}

From above code it provides me Folder name HomeFolder/ only.
Thanks in advance


Q: Flutter - Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator After updating to Catalina 10.15.4 beta with Xcode 13.4 beta, which also updated Simulator to 13.4 (921.4).
The application compiles and runs correctly on a physically attached device, but no simulators of any devices can pass this stage.
I got the errors

Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator.

or

Building for iOS Simulator, but the linked and embedded framework 'App.framework' was built for iOS.

How can I fix this?

A: Xcode 11.4 changed the way frameworks are linked and embedded, and you may experience issues switching between iOS devices and simulators. Flutter v1.15.3 and later will automatically migrate your Xcode project.
To get unstuck, follow the instructions below;

*

*Quick fix (make your simulator work)

rm -rf ios/Flutter/App.framework

*

*Official recommended Steps to migrate manually

*

*From the Flutter app directory, open ios/Runner.xcworkspace in
Xcode.

*In the Navigator pane, locate the Flutter group and remove App.framework and Flutter.framework.

*In the Runner target build settings Build Phases > Link Binary With Libraries confirm App.framework and Flutter.framework are no longer present. Also confirm in Build Phases > Embed Frameworks.

*Change the Runner target build settings Build Phases > Thin Binary script as follows:

/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh"
  embed
/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh"
  thin

*In the Runner target Build Settings > Other Linker Flags
(OTHER_LDFLAGS) add $(inherited) -framework Flutter

Hope it helps!

A: Xcode 11.4 changed the way frameworks are linked and embedded, which is causing issues switching between iOS devices and simulators.
Please follow official guide on how to migrate your project.

A: After several days trying to find a solution to test the Flutter app on iOS device, I finally found this:
flutter clean
flutter build ios

-Open xCode and run app on your device.

A: Updated to Xcode 11.4. Ios 13.4, Iphone X. App just fetches data using API.
App started on white screen and then finally crashes, both on simulator and device.
I followed the offical guide (I also rm -rf ios/Flutter/App.framework)
flutter.dev/docs/development/ios-project-migration.
I ran several times flutter clean
I also tried deleting Pods/ folder and Podfile.lock, then reinstalling using pod install in the ios folder.
As I am using async data I also added as 1st line in main()
WidgetsFlutterBinding.ensureInitialized();

No help, app did not started either simulator.
Then I removed ios/ and android/ folders. After that in project folder I ran command flutter create . that regenerates mentioned folders.
After this my app started fine both on simulator and on device.
I hope this would be help to others.  NOTE!! if you have done any modifications manually to those folders please take backup or commit beforehand.

A: *

*Select your Target from "TARGETS"

*Select 'Build Settings'

*Under 'Build Options' -> Set 'Validate Workspace' To 'YES'

*After successfully building, set it back to 'NO'

Reason :
"In Xcode 12+, the default option for Validate Workspace is internally not set. We need to set it manually to avoid this kind of error. There is no problem in setting back to the default 'NO' option.

A: I have tried the solution on the official website of flutter but it didn't work for me, so I found a temporary solution which worked for me, but it took me some hard works:
Here is my example with project stuck_framework which is a fresh new project (first time run on the simulator)

*

*I created 2 folders inside flutter project called
"ios_simulator" and "ios_real_device".
enter image description here

*Now my first build was for the simulator, then I want to switch to a real device, I will move ios folder inside Flutter project to the "ios_simulator"

*I open the project with visual studio code and run "flutter create ." and now I will choose a real device to rebuild the project ( if your simulator is online, please quit ).
enter image description here

*Now I wait for the build finish and run on the real device without any errors. Now I have 2 ios project 1 for simulators and one for real devices.

*Next time when I want to run on the simulator again, I just remove the current ios folder and copy the ios folder which I placed on "ios_simulator" back out to flutter project folder. Hope this help

A: Manually upgrading flutter to version 1.15 solve this issue as well. Running flutter version v1.15.17 helped me.
Also, you can switch to beta or dev channels by running flutter channel command but be sure you check your code against all BC changes...

A: In my case, it works only simulator(debug). if you want to deploy your app on the app store(release) i highly recommend you to upgrade flutter version using
flutter version v1.15.17

otherwise you would encounter crashed app with white screen.
just upgrade flutter version then all things work well

A: This error is caused by the Xcode 11.4 and can be resolved by Removing / Re-Embedding frameworks and adding a new Run Script Phase.

*

*Under General -> "Frameworks, Libraries, and Embedded Content"

*

*Delete the frameworks that are causing errors.

*After deleting, re-embed the frameworks in the same location.

*Under Build Phases add a new run script phase.

*

*Select the "+" button in the "Build Phases" pane to create a "New Run Script Phase".

*Confirm the script is the bottommost build phase, and configure its fields.

*

*The Shell text field should read /bin/sh (which is the default value).

*In the text-input area, enter the shell command rm -r "FRAMEWORK_DIRECTORY/YOUR_FRAMEWORK.framework/"

A: None of the other solutions here worked for me. In my case, the problem was fixed by searching my project for ONLY_ACTIVE_ARCH and changing them all to YES. I found my solution here:
https://developer.apple.com/forums/thread/656509


Q: Convert plaintext to perform elgamal encryption Hi i'm writing a program in java to test a variant of the elgamal encryption, however my problem is not the encryption/decryption chain itself, but how to perform the operations on the input given: a text file. I have a text file with some words in it (for example the content can be: "Hello world, this is a test") and i need to perform numeric operations on them like this:

ciphertext= (message * y) mod p

where y and p are two biginteger. I tried this conversion chain: (reading one string at time):

String->Hexadecimal->Decimal

Then perform the encrypt operation, and then the inverse:

Decimal->Hexadecimal->String

But this doesn't work all the time (i'm currently investigate on this issue). fixed.
My question is, there is a better way to do this? I was reading about the byte array's but i'm not sure how to use them.
[i can post an example of the encryption/decryption chain if needed]

A: BigInteger has a constructor taking a byte array as argument.
Any String can be converted to a byte array, without loss, using (for example), UTF-8 encoding:
byte[] bytes = string.getBytes(StandardCharsets.UTF_8);

Combine both, and you have an easy way to transform a String into a BigDecimal.
For the reverse operation, use BigInteger.toByteArray(), and then new String(bytes, StandardCharsets.UTF_8).


Q: Err HTTP 200 in Node.Js on Windows Server 2012 I created an application that is running correctly, but when run on the server this error is occurring.
Server: Windows Server 2012.
Any suggestion?
iisnode encountered an error when processing the request.

HRESULT: 0x2
HTTP status: 500
HTTP subStatus: 1002
HTTP reason: Internal Server Error
You are receiving this HTTP 200 response because system.webServer/iisnode/@devErrorsEnabled configuration setting is 'true'.

In addition to the log of stdout and stderr of the node.exe process, consider using debugging and ETW traces to further diagnose the problem.

The node.exe process has not written any information to stderr or iisnode was unable to capture this information. Frequent reason is that the iisnode module is unable to create a log file to capture stdout and stderr output from node.exe. Please check that the identity of the IIS application pool running the node.js application has read and write access permissions to the directory on the server where the node.js application is located. Alternatively you can disable logging by setting system.webServer/iisnode/@loggingEnabled element of web.config to 'false'.


Q: What is _GLIBCXX_USE_NANOSLEEP all about? A preprocessor macro called _GLIBCXX_USE_NANOSLEEP appears in two standard header files:

*

*c++/4.7.1/x86_64-unknown-linux-gnu/bits/c++config.h

*c++/4.7.1/thread
In a default build of GCC 4.7.1 (Linux, 64-bit) the only thing c++config.h includes is this comment:
/* Defined if nanosleep is available. */
/* #undef _GLIBCXX_USE_NANOSLEEP */

Whereas in thread, the definition of std::this_thread::sleep_for() and std::this_thread::sleep_until() depend on the macro to be defined. If it isn't defined, both functions – although required by the C++ Standard – won't be defined either.
On my system (glibc 2.15), the macro is not defined, although the nanosleep() function (declared in ctime) exists and is operational.
I'd like to know what this is all about and how to deal with it. Specifically:

*

*Is there a configuration option that should be used when building GCC to activate this macro by default, as suggested by this post? (I couldn't find any in the online documentation of the build process.)

*Is there really a relation between the nanosleep() function and the macro? The declaration of nanosleep() in ctime/time.h does not seem to depend on, or define, the macro.

*Is there any specific risk involved in defining the macro in my own header files, or as a -D option on the command line (as suggested in this related question)? What if I do this on a system where nanosleep() is not available, and how can I actually find out?

Update From GCC 4.8 onwards, support for std::this_thread::sleep_for() and the like is automatically included in libstdc++. No configuration flag is required any more. From the GCC 4.8 change log:

this_thread::sleep_for(), this_thread::sleep_until() and this_thread::yield() are defined without requiring the configure option --enable-libstdcxx-time;

But note the further details on this for GCC 4.8 and 4.9 given in Jonathan's answer.

A: When libstdc++ is built its configure script tests your system to see what features are supported, and based on the results it defines (or undefines) various macros in c++config.h
In your case configure determined that the POSIX nanosleep() function is not available and the macro is not defined.  However, as you say, nanosleep() is available on your system. The reason it's not enabled by configure is that the checks for it don't even run unless you use the --enable-libstdcxx-time option (documented in the Configuration chapter of the libstdc++ manual, not the GCC configure docs)

*

*Is there a configuration option that should be used when building GCC to activate this macro by default, as suggested by this post? (I couldn't find any in the online documentation of the build process.)

Yes, --enable-libstdcxx-time

*

*Is there really a relation between the nanosleep() function and the macro? The declaration of nanosleep() in ctime/time.h does not seem to depend on, or define, the macro.

The declaration of glibc's function doesn't depend on libstdc++'s macro, no.  But the macro tells libstdc++ whether to use the function or not.

*

*Is there any specific risk involved in defining the macro in my own header files, or as a -D option on the command line (as suggested in this related question)? What if I do this on a system where nanosleep() is not available, and how can I actually find out?

It's naughty and is unsupported, but will work. The macro is an internal implementation detail that should be set by configure and not by users and changing the definition of the implementation's internal macros can break things.  But in this case it won't because the only code that depends on it is in a header, no library code in libstdc++.so is affected.
But it would be better to reinstall GCC and use the --enable-libstdcxx-time option, or if that's not possible edit your c++config.h to define the macro to true.
If you define it on a different system where nanosleep() isn't available you'll get a compilation error when you #include <thread>.
I have some ideas for improving that configuration, so nanosleep() and sched_yield() will be checked for by default, but I haven't had time to work on them yet.
Update: I've committed some changes so that building GCC 4.8 without --enable-libstdcxx-time will still define std::this_thread::yield() (as a no-op) and will implement std::this_thread::sleep_for() and std::this_thread::sleep_until() using the lower resolution ::sleep() and ::usleep() functions instead of ::nanosleep().  It's still better to define --enable-libstdcxx-time though.
Another update: GCC 4.9.0 is out and now defaults to automatically enabling nanosleep and sched_yield on platforms that are known to support them. There is no longer any need to use --enable-libstdcxx-time.


Q: Apachebench making more requests than I ask for I am trying to use apachebench to make a number of requests to test my server.  However it often times makes a ton more requests than I ask for.  I am using this to test a node.js server which uses express.
ab -n 1 http://myserver/

It seems finicky as sometimes it will make only one request, but other it will make 10s to 100s of requests.  The bad part is that it still just reports it made only one request.  Am I doing something wrong?  Does this have anything to do with node.js being asynchronous?
Anyone else had problems using 'ab' to benchmark a node.js server?

A: Looks like a problem with ab on OSX Lion:
http://simon.heimlicher.com/articles/2012/07/08/fix-apache-bench-ab-on-os-x-lion
That fixed my problem.


Q: how to download and install an APK file by an intent? I am making my app to be updated via my own file server instead of Google Play-store. However, it does not work well. After confirming to "update", APK file is downloaded, it is not opened correctly. Please check the demonstration https://youtu.be/qDSGZ9fQ1Oo
class MainActivity : Activity() {
    private fun checkUpdate(){
        val jsonObjectRequest = JsonObjectRequest(
            Request.Method.GET,
            "https://myserver/release.json",
            null,
            Response.Listener { response ->
                if(response.getInt("version") > versionCode){
                    val builder = AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert)
                    builder.setTitle("Update to v" + response.getString("version") + " ?")
                    builder.setMessage(response.getString("note"))

                    builder.setPositiveButton("Yes") { _, _ ->
                        downloadUpdate(response.getString("version"))
                    }

                    builder.setNegativeButton("No") { _, _ ->
                        showUserInteraction()
                    }

                    builder.setCancelable(false)

                    builder.show()
                }else{
                    showUserInteraction()
                }
            },
            Response.ErrorListener{ _ ->
                showUserInteraction()
            }
        )

        requestQueue.add(jsonObjectRequest)
    }

    private fun downloadUpdate(versionCode: String) {
        registerReceiver(onDownloadComplete(), IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))

        val request = DownloadManager
            .Request(Uri.parse("https://myserver/app-release.apk"))
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myapp_v" + versionCode + ".apk")

        downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
        downloadId = downloadManager.enqueue(request)
    }

    private class onDownloadComplete: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val c = downloadManager.query(DownloadManager.Query().setFilterById(downloadId))
            if(c != null){
                c.moveToFirst()
                val fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
                val mFile = File(Uri.parse(fileUri).path!!)
                val fileName = mFile.absolutePath

                context.unregisterReceiver(this)

                val intent = Intent(Intent.ACTION_VIEW)
                var contentUri: Uri
                if (SDK_VER >= Build.VERSION_CODES.N) {
                    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", File(fileName))
                }else{
                    contentUri = Uri.fromFile(File(fileName))
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }

                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
                startActivity(context, intent, null)
            }
        }
    }
}

May anyone please point out my mistake? Thanks.

A: You need to add below permission in your manifest.xml file.
If an app uses a targetSdkLevel of 26 or above and prompts the user to install other apps, the manifest file needs to include the REQUEST_INSTALL_PACKAGES permission:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

You can see below link why it's needed

*

*Link1

*Link2


Q: why is that there is a dark area around the buttons when they are tapped on mobile devices the code is: https://codesandbox.io/s/gatsby-starter-default-og782
I used styled-component to style a <a> tag to be my button.
for example,
const CloseButton = styled.a`
  position: relative;
  font-size: 30px;
  top: 30vh;
`

And I implemented a hover effect with the <a> tag with transform: translateY(-3px);
  a {
    outline: none;
    font-size: ${fontSizes.medium};
    ${media.phablet` font-size: ${fontSizes.small};`}
    font-weight: 500;
    display: inline-block;
    text-decoration: none;
    text-decoration-skip-ink: auto;
    color: inherit;
    position: relative;
    transition: ${theme.transition};
    cursor: pointer;
  margin: 0 auto;
  padding: 7px;
    &:hover,
    &:focus
     {
    transform: translateY(-3px);
    }
    -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;

  }

Now it works fine on desktop. But when I view it on mobile devices(you can try the demo here https://og782.sse.codesandbox.io/)
There is a dark area around the buttons when they are tapped
Could someone please help me to get rid of this?

A: Most likely this is because of -webkit-tap-highlight-color
You can try to make a transparent style:
a {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}


Q: Identify all objects of given class for further processing Assume you are working with a large working environment and you aren't great about keeping up with your environment variables, or you have some process that generates a lot objects automatically. Is there a way to scan your ls() to identify all objects that have a given class? Consider the following simple example:
#Random objects in my environment
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)

#I estimate some linear models for fun.
lm1 <- lm(y ~ x)
lm2 <- lm(y ~ z)
lm3 <- lm(y ~ x + z)

#Is there a programmatic way to identify all objects in my environment
#that are of the "lm" class? Or really, any arbitrary class?
outList <- list(lm1, lm2, lm3)

#I want to look at a bunch of plots for all the lm objects in my environment.
lapply(outList, plot)

A: Use the class function:
Models <- Filter( function(x) 'lm' %in% class( get(x) ), ls() )
lapply( Models, function(x) plot( get(x) ) )

(Modified slightly to handle situations where objects can have multiple classes, as pointed out by @Gabor in the comments).
Update. For completeness, here is a refinement suggested by @Gabor's comment below. Sometimes we may want to only get objects that are of class X but not class Y. Or perhaps some other combination. For this one could write a ClassFilter() function that contains all of the class filterling logic, such as:
ClassFilter <- function(x) inherits(get(x), 'lm' ) & !inherits(get(x), 'glm' )

Then you get the objects that you want:
Objs <- Filter( ClassFilter, ls() )

Now you can process the Objs whatever way you want.

A: You can use Filter with inherits and ls in mget to get a named list of in this case of lm objects.
L <- Filter(\(x) inherits(x, "lm"), mget(ls()))
#L <- Filter(\(x) inherits(x, "lm") & !inherits(x, "glm"), mget(ls())) #In case glm need to be excluded

identical(unname(L), outList)
#[1] TRUE

lapply(L, plot)


Q: Spark SQL take 4 consecutive time intervals it's my table:
+--------+----+----------+----+
| station|temp|     dateS|hour|
+--------+----+----------+----+
|Roma    | 2.2|2018-10-02|   1|
|Roma    | 1.5|2018-10-02|   2|
|Roma    | 1.4|2018-10-02|   3|
|Roma    | 1.4|2018-10-02|   4|
|Milano  | 0.6|2018-11-02|  12|
|Milano  | 1.0|2018-11-02|  13|
|Napoli  | 0.3|2018-12-02|  20|
|Napoli  | 0.0|2018-12-02|  21|
|Napoli  | 1.8|2018-12-02|   4|
|Napoli  | 2.0|2018-12-03|   5|
|Napoli  | 1.8|2018-12-03|   6|
+--------+----+----------+----+

I want take the station that are present in record for 4 hours consecutive(4 consecutive hours obviously on the same day).
For example only show Roma because there are 4 consecutive hour in the same day(2018-10-02)...
I try to write the query but nothing...

A: I have tried using lead window function. I arranged the dataframe by partitioning on station and dateS and ordering by hour and calculated the difference with the previous hour. If we are considering for 4 consecutive hours, there should be three 1's in the difference column one after another. To find out that, I have collected all the diffs based on station and dateS and checked if it contains " 1 1 1 ". The code for the same is shown below. I hope it is helpful.
//Creating Test Data
  val df = Seq(("Roma",2.2,"2018-10-02",1 )
    , ("Roma",1.5,"2018-10-02",2 )
    , ("Roma",1.4,"2018-10-02",3 )
    , ("Roma",1.4,"2018-10-02",4 )
    , ("Milano",0.6,"2018-11-02",12 )
    , ("Milano",1.0,"2018-11-02",13 )
    , ("Napoli",0.3,"2018-12-02",20 )
    , ("Napoli",0.0,"2018-12-02",21 )
    , ("Napoli",1.8,"2018-12-02",4 )
    , ("Napoli",2.0,"2018-12-03",5 )
    , ("Napoli",1.8,"2018-12-03",6))
    .toDF("station", "temp", "dateS", "hour")

  val filterDF = df.withColumn("hour_lead", lead($"hour", 1)
                   .over(Window.partitionBy("station","dateS")
                               .orderBy(col("hour")))
                   .filter($"hour_lead".isNotNull)
                   .withColumn("hour_diff", $"hour_lead" - $"hour")
                   .groupBy("station","dateS")
          .agg(collect_list($"hour_diff".cast("string")).as("hour_diff_list"))
          .withColumn("hour_diff_list_str",
                      concat(lit(" "),
                      concat_ws(" ", $"hour_diff_list"),
                      lit(" ")))
          .filter($"hour_diff_list_str".contains(" 1 1 1 "))

  filterDF.show(false)
  +-------+----------+--------------+------------------+
  |station|dateS     |hour_diff_list|hour_diff_list_str|
  +-------+----------+--------------+------------------+
  |Roma   |2018-10-02|[1, 1, 1]     | 1 1 1            |
  +-------+----------+--------------+------------------+


Q: Internet Explorer 9 in compatibility-mode shows error While testing my jQuery script in IE 9 it shows error in jquery-1.6.2.js --
SCRIPT5022: Exception thrown and not caught
jquery-1.6.2.js, line 548 character 3

My js file used to work with no problems in other browsers - firefox 3.6, 5.0, opera 11, chromium, chrome. I do not understand. Is there a bug in the jquery source or is there a bug in my js file ? How do I find it ?
It hasen't been long since I started in this area so please I would really appreciate some ideas.
Thank you in advance.
[edited]
I've added the complete code.
I've learnt from :
 http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-jquery-image-cropping-plug-in-from-scratch-part-ii/
I don't know which part to add. The whole code does not fit in stackoverflow's submit. says "body is limited to 3000 characters; you entered 42121 "
[2nd edit]
I have used 'error' in my ajax submit.
    //jquery ajax submit for resizing
    function submit(myform,e){
        $n.val($image.attr('src').replace(/^[^,]*\//,''));

        var mydata = myform.serialize();
        $.ajax({
            url: $myform.attr('action'),
            cache: false,
            type:$myform.attr('method'),
            data: mydata,

            success: function(response){
                var img = $("<img />").attr('src', 'images/'+response+'?'+ e.timeStamp) //<-- img name here
                    .load(function() {
                       if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                           alert('Incorrect image.');

                       } else {
                           $("#result").html(img); //<-- put cropped img here.

                       }
                    });

                    },
            error: function(){ //<-- error used here
                        $('#result').html("Err. Loading Image");
                    }
        });
    };

A: I traced out my problem. IE prevented changing of attribute which let to the jQuery error.
 Note: jQuery prohibits changing the type attribute on an or element and
 will throw an error in all browsers. This is because the type attribute
 cannot be changed in Internet Explorer."

from http://api.jquery.com/attr, just after 1st warning notice.
So I changed my code from earlier
$('input').clone()

to
$('<input />').attr({'type':'hidden'})

and it solved my problem.
Thanks everyone.

A: Just a guess, but do you somewhere use $.error() inside your code? If yes: don't use it.

<edit>

However, this error comes from jQuery.error().
The original error-function looks like this:
error: function( msg ) {
        throw msg;
    }

You may test it without jquery:
(function( msg ) {
        throw msg;
    })('errormessage');

You'll get the same error.
If you don't use jQuery.error() maybe you use some plugin that uses it.
You may override this (buggy?) function by executing the following right after the embedded jquery.js:
jQuery.error=function(){}

</edit>

A: jQuery.error() (which throws the message passed as an argument), is totally different to the error handler specified in an AJAX call.
jQuery.error() is used internally by jQuery (search for "error("). You should debug your code and follow the stack trace to find which of your methods is calling the jQuery method which is erroring.


Q: Fedlet Service Provider and CA Siteminder Identity Provider Has anyone used Fedlet as their service provider and CA Siteminder as their identity provider? Our client is using CA Siteminder Federation Security services and we need to configure our end to be a service provider that can accept SAMLv2 assertions with attribute mapping. Is the IDP iniatiated SSO possible with this setting?
I was only able to make Fedlet work with an OpenSSO identity provider, but not with the CA Siteminder. The client only gave the idp and sp ID to use, their metadata, protocol and binding standard and nothing else. I gave them our Assertion consumer service URL (I got from the sp.xml on our Fedlet conf) and the relay state url where we will redirect the user upon successful login on their side.
Or do you recommend a different technology to use as a service provider for the CA siteminder IDP?
Please advise.

A: The Fedlet is pretty bare bones and was designed by Sun (now Oracle) to work with OpenSSO as the IDP. While it is probably compliant to some degree, I would imagine that it may not be a full implementation of SAML 2.0 SP-Lite but a sub-set of that.
I'd check out PingFederate from PingIdentity if you are looking for a more robust option. We have dozens of SPs who are integrating with CA SM FSS as the IDP (and vice versa) using SAML 1.x and 2.0. It has a very light footprint, can support a multitude of development languages/platforms and can be setup and in Production extremely quickly.
HTH - IanB

A: If you already have a SiteMinder installation setup then SMFSS is the fastest, easiest and most robust solution, IMHO but then I support it. I am able get new customers up and running in less than a day for SAML 2.0 POC when they already have a working SiteMinder architecture in place and there are no known issues with OpenSSO.  If you have a particular issue you should give a fiddler trace with HTTPS decryption enabled and logs so we can assist.  Also, the R12 SP3 or SM6 SMFSS docs have the chapter on what settings need to match, the setting up the IDP and SP for SAML 2.0 chapters which are step by step as long as you have the settings for the matching values chapter which is the second to last chapter and chapter number changes depending on version of the docs.
You can also do Authorization on the SP side using the Attribute Authority we provide if your SP implements the Attribute Query SAML specification. In other words, if there was no attribute authority then you would need to store attributes on the SP side for use later. With that being said, if you used an SMFSS (SiteMinder Federation Security Services) SP you could use the Session Store on the SP side and store the assertions attributes there at authentication time. Let me know if you have any more questions on this.  The thing I like about SMFSS is you really get a good idea of what your doing and can become quite proficient where a lot of other products seem to use a lot of the MetaData to add stuff into their UI's which IMHO results in people not really understanding the federation that they are setting up and administering.
I am wondering if IanB is my old co-worker Ian Barnett of Ping?  If so hello!!!
Crissy Krueger Stone
SiteMinder Support est. 5/1/2000


Q: How to remove a large number of rows from Excel spreadsheet based on time? I have an Excel spreadsheet with over 44,000 rows (sensor readings taken each minute for a month). I want to reduce them to every 15 minutes.

I want to remove rows where Time -column does not end in :
01
16
31
46

A: We can do something using two main figures:

*

*openpyxl package to retrieve the data from the Excel sheet.

pip3 install openpyxl

*String Operation to compare the value if its == 15 minutes:

*Insert into a list.

*If you want to appened it into the Excel sheet, again. Please, check this reference writing into Excel using openpyxl
# importing openpyxl module
import openpyxl

# Give the location of the file
path = "C:\\Users\\Admin\\Desktop\\demo.xlsx"

# workbook object is created
wb_obj = openpyxl.load_workbook(path)

sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
aList = []
# Loop will print all values
# of first column
for i in range(2, m_row + 1):
    cell_obj = sheet_obj.cell(row = i, column = 1)
    if (cell_obj.value[:-2] == 15):
        aList.append(cell_obj.value)

For more information about openpyxl, please check this hyperlink;
How to read from Excel sheet using openpyxl

A: I managed to find a solution using Python, so this is no longer an issue.  Thank you.
data2 = data.set_index('Time').resample('15T').mean()
data2


Q: Inserting arrays into SQL table from form I was trying to insert arrays from my form, let's say for example I have select with options such as A, B, C, D, E for first select group, and 1, 2, 3, 4, 5 for second select group. When selecting options from these two select group, I should have the values to be inserted as:

letter
number

A
1

B
1

A
2

B
2

There's also a default number of 0 to be included during insertion.
I have tried this code I have seen:
    $statement = $conn->prepare("INSERT INTO letter_num_tag (default_zero, letter_tag, number_tag) VALUES (?,?,?)");
    foreach ($_POST as $row) {
        $statement->bind_param($row['default_zero_post'], $row['letter_tag_post'], $row['number_tag_post']);
        $statement->execute();
    }

However, this will result in this error:
Uncaught TypeError: trim(): Argument #1 ($string) must be of type string, array given

This is what my form submit looked like:
$default_zero_var = $_POST["default_zero_post"];
$letter_tag_var = $_POST['letter_tag_post'];
$number_tag_var = $_POST['number_tag_post'];

if (empty(trim($_POST["letter_tag_post"]))) {
    $letter_tag_var_err = "Please enter event date.";
} else {
    $letter_tag_var = trim($_POST["letter_tag_post"]);
}

if (empty(trim($_POST["number_tag_post"]))) {
    $number_tag_var_err = "Please enter event date.";
} else {
    $number_tag_var = trim($_POST["number_tag_post"]);
}

My form looks like this:

A
<input type='checkbox' name='letter_tag_post[]' value='A'>

B
<input type='checkbox' name='letter_tag_post[]' value='B'>

C
<input type='checkbox' name='letter_tag_post[]' value='C'>

D
<input type='checkbox' name='letter_tag_post[]' value='D'>

E
<input type='checkbox' name='letter_tag_post[]' value='E'>

1
<input type='checkbox' name='number_tag_post[]' value='1'>

2
<input type='checkbox' name='number_tag_post[]' value='2'>

3
<input type='checkbox' name='number_tag_post[]' value='3'>

4
<input type='checkbox' name='number_tag_post[]' value='4'>

5
<input type='checkbox' name='number_tag_post[]' value='5'>

Help is greatly appreciated. Thanks!


Q: textfield Validation in blackberry java i am validating a password field where it has to contain atleast one capital letter and one number.i used below code but its not working?
for (int i = 0;i<Password.getText().length(); i++) {

        char i1 = Password.getText().charAt(i);
        boolean valid;
    if ( valid=(i1!='A'||i1!='B'||i1!='C'||i1!='D'||i1!='E'||i1!='F'||i1!='G'||i1!='H'||i1!='I'||i1!='J'||i1!='K'||i1!='L'||i1!='M'||i1!='N'||i1!='O'||i1!='P'||i1!='Q'||i1!='R'||i1!='S'||i1!='T'||i1!='U'||i1!='V'||i1!='W'||i1!='X'||i1!='Y'||i1!='Z')&&(i1!='1'||i1!='2'||i1!='3'||i1!='4'||i1!='5'||i1!='6'||i1!='7'||i1!='8'||i1!='9'||i1!='0')) {

        if(valid=true){
                return true;
            }else{
            return false;
            }
        }

    }

A: If your password must have at least one capital letter and at least one number your logic is wrong. You should have two booleans.
boolean hasCapitalLetter = false;
boolean hasNumber = false;

for (int i = 0;i<Password.getText().length(); i++) {
    char i1 = Password.getText().charAt(i);

    if (!hasCapitalLetter) {
        hasCapitalLetter = Character.isUpperCase(i1);
    }
    if (!hasNumber) {
        hasNumber = Character.isDigit(i1);
    }
    if (hasCapitalLetter && hasNumber) {
        return true;
    }
}

return false;


Q: How do I return a value from my Node.js module AFTER it has been updated by an async function? Forgive me, but as an extremely new developer I fail to see how this is an exact duplicate of the questions referred to. I have no idea what ajax is, and I certainly don't understand how to adapt the proposed solutions to work in my situation.
I'm writing a very simple node app that gets a stock price from a web api, get a currency conversion value from another web api, and converts the stock price from USD to AUD. I had this working perfectly in a single file, but I've chosen to split it out in to several modules to make it easier. And now I've broken it :)
Basically I pass the ticker I wish to lookup into my GetStockPrice() function, which then perform the necessary query and returns the result.....in theory.
This is how I call my module:
var returned = GetStockPrice('AMZN');
console.log(returned);

The returned value is always 10, as it's not being updated in my GetStockPrice module.
Here is the code in my module:
var http = require('http');
var stockPrice = 10;

function GetStockPrice(ticker) {
  var options = {
    host: 'dev.markitondemand.com',
    port: 80,
    path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker,
    method: 'GET'
  };
  http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      const json = JSON.parse(chunk);
      stockPrice = json.LastPrice;
    });
  }).end();

  return (stockPrice)

};

module.exports = GetStockPrice;

I understand what I'm doing wrong, the http.request is being run asynchronously, so by the time my function gets to the return statement, the async call hasn't completed, so my return value, stockPrice, is still the same as when I first initialized it. Unfortunately, I don't know how to fix it. I tried moving the return statement inside the http.request function, but that doesn't work either.
Can anyone help please?

A: You can use callback to get response from asynchronous functions.
var http = require('http');
var stockPrice = 10;

function GetStockPrice(ticker, callback){
   var options = {
      host: 'dev.markitondemand.com',
      port: 80,
      path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker,
      method: 'GET'
   };
   http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      res.setEncoding('utf8');
      var stockPrice='';
      res.on('data', function (chunk) {
        stockPrice = stockPrice + chunk;
      });
      res.on('end', function(){
          return callback(JSON.parse(stockPrice));
      });
   });
};

module.exports = GetStockPrice;

And
GetStockPrice('AMZN', function(data){
   console.log(data);
});

Pardon me, if there are any typos.


Q: Block all personal sites in Sharepoint (Microsoft cannot help) Is there a way to lock all personal sites.
I found a script to block one site
$siteUrl = "https://xxx-my.sharepoint.com/personal/adelev_xxx_onmicrosoft_com"
$site = Get-SPOSite $siteUrl -Detailed
Set-SPOSite $site -LockState NoAccess

It works, but I have hundreds of sites to block. First I would need to list all sites and then one by one block them.
Hello,
Is there a way to automate it and BLOCK all sites?
I want to lock sites temporarily. This lock prevent users that has a personal site to use them (new ppl are blocked by MySite setting).
I contacted Microsoft directly and they provided me with some data - they told me that I should use ForEach, but I have no idea how to use it, and they won't help me any further cause it is against some policy.

A: To sum up, what you need is to:

*

*Get all personal sites

*Run Set-SPOSite for each of them using any mechanism like foreach
Here's helpful article for 1: Get a list of all user OneDrive URLs in your organization. So, you need to run something like:
$allSites = Get-SPOSite -IncludePersonalSite $true -Limit all -Filter "Url -like '-my.sharepoint.com/personal/'" | Select -ExpandProperty Url

And for 2. you can use something similar to:
foreach ($site in $allSites) {
  Set-SPOSite -Identity $site -LockState NoAccess
}

A: Here's what I came up with to get all sites that are locked.  It includes all information fields.  Change the export path to a destination that's appropriate for you:
Get-sposite -includepersonalsite $true -Limit ALL -Filter "LockState -like 'NoAccess'" |Export-csv -Path 'C:\PowerShell\OneDriveSitesLocked.csv' -Delimiter ',' -NoTypeInformation


Q: Using structs as arguments: Error: Struct not defined I am creating a class where I defined a Struct called "Room" which I declare as private in the header file. I have several public functions that require a "Room" as an argument. When I compile (in g++) I get an error saying:
Graph.h:42:17: error: "Room" has not been declared

Yet here lies the declaration (whole header file now):
#ifndef GRAPH_H
#define GRAPH_H

#include <iostream>
#include <string>
using namespace std;

class Graph {

public:

    // destructor
    ~Graph();

    // copy constructor
    Graph(const Graph &v);

     // assignment operator
     Graph & operator = (const Graph &v);

    //Create an empty graph with a potential
    //size of num rooms.
     Graph( int num );

        //Input the form:
    //int -- numRooms times
    //(myNumber north east south west) -- numRooms times.
    void input(istream & s);

    //outputs the graph as a visual layout
    void output(ostream & s) const;

    //Recursively searches for an exit path.
    void findPath( Room start );

    //Moves room N E S or W
    void move( Room &*room , String direction );

    //inputs the starting location.
    void inputStart( int start );

    //Searches the easyDelete array for the room with the
    //number "roomNumber" and returns a pointer to it.
    const Room * findRoom( int roomNumber );

private:

    struct Room
    {
        bool visted;
        int myNumber;

        Room *North;
        Room *East;
        Room *South;
        Room *West;
    };

    int numRooms;
    int _index;
    int _start;

    Room ** easyDelete;
    string * escapePath;

    Room * theWALL;
    Room * safety;
};

#endif

Are you not allowed to use structs defined inside the header file as arguments? If so, what's the workaround?
Thanks.

A: It compiles fine without the private: header. Why do you have this? Is the struct declared inside of a class?
EDIT
You have used Room before you declare it:
const Room * findRoom( int roomNumber );

Also, you can't return a Room object through the public method you have declared, since outside code won't know anything about it.
You need to predeclare it before using it:
class Graph {

public:

struct Room;

const Room * findRoom( int roomNumber );

struct Room
{
    bool visted;
    int myNumber;

    Graph::Room *North;
    Graph::Room *East;
    Graph::Room *South;
    Graph::Room *West;
};

Room room;
};

int main (){

  Graph x;

  return 0;
}

Or you could just move the second private up, above the public section.

A: If you are using a nested struct as an argument to a mthod of the containing class, then you must use the fully-qualified name such as void outerclass::mymethod(outerclass::room); Try that. You may need to make it public too.

A: *

*Room cannot be private since you use it in your public member functions.

*Either forward declare it like this :
struct Room;
// destructor
~Graph();

*Or just declare and implement it before you use it at the top of the class.

*void move( Room &*room , String direction ); //this is not valid C++

A: You have to declare any type before using it. A forward declaration suffices because you are defining Graph::Room in the same scope. However, since you have to define it anyway, I would suggest moving it up to some point before first using it.
Making Room private within Graph is perfectly legal (it is questionable if it is reasonable, though, if your public interface fumbles with it).
On a side note: Pointers to references are no valid types (references to pointers are!). Your move function is therefore invalid.


Q: gradle cannot compile, but final Annotation var is not syntax error Using gradle 4.10.2
@Table
public class MyClass{
    public static final String COL_NAME = "name";
    public static final String COLTYPE_NAME = DB.DataType.VARCHAR;
    @Column(name = COL_NAME, columnDefinition = COLTYPE_NAME)
    private String name;
}

This should not be a syntax error, but when I run gradle clean publishtomavenlocal, I get

@Column(name = COL_NAME, columnDefinition = COLTYPE_NAME) error: element value must be a constant expression

                                             ^

the above is pointing at COLTYPE_NAME.
DB.DataType.VARCHAR is defined as
public final class DB{
    public static final class DataType{
        public static final VARCHAR = "varchar";
    }
}

How to fix this problem with gradle?


Q: C++: Issues with manipulating a PPM file I'm working on a program that can perform various effects and manipulations on a PPM file. However for testing reasons, it uses cin rather than an input file. It is supposed to be able to perform multiple effects at once, but I am having trouble even getting one right. I'll run a removeBlue() on a line that will work, then try again with different values and it will remove red or green instead. That sort of thing. There's a lot of code, so I'll try to include only what is necessary.
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

class SimpleImageEffect
{
public:
    virtual void processImage(vector<Point> &points) = 0;
};

class RemoveRed : public SimpleImageEffect
{
public:

    virtual void processImage(vector<Point> &points)
    {
        for (Point& p : points)
        {
            p.setRed(0);
        }
    }
};
//Just an example of one of the effect classes.
//The code in them is correct, so I won't include the others unless needed.

vector<Point> parse_line(string line)
{
    istringstream scanner{line};
    vector<Point> result{};
    int red = -1;
    int green = -1;
    int blue = -1;
    int counter = 0;

    while(scanner.good())
    {
        if (counter == 0)
        {
            counter++;
            scanner >> red;
        }
        else if (counter == 1)
        {
            counter++;
            scanner >> green;
        }
        else if (counter == 2)
        {
            scanner >> blue;
            Point p{ red, green, blue };
            result.push_back(p);
            counter = 0;
        }
    }
    return result;
}

void readFromCin()
{
    string line = "";

    vector<string> lines_in_file{};
    int i, effect_choice;
    SimpleImageEffect *effect = nullptr;

    getline(cin, line);

    while (line.length() > 0)
    {
        lines_in_file.push_back(line);
        getline(cin, line);
    }

    for (int i = 0; i < lines_in_file.size(); i++)
    {
        if (lines_in_file[i] != "P3")
        {
            effect_choice = strToInt(lines_in_file[i]);
        }

        else if (lines_in_file[i] == "P3")
        {
            cout << lines_in_file[i] << endl;
            cout << lines_in_file[i+1] << endl;
            cout << lines_in_file[i+2] << endl;
        }

        vector<Point> points = parse_line(lines_in_file[i]);

        if (effect_choice == 1) effect = new RemoveRed;
        if (effect_choice == 2) effect = new RemoveGreen;
        if (effect_choice == 3) effect = new RemoveBlue;
        if (effect_choice == 4) effect = new NegateRed;
        if (effect_choice == 5) effect = new NegateGreen;
        if (effect_choice == 6) effect = new NegateBlue;
        if (effect_choice == 7) effect = new AddNoise;
        if (effect_choice == 8) effect = new HighContrast;
        if (effect_choice == 9) effect = new ConvertToGrayscale;

        effect->processImage(points);

        for (auto p : points)
        {
            cout << p;
            cout << endl;
        }
    }
}

int main(int argc, char** argv)
{
    string menu_choice;
    getline(cin, menu_choice);
    if (menu_choice == "1")
    {
        readFromFile();
    }
    else
    {
        readFromCin();
    }
    return 0;
}

So for example, running it with an input of
2
1
P3
1 1
255
50 50 50

will return
P3
1 1
255
0 50 50

but if I run it with
2
3
P3
1 2
255
50 50 50
1 2 3

it returns
P3
1 2
255
0 50 50
0 2 3

I have absolutely no idea what's causing the issue, so any help at all would be greatly appreciated. Thanks.

A: Your algorithm logic structure smells a lot, this is what I see:

*

*read all non empty lines into lines_in_file (looks good to me)

*for EVERY line (problematic, requires additional logic in inner loop):

*

*if not "P3", try to parse [EVERY] line as integer and set effect_choice (it's not clear from your code, what happens on lines where several integers are provided, but judging from your problem description the first integer is successfully parsed by strToInt function)

*if "P3", the current line and next two are copied to output

*[EVERY] line is parsed as vector of triplets of numbers

*effect is set by new effect for actual value of effect_choice (for EVERY line, also you don't delete the effect at end, so you are leaking memory in per-line counts. Also your current effects look like they may be implemented as static functions of "process" function type, so you don't need to allocate each of them, just store the particular memory address of requested function. And you call it processImage, while you are processing only line, not whole image.

*effect is run for current line triplets

*the line triplets are outputted

*loop to next line (!)

So for example for input:
2
3
P3
1 2
255
50 50 50
1 2 3

I believe (can't run it, as you didn't provide lot of code) this happens:
lines are read, and per particular line this happens:
line "2": effect_choice = 2, effect = RemoveGreen, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed (ie nothing).
line "3": effect_choice = 3, effect = RemoveBlue, zero triplets parsed into points, RemoveBlue::processImage() run over empty vector, empty vector printed.
line "P3": Lines: {"P3", "1 2", "255"} are printed, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed.
line "1 2": effect_choice = 1, effect = RemoveRed, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed.
line "255": effect_choice = 255, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed.
line "50 50 50": effect_choice = 50, one triplet {50, 50, 50} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 50, 50}.
line "1 2 3": effect_choice = 1, effect = RemoveRed, one triplet {1, 2, 3} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 2, 3}.
All of this should be clearly visible in debugger, while stepping over the code, so you probably are not debugging it, which gets downvoting the question from me, and you will pay in tremendous pain over time, as debugging without debugger is lot more difficult.
Also writing code without thinking about algorithm and code architecture makes the need of debugging lot more likely, so you wasted even more time here, by starting by writing the code.
You should have first design some algorithm and code architecture (what data are processed, how, when new memory is needed, how it will be freed, where the code need to loop, where it need to skip over, or run only once, etc).
Write only overview of how it will work into single-line comments, then split too generic comments into simpler steps until they can be implemented by few lines of C++ code, and move/modify them around until you feel the wanted algorithm will be implemented with minimal "cruft" added (most of the comments does, what is really requested, like "set red in point to zero", and any processing/preparations/moving/etc is minimized only to cases where you can't avoid it by smarter design). (for example in your current code you can read through the header of the file without looping, and start looping only after the pixel data pours in)
Then write the code, start probably with some empty function definition so you can already "run" it in debugger and verify the emptiness works, then implement the comment (or small group of them) which you feel is clear enough to be implemented and can be tested easily (no big dependency on yet-to-implement parts). Debug + test new code. If it works, try to clean up the source to remove anything not really needed, work-in-progress variable names, etc... Then verify it works in final version.
And do it again for another comment (group of), until the implementation is done.
Using unit-testing makes the write-short-code, test+debug, clean-up-source rounds even easier, especially in cases like this, where I/O are pure data, so it's easy to feed specialized test input data into test, and verify the expected output data were produced.


Q: Image processing with sub pixel accuracy I'm writing a user interface program which controls industrial machinery.
The machine is an automatic inline screen printer used in the electronic production industry. The exact purpose of the machine is to print solder paste onto bare PCBs.
The system includes 2 cameras which form a vision system used to locate fiducials and automate the process that the machinery is involved in.
The issue I have is that I need to be able to locate shapes and objects within images taken from the cameras, which is straight forward enough, but - in order to get the required accuracy I need to be able to do this with sub pixel accuracy.
The two cameras form one twin vision camera, with one camera will be looking up at a stencil, and the other looking down at a PCB. The twin vision camera is on a moving carriage that moves in X and Y. The PCB is clamped onto a table than can move in X, Y and theta. The vision system is used to detect the difference between PCB position and stencil position, and the table is then adjusted to align the two together.
EDIT:
This is a partial screen shot taken from an existing UI program:

The stencil image is the top image, the PCB is the bottom, the images here are grayscale images - in the new system I am looking at using colour but will use grayscale is required.
NOTE: As you're reading this you're probably thinking "well why don't you just use whatever you use in the existing UI?" The existing UI is written in VB6, something I want to move away from, and the vision side of the program is an .ocx written by a third party company who no longer exists.
I have played with AForge.NET a little bit and found it was really easy to use and I was able to use it to locate various different shapes and find the center of them which was great, but it doesn't have the sub pixel accuracy. However I could possibly use this as a starting point then apply a sub pixel algorithm to the individual center pixel or even the whole shape.
EDIT:
Here is a sample image taken from the test program I've written using AForge:

The red outline and crosshair is what I've added as a visual aid/ experiment. This was taken with the camera that I'm likely to use, which has a resolution of 1280 x 1024, however the lens is not the actual lens I'll use, which is why the image is slightly 'fisheyed'. Also the objects of interest will be better light than this.
In the actual system the lens will look at a 10mm x 8mm sqaure on both stencil and PCB, meaning each pixel will represent 7.8125um^2, however I can move the XYY table by increments of 1.25um at a time, which is essentially useless if I can't see those movements with the camera.
I require 1um (sub) pixel accuracy.
Does anyone know of anything I can use to do this? I have been searching for quite a while now but all I ever seem to find is information on rendering images with sub pixel accuracy.
Or, better still, does anyone know how I could write something to do this myself? I wouldn't even know where to begin!
Any feedback will be greatly appreciated.

A: new info tells a lot... I think you should be more focused on the paste application accuracy then the carriage position precision. My bet is that the printer has far bigger dot size and error then 1 um and also the desired accuracy is dependent on the PCB usage (wiring and gaps widths). Anyway I would do this:

*

*linearize image geometry
you need to de-fisheye image. As you camera/optics setup will be fixed (especially focus and distance to PCB) you should for each PCB thickness make an image of a chess board grid. then create mapping that will linearize the chessboard to real rectangles so you discard deviations before the next process.

*normalize lighting conditions

*

*see Enhancing dynamic range and normalizing illumination

*sub pixel accuracy
each pixel of the image is integration of all the stuff in its area. So if we know the 2 colors (c0,c1) of any boundary (background/foreground) then we can estimate their sub-pixel position. Let start with axis aligned rectangles. I see it like this:

Each square of the grid represents a pixel area. c0 is the gray and c1 is the green color. In the camera image you got the final color as combination of all the colors inside each pixel:

*

*c = s0*c0 + s1*c1
where c is the final pixel color and s0,s1 are area coresponding to c0,c1 colors in range <0,1> where s0+s1=1.0. Now we want to compute the s0,s1 to obtain sub-pixel precision. So first detect the pixel position on the boundary as one of these:

*

*horizontal edge

*vertical edge

*corner

this can be done by inspecting the neighboring pixels. c0,c1 can be obtained from pixels with saturated color (all neighbors have the same color) These are in inside areas pixels. I would ignore the corner pixels as their position can be obtained from nearest H/V edge pixels (it is not possible to get both x,y coordinates from the equation above). So now for each H,V edge just solve system:
I.  c = s0*c0 + s1*c1
II. s0 + s1 = 1.0;

compute the s0,s1 and the edge position for vertical edges is one of these:
x=x0 + pixel_size*s0 // if c0 is on the left
x=x0 + pixel_size*s1 // if c1 is on the left

horizontal edges are like this:
y=y0 + pixel_size*s0 // if c0 is on the top
y=y0 + pixel_size*s1 // if c1 is on the bottom

where x0,y0 is pixels top left position in pixels and the coordinate system is x+ is going to right and y+ is going down. If you got different setup just change the equations ...
Now if you got non axis aligned edges then you need to compute the slope (how many pixels it takes in one axis to change in the other dy/dx. and handle the areas accordingly:

So the only thing what changes is the conversion from computed s0,s1 to actual edge position. now you need to compute the left/right side or up/down. if you use the equation from the axis aligned example then you obtain the edge position in the middle of pixel. So you just shift it by the slope on both sides by x +/- 0.5*dx/dy or y +/- 0.5*dy/dx where dx,dy is the edge slope.

To obtain dx,dy just search along the edge for fully saturated pixels and if found then (dx,dy) is the distance between 2 closest such pixels...
[Notes]
you can do this on booth grayscale and RGB. Hope this helps a bit.


Q: Keyboard from EditText destroing Layout I have EditText, when i toutch this, keyboard will show, but instead of covering the bottom part of the application, it shifts all the elements at the top and makes them smaller, everything looks distorted ...
How do I display the keyboard so that it does not affect our layout?

A: Please check this Link:
You can add in your menifest for the activity you want to prevent such issue.
Also make sure if you are having a bit more content use scrollView as a parent.
And soft input mode as "adjustResize"
android:windowSoftInputMode="adjustResize"

or
android:windowSoftInputMode="adjustPan"

you can use as per your need.

adjustResize
to ensure that the system resizes your layout to the available space—which ensures that all of your layout content is accessible (even though it probably requires scrolling)—use this one.
adjustPan
The activity's main window is not resized to make room for the soft keyboard, and the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing.
adjustNothing
Do nothing with layouts


Q: Incrase WebView HTML5 Canvas in QT I'm porting a current HTML5 Canvas application to a QT wrapper. however its performance is quite low. This HTML5 canvas app runs at 60fps in Chrome and IE11, however it still at 10fps on QTWebView.
How can I increase the render speed of this existent HTML5 canvas application inside a QT project?
the question is about if there is any parameter to use some more fast renderer (like GPU)
Note. this project was created using the default qt creator wizard for HTML5 applications.


Q: SAML and Java Standalone application without browser? I am testing SSO with SP (Spring-SAML) and IDP (WSO2IS). They are working fine on browser.
Now I want to bring it to a Java standalone application. Providing user credentials and SP URL, then a user can log in the application and access SP.
To implement this, basically I need to use HTTPClient (for handling Cookie, POST, Redirect, Auto-POST) and follow the SAML message flow as it happens on browser.
I would like to know the most efficient way to do it. Is there any library or example?
Your help is highly appreciated.

A: I managed to create a relatively simple solution using the HtmlUnit headless browser. In my case i had to download a PDF file from a website which required SAML authentication.
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

...

private static byte[] samlAuthenticateAndDownloadFile(String url, String username, String password) throws Exception {
    byte[] fileBytes;
    try (final WebClient webClient = new WebClient()) {
      final HtmlPage loginPage = webClient.getPage(url);

      final HtmlForm loginForm = loginPage.getForms().get(0);

      final HtmlSubmitInput button = loginForm.getInputByName("login");
      final HtmlTextInput usernameField = loginForm.getInputByName("username");
      final HtmlPasswordInput passwordField = loginForm.getInputByName("password");

      usernameField.setValueAttribute(username);
      passwordField.setValueAttribute(password);

      final UnexpectedPage pdfPage = button.click();

      InputStream inputStream = pdfPage.getInputStream();

      fileBytes = IOUtils.toByteArray(inputStream);
    }

    return fileBytes;
  }


Q: Is there an edit distance algorithm that takes "chunk transposition" into account? I put "chunk transposition" in quotes because I don't know whether or what the technical term should be. Just knowing if there is a technical term for the process would be very helpful.
The Wikipedia article on edit distance gives some good background on the concept.
By taking "chunk transposition" into account, I mean that
Turing, Alan.

should match
Alan Turing

more closely than it matches
Turing Machine

I.e. the distance calculation should detect when substrings of the text have simply been moved within the text. This is not the case with the common Levenshtein distance formula.
The strings will be a few hundred characters long at most -- they are author names or lists of author names which could be in a variety of formats. I'm not doing DNA sequencing (though I suspect people that do will know a bit about this subject).

A: In the case of your application you should probably think about adapting some algorithms from bioinformatics.
For example you could firstly unify your strings by making sure, that all separators are spaces or anything else you like, such that you would compare "Alan Turing" with "Turing Alan". And then split one of the strings and do an exact string matching algorithm ( like the Horspool-Algorithm ) with the pieces against the other string, counting the number of matching substrings.
If you would like to find matches that are merely similar but not equal, something along the lines of a local alignment might be more suitable since it provides a score that describes the similarity, but the referenced Smith-Waterman-Algorithm is probably a bit overkill for your application and not even the best local alignment algorithm available.
Depending on your programming environment there is a possibility that an implementation is already available. I personally have worked with SeqAn lately, which is a bioinformatics library for C++ and definitely provides the desired functionality.
Well, that was a rather abstract answer, but I hope it points you in the right direction, but sadly it doesn't provide you with a simple formula to solve your problem.

A: Have a look at the Jaccard distance metric (JDM). It's an oldie-but-goodie that's pretty adept at token-level discrepancies such as last name first, first name last. For two string comparands, the JDM calculation is simply the number of unique characters the two strings have in common divided by the total number of unique characters between them (in other words the intersection over the union). For example, given the two arguments "JEFFKTYZZER" and "TYZZERJEFF," the numerator is 7 and the denominator is 8, yielding a value of 0.875. My choice of characters as tokens is not the only one available, BTW--n-grams are often used as well.

A: One of the easiest and most effective modern alternatives to edit distance is called the Normalized Compression Distance, or NCD.  The basic idea is easy to explain.  Choose a popular compressor that is implemented in your language such as zlib.  Then, given string A and string B, let C(A) be the compressed size of A and C(B) be the compressed size of B.  Let AB mean "A concatenated with B", so that C(AB) means "The compressed size of "A concatenated with B".  Next, compute the fraction (C(AB) - min(C(A),C(B))) / max(C(A), C(B))   This value is called NCD(A,B) and measures similarity similar to edit distance but supports more forms of similarity depending on which data compressor you choose.  Certainly, zlib supports the "chunk" style similarity that you are describing.  If two strings are similar the compressed size of the concatenation will be near the size of each alone so the numerator will be near 0 and the result will be near 0.  If two strings are very dissimilar the compressed size together will be roughly the sum of the compressed sizes added and so the result will be near 1.  This formula is much easier to implement than edit distance or almost any other explicit string similarity measure if you already have access to a data compression program like zlib.  It is because most of the "hard" work such as heuristics and optimization has already been done in the data compression part and this formula simply extracts the amount of similar patterns it found using generic information theory that is agnostic to language.   Moreover, this technique will be much faster than most explicit similarity measures (such as edit distance) for the few hundred byte size range you describe.  For more information on this and a sample implementation just search Normalized Compression Distance (NCD) or have a look at the following paper and github project:
 http://arxiv.org/abs/cs/0312044 "Clustering by Compression"
 https://github.com/rudi-cilibrasi/libcomplearn C language implementation
There are many other implementations and papers on this subject in the last decade that you may use as well in other languages and with modifications.

A: I think you're looking for Jaro-Winkler distance which is precisely for name matching.

A: You might find compression distance useful for this.  See an answer I gave for a very similar question.
Or you could use a k-tuple based counting system:

*

*Choose a small value of k, e.g. k=4.

*Extract all length-k substrings of your string into a list.

*Sort the list. (O(knlog(n) time.)

*Do the same for the other string you're comparing to.  You now have two sorted lists.

*Count the number of k-tuples shared by the two strings.  If the strings are of length n and m, this can be done in O(n+m) time using a list merge, since the lists are in sorted order.

*The number of k-tuples in common is your similarity score.

With small alphabets (e.g. DNA) you would usually maintain a vector storing the count for every possible k-tuple instead of a sorted list, although that's not practical when the alphabet is any character at all -- for k=4, you'd need a 256^4 array.

A: I'm not sure that what you really want is edit distance -- which works simply on strings of characters -- or semantic distance -- choosing the most appropriate or similar meaning.  You might want to look at topics in information retrieval for ideas on how to distinguish which is the most appropriate matching term/phrase given a specific term or phrase.  In a sense what you're doing is comparing very short documents rather than strings of characters.


Q: How can I manipulate the data in receiving CAN frame via CAPL script and forward it into the same CAN bus? For example, I'm receiving a CAN frame from ECU with id 0x100 with some data inside in CAN channel 1. I want to change only byte 7 to 0xFF and forward this frame further in channel 1. My code is below:
on message 0x100
{
  message 0x100 msg;
  msg = this;
  msg.byte(7) = 0xFF;
  output(msg);
}

But, in CAN trace, I see the message as it is, without byte 7 changed. What I do wrong? Maybe there is something that I do not understand..
I have one assumption to solve it, but this requires wiring changes to my hardware. If I make one channel for input and another channel for output, then I can use CAPL as a gateway and send frame from CAN1 to CAN2 inside one CAN-bus.
Any ideas are welcome. Thank you.


Q: Why is it not possible to shadow a local variable in a loop? I got this situation I can't understand about shadowing. For example the following code:
class Foo {
   int a = 5;
   void goFoo(int a) {
       // No problem naming parameter as same as instance variable
       for (int a = 0; a < 5; a++) { }
       // Now the compiler complains about the variable a on the for loop
       // I thought that the loop block had its own scope so I could shadow
       // the parameter, why the compiler didn't throw an error when i named
       // the parameter same as the instance variable?
   }
}

A: void goFoo(int a) {

       for (int a = 0; a < 5; a++) { }

}

it is similar to
void goFoo() {
       int a;
       for (int a = 0; a < 5; a++) { }

}

so multiple declaration of a on the same scope, it is not acceptable.
or simply it is similar to
void goFoo() {
  int a;
  int a;
}

Also See

*

*java-variable-scope-shadowing

A: You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter).
From the Java Language Specification, section 14.4.3:

If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable.

Note the "field name" part - it's specifying that it has to be a field that is shadowed.
And from section 8.4.1:

The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.
These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor.

(It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.)

A: The scope of the variable depends on the hierarchy of the block as well.
ie if u use like this
void goFoo(int a) {
       // No problem naming parameter as same as instance variable
       for (int b = 0; b < 5; b++) { }
       //Now the compiler complains about the variable a on the for loop
       // i thought that the loop block had its own scope so i could shadow
       // the parameter, why the compiler didnt throw an error when i named
       // the parameter same as the instance variable?

       int b; // you can do this.

   }

That is if a variable is declared in the outer block then you can not declare the same in the block which is inner. the other way you can do it.

A: But you don't declare the second "a" in that new scope, as your code shows.  It's in the scope of the goFoo() block itself.

A: The problem isn't that the loop is shadowing the class field, the name is already used by the parameter.
Two options:  One is to change the loop:
for (a = 0; a < 5; a++) { }

This uses the parameter as the index variable.  Not clear why you would have a parameter, but all the same...
The other option is to rename the loop variable or the parameter to something else.

A: It is not shadowing, it is a conflict here. Both a are in the method scope. One cannot define two variables of same name in the same scope.

A: In Java (unlike, say, in c++) you cannot declare a local variable when another local variable with the same name is "in scope".
You cannot do this in Java
void foo() {
    int a;
    {
         int a;  // You cannot declare 'a' here because a
                 // from the outer block is still in scope
                 // here. Local variables in Java cannot be
                 // shadowed by another local variable with
                 // the same name. Only instance variables
                 // can be shadowed by the local variables
                 // with the same name.
    }
}

However c++ allows you to do this
void foo()
{
    int a;
    a = 10;
    cout << a << endl;  // prints 10 duh
    {
        int a;   // this declaration shadows the local
                 // variable 'a' from the outer scope.

        a = 20;  // assigns 20 to the variable 'a' in
                 // current inner scope, like you'd expect.
        cout << a << endl;  // prints 20.
    }
    cout << a << endl;  // prints 10
}


Q: writing to a json file from python how do i edit/change a particular field in a json file using python code:
{
   "EZMessage":{
      "action":"account.cash",
      "data":{
         "authToken":"123456",
         "account":"#ACCOUNTID#",
         "portfolio":"true",
         "historical":"true"
      }
   }
}

in this json code, i want to replace 123456 with 789123
string replace only works if i know what is written there. in my code, i would only know what to write, and the identifier "authToken". Is there a way to overwrite the 123456 by identifying that it is the value of "authToken" ?
thanks,
RS

A: Use the json module to convert the string to a set of nested dict objects, make your changes, and then dump the dictionary back to a json string.
import json
jstr = '''{
   "EZMessage":{
      "action":"account.cash",
      "data":{
         "authToken":"123456",
         "account":"#ACCOUNTID#",
         "portfolio":"true",
         "historical":"true"
      }
   }
}'''

j = json.loads(jstr)
j['EZMessage']['data']['authToken'] = 654321
jstr = json.dumps(j)

For how to read-from/write-to a file see the fine tutorial.

A: Convert the JSON object to a Python object, then change the value just like any other Python object.


Q: Excel VBA. Matching the BackColor of a TextBox to the .Interior.Color of a cell I can't seem to find an answer for this.  I have a spreadsheet with a userform, and I'm trying to match the back colour of TextBox47 with the corresponding cell on the sheet, the value of which is fetched via a Listbox.  What I need is to be able to click on the list item, and the text box to fill with that colour.
I have the following code to colour the cells in the sheet, according to date, and with named ranges for parameters.. and this runs on UserForm Initialise()
Dim cell As Range
      With Range("data_table[Date Test]")

    For Each cell In Range("data_table[Date Test]")
        If cell.Value < Range("Today") Then
            cell.Interior.ColorIndex = 6
            ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then
            cell.Interior.ColorIndex = 3
            ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then
            cell.Interior.ColorIndex = 45
            ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 43
            ElseIf cell.Value > Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 18

         End If

    Next cell
    End With

This works fine, I then tried the following to colour the textbox
 Private Sub TextBox47_Change()
    Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
    Dim cell As Range
For Each cell In Range("data_table[Date Test]")
          With Range("data_table[Date Test]")
    Me.TextBox47.BackColor = .Interior.Color
        Next cell

    End With

I think I need to add the following somewhere..
TextBox47.Value = Me.ListBox1.List(ListBox1.ListIndex, 65)

Which is the ListBox reference for the TextBox.. but I'm starting to get very confused now.  I've been looking at this for a couple of days.

Edit to add Listbox code as asked.
    Private Sub ComboBox8_Change()

Dim i As Long

Me.ListBox1.Clear
For i = 2 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A"))
If Sheet1.Cells(i, 10).Value = Me.ComboBox8.Value Then

Me.ListBox1.AddItem Sheet1.Cells(i, 10).Value
'ID Number
Me.ListBox1.List(ListBox1.ListCount - 1, 0) = Sheet1.Cells(i, 1).Value
'Title
Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value

So would it be more something like this..
 Private Sub TextBox47_Change()
    Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
Me.TextBox47.BackColor = .Interior.Color
    End Sub

Which gives a Compile Error
1
Newer code
I've now changed it to this..
Private Sub TextBox47_Change()
    Dim cell As Range
        Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
            With Range("data_table[Date Test]")
                Me.TextBox47.BackColor = Range("data_table[Date Test]").Interior.Color
            End With
End Sub

Which at least doesn't throw up an error, but on every selection the BackColor is black.  I started with ..
Private Sub TextBox47_Change()
        Dim cell As Range
            Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy")
                With Range("data_table[Date Test]")
                    Me.TextBox47.BackColor = Range("cell").Interior.Color
                End With
    End Sub

But that just stopped at a Run Time error 1004
Yet another edit.. please tell me if continual adding to this post is the wrong way to do it.

This, when hovering over is actually picking up the correct info from the cell that I'm after (I've tried different ones to make sure), in the Listbox selection that I'm clicking on, so I guess now it's a case of telling the Interior.Colour to look at the cell that is chosen?

A: I managed to get it to work.. although not sure if it's the most elegant solution.  :)
To save confusing it with the code above, which has gotten a bit disjointed and messy, here's all the new working code and the explanation I came up with
Code to colour cells in sheet:
Dim cell As Range

      For Each cell In Range("data_table[Date Reviewed]")
        If cell.Value < Range("Today") Then
            cell.Interior.ColorIndex = 7  'Magenta
            ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then
            cell.Interior.ColorIndex = 3  'Red
            ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then
            cell.Interior.ColorIndex = 45  'Orange
            ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 4  'Green
            ElseIf cell.Value > Range("Ninety_Days") Then
            cell.Interior.ColorIndex = 19  'Beige
        End If

    Next cell

This is in UserForm_Initialize()
And then to match the cell colour with TextBox.BackColor, I've used the ListBox.ListIndex to get the date, using the following code:
Private Sub TextBox47_Change()

      Me.TextBox47.Text = Format(TextBox47.Text, "dd/mm/yyyy")

                    If (Me.ListBox1.List(ListBox1.ListIndex, 65)) < Range("Today") Then
                     TextBox47.BackColor = RGB(255, 0, 255)  'Magenta
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) >= Range("Today") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Thirty_Days") Then
                     TextBox47.BackColor = RGB(255, 0, 0)  'Red
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Thirty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Sixty_Days") Then
                     TextBox47.BackColor = RGB(255, 153, 0)  'Orange
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Sixty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Ninety_Days") Then
                     TextBox47.BackColor = RGB(0, 255, 0)  'Green
                ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Ninety_Days") Then
                     TextBox47.BackColor = RGB(255, 255, 204)  'Beige
        End If

     End Sub

I can now call that TextBox.BackColor to set the associated Interior.Color of any other cell I'm forwarding on that value to, such as the Report I'm generating in Sheet2:
Sheet2.Range("D105").Value = Me.TextBox47.Text
Sheet2.Range("D105").Interior.Color = Me.TextBox47.BackColor

Thankyou for your help and patience.  It was your comment "So you have a listbox which returns a date" which helped me to see where I was actually getting the date from when hovering over the line of code, rather than it seeing a particular Cell.Address, and hence how I got the above to work.
Again, thankyou, and I hope I didn't break too many posting rules in the meantime.  :)
Apologies, but I couldn't see a thanks button anywhere.
Cheers
Liam


Q: Getting Started with EC2 Container Registry This is giving me a headache.
Here's what I've done so far

*

*Created an EC2 Virtual Server Instance, and its running

*Installed the AWS CLI

*Installed Docker on my EC2 Virtual Server after I SSH'd into it

So looking at the docs it tells you how to build an image.  Now comes my confusion.
Question 1: So am I right by assuming that one basically have an option to a) build an image off your host or b) pull an image created by others from Docker Hub?
Question 2: If I'm right about Question #1 then what am I building an image ** off of** if I am not pulling one from docker hub? with the AWS docs here?
Question 3: then I see a whole different route I can take, using Docker Compose, so I'd use that instead of all this above?  This is so confusing.
EC2 Container Registry – Now Generally Available
So again, here, it tells you to install docker on the Host.  Then immediately jumps into "create an image".  Create an image off what, that host's OS?  I don't get it, I guess that's what it means OR I can pull an image from Docker Hub and not go this route?
Same here, it's talking about creating a docker image, what off the Host?
Or..maybe I'm not understanding what "image" means but I assume going this route, instead of pulling a Docker image from Docker Hub that I'm creating an image off my EC2 virtual Instance?

A: A1: No. You can't build an image off your host.
You can create an new image according to your requirement like which Operating Sytem (Ubuntu, Fedora), Stack(LAMP, LEMP) and many other things.
Or you can pull an image which will be pre-configured with all the packages like Wordpress Stack image, Magento stack image, Bitnami image which you can pull from docker-hub.
A2: As I have mentioned earlier you can build an image of any operating system you want(Ubuntu, Fedora, Debian) but not off the host.
You just need to pull image from docker-hub. e.g docker pull ubuntu will pull mininmal image of Ubuntu-14.04. And if you need specific version of Ubuntu
like Ubuntu-12.04 version e.g docker pull ubuntu:12.04 will pull minimal image of Ubuntu-12.04
A3: Docker-compose is a tool for defining and running multi-container docker applications. docker-compose conatins a compose file
in which you can configure your application services.
And finally Amazon EC2 Container Registry is little bit different thing. The Idea is the same as docker but Amazon is providing
this as a EC2 Container Service with many other functionality which docker doesn't have right now.
Hope it hepls:-)


Q: What does Qt do if an error occurs in a constructor? It is generally recommended to raise an exception if an error occurs in the constructor of a class.
In Qt, none of the classes throw an exception (as far as I know).
How does Qt handle errors that occur in constructors?

A: As you said Qt does not use exceptions, building a QObject will not fail on the Qt side (still the C++ memory allocation could fail).
What kind of error in constructor do you have in mind?
Qt will create object with an invalid state if necessary, in my opinion it is not a constructor error that should cancel the object creation but more of a not-fully-initialized-yet-to-work-well object-state.
Examples:
QRegExp regex1; // isValid() : false
QRegExp regex2("nop{"); // isValid() : false
// regex2.errorString() => "bad repetition syntax"

QSqlDatabase db; // isValid() : false

QDate date1; // isValid() : false
QDate date2(0, 0, 0); // isValid() : false
QDate date3(-1, 0, 1024); // isValid() : false

QString str1; // isNull() : true, isEmpty() : true
QString str2(""); // isNull() : false, isEmpty() : true