text:
Q: Fading in and out CSS stylesheet with Javascript I am trying to implement more elegant elements in my site using Javascript.

Snippet

That switches the site to nightmode. If you click the button, it switches nightmode on, or off. Simple enough.
However, I'd like a .5 second fadein/fadeout effect on each click, to make it less jarring. I've tried adding it via CSS, but that only works for fade in. How can I get both fade in and fade out effects?

A: Here are a few different ways to keep transitions working whenever you switch between styles.  The underlying thing to keep in mind is that you have to have a transition rule available for the transition to happen.  If you have it in one style but not the other, it will only happen whenever you change to the style that has it because otherwise there is no rule saying that there needs to be a transition.

<link> Swapping Method
Basically, make sure that the transition rules are always available.  If they are in your night/day stylesheet but not other, then there is no longer a rule to transition.  That's why it would only work whenever you fade in.
Ideally though, you would probably want both sets of rules in a single file and then change between the active styles using a class on the  tag.  However, there are certainly use cases where you might want to still use two separate stylesheets that aren't both loaded simultaneously.  For example a high contrast stylesheet that might not be used by all users would waste memory.  However, I'd still probably use the class attribute on the  tag in case I ever wanted to combine them.
index.html

    <title>CSS Test</title>
    <link rel="stylesheet" href="base.css">

Hello!

I am text

                <button id="day_mode">Day</button>

                <button id="night_mode">Night</button>

index.js
/*jslint browser:true*/

(function () {
    "use strict";

    function addStylesheet(name, loc) {
        var sheet = document.createElement("link");
        sheet.id = name;
        sheet.href = loc;
        sheet.rel = "stylesheet";
        sheet.type = "text/css";

        document.head.appendChild(sheet);

        return sheet;
    }

    function removeStylesheet(sheet) {
        sheet.parentNode.removeChild(sheet);
        //document.getElementById(name).removeChild();
    }

    function go() {
        var dayButton = document.getElementById("day_mode"),
            nightButton = document.getElementById("night_mode"),
            daySheet,
            nightSheet;

        dayButton.addEventListener("click", function (e) {
            e.preventDefault();
            if (!daySheet) {
                if (nightSheet) {
                    removeStylesheet(nightSheet);
                    nightSheet = null;
                }
                daySheet = addStylesheet("day", "day.css");
            }
        });

        nightButton.addEventListener("click", function (e) {
            e.preventDefault();
            if (!nightSheet) {
                if (daySheet) {
                    removeStylesheet(daySheet);
                    daySheet = null;
                }
                nightSheet = addStylesheet("night", "night.css");
            }
        });
    }
    document.addEventListener("DOMContentLoaded", go);
}());

base.css
h1 {
    transition: color 1s;
}

p {
    transition: background-color 1s, color 1s;
}

day.css
h1 {
    color: orange;
}

p {
    background-color: yellow;
    color: red;
}

night.css
h1 {
    color: blue;
}

p {
    background-color: black;
    color: blue;
}

 Class Namespacing
If you do want to try the  class method, here is a short implementation showing how to do that.
The basics of this is that you have a namespace for each version, day/night, of the CSS that you want to use and you prefix those mode rules with the relevant namespace.
Then, using JavaScript, you would remove or add the namespace class from your  tag using document.body.classList.add() and document.body.classList.remove().

/*jslint browser:true*/

(function() {
  "use strict";

  function go() {
    var dayButton = document.getElementById("day_mode"),
      nightButton = document.getElementById("night_mode");

    dayButton.addEventListener("click", function(e) {
      e.preventDefault();
      document.body.classList.remove("night");
      document.body.classList.add("day");
    });

    nightButton.addEventListener("click", function(e) {
      e.preventDefault();
      document.body.classList.remove("day");
      document.body.classList.add("night");
    });
  }
  document.addEventListener("DOMContentLoaded", go);
}());
h1 {
  transition: color 1s;
}
p {
  transition: background-color 1s, color 1s;
}
body.day h1 {
  color: orange;
}
body.day p {
  background-color: yellow;
  color: red;
}
body.night h1 {
  color: blue;
}
body.night p {
  background-color: black;
  color: blue;
}

  <title>CSS Test</title>
  <link rel="stylesheet" href="index2.css">

Hello!

I am text

        <button id="day_mode">Day</button>

        <button id="night_mode">Night</button>

Alternate Stylesheet Relation
One other thing to note, is that if you use the <link ... rel="stylesheet alternate" ...> approach, the transitions will also still work.  I'm not sure what browsers still provide a means for users to switch their preferred rendering style manually.  Chrome does not provide a way, but FireFox does.  See the below screenshot.

Here is the markup I'm using for my  element.

    <title>CSS Test</title>
    <link rel="stylesheet" href="base.css">
    <link rel="stylesheet" href="day.css" title="Day">
    <link rel="stylesheet alternate" href="night.css" title="Night">


text:
Q: Setting a Sharepoint Site Theme through a Web Service? Is it possible to change a Sharepoint 2007 Site Theme through a Web Service? I know it can be done through the Object Model with (i think) SPWeb.ApplyTheme, but I did not see anything in the available Web Services, apart from CustomizeCss in Webs.asmx, which does not seem to be exactly what I need.

A: This is not possible out of the box. However, you can write your own custom SharePoint web service that exposes this feature to you. A walkthrough on how to make your own custom web service in SharePoint can be found here:
http://msdn.microsoft.com/en-us/library/ms464040.aspx
Another way would be to create your own themesetter and invoke it via a request. An example of this can be found here:
http://www.sharepoint-tips.com/2006/03/automatically-applying-theme-to-site.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Default volume too high for headphones Is there a way to change the default volume setting for headphones/line out, i.e. the one you get after plugging a jack in for the first time since you've turned your Mac on and started OSX?
I'm using a 2008 unibody (aluminum) Macbook, running Snow Leopard. And several times I've run the risk of hurting my ears because of that default value (half of the scale).

A: Take a look at breakaway. You can write a quick applescript to change the volume back and forth when when the headphone is connected/disconnected, and much more

A: I had the same problem.  Setting the volume as low as it could go was still too loud.
Here's a solution that worked for me:

*

*Download Loopback

*Set it up so that you have the following:

*Sources: Pass-Thru

*Output Channels: Channels 1&2

*Monitors: [Select your headphone device]

Now all audio is routed to a virtual device, which outputs to your headphones.  This gives you an additional volume slider for more fine grained control, which will allow you to set your headphones to be much quieter than you could normally with the default OSX volume options.

A: Open "AppleScript Editor"
Add this line:

set volume 1.5

Then File > Save As
In the file format box choose "Application" and check the "Run Only" box. Name the file and save it somewhere you can find it.
Then if you drag that app into your dock, you can right click it, select Options > Open at Login.
This will set the volume to around 3 boxes of the scale on startup. However it will not detect if you have headphones plugged in or not. It will just always set the volume lower.

A: Check these values each time before you plug in your headphones.

Check the box for "Show volume in menu bar." Each time before you plug in any headphones, go to your Menu bar and manually lower the volume.

Trying to solve this problem with AppleScript and the like is severly over-engineering a solution.


text:
Q: TeamCity Backup on schedule and copy to Azure, REST script improvements I was working on a script to run TeamCity backups on a scheduled basis, as by default it doesn't have such an option, and then copy it to Azure storage account.
The script is working but I want to do some improvement.

*

*I want Powershell to check backup file availability for download (Test-Path or etc.) For now, it just takes sleep for 360 seconds.

*I want to configure the retention policy on the Azure storage account.

#API key for TeamCity as TC parameter
$key = "%key%"

$date = Get-Date -Format "yyyy-MM-dd"

$file = "TeamCity-Backup-$date.zip"

#URI for initialize backup
$uri = "https://teamcity.test.com/app/rest/server/backup?addTimestamp=false&includeConfigs=true&includeDatabase=true&includeBuildLogs=false&fileName=$file"

#URI for downloading backup
$uri1 = "https://teamcity.test.com/get/file/backup/$file"

 $header = @{  "Authorization"="Bearer $key"  }

#Initialize
Invoke-RestMethod -Method Post -Uri $uri -Header $header

#Wait for backup
sleep -Seconds 360

#
#Need function or method for checking file availibility
#

#Download
Invoke-RestMethod -Method Get -Uri $uri1 -Header $header -OutFile "$file"

#Key to BLOB
$key_storage = "%key_storage%"

#Copy to Azure
azcopy.exe copy $file "https://myblob.blob.core.windows.net/teamcity-backups$key_storage"

#
#Funtion for retention Azure Blob
#


text:
Q: SharePoint 2010 - Add WebPart to a Web with PowerShell I want to add a webpart to a great number of existing pages.
Is there any PowerShell command to add a webpart to a webpart page?

A: Theres nothing like this OOB, but you have pretty much the same options in PowerShell as in say a console application in C#.
So theres the option of coding your own cmdlet that does this for you.
On NBSP i found this script that should get you going.

A: There's no PowerShell Command, but you can use the AddWebPart method of the SPWebPartManager class to add the WebPart to a WebPartPage:
http://msdn.microsoft.com/EN-US/library/ms157507(v=VS.90)
You can get a SPWebPartManager object by calling WebPartManager.GetCurrentWebPartManager and providing it your WebPartPage:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webpartmanager.getcurrentwebpartmanager(v=VS.90).aspx

A: Here are some sample powershell scripts for adding webparts to sites:
A nice, simple, clean code for adding a CEWP:
https://www.nothingbutsharepoint.com/sites/devwiki/SP2007Dev/Pages/How%20to%20create%20Web%20Part%20instances%20on%20pages%20using%20PowerShell%20and%20SPLimitedWebPartManager.aspx
This one adds a customized web-part:
http://www.sharemuch.com/2010/11/17/using-powershell-to-add-and-configure-sharepoint-2010-webparts/
And this adds a page-viewer webpart - Mr. Hahner made this blogpost especially for me!
http://spcrew.com/blogs/lists/posts/post.aspx?id=21

A: Here is a simple script to add a webpart to a page using PowerShell which is tested and working fine.
Please note that to add a webpart to a page export webpart to your local drive .webpart/.dwp file will be in xml format.
cls

asnp "*sh*"

$web=Get-SPweb -Identity "http://SP2013dev.com/sites/addwebpart/"

[xml]$webpartxml= Get-Content -Path "C:\Manju\WPRequest.xml"

$SR = New-Object System.IO.StringReader($webpartxml.OuterXml)

$XTR = New-Object System.Xml.XmlTextReader($SR)

$err=$null

$WebPartZoneID = "Topzone"

