text:
Q: Parsing plain text to some structured object I am working on parsing plain text and converting it to key-value pairs.
For example, plain text:
some_uninteresting_thing
key1 valueA, some_uninteresting_thing  valueB
key2 valueD
key3 some_uninteresting_thing  valueE
key4 valueG(valueH, valueI)
key5 some_uninteresting_thing

And possible mappings:
 Map(

 key1 ->(valueA, valueB,valueC),
 key2 ->(valueD, valueE),
 key3 ->(valueF)
 key4 ->(valueH, valueI)

 ...
 )

Amd result will be :
key1 ->(valueA, valueB)
key2 ->(valueD)
key4 ->(valueH, valueI)

(key5 shouldn't be mapped because has no appropriate values. As you can see plain text is lenient. What java library will help to handle this?

A: If you are familiar with formal languages, tokenization/grammars etc., you could use a parser generator like, JavaCC. JavaCC takes the grammar file that you write and generates java code that parses the text file into a series of tokens, or a sytax tree. There are plugins for Maven and Ant that can help integrate this additional source into your build.
For a runtime-only solution, there is RunCC, which I've used with good results. (I suspect it is not as fast as JavaCC, but for my case the performance was fine.)
There is also Chaperon, which converts plain text to XML, using a grammar file.
An alternative to these is to use an ad hoc mix of regex and StringTokenizer.
With a parser project or regex armed and ready, your general approach is then like this:

*

*write a grammar for your plain text file. Some details are missing about the your plain text format, but you may simply be able to use a BufferedReader.readLine() to read lines of the file, and StringTokenizer to split the line into substrings at spaces and commas.

*The strings you get form the parser, the first string you use as the key, and the subsequent strings are values, that you add to a Map. E.g. in pseudocode
Map> map = new HashMap>();
for each line {
   List tokens = ...; // result of splitting the line
   String key = tokens.get(0);
   map.add(key, tokens.sublist(1, tokens.size());
}
Even if the parser doesn't filter uninteresting text, it will be filtered later.

*Build a parser with the above projects to parse the map file format. Again, you may be able to build a simple parser with regexes and StringTokenizer. Use the parser to build a map. The map has the same signature as above, i.e Map<String,List<String>>.

*Finally, filter the input map against the allowed values map.
Something like this.
   Map<String,List<String>> input = ...; // from step 1.
   Map<String,List<String>> allowed = ...; // from step 3.
   Map<String,List<String>> result = new HashMap<String<list<String>>(); // the final map
   for (String key : input.keySet()) {
      if (allowd.contains(key)) {
         List<String> outputValues = new ArrayList();
         List<String> allowedValues = allowed.get(key);
         List<String> inputValues = input.get(key);
         for (String value: inputValues) {
            if (allowedValues.contains(value))
                outputValues.add(value);
         }
         if (!outputValues.isEmpty())
            output.put(key, outputValues);
      }
   }
   // final result in filter

A: You can use an Interpreter and a Builder.
The Interpreter parses the source and identifies keys and values, which are passed to the Builder, which constructs any data structure you desire.


text:
Q: Using ResultSet to return string value from database but method skips the "Try" clause? Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");

not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
   String result = "";

   try
   {
       Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
       PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
       ResultSet rs = pst.executeQuery();

       while (rs.next())
            result = rs.getString(colName);

       conn.close();

       return result;
   }
   catch (Exception e)
   {
       e.printStackTrace();
   }

   return result;
}

In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";

I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
 public static void getValueOf(String sql, String colName, PrintWriter pw)
    {

       try
       {
           Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
           PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
           ResultSet rs = pst.executeQuery();

           while (rs.next())
                pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"

           conn.close();

       }
       catch (Exception e)
       {
           e.printStackTrace();
       }
    }

A: Based upon your last edit, I would guess that you have more than one records.
So change your code to
 if (rs.next()) {
        result = rs.getString(colName);
 }

And also, your code does not skip that try block

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting to Oracle Database using 0xDBE I am trying to use 0xDBE and I am able to connect to the database with the host name and the database name but there are no tables populating. I checked the schemas & tables and the tables are not listed there either. I was thinking since there is an instance name that stays the same but there is also an Oracle alias that changes. There are two database, one for test and one for production. I am trying to connect to test. I can connect successfully to the instance name but I am not sure how to get to the Oracle instance and see my tables.
Actually, when I try to connect to the test database it gives me and error Listener refused the connection with the following error: ORA-12514, TNS:listener does not currently know of service requested in connect descriptor


text:
Q: Redirecting to Login page using javascript's settimeout() function when server session expires After server session expires user must be redirected to Login page. For this purpose using SetTimeout() function when the user is inactive for the given Timeout period in web.config.
<sessionState mode="InProc" cookieless="false" timeout="30" />

Master Page load

StringBuilder script = new StringBuilder();
            script.Append("function expireSession(){ \n");
            script.Append("var jsId = document.cookie.match(/JSESSIONID=[^;]+/);");
            script.Append("if jsId == null) ");
            script.Append("{");
            script.Append(string.Format("window.location='{0}';", ResolveUrl("~/Login.aspx")));
            script.Append("}");
            script.Append("} \n");
            script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000));
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);

But it does not work. Please any advice?

A:   protected override void OnPreRender(EventArgs e)
 {
  base.OnPreRender(e);
   AutoRedirect();
 }

   public void AutoRedirect()
  {
      int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000);
      string str_Script = @"
     <script type='text/javascript'>
     intervalset = window.setInterval('Redirect()'," + int_MilliSecondsTimeOut.ToString() + @");

   function Redirect()
    {
        alert('Your session has been expired and system redirects to login page now.!\n\n');
        window.location.href='/login.aspx';
    }
     </script>";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
     }
   }

A: review this url
http://www.aspsnippets.com/Articles/Automatically-redirect-User-after-Session-Timeout-in-ASPNet.aspx
i hope this may help


text:
Q: When tomcat redeploy, the previous upload files are missing I'm writing a website with the function file uploading.
And the Path I save the file is by ServletActionContext.getServletContext().getRealPath("xxxx")
It will save the file to webapps/mywebsit/xxxx
to allow the clients are able to access the data directly by http://  mywebsit/mebsite/xxxxx
the function is ok.
But when it comes to redeploy on tomcat here comes the problem.
When I redeploy by war file.
It seems sorts of remove the all webapps/mywebsit.
And deploy it with the new war file.
And the previous upload files are missing.
Is there anyway I can let tomcat don't remove my file while it's redeploying?
Or I should store files outside the webapps? But how can I let client be able to reach the file?

A: When tomcat redeploys your application, it will remove it's directory under /webapps/ completely and unpack the WAR from scratch. TI'd recommend keeping your files outside the webapp's directory. You could try using environment variables to point your application to directory you'd like to use, taking care that the user tomcat runs under has appropriate access rights.


text:
Q: Azure load balancer inside a subnet I have a VNET with a subnet, there are 3 VMs in the subnet, the VNET is connected via a VPN connection to an on-premises server. The on-premises server will send requests to an internal IP of the subnet.
What I'd like to do is host a load balancer with no public IP, but has an IP in the subnet range. The on-premises app would then talk to the single load balancer, which would in turn forward the request on to any of the servers hosting my app in the subnet.
Can anyone tell me if this is possible, or an alternative if possible.

A: I believe you are looking for an internal load balancer.
You can find documentation for that here: https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-get-started-ilb-arm-portal.

Azure Internal Load Balancer (ILB) provides network load balancing between virtual machines that reside inside a cloud service or a virtual network with a regional scope.

Create a Load Balancer as usual, but specify Type: Internal.
Probably best to make it use a static IP address as well so it won't change.
Then you'll need to configure its back-end pool and health probe so it knows where to route traffic.


text:
Q: If IE didn't exist, what css, js or html features could we use that currently are not really usable? In a world where IE didn't exist, what things would be easier, less hacky, less buggy and generally more used.
What could the internet have been if all features were available cross browser?
List one point per post.
This is community wiki, so feel free to amend the question/answers for clarity.

A: 1) :before and :after psuedo elements.
2) 'content' attribute.
3) :hover on any element (not just anchors).

A: Better adoption of PNG due to support in earlier versions of IE.

A:
"In a world where IE didn't exist, what things would be easier?"

Web Programming

A: Just easier? Anything involving floats, or box-models
Possible? display:table and :focus would be nice but the real biggie would be min and max dimensions which just worked.

A: Canvas... they've just decided to skip it in ie8 too

