Gradle project sync failed. Basic functionality (e.g. editing, debugging) will not work properly on Android Studio 4.2

Question: I encountered "Gradle project sync failed" on Android Studio 4.2 and some of the class members are mostly red. I have done some troubleshooting as below.

File->Sync Project with Gradle Files
File-> invalidates caches/restart
Restart Android Studio
Clean and Rebuild
Try deleting .gradle

However, the problem still persists. What went wrong actually?
Trace logfiles:
2021-05-12 17:50:44,928 [24467617]   WARN - ues.SyncIssueUsageReporterImpl - Multiple sync failures reported. Discarding: SDK_BUILD_TOOLS_TOO_LOW
2021-05-12 17:50:44,928 [24467617]   WARN - ues.SyncIssueUsageReporterImpl - Multiple sync failures reported. Discarding: SDK_BUILD_TOOLS_TOO_LOW
2021-05-12 17:50:44,929 [24467618]   INFO - adleSyncState$SyncStateUpdater - onFailure(RESOLVE_PROJECT:5, com.intellij.openapi.externalSystem.model.ExternalSystemException: A problem occurred configuring project ':app'.)
2021-05-12 17:50:44,929 [24467618]   INFO - cState$SyncStateUpdaterService - stopTrackingTask(RESOLVE_PROJECT:5)
2021-05-12 17:50:44,929 [24467618]   WARN - e.project.sync.GradleSyncState - Gradle sync failed: A problem occurred configuring project ':app'. (3 s 326 ms)
2021-05-12 17:50:44,930 [24467619]   WARN - e.project.sync.GradleSyncState - A problem occurred configuring project ':app'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: A problem occurred configuring project ':app'.
    at org.jetbrains.plugins.gradle.service.execution.GradleExecutionErrorHandler.createUserFriendlyError(GradleExecutionErrorHandler.java:153)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:46)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.doGetUserFriendlyError(BaseProjectImportErrorHandler.java:181)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:45)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.checkErrorsWithoutQuickFixes(BaseProjectImportErrorHandler.java:59)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$1.getUserFriendlyError(GradleProjectResolver.java:798)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:745)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:720)
    at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.lambda$execute$0(GradleExecutionHelper.java:128)
    at org.jetbrains.plugins.gradle.GradleConnectorService.withGradleConnection(GradleConnectorService.java:246)
    at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.execute(GradleExecutionHelper.java:114)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:142)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:64)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.lambda$resolveProjectInfo$0(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:43)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:36)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:46)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:102)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:147)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:133)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.executeImpl(ExternalSystemUtil.java:523)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.lambda$execute$1(ExternalSystemUtil.java:372)
    at com.intellij.openapi.project.DumbServiceHeavyActivities.suspendIndexingAndRun(DumbServiceHeavyActivities.java:20)
    at com.intellij.openapi.project.DumbServiceImpl.suspendIndexingAndRun(DumbServiceImpl.java:153)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:372)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4.run(ExternalSystemUtil.java:631)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:935)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcessWithProgressAsync$5(CoreProgressManager.java:442)
    at com.intellij.openapi.progress.impl.ProgressRunner.lambda$null$3(ProgressRunner.java:235)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:629)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:581)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:60)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
    at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:235)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668)
    at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.

Answer: I had faced the same problem.
Solution:
If your Android Studio version is 4.2.2 and your app contains more than one modules then make sure to keep the targetSdkVersion and compileSdkVersion as same for all your build.gradle files(including your modules).
Comment: I need a help. Can you explain this where I should check for this. I checked app level gradle file and it is OK. anywhere else?
Answer: I have just experienced this issue seemingly out of thin air, and found the cause:
I updated the google play services ads module to:
api 'com.google.android.gms:play-services-ads:20.1.0'
This causes the gradle sync to fail.
Looking into the IDEA log I found the line com.android.tools.idea.gradle.project.sync.idea.issues.SdkPlatformNotFoundException: Module: 'my-module' platform 'android-28' not found.
So I updated my-module to use the targetSdkVersion 29 and the build works again.
Comment: @Reyha: "SDK_BUILD_TOOLS_TOO_LOW" looks like the actual warning. Downgrading your AS will not help, if you plan to use update the Studio some other time. One line of the log is not enough to determine the error, though. Also, please upload and link the logfile, instead of posting it unformatted.
Comment: Thanks...Yes, I did upgrade mymodule to targetSdkVersion 29. However, It still gets stuck on the Gradle project sync failed
2021-05-12 09:49:04,807 [57078920]   INFO - s.plugins.gradle.GradleManager - Instructing gradle to use java from D:/Android studio/jre
2021-05-12 09:49:04,809 [57078922]   INFO - ativeWorkspaceModificationTask - NDK support for project 'Android_CrowdSourcing' is disabled because the project doesn't contain any valid native configurations.
Comment: @Reyha Can you upload your log file somewhere? (Help -> Show log in Files). Run the gradle sync again before copying the file. For me, the cause for the error was logged some lines above the most recent line.
Comment: Please see the above logfiles
Comment: I've found the solution. I downgraded my Android Studio from 4.2 to 4.1.2 version and no such error. Thanks McFarlane
Answer: Please Downgrade Studio Version to 4.1.3
Currently, 4.2.* versions are having the significant number of issues.
Answer: You maybe need to upgrade or downgrade your "targetSdkVersion"
i experienced the same issue and the solution was upgrading my "targetSdkVersion"


When does a map become better than two vectors?

Question: A map does binary search on all its elements, which has logarithmic complexity — this means that for a small enough collection of objects, a map will perform worse than two vectors that have linear search.
How large should the object (key) pool be for a map to start performing better than two vectors?
Edit: A more generalized version of the question: how large should the object pool be for binary search to perform better than linear search?
I'm using strings as keys and the values are pointers, but my particular use case probably shouldn't matter. I'm more curious to understand how to use the two tools properly.
Comment: There are enough variables that if this is important to you, you should do your own timing. Also note that you can do a binary search on a sorted vector.
Comment: Complexities only describe asymptotic behaviour. Any given implementation will have different concrete runtimes, as the complexity guarantees say nothing about the magnitude of the various constants. So there's really no better solution than to rig up a simple test framework and profile this on your target environment.
Comment: The question should not really be about searching, as searching a sorted vector (just like a map)) is quite quick. The question should really be about the cost of maintaining a vector in sorted order.
Comment: Why do you assume that you would be performing linear search on the vectors ? If they are sorted, it's simple enough to call `binary_search` or `lower_bound` to get O(log N) search.
Comment: @Matthieu I guess then the question becomes, how large should the object pool be for binary search to perform better than linear search?
Comment: "The usual implementation is a self-balancing binary search tree ..." http://en.wikipedia.org/wiki/Map_%28C%2B%2B%29
Comment: @Paul: I would say it would demand on what you measure. What's the cost of the comparison function compared to the cost of loading elements into the CPU cache (which depends on the elements' size and your particular architecture). Measurements usually depend on the hardware, so it's hard to foresee :x
Answer: If you'll forgive my saying so, most of the answers sound to me like various ways of saying: "I don't know", without actually admitting that they don't know. While I generally agree with the advice they've given, none of them seems to have attempted to directly address the question you asked: what is the break-even point.
To be fair, when I read the question, I didn't really know either. It's one of those things what we all know the basics: for a small enough collection, a linear search will probably be faster, and for a large enough collection, a binary search will undoubtedly be faster. I, however, have never really had much reason to investigate anything about what the break-even point would really be. Your question got me curious, however, so I decided to write a bit of code to get at least some idea.
This code is definitely a very quick hack (lots of duplication, only currently supports one type of key, etc.) but at least it might give some idea of what to expect:
#include <set>
#include <vector>
#include <string>
#include <time.h>
#include <iostream>
#include <algorithm>

int main() {

    static const int reps = 100000;

    std::vector<int> data_vector;
    std::set<int> data_set;
    std::vector<int> search_keys;

    for (int size=10; size<100; size += 10) {
        data_vector.clear();
        data_set.clear();
        search_keys.clear();

        int num_keys = size / 10;
        for (int i=0; i<size; i++) {
            int key = rand();

            if (i % num_keys == 0)
                search_keys.push_back(key);

            data_set.insert(key);
            data_vector.push_back(key);
        }

        // Search for a few keys that probably aren't present.
        for (int i=0; i<10; i++)
            search_keys.push_back(rand());

        long total_linear =0, total_binary = 0;

        clock_t start_linear = clock();
        for (int k=0; k<reps; k++) {
            for (int j=0; j<search_keys.size(); j++) {
                std::vector<int>::iterator pos = std::find(data_vector.begin(), data_vector.end(), search_keys[j]);
                if (pos != data_vector.end())
                    total_linear += *pos;
            }
        }
        clock_t stop_linear = clock();

        clock_t start_binary = clock();
        for (int k=0; k<reps; k++) {
            for (int j=0; j<search_keys.size(); j++) {
                std::set<int>::iterator pos = data_set.find(search_keys[j]);
                if (pos != data_set.end())
                    total_binary += *pos;
            }
        }
        clock_t stop_binary = clock();

        std::cout << "\nignore: " << total_linear << " ignore also: " << total_binary << "\n";

        std::cout << "For size = " << size << "\n";
        std::cout << "\tLinear search time = " << stop_linear - start_linear << "\n";
        std::cout << "\tBinary search time = " << stop_binary - start_binary << "\n";
    }
    return 0;
}

Here are the results I get running this on my machine:
ignore: 669830816 ignore also: 669830816
For size = 10
        Linear search time = 37
        Binary search time = 45

ignore: 966398112 ignore also: 966398112
For size = 20
        Linear search time = 60
        Binary search time = 47

ignore: 389263520 ignore also: 389263520
For size = 30
        Linear search time = 83
        Binary search time = 63

ignore: -1561901888 ignore also: -1561901888
For size = 40
        Linear search time = 106
        Binary search time = 65

ignore: -1741869184 ignore also: -1741869184
For size = 50
        Linear search time = 127
        Binary search time = 69

ignore: 1130798112 ignore also: 1130798112
For size = 60
        Linear search time = 155
        Binary search time = 75

ignore: -1949669184 ignore also: -1949669184
For size = 70
        Linear search time = 173
        Binary search time = 83

ignore: -1991069184 ignore also: -1991069184
For size = 80
        Linear search time = 195
        Binary search time = 90

ignore: 1750998112 ignore also: 1750998112
For size = 90
        Linear search time = 217
        Binary search time = 79