$WebPartZoneIndex = 0

 try
   {

  $page=$web.GetFile("Pages/default.aspx");

  $bool=$page.CheckedOutBy

       if($bool)
        {
            Write-Host "Page is already Checkout to " $page.CheckedOutBy.UserLogin

            $page.UndoCheckOut()

            Write-Host "Page is Over ridded by " $web.CurrentUser.DisplayName + " to Add Webpart"
        }

    $page.CheckOut();

    $wmgr=$web.GetLimitedWebPartManager($page,    [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);

    $webpart=$wmgr.ImportWebPart($XTR,[ref]$err);

    $wmgr.AddWebPart($webpart,$WebPartZoneID,$WebPartZoneIndex);

    $page.CheckIn('dude');

    $page.Publish('Adding request Site Webpart')

    "Request Site WebPart SucessfullAdded" + (Get-Date -DisplayHint Date) | Out-File -Append "C:\OutPutLog.txt"

     $SR.Close();
    $XTR.Close();
     $web.Dispose()

    }
    catch
     {
        $ErrorMessage = $_.Exception.Message

        "Request Site WebPart Failure" + $ErrorMessage  +  (Get-Date -DisplayHint Date) | Out-File -Append "C:\ErrorLog.txt"
    }


text:
Q: Spring Boot: Application is displaying 404 error I am trying to run Spring Boot REST API application, but I am getting a 404 error.
package com.spring.boot.entry;
@SpringBootApplication
@ComponentScan(basePackageClasses = HelloController.class)
public class CourseApiApp {
    public static void main(String[] args) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

package com.spring.boot.entry.hello;
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello() {
        return "Hi First Spring boot application ";
    }
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.spring.boot.quickstart</groupId>
  <artifactId>course-api</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring Boot API</name>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
  </parent>

  <dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-solr</artifactId>
    </dependency>
  </dependencies>

  <properties>
    <java.version>1.8</java.version>
  </properties>
</project>

I also tried @ComponentScan(basePackageClasses = HelloController.class),
but no luck. Could you please help to resolve this issue?
If I hit http://localhost:8080/hello url then I am getting 404.

A: I executed your code on my system and unless you've messed up with the directory structure it is working as expected. Cross check that once.

CourseApiApp.java

HelloController.java

Output


text:
Q: Java 7 WatchService -- ENTRY_MODIFY triggered on file open I have a program that watches a directory for file update using WatchService.
I get events when I modify a file. However, I notice that even if I open a file in vi, and do not modify its contents, the watch service poll method is invoked.
My code is as follows:
watcher = FileSystems.getDefault().newWatchService();
Path path = Paths.get("conf");
path.register(watcher, ENTRY_MODIFY);
WatchKey key = null;

key = watcher.poll(MAX_WAIT_TIME, TimeUnit.SECONDS);
if (key != null) {
for (WatchEvent<?> events : key.pollEvents()) {
        WatchEvent<Path> ev = cast(events);
        Path fileName = ev.context();
    }

In the above code, watcher.poll waits for MAX_WAIT_TIME for an ENTRY_MODIFY event. However, when I open a file within the directory being watched, and close without changing its contents... the watcher.poll receives an event and stops waiting.
Is there some parameter that needs to be set and I am missing?

A: If you save the file before closing, the OS will see the file as modified even if there is no change to it and these will trigger the ENTRY_MODIFY event.
Also your code is taking only one watch key. If you want continue watching the directory you need to put your watcher.poll instruction into a loop.

A: I tried the below code in java7 and it works fine for me in windows.Also please try the watchkey reset option.Below is the code used for WatchService:
                    import java.nio.file.FileSystems;
                    import java.nio.file.Path;
                    import java.nio.file.Paths;
                    import java.nio.file.WatchEvent;
                    import java.nio.file.WatchKey;
                    import java.nio.file.WatchService;
                    import java.nio.file.StandardWatchEventKinds;

                    public class WatchServiceJava7Feature {

                        public static void main(String[] args) throws Exception {
                            System.out.println("here ");
                            WatchService  watchService = FileSystems.getDefault().newWatchService();
                            Path path= Paths.get("C:\\User\\code\\watchservice\\");
                            System.out.println("here 1");
                            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
                            while(true)
                            {
                            WatchKey key = watchService.take(); // this will return the keys
                            for(WatchEvent<?> event : key.pollEvents())
                             {
                                 WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
                                 WatchEvent.Kind<Path> kind = watchEvent.kind();
                                 switch(kind.name()) {
                                    case "ENTRY_MODIFY":
                                        System.out.println("Case Modify :Event on "+ event.context().toString() + " is "+ kind);
                                        break;
                                    case "ENTRY_DELETE":
                                        System.out.println("Case Delete :Event on "+ event.context().toString() + " is "+ kind);
                                        break;
                                    case "ENTRY_CREATE":
                                        System.out.println("Case Create :Event on "+ event.context().toString() + " is "+ kind);
                                        break;
                                }

                             }
                             key.reset();
                           }

                        }

                    }


text:
Q: Submit a form with link as button using Enter key Hi i'm currentyl having an issue with a form on a website, im using a link  instead of a button or an input to submit a form, but i cannot seem to make it submit when the user press the enter key, the Form values are being validated using javascript with the following format
onsubmit="return function();"
Anybody knows how to make it submit on enter keypress ?
Thanks

A: Try capturing the event.keyCode property when hitting a key on the particular link.
   $('#example').keyup(function(event) {
      if(event.keyCode === 13) {
        //do what you want
        **EDIT:** $('$FormName').submit();
      }
   });


text:
Q: Javascript coerces variable to string why? Consider the followng code
<!DOCTYPE html>
<html>
<head>
<script>
     var name = 0;
        while ( name < 6 ) {
            console.log('Masha');
            name = name + 1;
            console.log(name);
        }

</script>
</head>
<body>

</body>
</html>

I expect the output in Chrome Developer Tools to be:
Masha
name.html:9 1
name.html:7 Masha
name.html:9 2
name.html:7 Masha
name.html:9 3
name.html:7 Masha
name.html:9 4
name.html:7 Masha
name.html:9 5
name.html:7 Masha
name.html:9 6

Instead I get
Masha
name.html:9 01
name.html:7 Masha
name.html:9 011

Why is this the case? It also happens if I copy/paste the code directly. If I chop the n of of name then it does work. If I change the variable to myName it does work. Why is it coerced to a string? I'm using Version 57.0.2987.133 (64-bit) of Chrome. It also happens in Firefox 52.0.2 (64-bits).
This doesn't happen when I run the code in node or in Internet Explorer.

A: Because you're using name at global scope in a browser. Browers already have a built-in name global (specifically, the property name of window, which is the window's name) which is always a string. Either:

*

*Use a different name, or better:

*Don't use a global
This is a great example of why not using global variables is a good idea. :-)
Here's an example of #2:

(function() {
    var name = 0;
    while ( name < 6 ) {
        console.log('Masha');
        name = name + 1;
        console.log(name);
    }
})();

Now that name isn't a global anymore (you're shadowing it with a local variable called name), all is well.
In browsers that properly support ES2015's let*, you can also use let, because variables created with let (and const and class) are globals, but not properties of the global object. Your let name shadows the global that comes from the property even at global scope:

let name = 0;
while ( name < 6 ) {
    console.log('Masha');
    name = name + 1;
    console.log(name);
}

But again, just not using a global is best.

* Note: Some browsers have let but not with correct ES2015 semantics, such as IE11 (it's missing some important functionality around let in a for loop header declaration, it doesn't give each loop iteration its own a, with consequences for closures created in the body of the for), but most modern browsers — certainly Chrome, Firefox, and Edge — support it properly. And IE11's let works in the situation above (just not the for loop situation) as well.


text:
Q: Javascript change Object structure My object looks like this:
{34: true, 35: false}

How do I convert the Object to be exactly like this Array:
[{id: 34, _destroy: '1'}, {id: 35, _destroy: '0'}]

Thanks guys!

A: Try this function:
function convertIt(obj) {
        var keys = Object.keys(obj);
        var convertedObjs = [];
        keys.forEach(function(key){
              var destroy = obj[key] ? "1" : "0";
              convertedObjs.push({"id": key, "_destroy" : destroy  });
        });
        return convertedObjs;
    }

A: What do you guys think about this?
var myObject = {34: true, 35: false}
var result = [];
underscore.each(myObject, function(v, k) {
  result.push({id: k, _destroy: v ? '1' : '0'})
});

console.log(result);
> [{id: 34, _destroy: '1'}, {id: 35, _destroy: '0'}]


text:
Q: Could not get data from fifo I'm working with pipe such way (bash script). I write in one pipe $server and read from another pipe $serverPID. This is client sample code:
echo "Get var"
mkfifo "${server}$$"
echo "$$ 2" > $server
read var <  "${server}$$"
echo "var: ${var}"

This is server sample code:
int fd;
if ((fd = open(fifo, O_RDWR)) == -1) {
    fprintf(stderr, "Could not open fifo");
}

ssize_t written;

written = write(fd, buf, strlen(buf));
if (written == -1) {
    fprintf(stderr, "Could not write into fifo");
}
printf("written %d into %s\n", written, fifo);

I see that all data was written succesfully, but I get waiting on client side without appearing written data. Where is the problem?

A: Adding close(fd) solved the problem


text:
Q: Play MP3 few seconds with soundmanager2 Is there any way to recognize all the songs that can be played soundmanager2 few seconds.
I have initialized the soundmanager2
soundManager.setup ({
    url: 'stockings /',
    preferFlash: true,
    onReady: function () {
        console.log ('SM2 Ok!');
    }
});

And my mp3 files with sm2_button class, are about 10 files in total and I would like everyone to play a few seconds.

I hope you can give me a hand.

A: Yikes, i played a bit around. thanks for this interesting question. This will lookup with jQuery in your DOM for a list of mp3 files and creates playList which is played by clicking a startbutton.

<button id="startbutton">start</button>

test0.mp3

test1.mp3

test2.mp3

There is still something which could be smarter, but this works.
In example, what happen if a track is shorter than 4096ms, maybe you should check this out.
Hope this helps.
greetings from berlin

A: thanks for the ideas. At the end touch a little file code mp3-player-button.js, supported by the API documentation and add a few lines soundmanager2.
In the line:
thisSound.play ();

Add:
thisSound.play({
    whileplaying:function() {
        if (thisSound.position >= 30000) {
            self.stopSound(thisSound);
        }
    }
});

Greetings from Peru.