A: Lets starts with javascript EcmaScript: today you have to make one version for Mozilla/Opera/Safari and another version for IE.
Both Opera and Firefox support some CSS3. Guess what: IE don't. What about the CSS2-standard? No, IE still not ready to use that one. I'm not sure about how much of the CSS1-standard IE7 support, but I do know that IE6 didn't support it completely.
Today you can't use xhtml properly: IE doesnt suppert documents beeing served as xhtml..
A solution many webdevelopers does today, is to create a lot of nested <div>-tags to force IE to display the page properly. Most modern browser (not IE6) support css-rules on the 'html' and 'body'-tag, and therefor div-mania can be avoided. (Well; div-mania can be avoided on IE today, so this last point isn't that relevant)
PNG-pictures is also an issue, as Rich Bradshaw pointed out.

A: Standard box model, of course.
And we would get rid of colorful scrollbars, VBScript (I saw page on the Web scripted only with that!), hacks with VML, and so on.

A: IE is the bane of my life. Its a pain in the back-side having to work around all the unsupported features and the misinterpretation it does.
IE's like my mother, it doesn't hear what you ACTUALLY said, it hears what it THOUGHT you said.
You end up having to practise some bizzarre reverse psychology on it until it does what you want it to.


text:
Q: Where can I get more lollipops? I bought three from the candy merchant, found one in the forge and a few in the other house. I planted them all, but is there any way to get more without waiting for the farm (25 minutes)?

A: There are:

*

*3 for purchase from the Candy Merchant.

*3 in the empty house in plain view.

*1 in the empty house, hidden under the rug.

*1 in the forge.

*1 in the Sorceress's hut.

*3 from answering the Squirrel's questions.

making a total of 12.

A: There are 3 lollipops in the empty house; One on the shelf,  One inside the shelf,  And one under the rug.

A: You can get a few buying from the merchant, and reduce the price a lot to 50 each if you use the secret easter egg, that is listed here http://www.candyboxwiki.com/wiki/Easter_Egg#Lollipop
Page contents: magical easter egg 0+*=**~*~**=*+0


text:
Q: How to pass int from IEnumerable to custom Enum Validator? I have made a custom enum validator to check if int from IEnumerable is part of Enum
public class CustomEnumValidator<T> : AbstractValidator<int>
where T : struct, IConvertible
{
    public CustomEnumValidator(int value)
    {
        if (Enum.IsDefined(typeof(T), value))
        {
            throw new ArgumentException("Value must be part of enum");
        }
    }
}

I am not sure if this works yet because I have a problem passing the int value to the custom validator
RuleForEach(x => x.Values) //Values is IEnumerable<int>
    .SetValidator(new CustomEnumValidator<CustomEnumValues>(x))//this line is throwing error
    .When(x => x.Values.Any());

So how do I pass the each int value to the CustomEnumValidator, and is my validator correct?

A: I personaly would propaply not do it that way, for multiple reasons, but if you need to do it that way, why not pass the value like this?
foreach(var item in list)
{
      new CustomEnumValidator<TestEnum>(item);
}

Edit:
Other Version in LINQ:
list.Where(item =>
        {
            new CustomEnumValidator<TestEnum>(item);
            return true;
        })


text:
Q: Contact us form with image captcha I am new in PHP. I want my captcha validator to display error message if captcha is not the same with image. But if it is the same, I want to process the form and send email. Currently, if captcha is correct, an echo just says success and form does not process. I got my contact us form here http://www.html-form-guide.com/files/contact-form/contact-form-attachment-2.zip. Please help

A: In your contactform.php check the if condition for the submitting form.
Change
if(isset($_POST['submitted']))
To
if(isset($_POST['submit']))


text:
Q: The Ruby on Rails Way (guidance) I'm making a RoR app that is going to have a bunch of network diagnostic tools in it, like ping, traceroute, whois, etc.  It's an internal company thing.  Being that I'm learning Rails, I'd like to create it in that.
So, I'm curious what's the best structure to make this?  Would it make sense to have all the tools under one MVC, like 'tools', or to break each one out into their own MVC (i.e., ping_controller & model/ping, traceroute_controller & `model/traceroute', etc.)?
So:
App
|--models
|  |--tools (which would just write the `ip`, `tool_type` and `hitcount` to the DB.)
|
|--controllers
|  |--tools (which would contain the methods: `ping`, `traceroute`, etc.)
|
|--views
   |--tools
      |--index.html.erb (which would have the individual form to run a given tool and show results)

Or would it make more sense to break it out more, but still keep the individual tool form elements on the same page and direct them with something like form_for(controller: 'ping', action: 'show'):
App
|--models
|  |--ping (which would just write the `ip` and `hitcount` to the DB.)
|  |--traceroute (which would just write the `ip` and `hitcount` to the DB.)
|
|--controllers
|  |--ping (which would contain the normal CRUD and results)
|  |--traceroute (which would contain the normal CRUD and results)
|
|--views
   |--tools
      |--index.html.erb (which would have the individual form to run a given tool and show results)

What's the "Ruby Way" to do this?  I feel like the second option is not very DRY, but I'm still learning... hence my question.

A: If type is the only difference between each types of tools, I would suggest you to use the first way. If there will be more complex logic/columns differences, I would suggest you to have a look into Single Table Inheritance (STI):
http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-1/


text:
Q: can i add new key in models? I want to add a key while I'm getting any response of an API using Models in laravel,
Currently, I'm developing an API to get a response with a new one key to add to dynamically.

A: If I'm not wrong I guess you are trying to create a new field which is not present in table but need to be created dynamically with some logic inside it and you want to pass that field to each and every product of yours.
If so than I guess Laravel Eloquent Accessor will be a best option to use in this case. With the help of Accessor you can create any kind of field and can call it as same as we are calling others fields.
for more reference please take a look at this https://laravel.com/docs/5.7/eloquent-mutators Laravel Documentation.
A sample picked from Laravel Documentation.
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

Now I can use full_name inside my controller or blade files like $user->full_name and than it will give me the concatenated string of first_name and last_name.

A: first of all in your model add this to add custom field
protected $appends = ['is_favorite'];

public function getIsFavoriteAttribute($value)
{
    return $this->name;  // whatever you want add here
}

But it problem while you getting other models details while applying relations and select from relation.

A: Add the attribute to $appends.
class MyModel extends Model {
    ...
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['extra'];

    public function getExtraAttribute(){
        return "Extra Value";
    }
    ...
}


text:
Q: Snapshot tests fail after replacing usual imports on lazy imports jest Before I replaced imports on React.lazy, all tests were passed fine. But after replacing , error log told me that some code threw Exception(but no details about error)
 A React component suspended while rendering, but no fallback UI was specified.

    Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
        in Unknown (created by Context.Consumer)
        in Route (created by SuspenseComponent)
        in SuspenseComponent
        in Router
        in Provider
at throwException (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11518:13)
      at handleError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12502:7)
      at callback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12336:9)
      at eventHandler (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1825:24)
      at Scheduler_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:653:12)
      at runWithPriority (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1775:10)
      at flushSyncCallbackQueueImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1820:7)
      at flushSyncCallbackQueue (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1808:3)
      at scheduleWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11776:9)
      at updateContainer (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14747:3)
      at Object.create (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:15455:5)
      at checkOrCreateTheSnapshotOfState (__test__/user.test.js:27:34)
      at Object.<anonymous> (__test__/user.test.js:48:9)

So I have some code that tests snapshot
const checkOrCreateTheSnapshotOfState = (state, path) => {
    let store;
    const mockStore = configureStore([thunk]);
    store = mockStore(state);
    const history = createMemoryHistory();
    history.push('/' + path);
    const SuspenseComponent = () => {
        return <Suspense fallback={"Loading..."}><Route exact
                                                        path="/:user"
                                                        component={User}/></Suspense>
    };
    const element = renderer.create(<Provider store={store}><Router
        history={history}><SuspenseComponent/></Router></Provider>).toJSON();

    expect(element).toMatchSnapshot();
};
it("should render User component correctly when user is found and another user authed and post is active", () => {
        checkOrCreateTheSnapshotOfState(userState.userAuthedAndPostIsActive, userData.login);
    });

So the problem is that I don't know, what is wrong, with the component and testing code, because when I start app, all works fine. In code above I added Suspense , but it always receives "Loading...", so what should I do? Wait for some lazy loading components, may be?


text:
Q: Convenient way to show OpenCL error codes? As per title, is there a convenient way to show readable OpenCL error codes?
Being able to convert codes like '-1000' to a name would save a lot of time browsing through error codes.

A: For anyone who need different version of OpenCL error code to string, here is a small script can help you.
$ ./clext.py /directory/to/opencl/headers

For example, to create error code to string help function for OpenCL 2.2, you can run
$ ./clext.py ~/Developments/OpenCL-Headers/opencl22/CL

will create a file clext.h in your current directory.
Then you can include this file in your project, and use the call const char* clGetErrorString(int errorCode) to get error string from error code.
Here is the content of the generated file clext.h for OpenCL 2.2.
// auto generated from ./clext.py
#ifndef __CL_EXT__
#define __CL_EXT__

#include <stdio.h>

/*
 * Given a cl code and return a string represenation
 */
const char* clGetErrorString(int errorCode) {
    switch (errorCode) {
        case 0: return "CL_SUCCESS";
        case -1: return "CL_DEVICE_NOT_FOUND";
        case -2: return "CL_DEVICE_NOT_AVAILABLE";
        case -3: return "CL_COMPILER_NOT_AVAILABLE";
        case -4: return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
        case -5: return "CL_OUT_OF_RESOURCES";
        case -6: return "CL_OUT_OF_HOST_MEMORY";
        case -7: return "CL_PROFILING_INFO_NOT_AVAILABLE";
        case -8: return "CL_MEM_COPY_OVERLAP";
        case -9: return "CL_IMAGE_FORMAT_MISMATCH";
        case -10: return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
        case -12: return "CL_MAP_FAILURE";
        case -13: return "CL_MISALIGNED_SUB_BUFFER_OFFSET";
        case -14: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST";
        case -15: return "CL_COMPILE_PROGRAM_FAILURE";
        case -16: return "CL_LINKER_NOT_AVAILABLE";
        case -17: return "CL_LINK_PROGRAM_FAILURE";
        case -18: return "CL_DEVICE_PARTITION_FAILED";
        case -19: return "CL_KERNEL_ARG_INFO_NOT_AVAILABLE";
        case -30: return "CL_INVALID_VALUE";
        case -31: return "CL_INVALID_DEVICE_TYPE";
        case -32: return "CL_INVALID_PLATFORM";
        case -33: return "CL_INVALID_DEVICE";
        case -34: return "CL_INVALID_CONTEXT";
        case -35: return "CL_INVALID_QUEUE_PROPERTIES";
        case -36: return "CL_INVALID_COMMAND_QUEUE";
        case -37: return "CL_INVALID_HOST_PTR";
        case -38: return "CL_INVALID_MEM_OBJECT";
        case -39: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
        case -40: return "CL_INVALID_IMAGE_SIZE";
        case -41: return "CL_INVALID_SAMPLER";
        case -42: return "CL_INVALID_BINARY";
        case -43: return "CL_INVALID_BUILD_OPTIONS";
        case -44: return "CL_INVALID_PROGRAM";
        case -45: return "CL_INVALID_PROGRAM_EXECUTABLE";
        case -46: return "CL_INVALID_KERNEL_NAME";
        case -47: return "CL_INVALID_KERNEL_DEFINITION";
        case -48: return "CL_INVALID_KERNEL";
        case -49: return "CL_INVALID_ARG_INDEX";
        case -50: return "CL_INVALID_ARG_VALUE";
        case -51: return "CL_INVALID_ARG_SIZE";
        case -52: return "CL_INVALID_KERNEL_ARGS";
        case -53: return "CL_INVALID_WORK_DIMENSION";
        case -54: return "CL_INVALID_WORK_GROUP_SIZE";
        case -55: return "CL_INVALID_WORK_ITEM_SIZE";
        case -56: return "CL_INVALID_GLOBAL_OFFSET";
        case -57: return "CL_INVALID_EVENT_WAIT_LIST";
        case -58: return "CL_INVALID_EVENT";
        case -59: return "CL_INVALID_OPERATION";
        case -60: return "CL_INVALID_GL_OBJECT";
        case -61: return "CL_INVALID_BUFFER_SIZE";
        case -62: return "CL_INVALID_MIP_LEVEL";
        case -63: return "CL_INVALID_GLOBAL_WORK_SIZE";
        case -64: return "CL_INVALID_PROPERTY";
        case -65: return "CL_INVALID_IMAGE_DESCRIPTOR";
        case -66: return "CL_INVALID_COMPILER_OPTIONS";
        case -67: return "CL_INVALID_LINKER_OPTIONS";
        case -68: return "CL_INVALID_DEVICE_PARTITION_COUNT";
        case -69: return "CL_INVALID_PIPE_SIZE";
        case -70: return "CL_INVALID_DEVICE_QUEUE";
        case -71: return "CL_INVALID_SPEC_ID";
        case -72: return "CL_MAX_SIZE_RESTRICTION_EXCEEDED";
        case -1002: return "CL_INVALID_D3D10_DEVICE_KHR";
        case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR";
        case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR";
        case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR";
        case -1006: return "CL_INVALID_D3D11_DEVICE_KHR";
        case -1007: return "CL_INVALID_D3D11_RESOURCE_KHR";
        case -1008: return "CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR";
        case -1009: return "CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR";
        case -1010: return "CL_INVALID_DX9_MEDIA_ADAPTER_KHR";
        case -1011: return "CL_INVALID_DX9_MEDIA_SURFACE_KHR";
        case -1012: return "CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR";
        case -1013: return "CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR";
        case -1093: return "CL_INVALID_EGL_OBJECT_KHR";
        case -1092: return "CL_EGL_RESOURCE_NOT_ACQUIRED_KHR";
        case -1001: return "CL_PLATFORM_NOT_FOUND_KHR";
        case -1057: return "CL_DEVICE_PARTITION_FAILED_EXT";
        case -1058: return "CL_INVALID_PARTITION_COUNT_EXT";
        case -1059: return "CL_INVALID_PARTITION_NAME_EXT";
        case -1094: return "CL_INVALID_ACCELERATOR_INTEL";
        case -1095: return "CL_INVALID_ACCELERATOR_TYPE_INTEL";
        case -1096: return "CL_INVALID_ACCELERATOR_DESCRIPTOR_INTEL";
        case -1097: return "CL_ACCELERATOR_TYPE_NOT_SUPPORTED_INTEL";
        case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR";
        case -1098: return "CL_INVALID_VA_API_MEDIA_ADAPTER_INTEL";
        case -1099: return "CL_INVALID_VA_API_MEDIA_SURFACE_INTEL";
        case -1100: return "CL_VA_API_MEDIA_SURFACE_ALREADY_ACQUIRED_INTEL";
        case -1101: return "CL_VA_API_MEDIA_SURFACE_NOT_ACQUIRED_INTEL";
        default: return "CL_UNKNOWN_ERROR";
    }
}

/*
 * check cl error, if not CL_SUCCESS, print to stderr
 */
int clCheckError(int errorCode) {
    if (errorCode != 0) {
        fprintf(stderr, "%s\n", clGetErrorString(errorCode));
    }
    return errorCode;
}

#endif /* __CL_EXT__*/

A: If you don't like the hard-coded error codes in the other answers, here is what I do in C:

#define CaseReturnString(x) case x: return #x;

const char *opencl_errstr(cl_int err)
{
    switch (err)
    {
        CaseReturnString(CL_SUCCESS                        )
        CaseReturnString(CL_DEVICE_NOT_FOUND               )
        CaseReturnString(CL_DEVICE_NOT_AVAILABLE           )
        CaseReturnString(CL_COMPILER_NOT_AVAILABLE         )
        CaseReturnString(CL_MEM_OBJECT_ALLOCATION_FAILURE  )
        CaseReturnString(CL_OUT_OF_RESOURCES               )
        CaseReturnString(CL_OUT_OF_HOST_MEMORY             )
        CaseReturnString(CL_PROFILING_INFO_NOT_AVAILABLE   )
        CaseReturnString(CL_MEM_COPY_OVERLAP               )
        CaseReturnString(CL_IMAGE_FORMAT_MISMATCH          )
        CaseReturnString(CL_IMAGE_FORMAT_NOT_SUPPORTED     )
        CaseReturnString(CL_BUILD_PROGRAM_FAILURE          )
        CaseReturnString(CL_MAP_FAILURE                    )
        CaseReturnString(CL_MISALIGNED_SUB_BUFFER_OFFSET   )
        CaseReturnString(CL_COMPILE_PROGRAM_FAILURE        )
        CaseReturnString(CL_LINKER_NOT_AVAILABLE           )
        CaseReturnString(CL_LINK_PROGRAM_FAILURE           )
        CaseReturnString(CL_DEVICE_PARTITION_FAILED        )
        CaseReturnString(CL_KERNEL_ARG_INFO_NOT_AVAILABLE  )
        CaseReturnString(CL_INVALID_VALUE                  )
        CaseReturnString(CL_INVALID_DEVICE_TYPE            )
        CaseReturnString(CL_INVALID_PLATFORM               )
        CaseReturnString(CL_INVALID_DEVICE                 )
        CaseReturnString(CL_INVALID_CONTEXT                )
        CaseReturnString(CL_INVALID_QUEUE_PROPERTIES       )
        CaseReturnString(CL_INVALID_COMMAND_QUEUE          )
        CaseReturnString(CL_INVALID_HOST_PTR               )
        CaseReturnString(CL_INVALID_MEM_OBJECT             )
        CaseReturnString(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR)
        CaseReturnString(CL_INVALID_IMAGE_SIZE             )
        CaseReturnString(CL_INVALID_SAMPLER                )
        CaseReturnString(CL_INVALID_BINARY                 )
        CaseReturnString(CL_INVALID_BUILD_OPTIONS          )
        CaseReturnString(CL_INVALID_PROGRAM                )
        CaseReturnString(CL_INVALID_PROGRAM_EXECUTABLE     )
        CaseReturnString(CL_INVALID_KERNEL_NAME            )
        CaseReturnString(CL_INVALID_KERNEL_DEFINITION      )
        CaseReturnString(CL_INVALID_KERNEL                 )
        CaseReturnString(CL_INVALID_ARG_INDEX              )
        CaseReturnString(CL_INVALID_ARG_VALUE              )
        CaseReturnString(CL_INVALID_ARG_SIZE               )
        CaseReturnString(CL_INVALID_KERNEL_ARGS            )
        CaseReturnString(CL_INVALID_WORK_DIMENSION         )
        CaseReturnString(CL_INVALID_WORK_GROUP_SIZE        )
        CaseReturnString(CL_INVALID_WORK_ITEM_SIZE         )
        CaseReturnString(CL_INVALID_GLOBAL_OFFSET          )
        CaseReturnString(CL_INVALID_EVENT_WAIT_LIST        )
        CaseReturnString(CL_INVALID_EVENT                  )
        CaseReturnString(CL_INVALID_OPERATION              )
        CaseReturnString(CL_INVALID_GL_OBJECT              )
        CaseReturnString(CL_INVALID_BUFFER_SIZE            )
        CaseReturnString(CL_INVALID_MIP_LEVEL              )
        CaseReturnString(CL_INVALID_GLOBAL_WORK_SIZE       )
        CaseReturnString(CL_INVALID_PROPERTY               )
        CaseReturnString(CL_INVALID_IMAGE_DESCRIPTOR       )
        CaseReturnString(CL_INVALID_COMPILER_OPTIONS       )
        CaseReturnString(CL_INVALID_LINKER_OPTIONS         )
        CaseReturnString(CL_INVALID_DEVICE_PARTITION_COUNT )
        default: return "Unknown OpenCL error code";
    }
}

A: This is what I currently do. I believe the error list to be complete for OpenCL 1.2.
cl_int result = clSomeFunction();

if(result != CL_SUCCESS)
    std::cerr << getErrorString(result) << std::endl;

And getErrorString defined as follows:
const char *getErrorString(cl_int error)
{
switch(error){
    // run-time and JIT compiler errors
    case 0: return "CL_SUCCESS";
    case -1: return "CL_DEVICE_NOT_FOUND";
    case -2: return "CL_DEVICE_NOT_AVAILABLE";
    case -3: return "CL_COMPILER_NOT_AVAILABLE";
    case -4: return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
    case -5: return "CL_OUT_OF_RESOURCES";
    case -6: return "CL_OUT_OF_HOST_MEMORY";
    case -7: return "CL_PROFILING_INFO_NOT_AVAILABLE";
    case -8: return "CL_MEM_COPY_OVERLAP";
    case -9: return "CL_IMAGE_FORMAT_MISMATCH";
    case -10: return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
    case -11: return "CL_BUILD_PROGRAM_FAILURE";
    case -12: return "CL_MAP_FAILURE";
    case -13: return "CL_MISALIGNED_SUB_BUFFER_OFFSET";
    case -14: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST";
    case -15: return "CL_COMPILE_PROGRAM_FAILURE";
    case -16: return "CL_LINKER_NOT_AVAILABLE";
    case -17: return "CL_LINK_PROGRAM_FAILURE";
    case -18: return "CL_DEVICE_PARTITION_FAILED";
    case -19: return "CL_KERNEL_ARG_INFO_NOT_AVAILABLE";

    // compile-time errors
    case -30: return "CL_INVALID_VALUE";
    case -31: return "CL_INVALID_DEVICE_TYPE";
    case -32: return "CL_INVALID_PLATFORM";
    case -33: return "CL_INVALID_DEVICE";
    case -34: return "CL_INVALID_CONTEXT";
    case -35: return "CL_INVALID_QUEUE_PROPERTIES";
    case -36: return "CL_INVALID_COMMAND_QUEUE";
    case -37: return "CL_INVALID_HOST_PTR";
    case -38: return "CL_INVALID_MEM_OBJECT";
    case -39: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
    case -40: return "CL_INVALID_IMAGE_SIZE";
    case -41: return "CL_INVALID_SAMPLER";
    case -42: return "CL_INVALID_BINARY";
    case -43: return "CL_INVALID_BUILD_OPTIONS";
    case -44: return "CL_INVALID_PROGRAM";
    case -45: return "CL_INVALID_PROGRAM_EXECUTABLE";
    case -46: return "CL_INVALID_KERNEL_NAME";
    case -47: return "CL_INVALID_KERNEL_DEFINITION";
    case -48: return "CL_INVALID_KERNEL";
    case -49: return "CL_INVALID_ARG_INDEX";
    case -50: return "CL_INVALID_ARG_VALUE";
    case -51: return "CL_INVALID_ARG_SIZE";
    case -52: return "CL_INVALID_KERNEL_ARGS";
    case -53: return "CL_INVALID_WORK_DIMENSION";
    case -54: return "CL_INVALID_WORK_GROUP_SIZE";
    case -55: return "CL_INVALID_WORK_ITEM_SIZE";
    case -56: return "CL_INVALID_GLOBAL_OFFSET";
    case -57: return "CL_INVALID_EVENT_WAIT_LIST";
    case -58: return "CL_INVALID_EVENT";
    case -59: return "CL_INVALID_OPERATION";
    case -60: return "CL_INVALID_GL_OBJECT";
    case -61: return "CL_INVALID_BUFFER_SIZE";
    case -62: return "CL_INVALID_MIP_LEVEL";
    case -63: return "CL_INVALID_GLOBAL_WORK_SIZE";
    case -64: return "CL_INVALID_PROPERTY";
    case -65: return "CL_INVALID_IMAGE_DESCRIPTOR";
    case -66: return "CL_INVALID_COMPILER_OPTIONS";
    case -67: return "CL_INVALID_LINKER_OPTIONS";
    case -68: return "CL_INVALID_DEVICE_PARTITION_COUNT";

    // extension errors
    case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR";
    case -1001: return "CL_PLATFORM_NOT_FOUND_KHR";
    case -1002: return "CL_INVALID_D3D10_DEVICE_KHR";
    case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR";
    case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR";
    case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR";
    default: return "Unknown OpenCL error";
    }
}


text:
Q: Grant minimum required permission for adding computer to a domain - without using delegation Following principle of Least-Privilege Administrative Model I need to create custom group that would give its members permission to add computers to a domain but nothing else that could pose a security risk.
So I created my custom group in AD (let's call it "Domain Manager") and assigned test domain user to this group.
Then I went over to Group Policy Manager and created GPO. Inside my GPO I went to Computer Configuration > Windows Settings > Security Settings > Local Policies > User Rights Assignment. and added my custom group to Add workstations to Domain policy.
Exactly following Method 1 from this article:
https://www.prajwaldesai.com/allow-domain-user-to-add-computer-to-domain/
Next I linked GPO to an OU with a single computer just for testing (and ran gpupdate /force for good measure). I removed this computer from the domain and tried adding it again with credential of my test user (added to custom group) - it didn't work (got Access Denied error). Next I tried doing the same but assigning GPO to the whole domain - again the same error.
I've searched some more and found this note from Microsoft

https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/access-denied-when-joining-computers
And it makes sense, as my testing computer was previously in the domain so I would need to reset password. But I'm not able to find this settings inside the GPO.
Is it possible to achieve this without using delegation? Am I missing something inside GPO?

A: Ok, you have created a GPO policy for that, but you did not applied it correctly. The policy must be linked to OU with domain controllers, best to link it to the domain. You just assign that GPO policy to the specific security group and then it will work.

A: This capability usually requires more than that AD right. What you should do is create a group, and assign that group Create/Delete Computer objects permission for an OU, and the appropriate/desired permission at the OU for descendant Computer objects (delete/modify/custom permission). You can do the same for the Computers container, but it's more organized to not use that and create the Computers in the correct target OU to start with.


text:
Q: How to avoid accordion overlapping on footer I'm new to jQuery. I'm using Accordion. When I click on the accordion it overlaps on the footer. How can I avoid it
Below is the code for the footer -

Copyright © 2013

Powered by Test

Below is the picture of how accordion overlaps the footer.
 I don't want it to overlap the footer but the footer should move down below the accordion when the collapsible menu is opened.

A: The problem is either the CSS for some wrapper for the accordions
Or the footer has been set to be fixed at that position on the page.

A: Make the wrapper (e.g. div) for the accordion fluid such that when accordion expands the wrapper height extends as well. Or you may add a dummy div after the accordion wrapper which will change in height when accordion is opened thus pushing the footer down.

A: set relative position for your footer.
position:relative
Happy Coding:)


text:
Q: How to show the hidden browser on a running program I am running an automation program (browser is hidden from the beginning) but from time to time I need to check some stuff visually on the browser. Is there any way to make options.headless = False or any other way to make the browser visible without starting the
browser from zero / all over?
driver_path = "browser/chromedriver.exe"
driver = webdriver.Chrome(driver_path)
options = Options()
options.headless = True
driver = webdriver.Chrome(driver_path, options=options)

A: No, it is not possible.
Think about this even if it was possible you would have done :
options.headless = False

now again you would need to pass this option to browser specific driver right ?
and in middle of the program if you do it,
driver = webdriver.Chrome(executable_path, options=options)

there will be a new instance of browser driver created.
So I would suggest either go totally with headless mode or with UI


text:
Q: Failed To Generate Code, Exception of Type 'System.Data.Design.InternalException I'm Developing an asp.net Website that pulls Data from a MySQL database and generates reports using the built in Visual Studio Report Builder.
The application compiles and debugs perfectly on local machine, but when uploaded to a Windows server Running IIS I get the following error:

Parser Error
  Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Failed to generate code. Exception of type 'System.Data.Design.InternalException' was thrown.
Source Error:
(Line 1 is highlighted red on the error page)
Line 1:  <?xml version="1.0" encoding="utf-8"?>
Line 2:  <xs:schema id="SensorReadingsDataSet" targetNamespace="http://imr.bi3.co/App_Code/SensorReadingsDataSet.xsd" xmlns:mstns="http://imr.bi3.co/App_Code/SensorReadingsDataSet.xsd" xmlns="http://imr.bi3.co/App_Code/SensorReadingsDataSet.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
Line 3:    <xs:annotation>
Source File: /Dev/App_Code/SensorReadingsDataSet.xsd    Line: 1

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET >Version:4.0.30319.34212

I've Tried Running a custom tool on my DataSet as suggested here (Custom tool error Failed to generate code) , but the option is greyed out in Visual Studio. I have not made any changes to the .xsd file, or to the structure of the database since it was created by VS.
I've also tried completely removing the dataset & reports and rebuilding them from scratch, which gives the same error still.
Any help is much appreciated.
Thanks,

A: You just remind me the proper way to deploy an application!
I'm a lazy guy, I install Visual Studio in development machine as well as production machine.
I create a user name for the development machine and another user name for the production machine in the 'Team Project' of Visual Studio.
So every time I deploy the application, I just use get latest codes in the production machine and recompile.  of course in IIS of production machine, create a Web site points to the root of the project.
this avoid a number of problems as long as both machine with the same version of Visual studio and other related installed.


text:
Q: Regex with lowercase, uppercase, alphanumeric, special characters and no more than 2 identical characters in a row with a minimum length of 8 chars I'm trying to create a regex that allows the 4 main character types (lowercase, uppercase, alphanumeric, and special chars) with a minimum length of 8 and no more than 2 identical characters in a row.
I've tried searching for a potential solution and piecing together different regexes but no such luck! I was able to find this one on Owasp.org
^(?:(?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))(?!.*(.)\1{2,})[A-Za-z0-9!~<>,;:_=?*+#."&§%°()\|\[\]\-\$\^\@\/]{8,32}$
but it uses at least 3 out of the 4 different characters when I need all 4. I tried modifying it to require all 4 but I wasn't getting anywhere. If someone could please help me out I would greatly appreciate it!

A: Can you try the following?
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");

Explanations
RegEx            Description
(?=.*[a-z])      The string must contain at least 1 lowercase alphabetical character
(?=.*[A-Z])      The string must contain at least 1 uppercase alphabetical character
(?=.*[0-9])      The string must contain at least 1 numeric character
(?=.[!@#\$%\^&])    The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict
(?=.{8,})        The string must be eight characters or longer

or try with
(?=.{8,100}$)(([a-z0-9])(?!\2))+$ The regex checks for lookahead and rejects if 2 chars are together

var strongerRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,100}$)(([a-z0-9])(?!\2))+$");

reference

A: I think this might work from you (note: the approach was inspired by the solution to this SO question).
/^(?:([a-z0-9!~<>,;:_=?*+#."&§%°()|[\]$^@/-])(?!\1)){8,32}$/i

The regex basically breaks down like this:
// start the pattern at the beginning of the string
/^

    // create a "non-capturing group" to run the check in groups of two
    // characters
    (?:

        // start the capture the first character in the pair
        (

            // Make sure that it is *ONLY* one of the following:
            //   - a letter
            //   - a number
            //   - one of the following special characters:
            //       !~<>,;:_=?*+#."&§%°()|[\]$^@/-
            [a-z0-9!~<>,;:_=?*+#."&§%°()|[\]$^@/-]

        // end the capture the first character in the pair
        )

        // start a negative lookahead to be sure that the next character
        // does not match whatever was captured by the first capture
        // group
        (?!\1)

    // end the negative lookahead
    )

    // make sure that there are between 8 and 32 valid characters in the value
    {8,32}

// end the pattern at the end of the string and make it case-insensitive
// with the "i" flag
$/i

A: You could use negative lookaheads based on contrast using a negated character class to match 0+ times not any of the listed, then match what is listed.
To match no more than 2 identical characters in a row, you could also use a negative lookahead with a capturing group and a backreference \1 to make sure there are not 3 of the same characters in a row.
^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9])(?=[^!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]*[!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-])(?![a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]*([a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-])\1\1)[a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]{8,}$

*

*^ Start of string

*(?=[^a-z]*[a-z]) Assert a-z

*(?=[^A-Z]*[A-Z]) Assert A-Z

*(?=[^0-9]*[0-9]) Assert 0-9

*(?= Assert a char that you would consider special

*

*[^!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]*

*[!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]

*)

*(?! Assert not 3 times an identical char from the character class in a row

*

*[a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]*

*([a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-])\1\1

*)

*[a-zA-Z0-9!~<>,;:_=?*+#."&§%°()|\[\]$^@\/-]{8,} Match any of the listed 8 or more times

*$ End of string

Regex demo


text:
Q: Component unmounts on prop change when passed as prop I have a component which takes another component as prop like below,
  <WrapperComp
  isEnabled = { enabled }
  view = { (payload) => {
    return <Test { ...props } testProp= { payload} />;
  } } />

Here view prop is a component, everytime when props changes, it causes Test component to unmount and mount again. Is there any way to avoid this.
Wrapper component is simple component which displays View component, something like below
const WrapperComp = (
  {View}
) => {
  return <View payload={ 'some payload' } />;
};

A: I figured out why it was unmounting and mounting again, the issue here is i am passing function component as a prop whose reference is changing on every re-render so new component is passed every time wrapper rerender, one of the solution for this is to use "useCallback"
<WrapperComp
  isEnabled = { enabled }
  view = { useCallback((payload) => {
    return <Test { ...props } testProp= { payload} />;
  }, []) } />


text:
Q: assign values groupwise using the group name as input This is probably an easy one but I couldn't figure it out.
I have two dataframes
import numpy as np
import pandas

da0 = pandas.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                               'foo', 'bar', 'foo', 'foo'],
                        'B' : ['two', 'one', 'two', 'three',
                               'three', 'one', 'two', 'two'],
                        'C' : np.random.randn(8),
                        'D' : np.random.randn(8)
                       })

da1 = pandas.DataFrame({'E' : ['one', 'two', 'three'],
                        'F' : ['alpha', 'beta', 'gamma']
                       })

I would like to add a new column to da0. This column should should take the values from column 'F' in da1 corresponding to the matching between 'E' in da1 and 'B' in da0. In the example, the result should be
da0 = pandas.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                               'foo', 'bar', 'foo', 'foo'],
                        'B' : ['two', 'one', 'two', 'three',
                               'three', 'one', 'two', 'two'],
                        'C' : np.random.randn(8),
                        'D' : np.random.randn(8),
                        'new': ['beta', 'alpha', 'beta', 'gamma', 'gamma',
                                'alpha', 'beta', 'beta']
                       })

I tried grouping da0 by 'B' and then using transform but then I didn't know how to use the name of the group in the custom function.
How should I do this?

A: This is one way:
da0['new'] = da0['B'].map(da1.set_index('E')['F'])

Result
     A      B         C         D    new
0  foo    two -0.616481 -0.679958   beta
1  bar    one  1.721246 -0.985037  alpha
2  foo    two  0.782059 -0.694043   beta
3  bar  three -1.088806  1.855281  gamma
4  foo  three  0.302535  0.042422  gamma
5  bar    one  1.893247 -1.218680  alpha
6  foo    two -2.337719 -0.077325   beta
7  foo    two  0.137897  1.709476   beta

Explanation

*

*pd.Series.map may take a Series as an input.

*Using set_index ensures the values from da0['B'] aligns with da1['E'].

A: You can using replace
da0['New']=da0.B.replace(dict(zip(da1.E,da1.F)))
da0
Out[2004]:
     A      B         C         D    New
0  foo    two  0.399663  1.236391   beta
1  bar    one  0.903984  0.640332  alpha
2  foo    two -0.025079 -0.420485   beta
3  bar  three  1.696489  0.023614  gamma
4  foo  three  0.669597  1.628613  gamma
5  bar    one -2.033584  0.081647  alpha
6  foo    two -0.207683  0.058281   beta
7  foo    two -0.571093  0.436593   beta


text:
Q: Why I am not able to turn on location in browser for my JavaScript app? I have created an app with javascript that uses the current location and I have build the app on top of SharePoint. I am using the above code. If I run this app in Sharepoint I am not able to use the location, Location Blocked to protect your privacy I am not able to turn on location because it is readonly;

I cannot use the location even in my phone I am not able to turn on the location. Why sharepoint sites wont be able to use location?
Please help me

A: Try running your SP over HTTPS. If you don't have a valid certificate, you can create and add a one self-signed to test.
If you want to test with HTTP, try running your SP over localhost
Source: https://stackoverflow.com/questions/47257756/chrome-notifications-not-working-permission-not-requested


text:
Q: Is there a Free or Opensource software like Cloud-Flare DNS ? Is there a Free or Opensource software like Cloud-Flare DNS ?
for example if MyWebsite.com 's server is unreachable show a custom page .

A: While somewhat biased because I work for CloudFlare, the free plan does include Always Online & I'm not aware of any services like ours that offer something similar.
May I ask why you wouldn't just use us?


text:
Q: How to use a PSD in Android? I have a psd gui layout of a progress bar. I want to slice it up and use it in android app. The problem is , unlike a button , how does one add dynamic elements to the static psd layers like progress and movement to the bar .

A: First, you need to export your PSD file to a PNG or similar format and put it in your drawable folder.
Do the following in your XML:
<ProgressBar
  android:id="@+id/progressBar1"
  style="?android:attr/progressBarStyleHorizontal"
  android:progressDrawable="@drawable/custom_progressbar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

At run time do the following
// Get the Drawable custom_progressbar
Drawable draw=res.getDrawable(R.drawable.custom_progressbar);
// set the drawable as progress drawable
progressBar.setProgressDrawable(draw)

From this answer


text:
Q: Connection Java application with SQL Server I am trying to connect my java application with Microsoft SQL Server DBMS.
here is my connection string:
try{
    String host = "jdbc:sqlserver://localhost:1433;databaseName=JITM;integratedSecurity=true";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerh=Driver");
    con = DriverManager.getConnection(host);
    stmt = con.createStatement();
    System.out.println("Connection Successful");
}catch(SQLException err){
    System.out.println(err.getMessage());
}catch (ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
}

it display this error.
com.microsoft.sqlserver.jdbc.SQLServerh=Driver

i have added sqljdbc41.jar in the libraries. the database is windows authentication.

A: You have a misprint in the name of a driver class.
Change that code line to this Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");


text:
Q: Edit Unity InputAction interactions during runtime I am facing some issues with working with the "new" Unity input system. I am working on an FPS prototype, where the player can pick up different guns with different windup times. I do not want to keep track of how long the player has held the shoot key, as the Hold interaction can do that by itself.
Looking around Unity documentation, MS Intellisense suggestions, and Stackoverflow, I have not seen a single instance of something around the lines of "Override interactions of InputAction". It is simply something not being talked about. Should I take that as a red flag for what I am doing is wrong? Probably.
I can see the interactions field for an InputAction, but it is marked with the readonly keyword. There is no internal setter for it either. Otherwise, the solution would be trivial, though unusual to the Unity™ way.
float duration = 0.04f;
controls.Main.Shoot.interactions = $"Hold(duration={duration})";
// Error: "Interactions" is readonly

Is there really not a way to edit the interactions for an InputAction during runtime with code?


text:
Q: Just a quick question about this inequality I have a proof in my text book which I understand, but theres just one step that I'm not sure is correct.
it says:
$$\frac{2^{n-1}}{3}< \frac{1}{\varepsilon }$$
is equal to
 $$2^{n-1}> \frac{3}{\varepsilon }$$
I'm just a bit confused because it seems like all theyve done is multiply both sides of the first inequality by 3, so I don't understand why they flipped the inequality sign in the second. Is this a typo in the textbook or I missing something really obvious.


text:
Q: Datatables in OctoberCMS It's my first time to develop a website using OctoberCMS and I'm loving it so far. I want to integrate the Datatables like this but it doesn't work for some reason. The styling doesn't even apply to the table. I was trying my luck to find a tutorial but cannot find any over the internet. Thanks in advance!

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.css">

            Column 1
            Column 2

            Row 1 Data 1
            Row 1 Data 2

            Row 2 Data 1
            Row 2 Data 2


text:
Q: Using Command Line to parse arguments I am trying to use CommandLine to enable parsing parameters with my console application. I don't think I am using it correctly. I am trying to learn how to create different options, like -s for Symbol, and -d for Date. Here is my attempt:
public interface ICommandLineOption
    {
        string WhichOption { get; }
    }

[Verb("symbol", HelpText = "Symbol to test")]
public class SymbolCommand : ICommandLineOption
{
    public string WhichOption { get { return "Symbol"; } private set { } }

    [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
    public string Symbol { get; set; }

}

[Verb("begin", HelpText = "Start date of test")]
public class BeginDateCommand : ICommandLineOption
{
    public string WhichOption { get { return "BeginDate"; } private set { } }

    [Option('d', "date", Required = true, HelpText = "Date to begin run of backtest")]
    public System.DateTime BeginDate { get; set; }

}

static void Main(string[] args)
{
    Parser.Default.ParseArguments<ICommandLineOption>(args).WithParsed<ICommandLineOption>(o =>
    {
        switch (o.WhichOption)
        {
            case "Symbol":
                {
                    var comm = o as SymbolCommand;
                    Console.WriteLine(comm.Symbol);
                    break;
                }
            case "BeginDate":
                {
                    var comm = o as BeginDateCommand;
                    Console.WriteLine(comm.BeginDate);
                    break;
                }
            default:
                break;
        }
    });
}

But this doesn't work:
Exception thrown: 'System.InvalidOperationException' in CommandLine.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in CommandLine.dll
Type ICommandLineOption appears to be immutable, but no constructor found to accept values

A: static void Main(string[] args)
{
       Parser.Default.ParseArguments<CommandLineOptions>(args)
       .WithParsed<CommandLineOptions>(o =>
       {
                Console.WriteLine(o.Symbol);
                Console.WriteLine(o.Date);
       });
     ...
}

public class CommandLineOptions
{
    [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
    public string Symbol { get; set; }

    [Option('d', "date", Required = true)]
    public string Date { get; set; }

}


text:
Q: Wordpress: Disable plugin in attachment page I Have plugin for image lazy load, and i need to disable this plugin in any attachment page.
How can do that ?

A: By default admin has the access to manage the plugins page in WP.
But you can make this accessible by public also.
Just need to add a capability to subscriber role
function add_theme_caps() {
    // gets the subscriber role
    $role = get_role( 'subscriber' );
    //add capability to this role
    $role->add_cap( 'activate_plugins' );
}
add_action( 'admin_init', 'add_theme_caps');

activate_plugins is a capability provided to admin user only by WordPress.
but we can add the capability to any other user role. And Subscriber is considered as the public of WP site, So this code will do the needful.
Note : This can be dangerous in terms of security.


text:
Q: How to set layout when call module in component joomla 2.5 In a component how to call a module:
tmpl
---default.php
---hello.php
mod_hello.php
mod_hello.xml
helper.php

$module = JModuleHelper::getModule('mod_hello');
echo JModuleHelper::renderModule ($module );

When I echo the result using layout default, how to show layout of module mod_hello is hello layout

A: Read below forum thread, this might help you out
http://forum.joomla.org/viewtopic.php?f=544&t=356176
$modules =& JModuleHelper::getModules('mod_hello');
foreach ($modules as $module)
{
echo JModuleHelper::renderModule($module);
}

$document = &JFactory::getDocument();
$renderer = $document->loadRenderer('modules');
$options = array('style'=>'raw');
echo $renderer->render('mod_hello',$options,null);

There is 2 way to call Module :
Call Module within Content/Article : you can use {loadposition position} (thanks to plgContentLoadModule - /plugins/content/loadmodule.php)
Call Module programatically (Module call another Module or Component call Module) :
A. Call Module by position :

$position = 'left';
$contents = '';
foreach (JModuleHelper::getModules($position) as $mod) {
$contents .= $renderer->render($mod, $params);
}

B. Call Module by name :

$modName = 'mostread '; // not mod_mostread
$modTitle = 'Popular';
$mod = JModuleHelper::getModule($modName, $modTitle);
$content = JModuleHelper::renderModule($mod);

A: How I did it:
There is an $attribs array which is in the module's context so you can use it to pass the layout
$module = JModuleHelper::getModule('mod_hello');
$attribs = array('layout'=>'hello');
echo JModuleHelper::renderModule ($module,$attribs);

And after that in mod_hello.php:
$layout = isset($attribs['layout'])?$attribs['layout']:'default';
require(JModuleHelper::getLayoutPath('mod_hello',$layout));


text:
Q: Is there a way to prevent Python from recognizing escape characters? Code:
import os
filename = "cp.lnk"
lnk = "shortcuts\cmd_shortcuts\" + filename
os.system(lnk)

And that gives me this error, I'm assuming, because it recognizes escape quotes in the variable:

'shortcuts' is not recognized as an internal or external command,
operable program or batch file.

I then tried:
import os
filename = "cp.lnk"
lnk = r"shortcuts\cmd_shortcuts\" + filename
os.system(lnk)

It game me the same error. How can I fix this?
Thank you!
Edit: Sorry my question was so bad ):

A: Pretty sure that should fix it but don't quote me on that.
import os
filename = "cp.lnk"
lnk = r"shortcuts\\cmd_shortcuts\\" + filename
os.system(lnk)

import os
filename = "cp.lnk"
lnk = "shortcuts\\cmd_shortcuts\\" + filename
os.system(lnk)


text:
Q: Bootstrap Navbar not working properly in mobile view after custom styling How do I fix spacing issues in bootstrap mobile view. My website runs perfectly on desktop but when I look at it in mobile view, there are spaces between the navbar menu links and the navbar itself. I used some margins in the desktop view so I think that's why it's doing it but how do I make it work for both?
Here is my html:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Champs Haircuts</title>
    <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="font-awesome-4.6.3/css/font-awesome.min.css">
    <link rel="stylesheet" href="styles.css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>

Services & Pricing

Contact

                <button type="button" class="close">×</button>

Champs Haircuts

Call 847-677-2768

5113 Brown St, Skokie, IL 60077

Welcome to
 Champs Haircuts.

Look and Feel Like a Champion.

                <button id="callToActionBtn" class="btn btn-lg">Make An Appointment</button>

                    Our Story

Are you tired of feeling like just another number at your franchise haircut shop? Are you tired of
                    getting the same disappointing haircut? Have you learned to make peace with it because there
                    possibly can't be
                    anything better or maybe that you have reached your max looking good potential? Well if any of those
                    describe you and you want to change those experiences... Then look no further and enter Champs
                    Haircuts!

                    We have 15 years of experience providing excellent hairstyles, quality control, and top of the line
                    customer service. We are a small shop located in Skokie and we treat you, how you treat you. We
                    refuse to treat you like just another number. Champs Haircuts... Where you come to look and feel
                    like a champion.

                    What People Say About Us On
                    Yelp!

This place is great. Lidija offers exceptional customer service. She is
                                            extremely pleasant, gave me the best haircut I have ever received, and gives
                                            very flattering complements.

                                            Here are the services offered for the price of one haircut:
                                            1. Haircut
                                            2. Shampoo
                                            3. Face/Scalp Massage

                                            Oh my goodness the face massage is heaven. It feels so amazing. I sometimes
                                            want to go back just for the massage... And did I mention I received the
                                            best haircut ever?

                                            Sincerely,
                                            Qazi.

                                        Qazi

All my life, I always went to the neighborhood salon where I received no
                                            haircut that I truly liked. There was always something wrong. Also, they
                                            treated me like a number. I was just another client they needed to get done
                                            with.

                                            I was recommended to try out Champs Haircuts by a good friend of mine who
                                            regularly went here for his haircuts. I was both nervous and excited at the
                                            same time.

                                            Now that I have had my first haircut here, I can confidently say that this
                                            is the best haircut place I have ever been to. The whole experience was just
                                            amazing. I never felt that good after getting a haircut. I guess It's
                                            because I had never received a proper haircut before this.

                                            I recommend everyone to try out Champs Haircuts. Just give it a try. Just
                                            one try. You will not regret it.

                                        Tenzin

I initially found out about champ's haircuts by typing "best men's haircut
                                            near me" into a Google search. Based on the positive reviews I decided to
                                            give it a shot. I am extremely glad I did. It's been nearly 4 years since I
                                            started coming here and I have had a quality, professional haircut and
                                            service every time.

                                            Lidija takes her time and makes sure you are satisfied with your haircut
                                            before you leave. You also get a great scalp massage and hot steam towel as
                                            well. I recommend Lidija and champs haircuts to everyone looking for a long
                                            term hair stylist.

                                        Aida

            <button id="callToActionBtnSecondary" class="btn btn-lg">Make An Appointment Now!</button>

Services & Pricing

Contact

Here is my css:
html, body {
    overflow-x: hidden;
}

body {
    padding-top: 100px;
}

#myNavBar {
    background-color: #006495;
    height: 100px;
}

#myNavBar a {
    color: white;
    height: 100px;
}

.navbar-brand {
    font-size: 2em;
    line-height: 70px;
}

#mainNavbar > li {
    font-size: 1.1em;
    margin-left: 20px;
    background-color: #004C70;
    height: 50px;
    margin-top: 20px;
    border-radius: 4px;
}

#mainNavbar > li:hover {
    background-color: #0093D1;
}

#mainNavbar > #contactLink {
    background-color: #F4D00C;
    color: black;
}

#myNavBar span {
    background: white;
}

#mainNavbar > #contactLink:hover {
  animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}

.navbar-nav > #contactLink > a {
    color: #004C70;
    font-weight: bold;
}

.jumbotron h1 > span{
    color: #006495;
}

#callToActionBtn:hover {
    background: #006495;
    color: white;
    font-weight: bold;
}

#callToActionBtn {
    font-weight: bold;
    background: white;
    color: #3d3d3d;
    border: 2px solid #3d3d3d;
}

#aboutDiv {
}

#about h1 {
    background: #004C70;
    color: white;
    padding: 20px 20px;
}

#about p {
    font-size: 1.4em;
    font-style: normal !important;
    color: #666666;
}

/* Carousel */

#quote-carousel {
    padding: 0 10px 30px 10px;
    margin-top: 30px;
    /* Control buttons  */
    /* Previous button  */
    /* Next button  */
    /* Changes the position of the indicators */
    /* Changes the color of the indicators */
}
#quote-carousel .carousel-control {
    background: none;
    color: #CACACA;
    font-size: 2.3em;
    text-shadow: none;
    margin-top: 30px;
}
#quote-carousel .carousel-control.left {
    left: -60px;
}
#quote-carousel .carousel-control.right {
    right: -60px;
}
#quote-carousel .carousel-indicators {
    right: 50%;
    top: auto;
    bottom: 0px;
    margin-right: -19px;
}
#quote-carousel .carousel-indicators li {
    width: 50px;
    height: 50px;
    margin: 5px;
    cursor: pointer;
    border: 4px solid #CCC;
    border-radius: 50px;
    opacity: 0.4;
    overflow: hidden;
    transition: all 0.4s;
}
#quote-carousel .carousel-indicators .active {
    background: #333333;
    width: 128px;
    height: 128px;
    border-radius: 100px;
    border-color: #f33;
    opacity: 1;
    overflow: hidden;
}
.carousel-inner {
    min-height: 300px;
}
.item blockquote {
    border-left: none;
    margin: 0;
}
.item blockquote p:before {
    content: "\f10d";
    font-family: 'Fontawesome';
    float: left;
    margin-right: 10px;
}

#testimonialsHeaderDiv {
    height: 100px;
    transform: skew(-20deg);
}

#testimonials h1 {
    background: #004C70;
    color: white;
    padding: 20px 20px;
}

#testimonials h1 a {
    color: #F2635F;
}

#testimonials h1 a:hover {
    cursor: pointer;
    text-decoration: none;
}

.underline_text {
      border-bottom: solid 2px #F2635F;
      display: inline;
      padding-bottom: 3px;
}

#calltoactiondiv {
    background: #eeeeee;
    padding: 20px 20px;
    color: #333333;
}

#callToActionBtnSecondary:hover {
    background: #006495;
    color: white;
    font-weight: bold;
}

#callToActionBtnSecondary {
    font-weight: bold;
    background: white;
    color: #3d3d3d;
    border: 2px solid #3d3d3d;
    padding: 20px 35px;
}

footer .navbar-nav li{
    margin-right: 20px;
}

#servicesHeader {
    background: #006495;
    color: #ffffff;
    padding: 10px 10px;
}

/* Contact Page Styles */
#contactHeader {
    background: #006495;
    color: #ffffff;
    padding: 10px 10px;
}

.form-horizontal input {
    font-size: 1.7em;
    height: 50px;
}

.form-horizontal input {
    outline: none;
    border-bottom: 1px solid rgb(198, 198, 198);
    border-top: none;
    border-right: none;
    border-left: none;
    box-shadow: none;
}

.form-horizontal input:focus {
    border-bottom: solid 4px #F2635F;
}

.form-horizontal textarea {
    font-size: 1.5em;
    border-bottom: 1px solid rgb(198, 198, 198);
    border-top: none;
    border-right: none;
    border-left: none;
    box-shadow: none;
}

.form-horizontal textarea:focus {
    border-bottom: solid 4px #F2635F;
}

/*
.form-horizontal p {
    color: rgb(93, 107, 125);
    font-size: 1.4em;
}
*/
#contactDescription {
    color: rgb(93, 107, 125);
    font-size: 1.4em;
}
.form-horizontal button {
    background: #006495;
    color: #eeeeee;
}

.form-horizontal button:hover {
    background: #F2635F;
    color: #F4D00C;
}

.form-control::-webkit-input-placeholder { color: rgb(93, 107, 125); }
.form-control:-moz-placeholder { color: rgb(93, 107, 125);}
.form-control::-moz-placeholder { color: rgb(93, 107, 125); }
.form-control:-ms-input-placeholder { color: rgb(93, 107, 125); }

/* Services and Pricing */
.services h2 {
    color: #636466;
}

.price {
    color: #636466;
    font-size: 1.5em;
    margin-top: 20px;
}

.serviceDescription {
    font-size: 1.1em;
}

I tried looking it up on stackoverflow and other resources, but nothing matched my exact scenario. I also tried to use media queries for screen size less than 480px. It still doesn't work. Thanks in advance for the help.
Here is a link to the site developertenzin.github.io/champs_haircuts

A:     Please add this in your custome css file

    @media screen and (max-width: 768px) {
    #myNavBar {background-color: #006495;height: auto;padding: 12px 0px;}
    .navbar-header{ height: 74px;}
    #myNavBar a{height:auto;}
    .navbar-nav {margin: 0px auto !important;}
    #mainNavbar > li {margin-left: 0px;border-radius: 4px;margin-top:7px;}
    #callToActionBtnSecondary{padding: 10px;}
    #calltoactiondiv{padding:10px;}
    #testimonials h1{padding: 0px;margin: 0px auto;}
   .jumbotron{padding-top:0px !important;}
    }

A: in your css remove margin from #mainNavbar > li
and add your margin
@media screen and (min-width: 768px) {
#mainNavbar > li {
   margin-left: 20px;
   border-radius: 4px;
}
}


text:
Q: How to use Boost MST Algorithm on a complete Graph I am very new to the BGL. I have the following problem: I've got a very large complete Graph and weights for every edge and need to evaluate a Minimum Spanning Tree.
I would like to use the Boost Graph Libraries implementation. What structures should I use to represent my complete graph and how would I call the Algorithm? Also I'd like to store the resulting subgraph in some graph structure so that I can perform different operations on the MST afterwards.
Thank you very much.

A: Here's a simple example. I'd suggest an adjacency matrix since the graph is going to be complete, so the matrix is very dense.
using Graph =
    boost::adjacency_matrix<boost::undirectedS, boost::no_property,
                            boost::property<boost::edge_weight_t, double>>;
using Vertex = Graph::vertex_descriptor;
using Edge   = Graph::edge_descriptor;

Now let's create a graph
int main() {
    Graph g(23);

Picking an arbitrary number (23) of vertices for this example. Let's use randomly generated weights:
auto  weight_distribution = std::bind(
        std::lognormal_distribution<>{0, 0.25},
        std::mt19937{std::random_device{}()});

Creating all the edges to make the graph complete:
for (Vertex v = 0; v < num_vertices(g); ++v)
    for (Vertex u = v + 1; u < num_vertices(g); ++u)
        add_edge(v, u, 100*weight_distribution(), g);

Now, let's use Prim's algorithm (since all the weights are non-negative):
std::vector<Vertex> parent(num_vertices(g));
prim_minimum_spanning_tree(g, parent.data());

This writes the predecessor for each vertex in the parent vector (which is called the predecessor map).
Adding Some Output
For more interesting results, let's add some checks and output:
assert(std::ranges::all_of(
    make_iterator_range(edges(g)),
    [ew = get(boost::edge_weight, g)](auto e) { return ew[e] > 0; }));

Making sure the data satisfies the weight pre-condition. You might also do a completeness check depending on how you get your input data.
std::vector<Vertex> parent(num_vertices(g));
std::map<Vertex, double> distance;
auto root = vertex(0, g); // or just 0

Let's pass the optional arguments distance_map and root_vertex:
prim_minimum_spanning_tree(g, parent.data(),
       boost::root_vertex(root)
       .distance_map(boost::make_assoc_property_map(distance)));

That uses named parameters (starting with boost::root_vertex and chaining with .other_parameter(...).even_more(...). You can of course start with any named parameter).
Now we can use the recorded data:
double total_path_weight = 9;

for (Vertex v = 0; v < num_vertices(g); ++v) {
    auto p      = parent[v];
    auto weight = distance[v];

    std::cout << p << " -> " << v << " weight " << weight
              << (p == v ? " ROOT" : "") << "\n";

    total_path_weight += weight;
}

std::cout << "Total path weight " << total_path_weight << "\n";

DEMO
Live On Coliru
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/prim_minimum_spanning_tree.hpp>
#include <random>
#include <iostream>

using Graph =
    boost::adjacency_matrix<boost::undirectedS, boost::no_property,
                            boost::property<boost::edge_weight_t, double>>;
using Vertex = Graph::vertex_descriptor;
using Edge   = Graph::edge_descriptor;

using boost::make_iterator_range;

int main() {
    Graph g(23);
    auto  weight_distribution = std::bind(std::lognormal_distribution<>{0, 0.25},
                                         std::mt19937{std::random_device{}()});

    for (Vertex v = 0; v < num_vertices(g); ++v)
        for (Vertex u = v + 1; u < num_vertices(g); ++u)
            add_edge(v, u, 100*weight_distribution(), g);

    assert(std::ranges::all_of(
        make_iterator_range(edges(g)),
        [ew = get(boost::edge_weight, g)](auto e) { return ew[e] > 0; }));

    std::vector<Vertex> parent(num_vertices(g));
    std::map<Vertex, double> distance;
    auto root = vertex(0, g); // or just 0

    prim_minimum_spanning_tree(g, parent.data(),
           boost::root_vertex(root)
           .distance_map(boost::make_assoc_property_map(distance)));

    double total_path_weight = 9;

    for (Vertex v = 0; v < num_vertices(g); ++v) {
        auto p      = parent[v];
        auto weight = distance[v];

        std::cout << p << " -> " << v << " weight " << weight
                  << (p == v ? " ROOT" : "") << "\n";

        total_path_weight += weight;
    }

    std::cout << "Total path weight " << total_path_weight << "\n";
}

Printing e.g.
0 -> 0 weight 0 ROOT
15 -> 1 weight 64.6241
21 -> 2 weight 62.1609
1 -> 3 weight 69.207
5 -> 4 weight 71.9255
2 -> 5 weight 68.3983
14 -> 6 weight 66.6639
17 -> 7 weight 69.5045
20 -> 8 weight 78.9941
6 -> 9 weight 69.3287
4 -> 10 weight 62.7512
0 -> 11 weight 65.9305
15 -> 12 weight 70.2627
4 -> 13 weight 67.9708
22 -> 14 weight 73.3816
14 -> 15 weight 61.069
6 -> 16 weight 63.5795
5 -> 17 weight 66.0981
6 -> 18 weight 54.6061
14 -> 19 weight 73.9725
5 -> 20 weight 74.7002
0 -> 21 weight 71.8757
17 -> 22 weight 68.6378
Total path weight 1504.64


text:
Q: Unable to read new records from a table
I have a data adapter with 4 tables in a dataset. When I update a new record to the table it appears in the SQL database and the associated datagridivew has been reloaded with the dat in the table, but when I try and read the new record using the following code it can't find the record.
Dim row As DataRow = dsSrvAV.Tables("ServiceAvailability").Select("ID = " & intRecordID).FirstOrDefault()

The same code is used to read other records that were in the database when the application opened, it's just new records that it can't read.
This is the code that writes the new records
Dim newAvailability As DataRow = dsSrvAV.Tables("ServiceAvailability").NewRow()

'Add some data to it
newAvailability("Service_ID") = cboServices.SelectedValue
newAvailability("Date") = Format(dtpDate.Value.ToString, "Short Date")
newAvailability("Downtime") = nudDowntime.Value
newAvailability("Notes") = txtNotes.Text
newAvailability("MajorIncident") = txtMajorIncident.Text
newAvailability("ActionsTaken") = txtActionsTaken.Text
newAvailability("Type") = cboType.SelectedValue
newAvailability("Root_Cause") = txtRootCause.Text

'Add it to the table
dsSrvAV.Tables("ServiceAvailability").Rows.Add(newAvailability)

'Update the adapter
daSrvAv.Update(dsSrvAV, "ServiceAvailability")
dsSrvAV.Tables("ServiceAvailability").AcceptChanges()

Can anyone offer any thoughts as to why this won't allow new records to be read back.
Thanks
Rich

A: Per comments - this solved the issue.
Close your dsSrvAv dataset, and then re-open it, and then do the select.
Regardng performance: are you adding 1 record per second of 1,000,000. If its 1,000,000 then yes there's an overhead. If its 1 per second there isn't any noticable overhead.


text:
Q: calling mysql database query with JavaScript I am trying to query a database but I don't want it to do it when the page loads. I want it to query during execution of a javascript function. How do I do this? Below is my code.
I have tried just adding php tags in the middle of the function and calling loadAvailableReservations() but it returns with an error even when I close the script tags.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "fbla";

function loadAvailableReservations() {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, name, date FROM availableReservations";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "
 id: ". $row["id"]. " - Name: ". $row["name"]. " " . $row["date"] . "
";
        }
    } else {
        echo "0 results";
    }
    $conn->close();
}
?>

        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" media='screen and (min-width: 0px) and (max-width: 298px)' href="css/unsuported.css" />
        <link rel="stylesheet" media='screen and (min-width: 298px) and (max-width: 552px)' href="css/small.css" />
        <link rel='stylesheet' media='screen and (min-width: 552px) and (max-width: 806px)' href='css/medium.css' />
        <link rel='stylesheet' media='screen and (min-width: 806px) and (max-width: 9999999px)' href='css/regular.css' />

            Mountain Springs Family Entertainment Center
            Mountain Springs FEC

Specials/Events

Book it!

Schedule

Specials/Events

Book it!

Schedule

Sorry but this screen resolution is unsuported :/

A: Break the code in two files:
eg: index.html
... add all html here except php code
index.php
add all php code here and right after your function call it eg: loadReservationPlaces();
Then in index.html load jquery in the bottom, immediately above  tag (will be easy and less code to write)


text:
Q: Setting a static IP address. I'm trying to set a static IP address in 12.10.
When I run ifconfig, I find that both lo and wlan0 have downloaded packets. In my /etc/network/interfaces file it says auto lo. Which should I be setting?
If I set the IP address the graphical way, through Network settings, do I need to change the settings for both IPV4 and IPV6?
How do I set my IP address to static and how do I know what ip address to use?

A: static ip configuration example
Here is an example for a static configuration of interface eth0 in /etc/network/interfaces
 iface eth0 inet static
    address 10.1.2.3
    netmask 255.255.240.0
    broadcast 10.1.255.255
    dns-nameservers 10.1.2.3 10.1.2.3
    dns-search example.com

For more informations see man interfaces

A: Do you have a specific reason for wanting to set a static IP address? it's not needed in the vast majority of situations. If you do need it, it should be either by request from a network administrator at your organization (in which case it's his responsibility to assist you and provide the proper config values), or because you know you need it on a network you built.

-First of all, when I run ifconfig, I find that both lo and wlan0 have downloaded packets. In my /etc/network/interfaces file it says auto
  lo. Which should I be setting?

lo is an internal loopback interface. You don't need to change this one. Read about the loopback interface here:
http://en.wikipedia.org/wiki/Loopback

-Secondly, every guide I've found does it as though eth0 is the main connection, but it isn't for me? So what should I be doing
  differently?

What is your main connection? If it's eth1, you should apply the instructions from your guides to eth1 instead. Use common sense here :) It would help if you could tell us which guides you're looking at.

-Next: If I do it the graphical way, through Network settings, do I need to change the settings for both IPV4 and IPV6? Every guide I've
  found has only ever done it for IVP4.

Not unless you know you need IPV6. This would be something your network administrator can tell you. If it's your own network, you should know whether you have configured or need IPV6.

-Lastly, how do I know what to set my ip address as when I set it to static?

Ah, here's the crux of the matter. You should know this, either because your network administrator told you "configure a static IP on your machine, here are the config parameters") or because you decided "I'll make my home network fully static, here's how I'm going to allocate my address space, here's the IP address for the gateway, this is the IP for my computer" and so on.
If you don't really know what IP address to set, then potentially you don't really need to set one.
I suggest you read up on what setting up a private network with static addresses entails (http://www.wikihow.com/Set-up-a-Private-Network), you don't need to follow the instructions but it will help you understand how to plan a small network and determine whether you want/need to do this.

A: How to set a static IP address in Ubuntu 12.10
The best way to set a static IP address is through "DHCP reservation" on the router, not through the operating system because then you can leave your computer on "DHCP" so when you plug it in somewhere else, it just works.  I am using Ubuntu 12.10 and have a Cisco E2000 router to demonstrate.

*

*Run ifconfig on the Ubuntu Box.
eth0      Link encap:Ethernet  HWaddr d4:3d:7e:ea:9b:3a
          inet addr:192.168.13.88  Bcast:192.168.13.255  Mask:255.255.255.0
          inet6 addr: fe80::d63d:7eff:feea:9b3a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1268 errors:0 dropped:0 overruns:0 frame:0
          TX packets:872 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1114418 (1.1 MB)  TX bytes:150044 (150.0 KB)
          Interrupt:20 Memory:f7d00000-f7d20000

That tells you the IP address is 192.168.13.88  I am connected with DHCP

*Here my contents of /etc/network/interfaces, it is the default.  Don't touch this:
auto lo
iface lo inet loopback

*Log into your router.  Find the button called: "DHCP Reservation".
If you can't find that button for your router, use the Google to type in "where is DHCP Reservation for my crunch-whirrr-bang router?"
Click the "DHCP Reservation" button.  What that button means is you are telling the router to "remember the mac address of a computer, and when it requests an IP address, always give it THAT ip address, and give that IP address out to nobody else.

*Check the checkbox in the upper right corresponding to the computer you want to set a static IP address.

*Then click Add clients.

*Click save settings.  Note this freezes the IP address to this computer as-is.  You may want to define your own, you need to know your computer's mac address and you can use the "Assign IP address" feature to link an IP address to the mac address of your computer.

*Restart the computer, and the router will always give you that IP address.

A: If you come here looking for instructions for newer ubuntu versions, some of the commands refered to in these answers have become outdated.

*

*ifconfig has been replaced by ip run ip addr to see the ip addresses of your adapters

*ethX (where X is an integer) is no longer the default naming scheme.

Use ip addr to figure out your adapter name. from this example you can see that my adapter is called eno1
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 6Ø:1Å:PD:2M:9Y:X9 brd ff:ff:ff:ff:ff:ff
    altname enp1s0
    inet 10.11.12.13/24 brd 10.11.12.255 scope global eno1
       valid_lft forever preferred_lft forever
    inet6 fGG0::6YYd:eXXX:XeXX:94ÅÅ/64 scope link
       valid_lft forever preferred_lft forever

Editing the configuration
Some guides will say edit /etc/network/interfaces some will say use NetworkManager those are all outdated. You may experience upgraded servers that still use those old config files, but on a freshly installed Ubuntu 22.04 the config is in /etc/netplan/
In my case this is called /etc/netplan/00-installer-config.yaml since the config I had originally was made by Ubuntu's Ubiquity installer.
/etc/netplan/00-installer-config.yaml
network:
  ethernets:
    eno1:
       addresses:
         - 10.11.12.13/24
       nameservers:
         addresses: [4.2.2.2, 8.8.8.8]
       routes:
         - to: default
           via: 10.11.12.1
  version: 2

This is my config using the subnet 10.11.12.0/24 with a default gateway with IP  10.11.12.1 set up to use a level 3 dns (4.2.2.2) and Google's dns server (8.8.8.8).
Some  guides say to use gateway4: 10.11.12.1 instead of the routes: entry in my example. gateway4 is deprecated in Ubuntu 22.04
Applying the configuration
In order to apply the config execute sudo netplan apply if you sense that something is not working use sudo netplan --debug apply see the man page for more details.
Troubleshooting

*

*My adapter is still down according to ip addr after doing netplan apply Check if the adapter name in the configuration is the same as the one in ip

*I can't ping the internet ensure that you have entered everything as in my example. The format is a YAML array, and yaml files are normally indented with two spaces. Also ensure that you have written the correct gateway address (it may be 192.168.1.234 for example)


text:
Q: Button does not call function So, i was trying to make a game as Candybox. I do create a button which gets the onclick-attribute to call a function.
if (AnzahlTP === 10)
                    {
                        var para = document.createElement("button");
                        var node = document.createTextNode("Treuepunkte verschenken");
                        para.appendChild(node);

                        var element = document.getElementById("haupt-div");
                        element.appendChild(para);

                        var b1 = document.getElementsByTagName("button")[1]; //gibt dem Knopf eine Funktion
                        var att = document.createAttribute("onclick");

                        att.value = "TPVerschenken()";
                        b1.setAttributeNode(att);
                    }

The Button should call this function, which will print something into a p-Tag at the Top.
function TPVerschenken()
        {
            AnzahlTPV = AnzahlTPV + AnzahlTP;
            document.getElementById("TPVDisplay").innerHTML = "Verschenkte Treuepunkte: " + AnzahlVTP;
            AnzahlTP = 0;
        }

But if the button is pressed, the function doesnt work, or isn't called. I checked that the onclick-attribute is given to the button.

Here the whole code, if it's needed.

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="spiel.css"/>
    <meta charset="UTF-8">
    <title>Test, I guess...</title>

        <button id="Knopf" onclick="TPSammelnKnopf()">
            Anfangen Treuepunkte zu sammeln
        </button>

A: To set onclick event for the button you created from javascript code, you should do it like this:
para.onclick = (function () {
    return function () {
        TPVerschenken();
    };
})();

Or simpler, you can use:
para.addEventListener("click", TPVerschenken);

For the full tested code, please check JsFiddle.


text:
Q: In vb.net, how to change the color of each individual point of a point or line chart After adding a new point, I try to set its color, but it doesn't work:
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, Yvalue )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.Green

I want different color depending on Yvalue.


text:
Q: Fabric Api is installed on the version above. IntelliJ Idea i don't understand how to solve it. Build.gradle & properties is normal, but Fabric Api install a version above.
and I understand that he asks for a higher version of Minecraft. But I need 1,18,1
This a log
[11:41:49] [main/WARN] (FabricLoader/Resolution) Mod resolution failed
[11:41:49] [main/INFO] (FabricLoader/Resolution) Immediate reason: [HARD_DEP_INCOMPATIBLE_PRESELECTED fabric 0.47.8+1.18.2 {depends minecraft @ [~1.18.2-alpha.22.5.a]}, ROOT_FORCELOAD_SINGLE fabric 0.47.8+1.18.2]
[11:41:49] [main/INFO] (FabricLoader/Resolution) Reason: [HARD_DEP fabric 0.47.8+1.18.2 {depends minecraft @ [~1.18.2-alpha.22.5.a]}]
[11:41:49] [main/INFO] (FabricLoader/Resolution) Fix: add [], remove [], replace [[fabric 0.47.8+1.18.2] -> add:fabric 1 ([(-∞,∞)])]
[11:41:49] [main/ERROR] (FabricLoader) Incompatible mod set!
 net.fabricmc.loader.impl.FormattedException: Mod resolution encountered an incompatible mod set!
A potential solution has been determined:
     - Replace mod 'Fabric API' (fabric) 0.47.8+1.18.2 with any version that is compatible with:
         - minecraft 1.18.1
Unmet dependency listing:
     - Mod 'Fabric API' (fabric) 0.47.8+1.18.2 requires any version between 1.18.2-alpha.22.5.a (inclusive) and 1.19- (exclusive) of 'Minecraft' (minecraft), but only the wrong version is present: 1.18.1!
    at net.fabricmc.loader.impl.FabricLoaderImpl.load(FabricLoaderImpl.java:190) ~[fabric-loader-0.14.8.jar:?]
    at net.fabricmc.loader.impl.launch.knot.Knot.init(Knot.java:148) ~[fabric-loader-0.14.8.jar:?]
    at net.fabricmc.loader.impl.launch.knot.Knot.launch(Knot.java:68) [fabric-loader-0.14.8.jar:?]
    at net.fabricmc.loader.impl.launch.knot.KnotClient.main(KnotClient.java:23) [fabric-loader-0.14.8.jar:?]
    at net.fabricmc.devlaunchinjector.Main.main(Main.java:86) [dev-launch-injector-0.2.1+build.8.jar:?]

Process finished with exit code 1```

A: You need a matching version of the Fabric API.
The version you selected requires any version between 1.18.2-alpha.22.5.a.
Therefor you can't use it for Minecraft 1.18.1 and you need to get an older version of Fabric.
From the Fabric Website I can see that you should use the fabric version 0.46.6+1.18. Update you gradle file as shown on this website.


text:
Q: Adding translation in Wordpress Plugin I've create a plugin for wordpress and now I want translate it.
I've adding in my code .po and .mo files in "Plugin-name/locale" (I've create "locale" folder where I put de_DE, fr_FR, en_US, it_IT, es_ES, ru_RU folders)
Every language folder contains a folder called "LC_MESSAGES" containing .po and .mo file like "translation.mo and transolation.po"
Now I want connect these translation.
In my Config file I've created something like this:
    $locale = str_replace("-", "_", $culture);

    $textDomain = "translation";
    try {
        @putenv("LC_ALL=$locale");
    }
    catch (Exception $e) { }
    setlocale(LC_ALL, $locale . ".utf8"); //Set language
    bindtextdomain($textDomain, dirname(__FILE__) . "/locale"); //Specify location of translation tables
    textdomain($textDomain); //Choose domain

and in my page I've just added the gettext like:
_("Hello")

My site is in italian so I will see "Ciao" but the plugin doesn't take the translation so I see still "Hello"
Can anyone help me ?
Thanks in advance

A: With Wordpress you need to be using this format normally:
either
_e( 'your_text_to_be_translated' );

or
__( 'your_text_to_be_translated' );


text:
Q: Print f list items in one line I would like to print the list in one line. I works with simple print, but it doesn´t work when it´s f print. How could I do that, please? Thank you
list = ["A", "B", "C"]

print(*[n for n in list], sep=", ")

print(f"Item was added: {*[n for n in nazvy]}")

A: Use ' '.join
l = ["A", "B", "C"]
print(', '.join(l))
print(f"Item was added: {', '.join(l)}")

Output
A, B, C
Item was added: A, B, C

NOTE: Try not to use in-built keywords as variable names. Eg: list

Your code didn't work because f-string doesn't allow starred expression or unpacking.
Meanwhile
print(*[n for n in list], sep=", ")

worked because it translates to below due to list unpacking
print('A', 'B', 'C', sep=", ")

A: I'd suggest this :
list = ["A", "B", "C"]
print(f'Item was added: {",".join(str(x) for x in list)}')
print(f'Item was added: {", ".join(str(x) for x in list)}')

as per accepted answer on this question :
f-string syntax for unpacking a list with brace suppression

A: Use "end=" instead of "sep=";
list = ["A", "B", "C"]
for x in list:
   print(x, end=', ')

A: You can use *list to send each value to print statement. With this approach, you don't have to worry about converting data to string.
With that, you can just give
mylist = ["A", "B", "C", 4, 5, 6]

print(*my_list, sep=", ")

The output of this will be:
A, B, C, 4, 5, 6

If you want to use the fstring, you can also try giving:
print(f'{*mylist,}')

The output of this will be:
('A', 'B', 'C', 4, 5, 6)

Note here that it prints with brackets ().
For more details about unpacking f-string, see the post on Stackoverflow here
Also please try to avoid naming variables as list. It will get confusing later when you want to convert data to a list.
Example:
x = {1:5,2:10,3:15}
y = list(x)
print (y)

will convert dictionary x to a list y