Obviously that's not the only possible test (or even close to the best one possible), but it seems to me that even a little hard data is better than none at all.
Edit: I would note for the record that I see no reason that code using two vectors (or a vector of pairs) can't be just as clean as code using a set or map. Obviously you'd want to put the code for it into a small class of its own, but I see no reason at all that it couldn't present precisely the same interface to the outside world that map does. In fact, I'd probably just call it a "tiny_map` (or something on that order).
One of the basic points of OO programming (and it remains the case in generic programming, to least some degree) is to separate the interface from the implementation. In this case, you're talking about purely an implementation detail that need not affect the interface at all. In fact, if I were writing a standard library, I'd be tempted to incorporate this as a "small map optimization" analogous to the common small string optimization. Basically, just allocate an array of 10 (or so) objects of value_type directly in the map object itself, and use them when/if the map is small, then move the data to a tree iff it grows large enough to justify it. The only real question is whether people us tiny maps often enough to justify the work.
Comment: @MarkRansom: My point was that although you can't know precise data for every possible situation, it doesn't really take all that much to get *enough* hard data to make a reasonably informed decision.
Comment: @Paul: It's a bit hard to guess. Since it's about 10 ms, it could easily be a more or less accidental (that's basically one time-slice). It could also be that the exact sequence of numbers I got ended up producing a slightly better balanced tree (R-B and AVL trees keep the tree from getting *too* far out of balance, but one can still be *somewhat* better than another). It's also possible that it just happened to put the keys I searched for closer to the root.
Comment: You misunderstand - I wasn't saying "I don't know", I was saying I *can't* know. Big difference. It all depends on your compiler, your compiler's library, your machine, the types you're using it with, etc. +1 for suggesting hiding the implementation. P.S. for timing I use QueryPerformanceCounter in Windows because it doesn't have granularity problems.
Comment: I changed the accepted answer to yours. I find it very surprising that from 80 to 90 objects, binary search actually decreased in execution time. What happened there? 0_o
Answer: The code for map will be much cleaner than the code for two vectors; that should be your primary concern. Only once you've determined that the performance of map is a problem in your own application should you worry about the difference, and at that point you should benchmark it yourself.
Comment: If the performance of map is a problem, my first step would be to either replace it with a unordered_map, or replace it's allocator with a boost pool allocator.  Both (may) greatly improve performace, and still far simpler than two vectors.
Answer: A map will never equal a sorted vector search speed, because the vector memory is better packed, and memory access is more straightforward.
However, it's only half the tale. As soon as you start modifying the container, node-base containers (which do not need moving around their elements to accomodate insertions in the middle), get a theoritecal advantage. Like the search, the better cache locality still gives an edge to vector for a small number of elements.
Exact measurements are hard to provide and depend on specific optimizations, context usage and machine, so I would advise to simply go by functionality. A map has a natural interface for searching by key, so using it will make your life easier.
If you really find yourself measuring and need to really squeeze performance out of the use case, then you probably need a more specialized data structure. Look up B-Trees.


windows BAT file for java

Question: I have a stanalone application with a main class which used to run a windows BAT file ,the BAT file which invoke another java class(B),the class B refer so many JARs and configuration files which i configured through "build Path"
Now I want to refer the JARs and configuration files in BAT file.How I write the BAT file.
Comment: What do you mean by *refer the JARs*?
Answer: If you can make sure the .bat file and all needed jars are located in the same directory, this is quite easy:

rem sets the basedir to the directory where this batch file is locaed
set basedir=%~dp0

rem build the classpath for the Java command
set cp=%basedir%\jar_one.jar
set cp=%cp%;%basedir%\jar_two.jar
set cp=%cp%;%basedir%\jar_three.jar

(and so on...)

rem start your second class
java -cp %cp% your.package.ClassB
Answer: Is the program specific to one machine or does it need to be generic?
The issue would be, I think, would be how to get a jar file to return something outside of java.  The obvious answer would be, use the batch file to run the java.  Write the java so that it writes its 'return value' to a file.  Write the batch file so that it watches for the file/dir that the java writes to, and looks for the changed/new data and then use it.
Answer:
REM if all jar files contains in ./lib dir:
setlocal enabledelayedexpansion
for /r "./lib" %%a in (*.jar) do (set "CP=%%a;!CP!")
REM start your second class
java -cp %CP% your.package.ClassB

windows BAT file for java


Understanding Orchard placement.info files

Question: I'm new to orchard development and spent the last week studying it. I'm having a hard time in understanding some concepts, such as placement.info files.
I've read the article Understanding placement info from the project site and the section from the book "Orchard up and running" related to it.
What I understand:

Placement info files work on the content item level. It is used to reorder the rendering of the fields and content parts;
This file has three main tags: placement (basically a wrapper), match(which defines if the rules will be applied to the summary or detail display) and place (which effectively defines the placement rules);

What I don't understand:

How do I define the order of the tags? In the "place" tags I see "Content:Before", "Content:After.7", "Content:2.9" and some other rules. What does it mean to define "Place Parts_Tags_ShowTags="Header:after.7"/"? Is the placement file capable of moving parts to different zones?

I'm getting a bit frustrated using it. I don't know if I'm not using the right material (they seem very brief and/or outdated). If so, could someone suggest me some links?
I'd really appreciate some help, guys..
Thanks in advance
Answer: The name of the attribute is the shape name (usually as returned by a part driver), and the value is where to send that shape. It is a zone name, followed by a colon, and then ordering. The zone name can start with a slash if you want to target a top-level zone (those are defined in the Layout.cshtml file), like this: <code>/AsideSecond:1</code>. The ordering can be a special number, or a dotted sequence. For example, 1.1 comes after 1 but before 2. 1.1.1 would come after 1.1 and before 1.2, etc. after and before can also be used to send a shape after or before everything else.
I hope this helps.
Comment: Thank you for your answer, Bertrand. After some more reading, I'm starting to better understand orchard concepts.
Comment: Thanks for the note about starting with a slash to target a top-level zone, this tip was missing from http://docs.orchardproject.net/Documentation/Understanding-placement-info


How to survive to 6 Reapers rush on Starcraft II Lotv TvT

Question: Since LOTV, almost each time I play against Terran (I'm Terran, so TvT), the other guy build 6-8 reapers and go rush before my first Factory unit.
In best cases, I can scout a triple RAX, and in worst cases, when the map is large, I can't scout anything (Terran wall).
I don't like this cheesy opening but I have the feeling the only way to counter this is to do the same build order. Does this mean every Terran should make this opening in TvT matchup?
Or is there other builds that counter, maybe double RAX opening?
Answer: This opening is becoming more and more popular these days, but, also, is becoming popular how to handle it.
First point, SCOUT
Scout immediately after your first barrack gets finished.

If you are not able to stick into opponent's base then go and scout for proxies, if you feel like he's cheesing just throw a scan in his main
If you get into opponent's main and see 2/3 barracks immediately go back and prepare

Second point, DEFEND
As soon as you understand what's going on, you need to put on a proper defense.

Go for a really fast hellions while holding with marines + some scvs (tank) into banshee
Add 2 more barracks and make also mass reapers
Reactor first on your barracks (no marines), then adding a factory. You'll get lots of marines + hellions asap

Anyways, you really need to focus with micro and tank with Scvs while waiting for hellions. That's it, I'm sure that if you'll practice a bit with that you'll be able to handle it.
I hope I've been helpful, GL & HF.
Comment: Thanks for your answer. First point: the problem is Terran usually wall their entrance, preventing any scout. So two methods remains : make 1 reaper or buy a scan. I think making 1 reaper would be a better idea, but this delays the marine production. Thanks anyways, I'll try your defending suggestions next time i'll play.
Answer: I don't know the exact build order, but Hellion Reaper/Marine holds fine against 3 Barracks Reaper.
You start with the depot and rax, build 1 reaper to scout, then you start building marines. You build your factory ASAP after the Barracks finished and start to produce Hellions.
Normally, the enemy Terran will attack you with the first reaper and will rally his reinforcements to your base, so you'll head a steady growing army.
You need to be a bit careful with your first 2-3 marines and the first Hellion, but as soon as you get your second Hellion and marines you should be able to overwhelm the reapers.
Still, it's micro intensive, but that's the best counter I've seen by now on the Twitch steams from Polt and Winter.
Answer: depot barracks 1 reaper to scout is pretty standard opening. but if you just want to defend you can probably just build reactor and get the marines going. 3 rax 2 reactors and 1 tech lab building marines out of reactors and marauders with good timing on your tech upgrades was decent in hots.


pointer not returning the value correctly

Question: I have a problem to return the value of the pointer in my program, the value of the pointer is not being saved, and when it reads it is returning null.
Header Code:
class PlayerHK : public Player {
public:
    PlayerHK();

    ULONG player_hp();
    ULONG player_power();
    ULONG player_hp2();
    ULONG player_power2();

private:

    struct CPlayer
    {
        BYTE padding[0x20];
        ULONG hp;
        ULONG power;
    };

    CPlayer *player;
};

Main Code:
PlayerHK::PlayerHK() {

        player = reinterpret_cast<CPlayer*>(*reinterpret_cast<DWORD*>(0x00B1C4E5));

    }

    ULONG PlayerHK::player_hp() {
        return player->hp; //does not return the value
    }

    ULONG PlayerHK::player_power() {
        return player->power; //does not return the value
    }

    ULONG PlayerHK::player_hp2() {
        player = reinterpret_cast<CPlayer*>(*reinterpret_cast<DWORD*>(0x00B1C4E5));
        return player->hp; //returns the value
    }

    ULONG PlayerHK::player_power2() {
        player = reinterpret_cast<CPlayer*>(*reinterpret_cast<DWORD*>(0x00B1C4E5));
        return player->power; //returns the value
    }

when the program I run will read the PlayerHK, the value should not get saved? Did I forget to do something?
Comment: I commented on this question just a few minutes ago. Why did you delete it and ask it again?
Comment: `reinterpret_cast(*reinterpret_cast(0x00B1C4E5))` What do you think this does?
Comment: @user4581301 I believe this code is loaded into another process and wants to read values from the main program (probably to cheat at a game). So the address of those values is known in advance by reverse engineering the game, but there is no other way to refer to them.
Comment: @eerorika Obviously it non-portably reads the value at the address 0x00B1C4E5 and treats that as the address of a CPlayer structure.
Comment: 0x00B1C4E5 is the address to pick up the pointer.
Comment: Don't try to pick your own memory addresses unless you're programming an embedded OS and you have guarantees that what you want is really and truly at that address. `player = reinterpret_cast(*reinterpret_cast(0x00B1C4E5));` is a recipe for Le Grand Kaboom! on a modern  desktop OS.
Comment: @immibis I created it again because now the question would be another related to the pointer that does not save the value
Comment: So when you construct the PlayerHK instance are you saying that `player` gets the value NULL?
Comment: Since the behavior of your code is undefined, you'll need to provide the exact compiler, compiler version, and compiler options you used for anyone to be able to even begin figuring out what's "wrong".
Comment: @immibis Good point. Carl, perhaps [`ReadProcessMemory` and friends](https://learn.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-readprocessmemory) are what you are after. Mucking in the internals of other processes is tricky stuff to get right, so expect more problems like this.
Comment: @user4581301 Not if the code is running in the same process already, which it obviously is since player_hp2 works. But Carl only gave that information in his previous question, not in this question.
Answer: If I understand the question correctly you are asking why
player = reinterpret_cast<CPlayer*>(*reinterpret_cast<DWORD*>(0x00B1C4E5));

gives sets player to NULL when run in the constructor, but not when run in player_hp2 or player_power2.
The obvious answer would be that this memory location (0x00B1C4E5) holds the value NULL when you are constructing the object, and holds a different value when you're calling player_hp2 or player_power2. Perhaps the player hasn't been created yet when the constructor runs, so the pointer to the player (which you are reading) is NULL.


how to enable php mb_string only for 1 host?

Question: I have a centOS machine with cPanel. We have compiled PHP with mb_string and it works fine. We want to disable it in all hosting accounts except one, So we have disabled it in php.ini , but want to enable it in the specific host.
I know this is possible with apache's .htaccess file. But how, and what commands? Any insights?
Thanks !
Comment: possible duplicate of [edit .htaccess to load php extension?](http://stackoverflow.com/questions/2271910/edit-htaccess-to-load-php-extension)
Comment: That one refers to http://drupal.org/node/255970 again btw.
Answer: I don't think you can manipulate the extension/module itself via htaccess. Sure, you can adjust values, but the extension needs to be loaded for the values to have any effect.
Perhaps you can do with a per-user php.ini set-up?
http://www.sant-media.co.uk/2010/02/whmcpanel-per-user-php-ini-under-apache-2-x-and-suphp/
http://bibekshrestha.com.np/blogs/post/2010/02/05/using-custom-phpini-cpanel-server
Comment: Thank you very much dakdad. the second link helps  a lot !


Hot water at only one faucet

Question: I recently shut off the water main to the house to repair a leaky downstairs shower. When I finished and turned the water back on, I found that only my kitchen, which is upstairs and nearly directly over the water heater, was getting hot water. Other spouts in the house would run warm water for a few seconds and then go cold, while the kitchen continues to get a steady flow of very hot water. Pressure in all spouts is strong.
The house was built in the 1950s. The piping is simple, with one hot water source out of the water heater immediately going to a "T", turning left to feed the upstairs kitchen and right to feed the rest of the house. No anti scalding valves that I am aware of. Water heater is about 10 years old. Everything worked perfectly before.
Faucets are a mix of single and double handle, makes no difference. It's very confusing that water flows freely yet is cold, when the only source is the hot water heater. The line coming out of the water heater is quite hot. I need Colombo here.
Comment: Welcome to Stack Exchange. You should [take our tour](https://diy.stackexchange.com/tour) so you'll know how the site operates with up votes for helpful answers.
Comment: Try turning on the hot water at one of the bathroom sinks that has a separate hot faucet and let it run. Then go down to where the tee is above your hot water heater and feel the right side of the tee tracing it as far as you can toward the bathrooms. You should be able to hear the water running and feel the temperature increase in the pipe. Assuming the water is flowing and hot and the hot water side is open with water flowing in the bathroom - it should begin to warm. This might help you isolate the problem.
Answer: This is a very strange issue.  Do you have any shutoff valves for your cold water?  If so turn your cold water valves off so that only hot water lines can reach your fixtures.  Now run the hot water.  If no water at all comes out of your faucets clearly there is an issue and this could be a clue.  If water does come out of your faucets it eventually has to be hot.
Answer: Start with the only thing that has changed:  the plumbing at the shower you 'fixed.'  Since, according to your description, the kitchen hot water stays hot forever but everything on the lower floor doesn't get hot, I would be very suspicious that you forgot some check-valve or mixer-valve in the downstairs shower.  This would lead to cold water running freely backwards to all the other hot-water spouts on that floor.
If there are local cutoff valves at the shower (which, BTW, you should have installed while doing the repair if there weren't any), shut them down and see if hot water flows properly.

Hot water at only one faucet


Show the following inequality holds

Question: I want to show that $( 1 + x_1 ) (1 + x_2 )... ( 1 + x_n ) \ge ( 1 + (x_1 x_2 ... x_n ) ^\frac {1} {n } ) ^ n $ for all $x_i > 0$.
I started by taking logarithm on both sides and trying to use the concavity of logarithm but this reverses the inequality. I don't really know how to start, any help is apprecaited.
Comment: It follows directly from [Holder's Inequality](https://hcmop.wordpress.com/2012/04/19/holders-inequality/).
Answer: Note that the function $f(x) = \ln(1+e^x)$ is convex. Therefore,
\begin{align*}
\frac{1}{n}\sum_{i=1}^n \ln(1+x_i) &=\frac{1}{n}\sum_{i=1}^n \ln (1+e^{\ln x_i})\\
&\ge \ln\left(1+e^{\frac{1}{n}\sum_{i=1}^n \ln x_i}\right)\\
&=\ln\big(1+(x_1x_2\cdots x_n)^{1/n}\,\big).
\end{align*}
The required inequality follows immediately.
Answer: by induction:
$n=2, (1+x_1)(1+x_2)=1+x_1+x_2+x_1x_2 \ge 1+2\sqrt{x_1x_2}+x_1x_2=(1+(x_1x_2)^{\frac{1}{2}})^2$
when $n=k, (1+x_1)(1+x_2)...(1+x_k) \ge (1+(x_1x_2...x_k)^{\frac{1}{k}})^k$ holds,
$n=k+1, (1+x_1)(1+x_2)...(1+x_k)(1+x_{k+1}) \ge (1+(x_1x_2...x_k)^{\frac{1}{k}})^k(1+x_{k+1}) $
now, we prove
$(1+(x_1x_2...x_k)^{\frac{1}{k}})^k(1+x_{k+1}) \ge (1+(x_1x_2...x_kx_{k+1})^{\frac{1}{k+1}})^{k+1}$
let $a=(x_1x_2...x_k)^{\frac{1}{k}},x=x_{k+1} \implies (1+a)^k(1+x) \ge (1+(a^kx)^{\frac{1}{k+1}})^{k+1} \\ \iff \ln{(1+a)^k}+\ln{(1+x)} \ge (n+1) \ln{((1+(a^kx)^{\frac{1}{k+1}})} $
$f(x)=\ln{(1+a)^k}+\ln{(1+x)}-\ln{((1+(a^kx)^{\frac{1}{k+1}})}$
$f'(x)=\dfrac{1}{x}(\dfrac{x}{1+x}-\dfrac{y}{1+y}),y=(a^kx)^{\frac{1}{k+1}}$
$\dfrac{x}{1+x}$ is mono increasing function,$\implies \\ y=x(x=a), f'(x)=0, \\ y>x (x<a),f'(x)<0,\\ y<x(x>a),f'(x)>0 \implies \\f(x=a)=f_{min}=0 \implies f(x) \ge 0$
QED
Answer: The general term for LHS is $$\pi(\sum(1+x_{i})$$ for eg $$(1+x_1)(1+x_2)=1+x_1x_2+x_1+x_2$$ for $$(1+x_1)..(1+x_3)=1+x_1x_2x_3+x_1x_3+x_2x_3+1$$ while rhs is $$\sum(π(1+^n \sqrt{x_i})^n)$$ so i assume $(x_1..x_n)^{1/n})=a$ so by binomial theorem its $\sum{n\choose k}.a^k=(x_1..x_n)+\frac{1}{((x_1..x_n)^{1/n})}^1..+1$ so it can be easily observed that $π(\sum(1+x_i)>=(x_1..x_n)+\frac{1}{((x_1..x_n)^{1/n})}^1$.

Show the following inequality holds


Adjoining square root of a discriminant

Question: Let $f(X) = X^2 + bX + c \in K[X]$ be a quadratic polynomial whose discriminant is $\delta^2 = b^2 - 4c$. I understand that if $\alpha_1$ and $\alpha_2$ are the roots of $f$, then $\delta = \alpha_1 - \alpha_2$. But why is it that $K(\delta)$ is a splitting field for $f$? I can see how $K(\alpha_1 - \alpha_2) \subseteq K(\alpha_1, \alpha_2)$, but what justifies the inclusion in the other direction?
Answer: The roots of the polynomial can be calculated by completing the square. This gives
$$ \alpha_{1,2}=\frac{-b\pm\delta}{2} $$.

Adjoining square root of a discriminant


Nexus 7 won't start when I format a partition as "MS-DOS"

Question: I put Ubuntu 12.10 onto my Nexus 7 just to see what it looks like. I noticed that I only had 6 GB of space of storage even though I have a 32 GB tablet. So I downloaded GParted and tried to edit the partition but noticed that there was no partition and it told me I need to create a Partitioning Table. I do not know much about harddrives so I decided to create one to see if it fixes my problem. So I created an "MS-DOS" Partitioning Table and rebooted my device. It will not start. It just stays at a black screen and does nothing. I have tried these commands:
<code>"sudo fastboot reboot" -result: stuck at Waiting for Device
"sudo fastboot reset" -result: stuck at Waiting for Device
</code>
Note: I can not get a replacement and I need to get this fixed. I am willing to erase everything on my tablet if I need to.
Comment: Can you enter fastboot mode? Try pressing power and then volume down when starting up. If you can't, then it appears you erased everything, even the bootloader. You will have to get a replacement.
Answer: First try to reinstall Android. Here's a good explanation how this can be done:
How to return to stock Android after installing Ubuntu Touch
Then try to follow carefully the instructions how to install Ubuntu touch:
https://wiki.ubuntu.com/Touch/Install
and let us know if it works, what happens, and what the outcome is. If this works well then consider not using gparted without some research about gparted on tablet computers.
Answer: Boot your LiveCD again and reinstall Ubuntu.
What you say is you only created a partition table, but you must also create partition(s). If you do not know much about partitioning, best way is to install Ubuntu choosing one of the default options.
If you want to learn more about the subject,
you can read more here: How to Partition
and here: Partitioning for Ubuntu
Comment: Nexus 7 is an Android Tablet. You cannot boot it with a CD.
Comment: right, no USB?? How did he install Ubuntu then??
Comment: https://wiki.ubuntu.com/Touch/Install
Comment: Ahh, right, thanks. Am bit backwards here methinks...


Can we prove that $\operatorname{Tr}(ABC) = \operatorname{Tr}(CBA)$?

Question: I would like to verify the claim:

$$\operatorname{Tr}(ABC) = \operatorname{Tr}(CBA)$$

I tried verifying through an example:
Given the following $3$ different matrices:
\begin{align}
A & = \begin{pmatrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8 \\
9 & 10 & 11 & 12 \\
13 & 14 & 15 & 16
\end{pmatrix}\\[2ex]
B & = \begin{pmatrix}
4 & 3 & 2 & 1 \\
3 & 6 & 4 & 2 \\
2 & 4 & 6 & 3 \\
1 & 2 & 3 & 4
\end{pmatrix}\\[2ex]
C & = \begin{pmatrix}
4 & 3 & 2 & 1 \\
5 & 6 & 7 & 8 \\
8 & 7 & 6 & 5 \\
4 & 3 & 2 & 1
\end{pmatrix}
\end{align}
I calculated $\operatorname{Tr}(ABC) = 7930$ and
$\operatorname{Tr}(CBA) = 7510$.
Is there any thing wrong in my calculation, or does this prove that $\operatorname{Tr}(ABC) \neq \operatorname{Tr}(CBA)$?
Many thanks!
Comment: It's a well known result that the trace is invariant under cyclic permutation: $\mbox{tr}(ABC)=\mbox{tr}(CAB)$, but you have used $CBA$ rather than $CAB$, so there's no reason to expect the trace of $CAB$ to equal the trace of $CBA$.
Comment: I'm sure there will be examples with $2$ by $2$ matrices.
Comment: @Angina It sounds like you're saying that there will be examples with $2$ by $2$ matrices that disprove a true statement, which certainly isn't correct.
Answer: In fact, $\mathrm{Tr}\,(ABC)=\mathrm{Tr}\,(CBA)$ cannot hold for all $A$, $B$, $C$ so long as the ring of scalars is nontrivial. For let
\begin{align}
A &= \begin{pmatrix}0 & 1\\ 0 & 0\end{pmatrix} \\[2ex]
B &= \begin{pmatrix}0 & 0\\ 1 & 0\end{pmatrix} \\[2ex]
C &= \begin{pmatrix}1 & 0\\ 0 & 0\end{pmatrix} \\[2ex]
\end{align}
Then $ABC = C$, $CBA = 0$, so $\mathrm{Tr}\,(ABC) =  1$, $\mathrm{Tr}\,(CBA)=0$.
Answer: As suggested in the comments, the statement $\text{Tr}(ABC)=\text{Tr}(CBA)$ is not true in general, so you should not be concerned that you found a counterexample. Actually, there is a simpler counterexample. Take
$$ A=
\begin{bmatrix}
5&2\\
0&0
\end{bmatrix},\:\:\:
B=
\begin{bmatrix}
2&7\\
5&3
\end{bmatrix},\:\:\:
C=
\begin{bmatrix}
1&1\\
1&1
\end{bmatrix}.
$$
Then $\text{Tr}(ABC)=49$ while $\text{Tr}(CBA)=61$.


How to link Txt file key and entity values to the javascript?

Question: I'm currently working on Event calendar. Wherein I have to add the events to the calendar from the external txt file. How can i interlink the key values and entities to the JavaScript?. The event should be displayed correctly based on what i have given in the txt file.
Thank in Advance,
Code:
<!DOCTYPE html>

<meta charset='utf-8' />
<link rel='stylesheet' href='../lib/Theme/jquery-ui.min.css' />
<link href='../fullcalendar.min.css' rel='stylesheet' />
<link href='../fullcalendar.print.min.css' rel='stylesheet' media='print' />


socket.emit emits two times

Question: i am having problem with the socket.emit using socket.io. i have an object of connected clients, when i emit a message to a specific client using socket.emit, it emits two times!
any solution.
here is the code.
var clients ={};
    io.sockets.on('connection',function(socket){
    socket.on('verifyId',function(data){
         clients[data.user_id]=[];
             clients[data.user_id].push(socket);
        });

     socket.on('saveConverse',function(data){
    user1=clients[data.to];
    if(clients[data.to])
    user1[0].emit('newMessage',{msg:'hi, here is a new message!'});
            //here it is emitted two times.
     });
 });

Comment: What is `saveConverse` listening for?
Comment: saveConverse is an event triggered by client, to save a conversation. and then it is emitted to a particular client, whom it is sent for.
Answer: Try replacing
user1[0].emit('newMessage',{msg:'hi, here is a new message!'});

with this:
io.sockets.socket(socketid).emit('newMessage',{msg:'hi, here is a new message!'});

Because this is the proper way to emit to a specific client. Aslo,
you can save socket IDs instead of the whole socket object in clients array by socket.id.

socket.emit emits two times


Use string replace to change text color of URL link

Question: What I mean is, is it possible to change the text URL link to the color green in a single string?
For example when I have a string which includes muliple URLs like below example. (Part 1) is it possible to set the text color of "http://information.com/qokp076wulpw" to green using string replace so it gets like in Part2?
Part 1:
http://test.site/i7xt1.htm

Mirror:
http://information.com/qokp076wulpw

Part 2:
http://information.com/qokp076wulpw

Comment: Your link is dead.
Answer: You can see this solution to enable links in a TextView from a HTML content and, to set link colors you could set the android:textColorLink attribute in XML layout to specify the links' color.
If you want only convert text URLs to links, is not necessary Java code. You can simply add this in your TextView:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/txt_no_html_tags"
    android:textColorLink="#00FF00"
    android:autoLink="web"
    android:linksClickable="true/>

Comment: Hi dsdebastiani, that`s not what I am looking for, the complete String is indeed loaded into a CustomeTextView but not all the URL links need to be colored green only certain ones, the rest of the links should stay normal color. That why I am trying to achieve this with string replce and then inject "" in the nessecary places to get the color green for that specific URL.
Comment: So you could use ```SpannableString``` to do that. This solution can help you: http://stackoverflow.com/a/7364716/3851246
Comment: Not gonna work as have a function "setTextFromHtml" which cannot be used for this solution. I have a CustomTextView.
My function.

public void setTextFromHtml(String text) {
        this.setText(Html.fromHtml(Utils.parseSmiles(trim(text))));
        this.setMovementMethod(LinkMovementMethod.getInstance());
    }

I need to set the text as holder.text.setTextFromHtml(item);
Comment: http://stackoverflow.com/questions/7364119/how-to-use-spannablestring-with-regex-in-android/7364716#7364716 works! I needed to change some code but it works.
many thx!


How can variadic char template arguments from user defined literals be converted back into numeric types?

Question: This question is being asked because of this one.
C++11 allows you to define literals like this for numeric literals:
template<char...> OutputType operator "" _suffix();

Which means that 503_suffix would become <'5','0','3'>
This is nice, although it isn't very useful in the form it's in.
How can I transform this back into a numeric type? This would turn <'5','0','3'> into a constexpr 503. Additionally, it must also work on floating point literals. <'5','.','3> would turn into int 5 or float 5.3
A partial solution was found in the previous question, but it doesn't work on non-integers:
template <typename t>
constexpr t pow(t base, int exp) {
  return (exp > 0) ? base * pow(base, exp-1) : 1;
};

template <char...> struct literal;
template <> struct literal<> {
  static const unsigned int to_int = 0;
};
template <char c, char ...cv> struct literal<c, cv...> {
  static const unsigned int to_int = (c - '0') * pow(10, sizeof...(cv)) + literal<cv...>::to_int;
};
// use: literal<...>::to_int
// literal<'1','.','5'>::to_int doesn't work
// literal<'1','.','5'>::to_float not implemented

Comment: Same as before, just specialize on `.`... what's the problem? Are you asking strictly about floating point now?
Comment: @KerrekSB Yeah, I wanted a solution that also worked on floating points.
Answer: There's alwars the easy way.  A non-type parameter pack can be expanded into an initializer list as follows:
#include <iostream>

template<char... Chars>
  double
  operator "" _suffix()
  {
    const char str[]{Chars..., '\0'};
    return atof(str);
  }

int
main()
{
  std::cout << 123.456789_suffix << std::endl;
}

Answer: I think the following should work on floats without exponential part (untested):
template<bool fp, long long num, long long denom, char ...> struct literal;

template<bool fp, long long num, long long denom> struct literal<fp, num, denom>
{
   static constexpr double value() { return (1.0*num)/denom; }
};

template<long long num, long long denom, char digit, char... rest>
  struct literal<false, num, denom, digit, rest...>
{
  static constexpr double value()
  {
    return literal<false, 10*num + (digit-'0'), denom, rest...>::value();
  }
};

template<long long num, long long denom, char digit, char... rest>
  struct literal<true, num, denom, digit, rest...>
{
  static constexpr double value()
  {
    return literal<true, 10*num + (digit-'0'), 10*denom, rest...>::value();
  }
};

template<long long num, long long denom, char... rest>
  struct literal<false, num, denom, '.', rest...>
{
  static constexpr double value()
  {
    return literal<true, num, denom, rest...>::value();
  }
};

template<char... c> double operator "" _dbl()
{
  return literal<false, 0, 1, c...>::value();
}

How to extend this to also take an exponential part should be obvious.
Of course one would also want to do some error checking (make sure that the characters are indeed digits).
Comment: You can get rid of those function calls and make static member variables instead. As long as they're `constexpr`, they can be of non-integral type.
Comment: @KerrekSB: Thanks, I didn't know that you could have non-integral local constants via `constexpr`. Makes sense, though.


Continuous Power to Switched Outlet

Question: Power source is supplied by 12/2 romex to switch.
Feed from switch to duplex outlet is supplied by 12/2 romex.
Is it possible to provide continuous power to one of the outlets while the other outlet remains switched?
Answer: Not with the outlet on a spur with 12/2.
Worse, you cannot simply bypass the switch, unless there's another light in the room under control of a switch.  Code requires every room must have a light switch in the usual location, and the switch must either operate a light, or a socket.
Answer: You would need some 12/3 going from the switch to the outlet. You would need the neutral, which you have; you would need the switched hot, which you have but what you don't have is the always hot. that where the third wire comes in.
Are there any other wires in the outlet box?
Comment: Other than the ground, no.

Continuous Power to Switched Outlet


Calculating the angle of a ring segment

Question: So, say I have a sector of a ring. I know the thickness of the ring (in the diagram lines BC, DF, and GE are all this thickness). I also know the width of the sector which is set by the length of the chord which defines the outer arc (DE). And I also know the height between the base of the sector (the chord of the inner arc) and the peak of the ring (the line BH). From this, is it possible to calculate either the radii of the inner and outer arcs, and/or the angle the sector encompasses (the angle DAE)?

Diagram of what I'm trying to explain and the points I refer to.
I hope that makes some sense as a question? Any help would be great, I've tried working it through with what little I know about the geometry of a circular segment, but it's been a while since I dusted off my algebra and unless I'm missing something obvious, I don't know if I'm even looking for the right stuff...
Thanks for any help :)
Comment: It seems that length $FG$ is measurable as well, isn't it ?
Answer: Yes, it is possible. Here is how.
Let us give the names $a,b,c$ to the measurements:
$$\begin{cases}a&:=&DE=CB=GE\\ b&:=&HB \\ c&:=&FG& \text{assumed measurable}\end{cases}\tag{1}$$
(I have prefered to take $FG$ instead of $DE$ because the explanations are simpler like this).
Let us denote by $R,r$ the outer and inner radii resp., and $\theta = \angle BAD \ \iff \ 2 \theta = \angle EAD$.
(1) yields:
$$\begin{cases}a&=&R-r\\ b&=&HB=HC+CB=AC-AH+CB=r-r \cos \theta +a \\ c&=&FH+HG=2 r \sin \theta\end{cases}$$
These 3 equations with three unknowns $R,r,\theta$ can be written in the following way :
$$\begin{cases}R-r&=&a&(i)\\ r(1-\cos \theta)&=&b-a&(ii) \\ 2 r \sin \theta&=&c&(iii)\end{cases}$$
In order to be able to extract in particular $\theta$, let us use classical trigonometry formulas on equations (ii) and (iii):
$$\begin{cases}2 r(\sin \tfrac{\theta}{2})^2&=&b-a \\ 4r \sin \tfrac{\theta}{2}\cos \tfrac{\theta}{2}&=&c\end{cases}$$
Taking their ratio, one gets:
$$\tfrac{1}{2}\tan \tfrac{\theta}{2}=\tfrac{(b-a)}{c} \ \iff \ \theta=2 \tan^{-1}\tfrac{2(b-a)}{c}$$
which is perfectly defined quantity.
Having $\theta$, one can compute the value of $r$, using equation (ii) above, and finally the value of $R$ using equation (i).
Remark: having preferred $DE$ to $FG$, it is important to recall that the connection between these two lengths is very simple:
$$\frac{DE}{FG}=\frac{R}{r}$$
Comment: Deceived, 2 days later, not to have received any comment of yours.

Calculating the angle of a ring segment


ifstream can't locate file?

Question: I'm trying to read a file called "sample.txt" but whenever i try to do an ifstream, it can never locate the file. So my question is where do you put the file so that it can be located?
 ifstream iFile("sample.txt");

Comment: That file is expected to be found in the [current working directory](http://en.wikipedia.org/wiki/Working_directory), whatever that may be.
Comment: You can find the directory it is running from by right clicking the binary under "Products" and selecting "Show in Finder".
Comment: I did put the sample.txt file in the main.cpp directory but whenever i try to do something like   iFile.is_open(); // i get an error.
Answer: Here is the solution.
1) Open your project in Xcode;
2) Locate the Products folder in the Groups & Files tree on the left side of your Project window;
3) When you expand that folder, you should see the icon for the Unix Executable File (usually a black rectangle);
4) Ctrl-click on that icon and select Show in Finder_ (If you accidentally choose Open With Finder, the Finder will start your program in a Terminal window);
5) Show in Finder should bring up a Finder window showing the contents of the folder which includes your executable. You should see your output files in that window.
Source: https://discussions.apple.com/thread/2145737?start=0&tstart=0
Answer: If you don't specify an absolute path the file name is interpreted to be relative to the working directory of the program.
Comment: I did put the sample.txt file where main.cpp file was and I still could not read the file. I also tried                                 ofstream oFile("sample1.txt"); //creates sample.txt file somewhere                                            and when i tried to read sample1.txt file, it worked fine but when i went to the directory to look for it i could not find sample1.txt anywhere. So i'm guessing xcode 4 created sample1.txt file somewhere else or what?
Comment: @cantfindaname88 It just depends what the working directory of your program is, which need not be the directory of the main.cpp. It can be the directory of the executable, or maybe if you start your program from Xcode directly, it could be the directory of the Xcode project (VS does that), but I don't have any experience with Xcode or Apple in general. Just give the file a unique name and search for it. I'm sure it's one of the places I mentioned. Or use some OS function to determine the current working directory.

ifstream can't locate file?


AMD latest driver "18.04" install on "19.04" min server

Question: FWIW, I did look at a previous question supposedly answered, the "RX-460" one.
With RX-560 and 19.04 my system seems working fine but I need opencl so I tried that (latest) AMD driver at their site, the one that says 18.04.  The install failed "broken packages" but since all I needed was opencl then I read this
here
Tried installing the first item listed in the package, the "core" one, and got the following error that basically says the amd package 19.10 can only be installed on 18.04 !!!
<code>Get:1 file:/var/opt/amdgpu-pro-local ./ amdgpu-core 19.10-785425 [2,416 B]
(Reading database ... 100259 files and directories currently installed.)
Preparing to unpack .../amdgpu-core_19.10-785425_all.deb ...
ERROR: This package can only be installed on Ubuntu 18.04.
</code>
[EDIT] The 19.10 was driver version of AMD, not Ubuntu version, my bad.
I put in 18.04 and tried again but same problem.  The chatter from the install
./amdgpu-pro-install --opencl=legacy,pal is here In the mean time, I managed to install an SLIC2.1 on this really dual xeon system  so will try windows 7 pro
Answer: I finally got that AMD driver to install correctly on 18.04 but I had to do a minimal desktop. I am guessing that the dependency errors during the install on the server were caused by the AMD driver expecting some type of desktop to work with.  This was only a BOINC mining system (gridcoin) that did not need a desktop.  Pic here open rack frame


Null Pointer Exception when Setting View's Color

Question: I am trying to set the background of a view to red, just to try something. I added a view to the activity layout and gave it an id, "gradientView". In my Java code I create a new view like this:
    View gradientView = (View) findViewById(R.id.gradientView);

and in onCreate I do this:
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    gradientView.setBackgroundColor(Color.RED);

For some reason it gives me a Null Pointer Exception at findViewById. I thought I made it "not null" when I referenced it to my XML's view?!
Does anyone know what's going on?
Thanks.
Comment: If you're trying to initialize and declare your "gradientView" as a global member, that won't work. You can declare it but the initialization has to be done after you've set the contentview.
Answer: Your findviewById should come after setContentView(..);
Example:
 super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    View gradientView = (View) findViewById(R.id.gradientView);
    gradientView.setBackgroundColor(Color.RED);

Otherwise gradientView will be null and any operation on null reference results in NullPointerException.
Comment: Please change your example to call `setBackgroundColor()` *after* `findViewById()`, otherwise NPE too.
Comment: This is the correct answer.  An implicit call to `findViewById` as opposed to `someOtherView.findViewById` will use the context of the current layout (aka, `this`).  Although, you need to first set the layout by using the `setContentView` or it won't have any XML to search though.
Comment: Why does it make it null if you call it before the setContentView() ?
Comment: refr mrres comment. it explains well.


No sound on a HP Pavilion dv6 with ubuntu 12.04

Question: After installation Ubuntu 12.04 in my hp pavilion dv6 machine sound system is not working.
commands like
<code>gksudo gedit  /etc/modprobe.d/alsa-base.conf
killall pulseaudio  sudo alsa force-reload  pulseaudio -D
sudo alsa force-reload
sudo apt-get install --reinstall libasound2
gksudo gedit  /etc/modprobe.d/alsa-base.conf
killall pulseaudio  sudo alsa force-reload  pulseaudio -D
gksudo gedit  /etc/modprobe.d/alsa-base.conf
</code>
had tried as revealed from forum's discussion. Inspite of all these its not working.
Answer: This works!  Just close the test files that open to proceed to the next step.  then turn your volume on the HP pavilion up at the bar above the keyboard.  It starts at mute.


Google map leave by time

Question: I am currently trying to figure out if there is a way to calculate what is the best time to leave by in order to reach my destination using google maps api.
example: San Francisco -> Menlo Park
ArrivalTime: 12pm
CurrentTime: 11:00am
Leave by time: 11:30am
Currently distancematrix api seems to fit my needs; however, setting the arrival time or departure time does not give a response with when to leave.
So I am wondering, if I am missing something or is there another api within google that can be used.
Thank You
Answer: It is not implemented in the Google Maps API yet. There is a feature request in Google issue tracker that is tracked in the
https://issuetracker.google.com/issues/35829984
Currently the feature request has 28 stars, however it looks like Google didn't set high priority on this task. I would suggest starring a feature request to add your vote and subscribe to further notifications.
Hopefully one day Google will implement this feature.
Answer: In the API, setting arrival time only works for public transit, not fit driving. You could still calculate it by using a guess and check method if it's a desperate need and you're willing to burn additional API calls.

Google map leave by time


Composition API arrow function is not recognized in Nuxt js

Question: I am using the Nuxt Composition API and trying to render the elements in getList to my page. When I load the page I get an error saying that "_vm.getList is not a function".
 <template>

      {{item.title}}

</template>

Comment: The reason for a property to not exist in the instance is that there are other errors in the component, e.g. what the answer suggests. Another one is that you use old framework version that is unaware of  `setup`. Debug your code to make sure that `return` is reached.
Answer: You need to import ref (not sure how), then this one should work
<template>

      {{ item.title }}

</template>

At least, ESlint is not complaining with this. Sorry if I can't help more, didn't worked with Vue3 so far (yet).
Comment: I had added the following: import { ref } from '@nuxtjs/composition-api' and it still doesn't work. I get the same error
Comment: There were some minor issues with your template too. Did you tried mine or turned on ESlint?
Comment: I used your version of the code. I still have the same error about the getList function
Comment: Maybe you need to define it as a function, idk. Sorry, cannot help more here.
Comment: @el_M There seems to be no `ref` in '@nuxtjs/composition-api' . You need to import it correctly any way because otherwise you use a function that is not defined in this component.
Comment: `ref` seems to be available in the nuxt module: https://composition-api.nuxtjs.org/lifecycle/useFetch
Comment: @kissu yes I had seen it in the documentation too


VS + Cordova + WP8 = requirejs load timeout for modules

Question: I am building a windows phone mobile game using Visual Studio 2015 + Cordova.
When trying to debug on device I get this error:

Unhandled exception at line 8, column 137 in
  ms-appx-web://net.boardgamesonline.drawit/www/js/libs/require.js
  0x800a139e - JavaScript runtime error: Load timeout for modules:
  sounds,libs/signals.min,config,components/share....

My VS runs on Windows 10 and has everything updated (cordova, sdks, tools..)
The same project was built for Android and iOS using Intel XDK and works.
But on VS it doesn't work on Windows Phone 10 when debugging.
If I release it - it works, but I need the debugger working.
Here is my index.html:
<!DOCTYPE html>

    <title>DrawIt</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" type="text/css" href="debug.css">

Update:
Here is the initialization code:
requirejs.config({

});

require([
    'assets',
    'game',
    'lobby',
    'utils/stage',
    'utils/fontFaceImport',
    'components/popup',
    'libs/pixi.min',
    'sounds'
], function(AssetsReady, Game, Lobby, Stage, FontLoader, Popup, PIXI, Sounds) {

Comment: The errors starts from "require.js". Please Check if the modules are defined correctly in your "main.js" file. See "LOAD TIMEOUT FOR MODULES" section of [Common Errors of RequireJS](http://requirejs.org/docs/errors.html).
Comment: I saw it. It says it is either error in the modules (not the case), or paths problem. I tried putting the require in different places, staring with slash, removing modules..etc..same error pops again and again
Comment: Would you please post the code that sets up your app with the require `config` function?
Comment: I added it. The config is empty. I tried waitSeconds: 0 and some other values but that is not the problem.
Answer: The problem was solved by recreating the Cordova project in Visual Studio.
New Project + copying the files.


showing object attributes from active record relations

Question: I try to display ingredient.name after the line quantitiy.amount
but don't know how to retrieve the name from object
Ingredient.where(ingredient_id: quantity.ingredient_id)

which returns
#<Ingredient::ActiveRecord_Relation:0x8e30590>

Code
def show
  @recipe = Recipe.find(params[:id])
  @quantities = @recipe.quantities
  @ingredients = @recipe.ingredients
end

- @quantities.each do |quantity|
  %ul
    %li
      = quantity.amount
      = Ingredient.where(ingredient_id: quantity.ingredient_id)

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
end

class Ingredient < ActiveRecord::Base
  has_many :quantities
  has_many :recipes, :through => :quantities
end

Answer: why you do so you already have the relation name in Quantity model, so you can access it direct:
= quantity.amount
= quantity.ingredient.name

and in case Quantity don't have a quantity so you should say the following to not raise an error:
= quantity.ingredient.try(:name)

Answer: The assciations that I need in this case are
class Recipe
  has_many :quantities
end

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

class Ingredient < ActiveRecord::Base
end

Then in the controller, we use eager loading to prevent doing queries in the loop
def show
  @recipe = Recipe.includes(quantities: :recipe).find(params[:id])
end

add a delegation in the quantity model
class Quantity < ActiveRecord::Base
  # relations and stuff

  delegate :name, to: :ingredient, prefix: :true, allow_nil: :true
end

The view
- @recipe.quantities.each do |quantity|
  %ul
    %li
      = quantity.amount
      = quantity.ingredient_name


intuition on multicombinations in combinatorics

Question: I do not understand the formula for multicombinations:
Multicombination$(n, k)$ = Combination$(n+k-1, k)$
What is the intuition and maybe even proof behind this formula?
Comment: Please explain what part of the Wikipedia sections ([here](http://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition) and [here](http://en.wikipedia.org/wiki/Multiset_coefficient#Counting_multisets)) on counting multicombinations you don't understand; otherwise we'd just be rewriting them for you from scratch.
Answer: Nothing new here, but maybe this helps you understand.
Suppose you must choose, with repetition allowed, $k$ items from $n$ allowed options. You could perform this choice by considering the options in order, at each point making the choice between "take one more of this option" and "pass to the next option" (in the former case you stay at the same option, in the latter case you go definitively past it). You must choose the possibility "take one" exactly $k$ times, and the possibility "pass on" exactly $n-1$ times. In the end you've had a choice $k+n-1$ times, out of which the first possibility must have been chosen $k$ times, for a total of $\tbinom{k+n-1}k$ different possible outcomes.
(Maybe you find the word "choice" confusing, since if at some point you have exhausted either your $k$ times "take one" or your $k+n-1$ times "pass on", then no real choice is left. However, this is not different from what happens when you are choosing $k$ out of $n$ objects without repetition allowed, considering the objects one by one.)
Comment: It took me a while, but it's starting to make sense now. Thank you!
Answer: Consider this concrete question: what's purchase options to pick k donuts out of n donuts options in the menu?
To solve it, we assume each donut is considered and the consideration is in order from donut1, donut2, ... donut n. A valid purchase option is a sequence of choices we made which meets the following requirement:

We should have made n - 1 choices to pass to the next donuts
We should have made k choices to pick the one under consideration

(This is the same concept as star & bar representation: * - pick choices / | - pass choices.)
So the problem is transformed into how many are unique valid sequences of choices? Let's compute that.
There are P(n - 1 + k) permutations for valid sequence of choices.
We don't care the order for the "pass" choices and we
don't care the order for the "pick" choices. Because they represent the same "purchase solution". For example, the following is the same

{pick1, ..., pick2, ..., pass1, ..., pass2, ..., pass3}
{pick2, ..., pick1, ..., pass1, ..., pass2, ..., pass3}
{pick1, ..., pick2, ..., pass3, ..., pass2, ..., pass1}
...

So the total number of valid choices are:
P(n - 1 + k) / (P(n - 1) * P(k))
which equals to
P(n - 1 + k) / (P(n - 1 + k - k) * P(k))
and finally
C(n - 1 + k, k)


Are these walls near a skylight, load bearing?

Question: My master and guest bathroom are back-to-back (toilet-to-toilet). Both bathrooms have a tall skylight this size (~4' square). The skylights are about 5 feet apart from one-another.
Master Bathroom, looking south east:
Layout:
I want to remove the four short walls to end up with one long smooth wall. Does the presence of a skylight nearby make these walls likely to be load bearing?
I searched and found: Are there ways to determine if a wall is load bearing?
Walls
Though each wall shown runs perpendicular to the roof ridgeline, it occurs to me that taken together, they are parallel with the roof ridgeline and might constitute a supporting structure.
The closet walls have a double top plate, as shown. The East wall of the master bath is parallel with the roof ridgeline and just short of 20' long.
Attic
This roof ridgeline is about 20' long here. On the South end of that ridge, the roof stair-steps down twice to an external wall. On the North end of the ridge, is a chimney and a vertical wall where this roof ends and stands above the living room roof by 2 or 3 feet. There are a few boards vertical boards in the attic that connect joists to the ridgeline, but they don't seem structural to me.
Foundation
It's a concrete slab.
There is no basement.
Comment: That ridge beam does not look sized to span that distance unsupported. I would say that your walls below and the verticals are indeed contributing to support the roof.
Comment: Hi! Stack Exchange allows photos to be embedded directly in your post. Please see http://meta.diy.stackexchange.com/questions/523/how-can-i-add-an-image-to-a-question-answer and http://meta.diy.stackexchange.com/questions/989/how-do-i-add-pictures-to-a-question-from-my-phone for full instructions on how to do it from a computer or from the mobile apps respectively. Thanks, and welcome to the site.
Comment: Thanks, Niall, for the suggestion, link, and the welcome!
Comment: Thanks @JimmyFix-it, for your input - I'm leaning a lot! That's a good point about the ridge beam size.
Comment: I could be wrong though, use of metal joist hangers allows ridge beam of smaller dimension... I can't tell from the pic if it's just nailed or has hangers.
Comment: @colbybhearn Could You arrange a simple sketch - the plan view of this story? Proportions may help a lot, but dimensions themselves are not really needed. And, if it is possible, a sketch of the roof (with direction and supports of structure elements), same oriented, also with proper proportions.
Comment: Thanks, guys. @Marek, Sure thing about the sketches - I'll get back to ya!
Comment: Updated with a diagram. Sorry I edited my question so much.
Answer: OK, I've had remodelers tell my wife that those walls are not load bearing (they didn't go into the attic).
Meanwhile, I've had a friend from church with framing experience look closely in the attic and say I definitely need to transfer the load being carried by these boards and walls and have at least one board to keep the roof from racking away from the rest of the house.
While drawing the diagram in my heavily edited question, I came to see how there must be some load on these few vertical boards, so I'm going that route recommended by my friend.
I'll cut a few boards to go from the ridge-line beam to the nearby load bearing hallway wall and closet walls, toenail them in, then begin removing the existing partitioning walls below.
Comment: I'll be removing the few vertical boards in the attic first. This is supposed to prevent them from cracking the drywall ceiling below when I remove the partition walls in the master bath. I'll be leaving the anti-racking board in the attic.


Installing an acrylic glass pane as a one-sided shower cabinet - feasibility & tools

Question: I'm moving into a new place at the end of month. It's in the attic of a tenement building, and all the wall (and ceilings) are drywall.
My first project is the bathroom: The bathtub doubles as a shower. Since it is a bit squeezed in between the slope roof and the sink, no shower cabinet has been installed. The former tenants installed a triangular curtain and supposedly showered while squatting down. See the picture for more details.

I am planning to both install a shower head on the ceiling (this is another question) and a one-sided shower cabinet in order to prevent the area around the sink from getting drenched every time I take a shower.
The bathtub is 75 cm (2'6") wide and there's 187.5 cm (6'3") space between tub and ceiling. The sink exactly does not clip the space above the tub, so I could install a cabinet directly at the edge of the tub. See the following image (I apologize for the rather crude drawing):

While I would prefer installing a pre-constructed cabinet made from glass, two issues prevent this:

There is a recess between the bathtub/sink/toilet and the actual drywall, which likely houses the drainage etc. This recess is about 120 cm (4') high from the ground (only 66 cm (2'2") above the tub) and 29 cm (almost 1') deep. Installing a heavy glass pane relying only on these 66 cm for support could be rather unsafe. Also, the recess would reduce the effectiveness of any single-pane cabin.

As already mentioned, the walls are all drywall - I'd rather not try to mount anything heavy on them - thus, no glass pane, again.

Therefore, I am planning on using acrylic glass (most likely 5 mm thick), which would allow me to make the cuts which are necessary in order to fit the recess. U-shaped plastic profiles would be glued to the tiles and the edge of the tub, in order to keep the pane roughly in place, then I'd secure the pane all around using silicone. Most likely the pane will not reach all the way to the ceiling and thus have to be fixated using a retainer (which is available for purchase at my local hardware store).
Actually, this leads me to two connected questions (I have never worked with acrylic glass before): How do I best cut the pane (tools & what to watch out for during the process) - and would it even be sturdy enough to not to wobble all the time?
ps: If the whole idea is nuts and/or I overlooked some mayor detail, please tell me so.
Answer: Main problem
Plexiglass and lexan are different from glass:

They are much more flexible for a given thickness.
They scratch very easily.
They don't break casually.

Of the two, lexan is tougher form.
Because of the greater flexibility, you probably don't want to use the "minimalist metal" designs favoured by the glass shower door set.  You probably want to do things to make the material stiffer.
In particular, the sheet will want to twist.  The ones secured to the tub and ceiling won't be a problem, but the door is attached only by the hinges.  This panel can twist, one corner going in, other going out.  You need to make the door more rigid.
Both lexan and plexiglass are easily glued.   I think that 2" wide strips glued to the face would make it much stiffer.  You might want to buy some scraps of 1/16" lexan and do a scale mockup of your door.
If you use lexan for making the mounts to attach to the walls/ceiling/tub, there is no reason to use the same colour.
Locally our plastic cut goods wholesalers will cut to your spec.  They will also sell you scraps at very low prices.  Buy a box of scraps first, and learn to work with it.  You will want to know now to glue, and polish edges.
Here's a guide for doing lexan:  https://www.cutplasticsheeting.co.uk/blog/uncategorized/how-to-glue-polycarbonate/
(My examples use lexan, because it's usually cheaper than plexiglass, but working with any of these is quite similar.)
Additional considerations.
Is there an additional place in the house to bathe?  If not, then you have to always have a usable bathtub for some block of time every day.  I did a kichen reno.  Washing dishes in the laundry room was a nuisance.  I swore my next kitchen would have two sinks just because of this.
In view of the considerations below, you may want to try to figure out how to put a shower somewhere else in the house before making a mess in your present bathroom, even if it's a $200 plastic stall rigged inside the mudroom entrance.  (Useful later with kids and dogs)
It also appears that your bath shares the room with the laundry.  Is there another possible laundry location?
Water damage potential
Your photo looks like a different tile is above, substantially higher than the 66 cm marked.  If it is actually dryall or cermalite or some panel product you need to address this too.
The ledge on the recess is going to have standing water on it after every shower, much more than gathers there during a bath.  Unless that tiling was VERY well done, you may have future problems.
While tile is very waterproof grout isn't.  Water will move through the grout and into the substrate.  If that substrate is cement backer board, and was properly sealed, you are golden.  I'm not sure how you find out.  If the tile was done with adhesive instead of mortar, especially the more recent low VOC adhesives, water will gradually remove it's sticking power.
Prevention:

Verify the silicon seal at corners.
Reapply grout seal.  I'd use several coats on that ledge.  Put a yearly reminder in your calendar program to redo it periodically.

That said:  At age 15 in the 60's I tiled our bath at home using non-low VOC adhesive directly onto non-water resistant drywall.  It was used daily for the next 15 years before needing to be redone.  Nothing is forever.
Future repairs
Is there access to the space under that ledge from the other side?  If not, then how do you plan to replace the faucets when the time comes.  As a general rule, put in access panels for the connection of utility plumbing to fashion.  Someone is going to want to change something at some time.  If for no other reason than you can no longer get the parts to keep it from dripping.  If you are going to have to wreck the tile work to fix plumbing, then you may want to do it now when its all under control and you can plan for it.
Alternate solution:
They make track shower curtains that are hung from the ceiling.  A half track of one of these, combined with the diagonal curtain at the wall, and a shower on hose attached to the present water supply may be a workable solution.
Comment: Thank you very much for sharing your insights. Luckily I wont have to worry about building a door, since I am rather sure this is far beyond my skill-level and didn't consider it in the beginning ;-) Other than that, I did consider neither lexan, nor the possibility to seal the tiles/grout on top of the recess. As for the track shower curtain: I had one of these in the past and wasn't that happy, also the ceiling should prevent me from using one. I could always shower at my work place, so this one is taken care of, too.


Convert a whole list to string

Question: import pandas as pd

raw_data = {'a': ['a'],'b':['b'],'c':['c'],'d':[['a','b']]}
df = pd.DataFrame(raw_data, columns = ['a','b','c','d'])

this results,
    a   b     c        d
0   a   b    c       [a, b]

then i'm adding it into a single column like this
df['test'] = df['a']+'+'+df['b']+'+'+df['c']
df['test'] gives a+b+c
After that I'm fetching each single value using this
finalArr = df['test'][0]
finalArr = finalArr.split("+")
one = finalArr[0]
two = finalArr[1]
three = finalArr[2]

How to add df['d'] to this :
df['test'] = df['a']+'+'+df['b']+'+'+df['c']
and fetch four = finalArr[3]
expected output :
df['test']

a+b+c+[a,b]

four = finalArr[3]
[a,b]

[a,b] should be in list format while fetching

Comment: Please add the desired output?
Answer: Use, Dataframe.agg on axis 1 to join the columns a, b, c around seperator + then use Series.str.join to join the list then concatenate it with square brackets:
df['test'] =  df[['a', 'b', 'c']].agg('+'.join, axis=1) + '+[' + df['d'].str.join(',') + ']'

# print(df)
   a  b  c       d         test
0  a  b  c  [a, b]  a+b+c+[a,b]

Comment: @D.S.D Edited the answer.
Comment: You could not be able to concat list with the string, its not possible. Please rethink what you are trying to do. You can use `finalArr[3].strip('[]').split(',')` to get the list.
Comment: @D.S.D If this answered your question you may accept the answer.
Answer: # Python program to convert a list to string

# Function to convert
def listToString(s):

    # initialize an empty string
    str1 = ""

    # traverse in the string
    for ele in s:
        str1 += ele

    # return string
    return str1

# Driver code
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))

Comment: Edited the question please check
Answer: you can simply use this line string=[str(value) for value in df.iloc[0,:]]
 import pandas as pd

 raw_data = {'a': ['a'],'b':['b'],'c':['c'],'d':[['a','b']]}
 df = pd.DataFrame(raw_data, columns = ['a','b','c','d'])

 string=[str(value) for value in df.iloc[0,:]]
 df['test']=pd.Series({0:string})
 print(string[3])

 "['a', 'b']"

Comment: Edited the question please check
Answer: Try this out:
s = '[' + df['d'].str.join(', ') + ']' #first convert your list to a string
df['test'][0] += '+' + s               #then add it to your variable

The result will be:
>>>print(df['test'][0])
"a+b+c+[a, b]"

And then if you want to fetch it as a list, you can use this:
arr = df['test'][0].split('+')
arr[3] = arr[3][1:-1].split(', ') #convert the string to a list.
# [1: -1] removes the brackets ('[', ']')
# you can also use .strip('[]') instead

Good luck with your project ;)
Comment: Edited the question please check

Convert a whole list to string


How can I configure a service to run at startup

Question: I have a daemon that runs fine if I start it manually with the service command:
ricardo@ricardo-laptop:~$ sudo service minidlna start
 * Starting minidlna minidlna                                                              [ OK ]

but it's not configured to auto start when the PC reboots.
How can I configure it to start automatically, even if no one is logged into the PC?
Comment: @user154721 What arguments did you give update-rc.d to make autostart work?
I've tried various options but haven't had any luck.
Comment: Auto-start programs are configured in `autostart` manifests or in `*.service` files in several locations, as well as in `init.d` or `crontab`. See: https://unix.stackexchange.com/a/525845/43233
Answer: On modern Ubuntu systems (15.10 and above):
sudo systemctl enable minidlna.service

On Ubuntu before 15.10:
sudo update-rc.d minidlna defaults

If you get System start/stop links for /etc/init.d/minidlna already exist., then run this instead:
sudo update-rc.d minidlna enable

For details, look at the man page for update-rc.d by typing the command man update-rc.d
Comment: @RicardoReyes use `sudo update-rc.d -f minidlna remove` to remove the existing links.
Comment: thanks, but what if I get this output when running that command?: `System start/stop links for /etc/init.d/minidlna already exist.`
Comment: I am also, got the same error `update-rc.d: /etc/init.d/mongod: file does not exist`. Then, `sudo systemctl enable mongod.service` worked for me.
Comment: I am getting below error
update-rc.d: /etc/init.d/usermanage: file does not exist
Comment: if minidlna doesnt write to any logfile you won't find it any where. Does it maybe fail because there is no network connection when it is started? Try to look at the configuration if it is possible turn on debugging and/or logging to find out whats wrong.
Comment: I grep'd for minidlna in all the files at /var/log and couldn't find any mention of the service at startup
Comment: Also getting the error that @RizwanPatel is getting
Comment: This worked for me: `sudo systemctl enable amazon-cloudwatch-agent`
Answer: Since Ubuntu 15.10 and newer (resp. Debian 8 "jessie" and newer), you have to use the following command to configure your service minidlna to run at startup:
sudo systemctl enable minidlna.service

And to disable it again from starting at boot time:
sudo systemctl disable minidlna.service

This works with all service names available on your system. To find out available service names, just list the filenames of the service files:
ls /lib/systemd/system/*.service
ls /etc/systemd/system/*.service

Comment: As for sudo, I recieve `Unknown operation enable.` If I discard sudo it will ask me which user I would like to choose. Pick your root user and you will be able to set the desired value.
Comment: @tanius I have followe the procedure of adding new services to /etc/systemd/system/*.service. I would like to know why no one suggested creating or editing these files as it seems to provide mode options (Restart, RestartSec, ExecStop, etc...)
Comment: @tiagoams Creating a service file was just not the question here, since the OP states that a service `minidlna` already exists but does not autostart. But thanks for the pointer to service files under `/etc`, I added that to the answer now.
Answer:
To start a daemon at startup:
update-rc.d service_name defaults

To remove:
update-rc.d -f service_name remove

defaults => default run levels 2,3,4 and 5
Example:
update-rc.d tomcat7 defaults

Comment: When I do this command, I get "System start/stop links for /etc/init.d/tomcat7 already exist".  however, when I reboot, it does not start tomcat, I always have to do "service tomcat7 start".
Comment: in my case *sudo update-rc.d myservice* default always completes with no output and the service won't start on boot-up or with *sudo service myservice start* which also completes silently. *sudo /etc/init.d/myservice start* works however
Answer: Sometimes you need to run a script on boot process, for example run an iptables config at boot process. So you don't have to run the script manually every rebooting.
You can run your script on boot process in Ubuntu by adding it to /etc/init.d/rc.local file. Look the steps below.

Open /etc/rc.local file with this command:
vim /etc/rc.local

Add your script that you want to run on boot process there, for example:
sh /home/ivan/iptables.sh
echo 'Iptable Configured!'

Review the comments included in that file and make sure an exit 0 is at the end.
Save the files. And your script will run on boot process.
Comment: Comments of /etc/init.d/rc.local in Ubuntu 12.04 says "Short-Description: Run /etc/rc.local if it exist", so maybe adding the scripts to /etc/rc.local would be better idea?
Comment: FYI: The difference between `rc.local` vs adding it to init, is that rc.local is executed at the end of the init startup sequence, rather than as part of it
Comment: Would this method issue "shutdown" command to the service or just kill the process upon OS shutdown?
Comment: Vadim, rc.local is just run at boot, nothing is achieved on shutdown. The process would most likely be killed by the OS on shutdown.
Answer: In ubuntu version 18.04 TLS, I found that update-rc.d does not work fine if there is no specific comment block in the start script that looks like this:
### BEGIN INIT INFO
# Provides: myprogram
# Required-Start: $ local_fs $ remote_fs $ syslog $ network $ time
# Required-Stop: $ local_fs $ remote_fs $ syslog $ network
# Default-start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: myprogram some description
### END INIT INFO


dlib and django. how to integrate and import dlib into django

Question: I am trying to use dlib in my django project. I am using aws ubuntu, but I was not able to use pip dlib, so I compiled directly according davisking instruction to use this PR https://github.com/davisking/dlib/pull/1040. So I was success to install compile dlib and install in my ubuntu.
Now is how to use dlib in django. I tried "import dlib" but its not recognized.
This is how I install dlib and last part of the execution.
$ python setup.py install
.....
.....
Processing dlib-19.8.99-py2.7-linux-x86_64.egg
creating /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg
Extracting dlib-19.8.99-py2.7-linux-x86_64.egg to /usr/local/lib/python2.7/dist-packages
Adding dlib 19.8.99 to easy-install.pth file

Installed /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg
Processing dependencies for dlib==19.8.99
Finished processing dependencies for dlib==19.8.99

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ...
    'mapwidgets',
    'dlib',
]

but it came out with errors below. removing this it still does not recognize "import dlib"
Traceback (most recent call last):
  File "manage.py", line 23, in <module>
    execute_from_command_line(sys.argv)
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'dlib'

How can I start to use dlib in my django project, what is the steps now to import dlib ?
Answer: From the stack trace it seems that Python 3.5 is used instead of 2.7, which dlib was built for. You need to install dlib for the right Python version.
Comment: how do i do that ? do like this ? python3 setup.py install
Comment: @Axil Please try it and report back with the results.
Comment: it doesnt work somehow https://gist.github.com/axilaris/353eaaa61f6b488e0a4b2eb5ac8254e3
Comment: @Axil You need to install setuptools (`pip3 install setuptools`) probably


How to separate a row in a CSV and generate another CSV file from it in R?

Question: I have a CSV file like
AdvertiserName,CampaignName
Wells Fargo,Gary IN MetroChicago IL Metro
EMC,Los Angeles CA MetroBoston MA Metro
Apple,Cupertino CA Metro

Desired Output in R
AdvertiserName,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA

I have done it like
record <- read.csv("C:/Users/Administrator/Downloads/Campaignname.csv",header=TRUE)
ad <- record$AdvertiserName
camp <- record$CampaignName
read.table(text=gsub('Metro', '\n', c), col.names=c('City', 'State'))

It throws an error.
How to get the desired result?
Thanks in advance.
Answer: You can do this for example:
## read the csv file, you change text here by your fileName
xx <- read.table(text ='AdvertiserName,CampaignName
Wells Fargo,Gary INMetro Chicago IL Metro
EMC,Los Angeles CAMetro Boston MA Metro',sep=',',header=TRUE)

##  use regular expression to create city and state variables
##  rows are separated  by ":"
##  columns are separated by a comma ","
res <-
gsub('(.*) ([A-Z]{2})*Metro (.*) ([A-Z]{2}) .*','\\1,\\2:\\3,\\4',
     xx$CampaignName)
## Use strsrsplit to extract rows and columns
## This is a compacted code !
yy <-
Map(function(x,y)
         cbind.data.frame(y,do.call(rbind,strsplit(x,','))),
       strsplit(res,':'),xx$AdvertiserName)
## create the final data.frame and set names
res <- do.call(rbind,yy)
setNames(res, c('AdvertiserName','City','State'))

  AdvertiserName        City State
1    Wells Fargo        Gary    IN
2    Wells Fargo     Chicago    IL
3            EMC Los Angeles    CA
4            EMC      Boston    MA

Comment: Do you mean you will have something like `Identity,AdvertiserName,CampaignName
 id1     ,Wells Fargo   ,Gary INMetro Chicago IL Metro`  as input?
Comment: What about the other two cities?
Comment: @user3188390 I update my answer. It was harder than I thought:)
Comment: @astudy Thanks, From where will I get to know all these things, new to R, Any suggestions?
Comment: @user3188390 there are many resources/tutorials in the net (in SO also). Read the base and try to do solve some simple problems.Exercise is the best method to tackle difficulty.
Comment: If I do have another column other than the Advertisername like Identity, what will change in the code?
Comment: Yes exactly like that. but also not limited to just 3 columns(Identity,AdvertiserName,CampaignName),there may be more columns, a more generalized answer.
Comment: I am actually on look out for the generalized one.How to do that?And thanks for the suggestions.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48421/discussion-between-agstudy-and-user3188390)
Comment: How to format the regex if the data is of the form "Gary IN MetroChicago IL Metro" instead of "Gary INMetro Chicago IL Metro"


RegEx to strip BBCode tags from a string

Question: I'm working on a feature that uses the JQuery MarkItUp! editor as a BBCode editor. I'm only allowing a small subset of BBCodes including the following:
[b]
[i]
[quote]
[quote=Mr Incredible]
[img]
[url]
[youtube]

I have a 1,500 character "Description" field that uses the editor, but I'm also planning to store a 150 character digest of the description with all of the BBCode stripped out.
I'm currently using a simple RegEx to do this in C#.  It basically nukes embedded BBCodes in a string, but it leaves behind a lot of "noisy content" like the [img] URL or the [youtube] video ID that I'd also like to remove from the digest.
Here's my current RegEx:
  public static String StripBBCode(string bbCode)
  {
     string r = Regex.Replace(bbCode,
     @"\[(.*?)\]",
     String.Empty, RegexOptions.IgnoreCase);

     // Finally, replace all newlines with a space
     r = Regex.Replace(r,
     @"(\r\n|\n\r|\r|\n)+",
     @" ", RegexOptions.IgnoreCase);

     return r;
  }

If I run the following string through this function, I get the result shown below:
source
This is [b]bold[/b]. This is [i]italic[/i].

Here is an image:
[img]http://www.phatmac.com/Pics/Movies/Incredibles.jpg[/img]

Here is a link to [url=http://espn.go.com]ESPN[/url].

Here is a YouTube video:

[youtube]WJ0UkZ3W4FA[/youtube]

result
This is bold. This is italic. Here is an image: http://www.phatmac.com/Pics/Movies/Incredibles.jpg Here is a link to ESPN. Here is a YouTube video: WJ0UkZ3W4FA
Here's what I want to get back
This is bold. This is italic. Here is an image: Here is a link to ESPN. Here is a YouTube video:
How can I modify my StripBBCode() function to achieve this?
EDITED
The suggestion from David below in the first answer was correct.
Here's what I'm using now:
 string r = Regex.Replace(s,
    @"\[youtube\].*\[\/youtube\]",
    String.Empty, RegexOptions.IgnoreCase);

 r = Regex.Replace(r,
    @"\[img\].*\[\/img\]",
    String.Empty, RegexOptions.IgnoreCase);

Answer: You've got several tags that you want the content removed, and the rest where you only want the tags removed.
Do replace of [img].*[/img] with string.empty, and [youtube].*[/youtube], and whatever else you need the contents removed, then do your removal of [.*].
Edit:
I'm not a regex expert either, but I think @"\[img\].*?\[/img\]" is what you want. I don't think you need the parentheses in @"\[(.*?)\]", I think in this context parentheses means to save the matched text so you can match it again with \1.
Comment: What does the RegEx for removing [img].*[/img] look like? I'm no RegEx maven, and the original regular expressions in my function were the result of many cut-and-paste sessions to get the syntax right.
Comment: Thanks.  I have a version added to the end of the original question that seems to work.  Mine doesn't have the embedded question mark as yours does.  Anyway, thanks for pointing me in the right direction. I appreciate it!
Comment: The question mark on `.*?` makes that expression lazy, consuming the minimum number of characters necessary to satisfy the expression. Without it, the regular expression will reduce `[img]asdf[/img] Important Text [img]asdf[/img]` to an empty string.


Load Netplan yaml file from other directory apart from "/etc/netplan" in Ubuntu 22.04 LTS Desktop

Question: System - Ubuntu 22.04 LTS Desktop
Netplan renderer - NetworkManager
Usecase -

By default, there is a netplan yaml 01-network-manager-all.yaml file in /etc/netplan.
On boot the netplan is applied.
During runtime, there is a need to apply another netplan file 02-network-manager-all.yaml that is kept at /home/$USER/ProjectX/02-network-manager-all.yaml

Due to security factors, it is not possible to write directly to the file, since all the files after bootup will be in read-only mode, except the /home/$USER/ProjectX/02-network-manager-all.yaml file.
So during runtime, this file can be updated and when it is updated, need to apply the configuration.
Is it possible to load the 02-network-manager-all.yaml file from the specified location rather than copy to /etc/netplan and do a netplan apply? If possible, How to do it?
Looks like there were options like sudo netplan apply -c /path/to/file
But, it does not work.
Answer: You could make a symlink - this would probably be the preferred way of doing this:
ln -s /home/$USER/ProjectX/02-network-manager-all.yaml /etc/netplan/02-network-manager-all.yaml

Then netplan would see this file normally in /etc/netplan, even though the actual file is located in /home/$USER/ProjectX.
Comment: The symlink option works, but is there any other way to update the default path of netplan files ?

As I understood, the netplan will look for the files in {run, etc, lib}/netplan

But can this configuration be changed so that permanently it will load from any location specified ?