text:
Q: How to transform this side-effect into an elegant chaining of Vapor operations? I am starting using Vapor to run an API, and I couldn't figure out an elegant way of doing the following: (1) load a Fluent relation and (2) wait for the response of an HTTP callback before (3) responding to the original request.
Here is what I ended up coding, after I transformed my real-life entities into planets and stars to maintain the examples from Vapor's documentation. It works™, but I couldn't achieve a nice chaining of operations ☹.
    func flagPlanetAsHumanFriendly(req: Request) throws -> EventLoopFuture<Planet> {
        Planet(req.parameters.get("planetID"), on: req.db)
            .unwrap(or: Abort(.notFound))
            .flatMap { planet in
                // I load the star because I need its ID for the HTTP callback
                _ = planet.$star.load(on: req.db).map {
                    let uri = URI(scheme: "http", host: "localhost", port: 4200, path: "/webhooks/star")
                    // HTTP Callback
                    req.client.post(uri) { req in
                        try req.content.encode(
                            WebhookDTO(
                                starId: planet.star.id!,
                                status: .humanFriendly,
                                planetId: planet.id!
                            ),
                            using: JSONEncoder()
                        )
                    }
                    .map { res in
                        debugPrint("\(res)")
                        return
                    }
                }

                // Couldn't find a way to wait for the response, so the HTTP callback is a side-effect
                // and its response is not used in the original HTTP response...
                // If the callback fails, my API can't report it.
                planet.state = .humanFriendly
                return planet.save(on: req.db).map { planet }
            }
    }

Issue #1. Combining 2 EventLoopFuture
My first issue was that I couldn't find a way to load a parent relationship while keeping the entity in the scope.
Planet(req.parameters.get("planetID"), on: req.db)
    .unwrap(or: Abort(.notFound))
    .flatMap { planet in // planet is in the scope
        return planet.$star.load(on: req.db) // returns a EventLoopFuture<Void>
    }
    .map {
      // I know that star has been loaded but I lost my `planet` reference ☹
      ???
    }

I assume there is an operator that should be able to return a mix of the 2 EventLoopFuture instances but I couldn't figure it out.
Issue #2. Chaining EventLoopFuture with an auxiliary HTTP request's response
Here as well, I assume I miss an operator that allows me to wait for the request's response, while keeping a reference to the planet, before I respond to the original request.

Help would be welcome on how to achieve this in a nice chaining of operations — if it is possible, of course — and I will more than happy to update Vapor's documentation accordingly.

A: In short, if you need the result of one future inside the result of another future then you have to nest the callbacks - you can't use chaining. So for instance:
Planet(req.parameters.get("planetID"), on: req.db)
    .unwrap(or: Abort(.notFound))
    .flatMap { planet in // planet is in the scope
        return planet.$star.load(on: req.db).map {
            // Star is now eager loaded and you have access to planet
        }
    }

If you have multiple futures that aren't reliant on each other but you need the results of both you can use and to chain the two together and wait for them. E.g.:
func flagPlanetAsHumanFriendly(req: Request) throws -> EventLoopFuture<Planet> {
    Planet(req.parameters.get("planetID"), on: req.db)
        .unwrap(or: Abort(.notFound))
        .flatMap { planet in
            // I load the star because I need its ID for the HTTP callback
            planet.$star.load(on: req.db).map {
                let uri = URI(scheme: "http", host: "localhost", port: 4200, path: "/webhooks/star")
                // HTTP Callback
                let postFuture = req.client.post(uri) { req in
                    try req.content.encode(
                        WebhookDTO(
                            starId: planet.star.id!,
                            status: .humanFriendly,
                            planetId: planet.id!
                        ),
                        using: JSONEncoder()
                    )
                }.map { res in
                    debugPrint("\(res)")
                    return
                }

                planet.state = .humanFriendly
                let planetUpdateFuture = planet.save(on: req.db)

                return postFuture.and(planetUpdateFuture).flatMap { _, _ in
                    return planet
                }
            }
        }
}


text:
Q: finding/verifying big O notation of recursive function The Function:
function multiply(x, y)
if y = 0:
  return 0
z = multiply(x, ⎣y/2⎦)
if y is even:
  return 2z
else:
  return x + 2z
The Question:
"If the input is an m-bit number x and an n-bit number y, how long does it take to multiply x and y?"
My Logic:
It takes n recursive calls to get to the base case*. It takes n steps to back out of each function call and either do 2z or x + 2z.
Therefore, it takes O(n2) time.
Is this right?
I was told it should be O(mn), but I don't believe it. If I'm wrong, please explain why.
*since it divides y by 2 repeatedly until it gets to the base case, the number of recursive calls is based on the closest power of 2 below the value of y. Since binary is just bits in the power of 2, the n-bits of y is equal to the number of recursive calls.

A: There are cases when you will always perform calculation of the 'x + 2z' in any recursive call except last case (when y will be 0). For example, multiply(5, 31) and etc.
So I think that main thing is in '+' operation. When numbers are very big, it will not take a 1 machine step to perform adding. As a result we have to calculate how much machine steps we have to spend for adding x number (which is m bits long) to another one. Result is O(m) steps.
That's why answer is O(mn).
P.S. '2z' will take a static number of steps because we can add 0 to the end of number and get the result. Imagine that number is very big and we store every bit as an element of array. So we can push 0 to the end of array and we will have the result of operation '2z'.


text:
Q: changing git branch base gone wrong I have a tree like this:
commit10 - commit11  <-- master
              |
              |-- commit3 <-- topic/branch1
                     |
                     |-- commit4 <-- topic/branch2

The git log looked like this:
$ git log -n 4
commit4
commit3
commit11
commit10

While I was working on commit4, commit3 was merged to master and was farther back in the history, so I wanted to change the branch base for topic/branch2 to master, as follows:
commit10 - commit11  <-- master
              |
              \-- commit4 <-- topic/branch2

So, I did the following git command:
$ git checkout topic/branch2
$ git rebase --onto master topic/branch2
First, rewinding head to replay your work on top of it...

And now I cant find commit4... anywhere.
Now the git log int topic/branch2 looks like this:
$ git log -n 2
commit2
commit1

If I go to the master branch and look 30 entries back in the git log history, I cant find the commit.
Where did my commit4 go? How do I get it back?

A: Thanks to Makoto's comment, I was able to solve this by looking in the reflog.
I used this restoring lost commits page to restore the commit. Turns out the rebase caused my commit to be treated as a dangling commit.
Luckily I had the SHA1 of the commit4 before I messed things up. So I used the following command to "prove git knew about my dangling commit":
$ git fsck --lost-found
<lots of output>
dangling commit 0c990572fd1fd20a5db42141a7a4e0e6e97f6462
<even more output>

I was also able to see commit4 in the reflog with this command:
$ git reflog

And according to the previously mentioned link, you can use either git merge  or git checkout  to recover it. I used merge, since the link said that was quicker.


text:
Q: Is there an English word whose meaning refers to 'mind' or 'memory', but whose etymology refers to 'heart'? I know that the English language has an expression, 'to know something by heart', that alludes to the heart but whose meaning is 'to know something from memory'.
I've discovered that this link between the heart and the memory was something that people believed at least in the 18th century and way before. This originated some Spanish words such as recordar 'remember', 'remind'. Recordar comes from Latin recordari and this one from cor 'heart', according to Spanish etymologist Joan Corominas.
So now I'm curious. Apart from the expression mentioned above, is there an English word (not an expression) whose meaning refers to 'mind' or 'memory', but whose etymology refers to 'heart'?

A: If you're ok with words/meanings that aren't still in use I found some words that match that description.
One is "perqueer", which is Scottish:

Once widespread, this  word may now have slipped out of use. It comes from Old French 'par queur', which translates directly into English as 'by heart'.
Scots Language Centre

There's also "record", which is obviously a cognate to "recordar"—both words are ultimately from the same Latin word. According to the OED one obsolete definition of record is:

To learn by heart, to commit to memory, to go over in one's mind; (also) to repeat or say over as a lesson or portion of memorized text, to recite.

Here's an example of this sense:

Some men..giue them [sc. children] masters to teach them to scoffe and bite at euery man, as if they had but recorded their lesson.
Thomas Lodge: Complete works, a1625

Another word like this is an old, now-obsolete (and probably pretty rare—even when it was in use) sense of "cordial" also meaning "by heart". "Cordial" itself comes from the medieval Latin word "cordialis". Here's an example of "cordial" in this sense:

I not aqueynted of birth naturall With frenshe his verray trew parfightnesse, Nor enpreyntyd is in mynde cordiall.
The romans of Partenay, or of Lusignen, c1475

A: Creed

*

*A 2015 movie in which a former World Heavyweight Champion...

O, wrong Creed...  Another try...

*

*any system, doctrine, or formula of religious belief, as of a denomination.

*any system or codification of belief or of opinion.

Etymology: From Latin credo "I believe".  From PIE compound *kerd-dhe- "to believe," literally "to put one's heart".


text:
Q: If I fix and relaunch a broken Chrome extension that hasn't been updated for 2+ years, will it get removed from store? I have the source code (from github) for this extension. It has gone from 5 stars with hundreds of thousands of users to now 3 stars because it just doesn't work anymore. The developer hasn't updated it for 2+ years. I'm really interested in fixing and relaunching it.
Will it get removed from Chrome store for "violating copyright", breaking TOS, or something? I would like to call it "[OLD EXTENSION NAME] Revived" or "[OLD EXTENSION NAME] Relaunched" so users of the old extension know that it's been relaunched.


text:
Q: Convert a time span in seconds to formatted time in shell I have a variable of $i which is seconds in a shell script, and I am trying to convert it to 24 HOUR HH:MM:SS. Is this possible in shell?

A: Here's a fun hacky way to do exactly what you are looking for =)
date -u -d @${i} +"%T"

Explanation:

*

*The date utility allows you to specify a time, from string, in seconds since 1970-01-01 00:00:00 UTC, and output it in whatever format you specify.

*The -u option is to display UTC time, so it doesn't factor in timezone offsets (since start time from 1970 is in UTC)

*The following parts are GNU date-specific (Linux):

*

*The -d part tells date to accept the time information from string instead of using now

*The @${i} part is how you tell date that $i is in seconds

*The +"%T" is for formatting your output. From the man date page: %T     time; same as %H:%M:%S. Since we only care about the HH:MM:SS part, this fits!

A: Another approach: arithmetic
i=6789
((sec=i%60, i/=60, min=i%60, hrs=i/60))
timestamp=$(printf "%d:%02d:%02d" $hrs $min $sec)
echo $timestamp

produces 1:53:09

A: The -d argument applies to date from coreutils (Linux) only.
In BSD/OS X, use
date -u -r $i +%T

A: If $i represents some date in second since the Epoch, you could display it with
  date -u -d @$i +%H:%M:%S

but you seems to suppose that $i is an interval (e.g. some duration) not a date, and then I don't understand what you want.

A: Here is my algo/script helpers on my site:
http://ram.kossboss.com/seconds-to-split-time-convert/
I used this elogant algo from here: Convert seconds to hours, minutes, seconds
convertsecs() {
 ((h=${1}/3600))
 ((m=(${1}%3600)/60))
 ((s=${1}%60))
 printf "%02d:%02d:%02d\n" $h $m $s
}
TIME1="36"
TIME2="1036"
TIME3="91925"

echo $(convertsecs $TIME1)
echo $(convertsecs $TIME2)
echo $(convertsecs $TIME3)

Example of my second to day, hour, minute, second converter:
# convert seconds to day-hour:min:sec
convertsecs2dhms() {
 ((d=${1}/(60*60*24)))
 ((h=(${1}%(60*60*24))/(60*60)))
 ((m=(${1}%(60*60))/60))
 ((s=${1}%60))
 printf "%02d-%02d:%02d:%02d\n" $d $h $m $s
 # PRETTY OUTPUT: uncomment below printf and comment out above printf if you want prettier output
 # printf "%02dd %02dh %02dm %02ds\n" $d $h $m $s
}
# setting test variables: testing some constant variables & evaluated variables
TIME1="36"
TIME2="1036"
TIME3="91925"
# one way to output results
((TIME4=$TIME3*2)) # 183850
((TIME5=$TIME3*$TIME1)) # 3309300
((TIME6=100*86400+3*3600+40*60+31)) # 8653231 s = 100 days + 3 hours + 40 min + 31 sec
# outputting results: another way to show results (via echo & command substitution with         backticks)
echo $TIME1 - `convertsecs2dhms $TIME1`
echo $TIME2 - `convertsecs2dhms $TIME2`
echo $TIME3 - `convertsecs2dhms $TIME3`
echo $TIME4 - `convertsecs2dhms $TIME4`
echo $TIME5 - `convertsecs2dhms $TIME5`
echo $TIME6 - `convertsecs2dhms $TIME6`

# OUTPUT WOULD BE LIKE THIS (If none pretty printf used):
# 36 - 00-00:00:36
# 1036 - 00-00:17:16
# 91925 - 01-01:32:05
# 183850 - 02-03:04:10
# 3309300 - 38-07:15:00
# 8653231 - 100-03:40:31
# OUTPUT WOULD BE LIKE THIS (If pretty printf used):
# 36 - 00d 00h 00m 36s
# 1036 - 00d 00h 17m 16s
# 91925 - 01d 01h 32m 05s
# 183850 - 02d 03h 04m 10s
# 3309300 - 38d 07h 15m 00s
# 1000000000 - 11574d 01h 46m 40s

A: I use C shell, like this:
#! /bin/csh -f

set begDate_r = `date +%s`
set endDate_r = `date +%s`

set secs = `echo "$endDate_r - $begDate_r" | bc`
set h = `echo $secs/3600 | bc`
set m = `echo "$secs/60 - 60*$h" | bc`
set s = `echo $secs%60 | bc`

echo "Formatted Time: $h HOUR(s) - $m MIN(s) - $s SEC(s)"

A: Continuing @Daren`s answer, just to be clear:
If you want to use the conversion to your time zone, don't use the "u" switch, as in: date -d @$i +%T or in some cases date -d @"$i" +%T.


text:
Q: How to consume the soul of an object I have a movable type that has no default constructor and I want to take away its internal data and destroy them.  My thought was to std::move it to a temporary, and let the temporary destructor happen (to destroy the internal data), leaving the original now-empty object behind.
The closest I've got makes use of a little helper template that's sole purpose is to destroy its argument (which is why it's passed by value, and why the body of the function is empty.)  (Maybe there's a better way?)  Then I call std::move to move the internals of the original object to a temp, and the temp will be destroyed, destroying the original internals, and leaving the object in whatever state it is in after having its internals moved to another object.
template <typename T>
void reset(T t) {}
};

reset(std::move(somevar));

For example, if I had a vector of really long strings and I wanted to "free up" the memory being used by one of the strings in the middle of the vector.  This is not the perfect example because string does have a parameterless constructor, but my type does not.  Nevertheless this captures the spirit of my motivation for attempting this.
std::vector<std::string> vec; // suppose I have a populated vector of strings

// Let's "reset" vec[3] to an empty string by moving it to a temp and destroying the temp
reset(std::move(vec[3]));

This moves the internals of vec[3] into the argument t of the reset function, and then, the destructor for t cleans up the internals.  This leaves vec[3] as an empty string.
The important part of this stunt is that we didn't need to construct an empty string.  This is important because my moveable type can be moved, but cannot be default constructed.
Other things I've tried:
{ std::move(somevar); } // this doesn't work

std::move all by itself doesn't work because you have to actually put the contents somewhere.
{ T t = std::move(somevar); } // works but cumbersome, and I have to name `T`

I'm just looking for a function I can call like reset(somevar).  That consumes the soul of some object.  And the std::move part isn't so bad.  It is kind of like the authorization of I expect you to die.  So it's ok, in my mind, to say reset(std::move(somevar)) But it doesn't finish the job.  So, maybe there's some other function that does do what I want.
So, is there a std::consume_soul that will accomplish the same as moving the contents of an object to a dummy and then destroing the dummy, leaving the original object behind with no contents (or whatever state the move constructor will leave it in)?
Maybe I'm unaware of some obvious approach?  I feel like there's likely some super easy way I'm just not aware of.

A: Moving isn't automatic, but non-const references are, so you can write
template<class T>
void dementor(T &t) {T(std::move(t));}

A: In addition to the great answer from @Davis Herring i'll provide a few more options you could use instead of moving to a temporary that might work better, dending on your usecase:
1. Adding a reset() method for your type
The easiest solution would be to just add a reset() method to your type that clears all internal data.
Then you don't need to perform the move-to-temporary just for the side-effect of clearing your object.
2. Using std::optional
This could also be a good use-case for std::optional.
If you wrap your expensive class into an std::optional you can destroy the contained value anytime by calling .reset(). Additionally with optional you're able to check if a value currently exists.
This is even more powerful than moving to a temporary, since calling reset() on an optional will result in destructing the contained object. So whatever was inside it gets yeeted straight out of existence.
For your array case you could e.g. use:
std::vector<std::optional<ExpensiveClass>> arr;

// add a new element
arr.emplace_back(std::in_place, /* constructor args for ExpensiveClass */);
// add a new (empty) element without needing a default constructor:
arr.push_back({});

// yeeting an instance out of existence
arr[0].reset();

// creating a new instance in an empty slot
arr[2].emplace(/* constructor args for ExpensiveClass */);

// checking if there's an element
if(arr[0]) { /* ... */ }

// using it
arr[0]->doSomething();

godbolt example
That way you can easily control the lifetimes of the ExpensiveClass instances.
You also avoid the shenanigans of moving objects, namely:

*

*The move constructor / move assignment operator might actually copy some (or all) of the members instead of moving them

*The moved-from object only needs to be in a valid state, but can be indeterminate. So the only things that need to work on a moved-from object are (1) destructing it or (2) moving (or copying) another object into it.
Example:
   std::string a = "FOO";
   std::string b = "BAR";
   a = std::move(b);
   std::cout << b << std::endl;

Could result in printing FOO, BAR, nothing or some random value. (depending on how move is implemented)

3. Smart Pointers
If your objects are rather large and you'd prefer to allocate them on the heap you could exchange std::optional in the above examples with std::unique_ptr / std::shared_ptr.
They also provide a .reset() function that will reset the pointer back to an empty state.


text:
Q: Sending a copy of email to sender in PHP I have a contact form in a website that i inherited to work on. I do not know the source. I need users to receive a copy of the email with a different message. Can anyone help?
HERE IS THE PHP
 // Adding e-mail headers
    $headers = "";
    if (FROM_EMAIL !== '') {
        $headers .= 'From: '.FROM_EMAIL."\r\n";
    }
    $headers .= 'Reply-To: '.$contact_email."\r\n";
    $headers .= 'Content-Type: text/plain; charset=UTF-8'."\r\n";

    /*
     * Formatting message.
     * It can be customizable in any way you like.
     */
    $title = 'Contact Form - New Message from '.$contact_name;
    $message = 'Hi,'."\n\n"
        .'You have received new message from your website. Check details below:'."\n\n"
        .'Sender\'s IP address: '.getIp()."\n\n"
        .'Name: '.$contact_name."\n\n"
        .'Title: '.$contact_sex."\n\n"
        .'E-mail: '.$contact_email."\n\n"
        .'Phone number: '.$contact_tel."\n\n"
        .'Selected department: '.$contact_department."\n\n"
        .'Message:'."\n\n"
        .$contact_message;

    // Mail it!
    $result = mail(TO_EMAIL, $title, $message, $headers);

    // Notify contact form about result of sending.
    if ($result) {
        $json['result'] = 'OK';
    } else {
        $json['result'] = 'SEND_ERROR';
    }
    header('Access-Control-Allow-Origin: *');
    echo json_encode($json);
    die();
}

A: Replace:
// Mail it!
$result = mail(TO_EMAIL, $title, $message, $headers);

With this:
$differentMessage = 'This is a string that contains sth and after this we append the old message' . $message;

// Mail it!
$result = mail(TO_EMAIL, $title, $message, $headers);
// Mail a copy
mail($contact_email, $title, $differentMessage, $headers);

Note that the header will stay the same (replay to), but this should give you an idea about how to modify variables and send a second email.


text:
Q: Make Exim send bounces to postmaster instead of the sender, for non-local sender I have a few e-mail aliases that forward to external hosts. Currently, if the external host rejects a message, Exim generates a bounce message and sends it to the original sender. This is bad because if the external host rejects the message as spam (a common case), then I'm a source of backscatter spam.
Thus, if the sender is non-local, I'd like to send the bounce to postmaster (me) instead. Alternately, sending all bounces to postmaster would be good enough.
The Exim documentation hints that this can be done ("when a message fails to be delivered ... Exim sends a message to the original sender, or to an alternative configured address", emphasis added), but I couldn't find how.
For example, here is a log excerpt showing a backscatter spam being created (in this case, the purported source server isn't accepting connections). foo@nacha.net is the purported sender of a spam e-mail to bar@reidster.net, which then forwards to baz@gmail.com; GMail then rejects the message and my server creates a bounce to foo@nacha.net. I want that bounce to go to postmaster@reidster.net instead. (Usernames obfuscated; the rest of the log is verbatim.)
2011-10-03 12:03:08 1RAkyw-0000cj-45 <= foo@nacha.net H=(gyajnj.com [113.190.35.111] P=esmtp S=33927 id=000e01cc51a7$ceee1700$6f23be71@nacha.net
2011-10-03 12:03:09 1RAkyw-0000cj-45 ** baz@gmail.com <bar@reidster.net> R=dnslookup T=remote_smtp: SMTP error from remote mail server after end of data: host gmail-smtp-in.l.google.com [74.125.47.26]: 552-5.7.0 Our system detected an illegal attachment on your message. Please\n552-5.7.0 visit http://mail.google.com/support/bin/answer.py?answer=6590 to\n552 5.7.0 review our attachment guidelines. i3si13239001yhk.107
2011-10-03 12:03:09 1RAkyz-0000cm-H5 <= <> R=1RAkyw-0000cj-45 U=Debian-exim P=local S=35124
2011-10-03 12:03:09 1RAkyw-0000cj-45 Completed
2011-10-03 12:03:30 1RAkyz-0000cm-H5 nacha.net [64.212.215.180] Connection timed out
2011-10-03 12:03:30 1RAkyz-0000cm-H5 == foo@nacha.net R=dnslookup T=remote_smtp defer (110): Connection timed out

Here is the relevant router:
dnslookup:
  debug_print = "R: dnslookup for $local_part@$domain"
  driver = dnslookup
  domains = ! +local_domains
  transport = remote_smtp
  same_domain_copy_routing = yes
  # ignore private rfc1918 and APIPA addresses
  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8 : 192.168.0.0/16 :\
                        172.16.0.0/12 : 10.0.0.0/8 : 169.254.0.0/16 :\
                        255.255.255.255
  no_more

A: Some rules are dumb because they cause more harm than good! And people advocating and creating them know that. I would care more about postmaster ethics than the dumb rules. And I hate dumb rules and obviously the people setting those rules.
If you are like me, aware of consequences (see above) and want to screw the rules then sure,
1) Establish sender and recipient verification to secure yourself OR
2) Fail or freeze all null postmaster bounces. Do it with an exim system filter
system_filter = /etc/exim/screwtherules.exim
vi /etc/exim/screwtherules.exim
if $sender_address is ""
then
if ${lookup{${extract{2}{@}{$recipients}}}lsearch{/etc/localdomains}{yes}{no}} is "no"
then
fail text "Delayed bounce message ignored"
seen finish
endif
endif

3) OR create an ACL at acl_smtp_data check time to forward, fail or freeze the null bounce emails being sent to or not to specific hosts. You can extract received header info as described in https://grepular.com/Exim_Trick_to_Extract_Received_Header_IP_Addresses

A: Your approach violates RFC 5321 where you must deliver or bounce back to sender. There are only very limited exceptions: https://www.rfc-editor.org/rfc/rfc5321#section-6.2
So you have three options

*

*Deliver all bounces to postmaster
This is invalid. No exceptions. Because there are situations where you discard legitimate bounces (quota exceeded, disk errors, ...) for all senders. Legitimate clients and evil Spammers.

*Deliver bounces from relayed mail to postmaster
This is legitimate. But it leaves a hole where you discard bounces that are not related to content violations (Spam, viruses) but user unknown, mailbox full and the like.

*Deliver bounces from relayed mail that indicate content violations to postmaster
Perfect solution but introduces extended configuration.

Go for option 3. But better would be to disallow forwarding mails or increase Spam filtering before forwarding these mails.

A: The way to do this is with the errors_to directive in the router. I believe Exim also supports some conditionals to do it selectively.


text:
Q: Preventing Duplicated Google Maps API Marker use ValueEventListener Firebase I am trying to make a marker in my app using google maps api and I got the location from my RLTB Firebase. The location is always changing so that is why I was using ValueEventListener.
I tried to setting the marker outside of ValueEvent but does not work properly.
getDataNewLoc = FirebaseDatabase.getInstance().getReference().child("Location").child(id_diriku);
        getDataNewLoc.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                Double new_lat = (Double) dataSnapshot.child("l").child("0").getValue();
                Double new_long = (Double) dataSnapshot.child("l").child("1").getValue();

                LatLng diriku = new LatLng(new_lat, new_long);

                mDiriku = mMap.addMarker(new MarkerOptions()
                        .title("Diriku")
                        .position(diriku)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_forme))
                );
                mDiriku.setTag(0);
                mMap.animateCamera( CameraUpdateFactory.newLatLngZoom(diriku, 19.0f ) );
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

How could I prevent this kind of thing?

A: If you only want to get the location information from the database once, use addListenerForSingleValueEvent.
So:
getDataNewLoc.addListenerForSingleValueEvent(new ValueEventListener() {
  ...

A: Write the following line at the top, inside the onDataChange method
mMap.clear()


text:
Q: Can you improve this C# regular expression code? In a program I'm reading in some data files, part of which are formatted as a series of records each in square brackets. Each record contains a section title and a series of key/value pairs.
I originally wrote code to loop through and extract the values, but decided it could be done more elegantly using regular expressions. Below is my resulting code (I just hacked it out for now in a console app - so know the variable names aren't that great, etc.
Can you suggest improvements? I feel it shouldn't be necessary to do two matches and a substring, but can't figure out how to do it all in one big step:
string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]";

MatchCollection matches=Regex.Matches(input, @"\[[^\]]*\]");
foreach (Match match in matches)
{
    string subinput = match.Value;

    int firstSpace = subinput.IndexOf(' ');
    string section = subinput.Substring(1, firstSpace-1);
    Console.WriteLine(section);

    MatchCollection newMatches = Regex.Matches(subinput.Substring(firstSpace + 1), @"\s*(\w+)\s*=\s*(\w+)\s*");
    foreach (Match newMatch in newMatches)
    {
        Console.WriteLine("{0}={1}", newMatch.Groups[1].Value, newMatch.Groups[2].Value);
    }
}

A: I prefer named captures, nice formatting, and clarity:
string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]";
MatchCollection matches = Regex.Matches(input, @"\[
                                                    (?<sectionName>\S+)
                                                      (\s+
                                                         (?<key>[^=]+)
                                                          =
                                                         (?<value>[^ \] ]+)
                                                      )+
                                                  ]", RegexOptions.IgnorePatternWhitespace);

foreach(Match currentMatch in matches)
{
    Console.WriteLine("Section: {0}", currentMatch.Groups["sectionName"].Value);
    CaptureCollection keys = currentMatch.Groups["key"].Captures;
    CaptureCollection values = currentMatch.Groups["value"].Captures;

    for(int i = 0; i < keys.Count; i++)
    {
        Console.WriteLine("{0}={1}", keys[i].Value, values[i].Value);
    }
}

A: You should take advantage of the collections to get each key. So something like this then:
        string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]";

        Regex r = new Regex(@"(\[(\S+) (\s*\w+\s*=\s*\w+\s*)*\])", RegexOptions.Compiled);

        foreach (Match m in r.Matches(input))
        {
            Console.WriteLine(m.Groups[2].Value);
            foreach (Capture c in m.Groups[3].Captures)
            {
                Console.WriteLine(c.Value);
            }
        }

Resulting output:
section1
key1=value1
key2=value2
section2
key1=value1
key2=value2
key3=value3
section3
key1=value1

A: You should be able to do something with nested groups like this:
pattern = @"\[(\S+)(\s+([^\s=]+)=([^\s\]]+))*\]"

I haven't tested it in C# or looped through the matches, but the results look right on rubular.com

A: This will match all the key/value pairs ...
var input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]";

var ms = Regex.Matches(input, @"section(\d+)\s*(\w+=\w+)\s*(\w+=\w+)*");

foreach (Match m in ms)
{
    Console.WriteLine("Section " + m.Groups[1].Value);

    for (var i = 2; i < m.Groups.Count; i++)
    {
        if( !m.Groups[i].Success ) continue;
        var kvp = m.Groups[i].Value.Split( '=' );
        Console.WriteLine( "{0}={1}", kvp[0], kvp[1] );
    }
}


text:
Q: Upload/Download files to Local Machine Network path using Jquery/HTML5 We have a web Application written in ASP.NET MVC 4 with a file upload functionality. It saves the file to a directory in the web server on upload and user can download it back, which worked fine.
Now our client wants all his files to be saved and retrieved to and from his local server in the LAN (\FileServer\Files) instead of hitting the web server through internet to avoid the bandwidth as their production files are big/huge upto 50 MB.
Can this be achieved using Jquery / HTML5?

A: I think what will work best is to have the html/JavaScript post to an endpoint on the server that's on the LAN.
I'm not sure what you mean by "can this be achieved using jQuery/ HTML5" but the answer is no from a perspective of you can't write lines of html or JavaScript that will send the file and force the server to store it/retrieve it. You'll want an application running on that server that will do that for you and the HTML / jQuery will just post to that server.
I would also suggest building it in such a way that the LAN server or the client side code redirected you to the web server to display either a failure or success page.


text:
Q: MonoDevelop 2.4: Help finding a dll : RemoteSoftDebuggerSession I am trying to build a MonoDevelop 2.4 add-in but I need the dll that contains the class: RemoteSoftDebuggerSession. Does anyone know what dll this class is stored in?

A: It's in MonoDevelop.Debugger.Soft.dll


text:
Q: DjangoRestFramework - How can I use 'pk' to filter a list? I want to filter a list of BatchLog objects according to pk that I send through the request - which is their batch_id. Is there a way to access it on views.py file?
I have this in my urls.py file
path('feed/<int:pk>', GetFeedItemView.as_view())

And in my views.py file I want to access a BatchLog object by filtering its batch_id
class GetFeedItemView(RetrieveAPIView):
    serializer_class = FeedSerializer

    def get_queryset(self):
        return BatchLog.objects.filter(batch_id=self.request.pk)

This filter(batch_id=self.request.pk) doesn't work but I want to implement it in the same logic.
How can I achieve this?
Thanks a lot.

A: You can use self.kwargs["pk"]
class GetFeedItemView(RetrieveAPIView):
    serializer_class = FeedSerializer

    def get_queryset(self):
        return BatchLog.objects.filter(batch_id=self.kwargs["pk"])


text:
Q: How can play mp3 when click on image between   tag (html5 code) In web source I used, when drafting, everything I wrote (by using CKeditor 3.2) is between

 tag, I can't play mp3 by js. I need to play mp3 (also on mobile device). Formerly, I used <object ... width="20" height="20" > to play mp3, but it does not work in mobile devices.
I need to play mp3 file both in PC and mobile device, and I just drafted in

 tag. Somehow for me to play mp3 when click on image ( put between
 tag) or how to edit this code to make it width=20, heigh=20
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>

A: Try labeling the audio tag with an id, hide the audio player, then attach an onclick event to the  tag which contains the image.
sample javascript:
var audioTagged = document.getElementById('audioID');
    audioTagged.src = 'audio.mp3';
    audioTagged.load();

sample html:


text:
Q: Regex with mix quantifiers I am trying to validate a telephone number in an ASP.Net MVC application using RegEx validation annotation.
Apart from allowed characters and max-min length, I want to allow maximum 2 spaces anywhere in the text. I have tried the following RegEx but its not working.
^(\+)?(\d|\s{0,2}|-|\(|\)){8,16}$

It works fine if I remove {0,2} without validating number of spaces.
I had tried different combination but no luck.
Update
"1234 5 6" should be valid but "123 4 5 6" should not.

A: You may consider the following pattern:
^(?!(?:\S*\s){3})(?=.{8,16}$)\+?[\d\s()-]+$

See the regex demo.
Details

*

*^ - start of string

*(?!(?:\S*\s){3}) - no 3 or more whitespace chars after any non-whitespace chars are allowed

*(?=.{8,16}$) - the string length must be from 8 to 16 (no line breaks, or replace . with [\s\S])

*\+? - an optional +

*[\d\s()-]+ - 1 or more digits, whitespaces, (, ), -

*$ - end of string.


text:
Q: authStateChanges with .map()?
Hi guys, I'm trying to understand how authStateChanges().map(——) works. Does authStateChanges return some value and send it to map? which then passes through the function of returning the Userid or Null.
sorry if this is a basic question, I just can't quite seem to understand how map() works and what's going on in this code.


text:
Q: How to setOnClickListener for AlertDialog with custom setView? i am showing an AlertDialog OnClickListener from Activity:
fav_btn.setOnClickListener {
        if(token.equals("false")){
            val builder = AlertDialog.Builder(this)
            val optionDialog = AlertDialog.Builder(this).create()
            builder.setView(R.layout.alert_reg)

            builder.setPositiveButton(android.R.string.yes) { dialog, which ->
                val intent = Intent(this, SignupActivity::class.java)
                startActivity(intent)
            }

            builder.setNeutralButton(android.R.string.no) { dialog, which ->
                optionDialog.dismiss()
            }

            builder.show()

        }
        else{
            if (isFavourite)deleteFavorite(eventId)
            else postFavImage(eventId)
        }
    }

this is the layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">

<LinearLayout
    android:background="@drawable/round_corner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Assalamualaikum Qalbies"
        android:textSize="19dp"
        android:fontFamily="@font/poppins_bold"
        android:gravity="center"
        android:layout_marginTop="@dimen/_20sdp"
        android:textColor="#AC6AA6"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/_20sdp"
        android:paddingTop="@dimen/_8sdp"
        android:paddingRight="@dimen/_20sdp"
        android:text="Text"
        android:textSize="14dp"
        android:fontFamily="@font/poppins"
        android:gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:textColor="#1AB7B8"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/_20sdp"
        android:paddingTop="@dimen/_8sdp"
        android:paddingRight="@dimen/_20sdp"
        android:text="To continue, please"
        android:textSize="14dp"
        android:fontFamily="@font/poppins"
        android:gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:textColor="#4C4F4F"/>

<LinearLayout
    android:background="@drawable/round_corner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/cancel_reg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/_20sdp"
        android:paddingTop="@dimen/_8sdp"
        android:paddingRight="@dimen/_20sdp"
        android:text="Cancel"
        android:textSize="14dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/rounded_edittext"
        android:backgroundTint="#F3F3F3"
        android:fontFamily="@font/poppins_bold"
        android:gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:textColor="#7D7D7D"/>

    <TextView
        android:id="@+id/confirmation_reg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_edittext"
        android:backgroundTint="#1AB7B8"
        android:layout_gravity="center_horizontal"
        android:paddingLeft="@dimen/_20sdp"
        android:paddingTop="@dimen/_8sdp"
        android:clickable="true"
        android:paddingRight="@dimen/_20sdp"
        android:text="Sign-Up"
        android:textSize="14dp"
        android:fontFamily="@font/poppins_bold"
        android:gravity="center"
        android:layout_marginBottom="@dimen/_5sdp"
        android:textColor="#FFFFFF"/>
    </LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>

so far everything is working fine but I want to set the textviews "cancel_reg" and "confirmation_reg" rather than "setPositiveButton" and "setNeutralButton"
I tried to do this in the activity:
fav_btn.setOnClickListener {
        if(token.equals("false")){
            val builder = AlertDialog.Builder(this)
            val optionDialog = AlertDialog.Builder(this).create()
            builder.setView(R.layout.alert_reg)
            val goreg = findViewById<TextView>(R.id.confirmation_reg)
            val cancel = findViewById<TextView>(R.id.cancel_reg)
            goreg?.setOnClickListener {
                val intent = Intent(this, SignupActivity::class.java)
                startActivity(intent)
            }
            cancel?.setOnClickListener {
                val intent = Intent(this, SignupActivity::class.java)
                optionDialog.dismiss()
            }
            builder.show()
        }
        else {
            if (isFavourite)deleteFavorite(eventId)
            else postFavImage(eventId)
        }
    }

i tried to delete "setPositiveButton" and "setNeutralButton" and replace them with Textviews "confirmation_reg" and "cancel_reg" from the view but i can't click them
am i doing anything wrong?

A: You need to call findViewById on the AlertDialog's View
currently its being called on your Activity or Fragment. to fix this update your dialog creation code as following
val builder = AlertDialog.Builder(requireContext())

// Inflate the XML with layout inflator and keep a reference to find TextView's
val dialogView = layoutInflater.inflate(R.layout.alert_reg, null)
builder.setView(dialogView)

// Find TextView's using the dialogView
val goreg = dialogView.findViewById<TextView>(R.id.confirmation_reg)
val cancel = dialogView.findViewById<TextView>(R.id.cancel_reg)

goreg?.setOnClickListener {
    // Do something
}
cancel?.setOnClickListener {
    // Do something
}
builder.show()

A: Try setting clickable attribute to true in xml.


text:
Q: document.getElementById("MyId").innerHTML = obj.My-Fieldname; I have made a websocket with a server in a html page with java.
I receive a json string an I need to get de data from the individual fields.
The code I use is this:
ws.onmessage = function (ev) {
      const obj = JSON.parse(ev.data);
          document.getElementById("COG").innerHTML = obj.COG;
          document.getElementById("AWA").innerHTML = obj.AWA;
          document.getElementById("demo").innerHTML = obj.Est Time en Route;
          document.getElementById("SOG-forward").innerHTML = obj.SOG-forward;

The first two are no problem but the second two are.
It seems that it is not possible to have spaces or the "-" in the fieldname.
I can not change that on the server side.
How can I get this working?


text:
Q: how can my Microsoft azure bot be more interactive and intelligent I have created a customer service LUIS-QnA bot using Microsoft bot framework. This bot is supposed to answer customer questions and problems they face so that FAQs are answered by the bot and not directed to the help desk.
However, it is not interactive in that it does not possess contextual intelligence.  How can i train it so that it can answer questions such as: "Can i get more details on that topic?" and more. If it is possible to do this using LUIS, i'd like to know how.

A: You can use LUIS Action Binding framework as it supports three main scenarios which are mentioned and referenced below, but it also provides tools that you can use to implement or support your custom scenarios within your own apps.
Scenario #1 : Switch from an Action to a new Action
Bot: What do you want to do?
User: Find me a hotel in Madrid                         -- This would trigger a new `FindHotels` intent with Madrid as Location entity
Bot: When do you want to check-in?
User: Today
Bot: When do you want to check-out?
User: I changed my mind, find flights to Madrid         -- This would trigger a new `FindFlights` intent with Madrid as Location entity (`FindHotels` progress is discarded)
Bot: When do you want to flight?

Scenario #2 : Trigger a Contextual Action within a valid Context
Bot: What do you want to do?
User: Find me a hotel in Madrid                     -- This would trigger a new `FindHotels` intent with Madrid as Location entity
Bot: When do you want to check-in?
User: Today
Bot: When do you want to check-out?
User: Sorry, change the checkin date to tomorrow    -- This would trigger a `FindHotels-ChangeCheckin` intent with tomorrow as date (but will execute within the context of `FindHotels` and will update its check-in date previously set)
Bot: Ok, I changed the check-in date to tomorrow
Bot: When do you want to check-out?

Scenario #3 : Trigger a Contextual Action with no previous Context (ie. from scratch)
User: Please change my check-in date to tomorrow
Bot: Ok, I changed the check-in date to tomorrow                -- This triggered the `FindHotels-ChangeCheckin` intent which should run in the context of the `FindHotels` action (so main action also is instanced)
Bot: I changed your reservation in Madrid from 03/25 to 03/27   -- The required parameters of the main context are iterated until it can call the action fulfillment

The examples that I mentioned and referenced relate to the Node sample, if you are working with C# you can find a sample here
You can also find a blog post about it to guide you through here


text:
Q: Display hidden css classes How to display hidden css classes on hover
Show the first
Show the second

The first

The second

I think it's clear
thanks!

A: A CSS only option would be to have 2 classes and with one you hide the div element as with the others you display it using the pseudo selector :hover
div {
    display: none;
}

a:hover + div {
    display: block;
}

A: You can use the general sibling selector:
div { display: none; }
.a1:hover ~ .div1 { display: block; }
.a2:hover ~ .div2 { display: block; }

http://jsfiddle.net/uK8KP/


text:
Q: ckeditor how to submit when it completes loading Hi There I am using CKEditor in one of my applications.
Is there a way that I can submit a form once the ckeditor has loaded.
 {
  CKEDITOR.replace( 'g_content_text' );
        toolbar : 'Basic'
  CKEDITOR.on('instanceReady',
      function( evt )
      {
         var editor = evt.editor;
         editor.execCommand('maximize');
      });
    };

I have the
{
  document.form1.submit();
}

but it submits the form before the ckeditor has finished loading.

A: Tried putting after the editor.execCommand('maximize'); ? It seems to be called once the instance is ready.
  CKEDITOR.on('instanceReady',
      function( evt )
      {
         var editor = evt.editor;
         editor.execCommand('maximize');
         document.form1.submit();
      });
    };


text:
Q: DirectX 9 Get Cursor Position So here's my problem: I want to get the cursor position which is in my directx 9 application. Not the default GetCursorPos(&rect). It should only be the mouse position inside of my application so for example if I draw a Rect at 100, 100, 200, 200 and when I hover my mouse over the rect the mouse x and y should be somewhere between 100 and 200. Is there any function like
myDevice->GetCursorPosition(), because I only saw a SetCursorPosition method.


text:
Q: How to avoid using ApplicationContext.getBean() when implementing Spring IOC I'm just getting started with Spring IOC concept. I often see most of the examples found in the internet use the code to get the object.
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello = (Hello) appContext.getBean("hello");

As a reference from these questions 1 and 2 in the stackoverflow. I've inferred that, it's not necessary to use appContext.getBean("hello") in the code which is considered to be the bad practice. Also, not recommended anymore. Correct me right here, If my inference is wrong.
Keeping that in view, I have made changes in my project accordingly.
Here's my applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="utilClassRef" class="org.hd.derbyops.DUtils" lazy-init="false" />
<bean id="appContext" class="org.hd.derbyops.ContextProvider" lazy-init="false">
   <property name="utils" ref="utilClassRef" />
</bean>
</beans>

My contextProvider Class Code
public class ContextProvider implements ApplicationContextAware {

    private static ApplicationContext ctx;

    /**
     * Objects as properties
     */
    private static DUtils utils;

    public void setApplicationContext(ApplicationContext appContext)
            throws BeansException {
        ctx = appContext;

    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    public static DUtils getUtils() {
        return utils;
    }

    public void setUtils(DUtils dUtilsRef) {
        utils = dUtilsRef;
    }

}

For instance, consider a class A that depends on org.hd.derbyops.DUtils.
I'm using the following code line
ContextProvider.getUtils();

inorder to get DUtils Object in class A, thus avoiding usage of  ApplicationContext.getBean() anywhere in my code.
Assume, if I have 10 classes and my class A is dependent on all of them, whose objects to be created and accessed without using ApplicationContext.getBean(). In that case also, as done above, I have a thought of creating properties of ContextProvider class followed by setter's and getter's of that property, where in get<PropertyName> is static. So that, I can use it wherever I'm in need of an object, like this
ContextProvider.get<PropertyName>;

Here's my brief question.
Firstly, Is my approach right? If it's right, loading all the beans at the start-up, wouldn't it be a performance killer? How would you do that in your applications without calling getBean atleast more than once?
If you were to design a web-application & you were to implement Spring IOC, without using ApplicationContext.getBean() in any of the code. How would you do that?
Note: with reference to the other questions tagged above

Calling ApplicationContext.getBean() is not Inversion of Control!

A: The simple answers are yes and no, no, and no. And finally, do a search online for spring MVC, as this probably does what you want.
So, your approach. Yes, you've got most of it right. However, it's considered very bad practice to use static methods for everything. And, you don't need to. Spring is based on the idea that you can simply create normal pojos, and spring will use them as singletons, and inject them into one another (it can also create objects on the fly, but I'm going for the common case here). If you use static classes and methods then:

*

*You can't mock them for unit testing (you're using JUnit right?)

*You can't use them with inheritance

*Static initialisers are a great way to loose exceptions

*etc, etc

So, yes to injection, and no to static stuff.
Next, performance. You're right in that it's a lot slower to use spring, but, if you do all your injection on startup it only happens once. Spring is meant for server side applications where there is likely to be a number of singleton classes passing data around. So, there might be a class to get stuff from a DB, one to process it, and one to display it, and spring is used to wire them together.
If you're using spring in an application where you start up repeatedly, like a command line app, then you are using it for the wrong sort of application, and you probably want to use a builder or something. Spring is meant for big enterprise apps that aren't restarted often.
Finally, if you simply inject all the dependencies for a class into it at startup, and you do this with all your classes, then you don't need to do any getBean stuff at all. Also, using the init-method and destroy-method attributes on a bean means that you can start up processes once spring has finished injecting dependencies. You need only load the context, and your app will spring (pun intended) into existence.
As for web projects, Spring MVC basically takes the whole inversion of control pattern and applies it to web applications. The spring stuff gets loaded by the container, and you can define the URLs to respond to using nothing more than bean names. And most of your code can stay as pojos. If you have something insanely complex, you may want to look at spring web flow, but I'd advise you to make sure that your spring foo is very strong before attempting that.

A: Here's my example for getting the first instance without actually calling getBean() on ApplicationContext.
public class Test{
  // Declare private static variable so that we can access it in main()
  private static Triangle triangle;

  // Use constructor injection to set the triangle
  public Test(Triangle triangle) {
      Test.triangle = triangle;
  }

  public static void main(String[] args) {
      // Specify the context file containing the bean definitions
      // Spring automatically creates instances of all the beans defined
      // in this XML file. This process is performed before you actually make
      // a getBean("beanName") call.
      ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

      // Use instance methods of triangle
      Test.triangle.draw();
  }
}

You can use another way:
In spring.xml (Your bean configuration XML file)
<bean class="com.example.Test" init-method="myMethod">
    <constructor-args ref="triangle"/>
</bean>

Now for your main class
public class Test {
  private final Triangle triangle;

  public Test (Triangle triangle) {
     this.triangle = triangle;
  }

  public static void main (String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  }

  // Called by Spring immediately after the Triangle Bean has been created and
  // all the properties for the bean have been set. This method name must match
  // the one specified with destroy-method attribute in spring.xml
  public void myMethod () {
     triangle.draw();
  }
}


text:
Q: Oksendal chapter 7, what does $E^x[f_1(X_{t_1})\ldots f_k(X_{t_k})]=E[f_1(X^x_{t_1})\ldots f_k(X^x_{t_k})]$ mean? I am trying to read Oksendal's book "Stochastic Differential Equations". In chapter 7, he consider processes like $$dX_t=b(X_t)dt+\sigma(X_t)dB_t$$ with the usual conditions ensuring unicity. Denote by $X^x_t$ the unique solution of the above equation such that $X_0=x$. Let $Q^x$ denote the probability law of $X^x_t$ when $X_0=x$ and $E^x(\cdot)$ be the expectation with respect to $Q^x$. Now this is claimed

[...]Hence we have $$E^x[f_1(X_{t_1})\ldots f_k(X_{t_k})]=E[f_1(X^x_{t_1})\ldots f_k(X^x_{t_k})]$$ for all Borel functions $f_1,\ldots,f_k$ and all times $t_1,\ldots,t_k$ where $E=E_P$ denotes the expectation with respect to the probability law $P=P^0$ for $\{B_t\}_{t\ge0}$ when $B_0=0$.

First I don't understand what are the processes on the left hand side : Is $X_{t_1}=X^0_{t_1}$? Or $X_{t_1}=X^x_{t_1}$? Or something else? This is not clear to me. Second, how do you show the identity properly?

A: Following Øksendal's notation, the LHS means:
$$
\text{LHS}= \int_{\left(\mathbb{R}^n\right)^{[0,+\infty)}}\prod_{i=1}^k f_i\left(Y_{t_i}\right) dQ^x(Y)=\int_{\mathbb{R}^{n\cdot k}}\prod_{i=1}^k f_i\left(y_{i}\right) dQ^x_{t_1,\ldots,t_k}(y),
$$
where the second equality follows from Kolmogorov's Extension Theorem, see, for instance, Chapter 2 of Øksendal's book. The RHS means:
$$
\text{RHS}= \int_{\Omega}\prod_{i=1}^k  f_i\left(X_{t_i}^{x}(\omega)\right) dP(\omega).
$$
Then, the equality follows from a standard result called "the law of the unconscious statistician" applied to the random vector $(X^x_{t_i})_{i=1}^k$ in $\mathbb{R}^{n\cdot k}$. See, for instance, Theorem 5.11 (figure below) in these notes of A. Grigoryan or Proposition 10.1 of Folland "Real Analysis".


text:
Q: set array .viewControllers from SplitViewController I'm trying to use a splitview inside a TabBar. By now I have a SplitView in my first TabBarItem. My problem comes when I try to access to a different DetailView or right view in the SplitViewController I have.
I'm trying to do it inside the didSelectRowAtIndexPath: of my Root (or Master) viewcontroller from the SplitView.
Here's the code, where I try to acces to my TabBarController from an AppDelegate object, and change the viewControllers array of my SplitView only changing the second view controller. I always get this crash error, saying that 2nd instance send is unrecognized: -[SecondViewController viewControllers]: unrecognized selector sent to instance 0x6852460
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//object AppDelegate
AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

//Objecte in Index 0 is my SplitVC
NSArray *barControllers = myDelegate.tabBarController.viewControllers;

if (indexPath.row == 0)
{
    SplitVC *temporalSplit = [barControllers objectAtIndex:indexPath.row];

    NSArray *mArray = temporalSplit.viewControllers;

    FirstViewController *detail = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil];

    UINavigationController *navigationDetail = [[UINavigationController alloc]initWithRootViewController:detail];

    temporalSplit.delegate = detail;

    temporalSplit.viewControllers = [[NSArray alloc] initWithObjects:[mArray objectAtIndex:0], navigationDetail, nil];

    myDelegate.tabBarController.viewControllers = [NSArray arrayWithObjects:temporalSplit.viewControllers, [barControllers objectAtIndex:1], nil];

}
else if (indexPath.row == 1)
{
    SplitVC *temporalSplit = [barControllers objectAtIndex:indexPath.row];

    NSArray *mArray = temporalSplit.viewControllers;

    Detail2VC *detail = [[Detail2VC alloc]initWithNibName:@"Detail2VC" bundle:nil];

    UINavigationController *navigationDetail = [[UINavigationController alloc]initWithRootViewController:detail];

    temporalSplit.delegate = detail;

    temporalSplit.viewControllers = [[NSArray alloc] initWithObjects:[mArray objectAtIndex:0], navigationDetail, nil];

    myDelegate.tabBarController.viewControllers = [NSArray arrayWithObjects:[barControllers objectAtIndex:0], temporalSplit, nil];
}
[myDelegate release];
}

And my AppDelegate code (that works without problems):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];

// Override point for customization after application launch.

NSMutableArray *controllersBar = [[NSMutableArray alloc]init];

UIViewController *viewController2 = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];

for (int i = 0; i<2; i++)
{
    if(i == 0)
    {
        _firstViewController = [[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil] autorelease];

        _masterApp = [[MasterVC alloc]initWithNibName:@"MasterVC" bundle:nil];

        _masterApp.firstViewController = _firstViewController;
        _firstViewController.mastervc = _masterApp;

        UINavigationController *navigationMaster = [[UINavigationController alloc]initWithRootViewController:_masterApp];
        UINavigationController *navigationDetail = [[UINavigationController alloc]initWithRootViewController:_firstViewController];

        _splitVC = [[SplitVC alloc] initWithNibName:nil bundle:nil];
        //_splitVC.tabBarItem = controller.tabBarItem;
        _splitVC.viewControllers = [NSArray arrayWithObjects:navigationMaster, navigationDetail, nil];
        _splitVC.delegate = _firstViewController;

        [controllersBar addObject:_splitVC];
    }
    else if (i == 1)
    {
        [controllersBar addObject:viewController2];
    }
}

//self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];

_tabBarController.viewControllers = controllersBar;
_tabBarController.selectedIndex = 0;
_tabBarController.delegate = self;

self.window.rootViewController = self.tabBarController;

[self.window makeKeyAndVisible];

return YES;
}

What am I doing wrong? Any help or suggestion is welcome.
Thanks to all in advance.

A: Split view controller MUST be root level controllers:
UISplitviewcontroller not as a rootview controller
If not, you can apparently get all sorts of strange things happening.


text:
Q: Error copying Files when setting up Xampp I was attempting to install the xampp(5.6) after uninstalling lamp from my ubuntu 17.04 but it shows me this error when setting up xampp .
I'm new to ubuntu and I can't  find out  the problem .
This is the error shown when setting up Xampp

A: I have faced same  issue, later I found out that because of a memory issue,
If you increase your volume size, it will solve the problem


text:
Q: Rails associations for fixtures with foreign_keys/primary_keys I'm wrestling with Rails fixtures trying to setup my tests but I'm having issues when I try to reference one fixture from another fixture file. The problem started when I changed the association in my model from a belongs_to to a has_one association.
DeviceReplacement.rb - OLD
class DeviceReplacement < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :user
  belongs_to :car

DeviceReplacement.rb - NEW
class DeviceReplacement < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :user
  has_one :active_car, primary_key: 'car_id', foreign_key: 'id', class_name: 'Car'

device_replacements.yml
mikes_device_replacement:
  old_device_number: "bdh9fa023bf6851cb8eb95hbd0d1019"
  new_device_number: "poe9fa023bf6851cb8eb95hbd0d939"
  return_status: "envelope sent"
  cancel_date: <%= Date.today %>
  subscription: mike_car_subscription
  car: mike_car
  user: mike

cars.yml
mike_car:
  model: 'XT-2000-G-X001'
  phone_number: '5551231238'
  device_number: 'bdh9fa023bf6851cb8eb95hbd0d1019'
  uid: 19191919191919
  lt: 25.782324
  ln: -80.2310801
  pricing_plan_id: 75
  title: "Mike's Car"
  status: "onboarded"
  device_purchase: mikes_purchase

I'm now getting the following error -
Ryans-MacBook-Pro:myautobrain ryangrush$ rake db:fixtures:load RAILS_ENV=test
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "car" of relation "device_replacements" does not exist
LINE 1: ...w_device_number", "return_status", "cancel_date", "car", "cr...
                                                             ^
: INSERT INTO "device_replacements" ("old_device_number", "new_device_number", "return_status", "cancel_date", "car", "created_at", "updated_at", "id", "subscription_id", "user_id") VALUES ('bdh9fa023bf6851cb8eb95hbd0d1019', 'poe9fa023bf6851cb8eb95hbd0d939', 'envelope sent', '2016-08-15', 'mike_car (Car)', '2016-08-15 17:46:15', '2016-08-15 17:46:15', 219175143, 88066445, 350169046)

I can get it to work if I hard code the :id for each but I'm trying to avoid doing that.


text:
Q: Google apps script not identifying sheet correctly I'm running a templated google script that constructs an html page with the contents of a google spreadsheet.
When I run the script with the spreadsheet https://docs.google.com/spreadsheet/ccc?key=0AtDy2rbIwVyldE82MG50SkR3UWYyam5YRVd1ajZlcnc&usp=drive_web#gid=0 everything works fine.
When I run the script with the spreadsheet https://docs.google.com/spreadsheets/d/1A0Kd_BKeO9IB-SJvRMhC68q0XMQLrXarVVPlFJa_fMg/edit#gid=0 I get the message that I need to first select an active spreadsheet.
Here is the script:
function doGet() {
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate();
}

function getData() {
  var mysheet = SpreadsheetApp.openById('SPREADSHEET_KEY').getDataRange().getValues();
  return mysheet;
}

Here is the index.html file:
<? var data = getData(); ?>

  <? for (var i = 0; i < data.length; i++) { ?>

      <? for (var j = 0; j < data[i].length; j++) { ?>
        <?= data[i][j] ?>
      <? } ?>

  <? } ?>

It seems that the problem lies in the second spreadsheet.
Any help will be apreciated.

A: The reference you are currently assigning to mysheet refers to the document as a whole.  You still need to grab a reference to the sheet that contains the data.
function getData() {
  var spreadsheet = SpreadsheetApp.openById('SPREADSHEET_KEY').getDataRange().getValues();
  var mysheet = spreadsheet.getSheetByName('NameOfTheSheet');
  return mysheet;
}

A: use .getActiveSheet()
and the script would be:
function doGet() {
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate();
}

function getData() {
  var mysheet = SpreadsheetApp.openById('SPREADSHEET_KEY')**.getActiveSheet()**.getDataRange().getValues();
  return mysheet;
}


text:
Q: Quoting columns with spaces in PostgreSQL? I migrated a database from SQL Server to PostgreSQL.
Most column names contain double words, for example:
SELECT [Column Name] FROM table;

...which does not work in PostgreSQL.
What is the correct syntax for PostgreSQL?

A: Moving to PostgreSQL convention
For more information on this see the post How do I adopt the PostgreSQL naming convention in legacy database?
In PostgreSQL by convention and with good reason, we neither use spaces nor capital letters in our identifiers (columns, tables, schemas, etc). The use of _ is purely style though.
SELECT FORMAT(
  'ALTER TABLE %I.%I.%I RENAME %I to %I;',
  table_catalog,
  table_schema,
  table_name,
  column_name,
  lower(
    -- replace all spaces with _, xX and Xx becomes x_x
    regexp_replace(
      -- First, replace spaces with an _
      replace(column_name, ' ', '_'),
      '([[:lower:]])([[:upper:]])',
      '\1_\2',
      'xg'
    )
  )
)
FROM information_schema.columns
WHERE column_name ~ ' |[[:lower:]][[:upper:]]';

From there you can edit the commands to be run, delete the ones you don't want, or run \gexec and all the problems go away.

A: In most RDBMSs, double-quotes are what are used to specify an exact spelling of something..  (single quotes being string delimiters).
SELECT
  tab."This IS My Column EXACTLY" AS col
FROM "My TabLE Name Contains Spaces Too!" tab
WHERE tab."ANOTHER UGLY COLUMN name" = 'MyFilterString';

Notice that capital/lowercase also matters when using double-quotes.  (Postgres lower-cases everything when double-quotes are not used ... Oracle upper-cases everthing, etc..)
SELECT COLUMN1 FROM TABLE

in postgres, is different from
SELECT "COLUMN1" FROM TABLE

where as in oracle, is different from
SELECT "column1" FROM TABLE


text:
Q: Invoiceninja loading invoices is extremely slow I'm self-hosting an instance of Invoiceninja on Ubuntu 16.04 using Nginx and mysql
I currently only have about 1400 clients, 1700 invoices and 13k products. however loading invoices takes roughly 5-15 seconds per invoice. This doesn't seem like a lot of data to be slowing down so much.
I've added query caching in mysql but that has not alleviated any performance issues.
I've also tried to identify what exactly is holding up the load times using chrome's dev tools but I can't decipher what's causing the loading issues.
I tried posting this to the invoiceninja forums but for some reason I'm unable to create a new post.
Where should I be looking in order to identify what is holding up loading invoices?

A: This problem is most likely related to the amount of products. Please use the new v5 which works hopefully more performant.
Currently v5 is in alpha state, the official release is roughly in one month.
Check the Github account or the forum how to get the v5 up and running.


text:
Q: Typescript won't emit import statements as-is My index.html imports only one script with <script type="module" src="./index.js"></script>
And at the top of index.ts are the now-standard import statements
import { PieChart } from "./pie-chart.js";
import { ChartLegend } from "./chart-legend.js";

But index.ts, when compiled to index.js, the import statements are completely removed, replaced with nothing else.  My tsconfig.json is set to
        "target": "ES2020",
        "module": "ESNext",

But regardless if "module" is set to ES6, ES2015, ES2020, or ESNext, they all work the same.
Browsers now understand the import statement natively, and will import the files correctly (assuming .js extension is there and the path is correct). I tried this by copy-pasting those import statements into the resulting .js file and everything lights up.
How could / why can't Typescript (Version 4.0.2) emit the imports??

A: Typescript drops imports from the file if the imported items are only used as types.
import { PieChart } from "./pie-chart.js";

const pie = document.querySelector("pie-chart") as PieChart;

Will not cause the import to be emitted.  However, you can import a module "for its side effects" with
import "./pie-chart.js";

and the import will be emitted. You can also do both.
import { PieChart } from "./pie-chart.js";
import "./pie-chart.js";

const pie = document.querySelector("pie-chart") as PieChart;

But this may not scale well for an app of any significant size.


text:
Q: 1 div, 1 text input, side by side, stretch input to 100% with no fixed width on either I've got 2 elements, a div and a text input side by side.
The widths of neither is unknown and I'm trying to get the text input to fill the remaining width of the container.

.wrap {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  background: #EFEFEF;
  margin-top: 30px;
}

#url {
  margin: 6px 2px 0 0;
  float: left;
}

#input_1 {
  box-sizing: border-box;
  overflow: hidden;
  padding: 3px;
  font-size: 12px;
}

http://example.com/images/

  <input id="input_1" name="input_1" type="text" value="somefile.jpg" />

Fiddle
Any suggestions?
*EDIT
Here's a working Fiddle using Nick's answer in case anybody else needs it.

A: Like this? If so, flexbox is your friend, my friend.

.wrap {
  display:flex;
  flex-direction: row;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  background: #EFEFEF;
  margin-top: 30px;
}
#url {
  margin: 6px 2px 0 0;
  width: auto;
}
#input_1 {
  box-sizing: border-box;
  overflow: hidden;
  padding: 3px;
  font-size: 12px;
  width: 100%;
}

http://example.com/images/

  <input id="input_1" name="input_1" type="text" value="somefile.jpg" />

A: You can do it with flex

.wrap {
  display: flex;
  width: 100%;
  padding: 10px;
  background: #EFEFEF;
  margin-top: 30px;
}

#url {
  margin: 6px 2px 0 0;
}

#input_1 {
  flex: 1;
  overflow: hidden;
  padding: 3px;
  font-size: 12px;
}

http://example.com/images/

  <input id="input_1" name="input_1" type="text" value="somefile.jpg" />

Solution without flex

.wrap {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  background: #EFEFEF;
  margin-top: 30px;
}

#left {
  margin: 6px 2px 0 0;
  float: left;
}

#right {
  overflow: auto;
  padding: 3px;
  font-size: 12px;
}

#input {
  width: 98%;
}

http://example.com/images/

    <input id="input" name="input_1" type="text" value="somefile.jpg" />


text:
Q: Excel VBA: How to Insert formula into an area of cells? Problem
I need to insert some formulas into a 2 dimensional area of cells with VBA. For example below

Of course I can do this for 1 row with VBA using the .Formulas = "=Sum(....)"
but how can I include an area instead of just a range? This seems so trivial but I can't seem to figure it out. I'm trying to avoid using a loop to fill out every row.

A: Range("yourrange").Formula = "=Sum(whatever)"

where yourrange is a Named Range, or for an actual reference
Range("A1:F8").Formula = "=Sum(whatever)"

A: range("A1:G10").formula = "=Sum(H1:H10)"
Fill in your own range/formula


text:
Q: How can I print the entire webpage at this url to a pdf file? I would like to download and convert https://spring.io/guides/gs/maven/ into a pdf file
But I tried several options of wkhtmltopdf in the following commands, and they can only print the beginning part of the webpage
wkhtmltopdf  https://spring.io/guides/gs/maven/ "Building Java Projects with Maven.pdf"
wkhtmltopdf -n https://spring.io/guides/gs/maven/ "Building Java Projects with Maven.pdf"
wkhtmltopdf --no-stop-slow-scripts https://spring.io/guides/gs/maven/ "Building Java Projects with Maven.pdf"

How can I print the entire webpage?
Also notice the code snippets have horizontal scroll bar. Is it possible to print the entire code snippets?
Thanks.