text:
Q: Error while compiling view in Ruby on rails? I'm coding with Ruby on rails 2.3.2 under BitNami RubyStack.  When I call the upload controller, I get error like this:
compile error
C:/Users/BitNami RubyStack/killerapp/app/views/upload/index.html.erb:6:
unterminated string meets end of file
C:/Users/BitNami RubyStack/killerapp/app/views/upload/index.html.erb:6:
syntax error, unexpected $end, expecting ')'

The code of index view:
<% form_for :picture, :html => { :multipart => true } do |form| %>
 First_Name:
 <%= form.text_field :first_name %>
 Last_Name:
 <%= form.text_field :last_name %>
 <%= submit_tag "upload" %>
<% end %>

String number 6 is:
<%= submit_tag "Upload" %>

What's the problem? Please, help me.

A: Try
<% form_for :picture, :html => { :multipart => true } do |form| %>
 <%= label :picture, :first_name, "First Name" %>
 <%= form.text_field :first_name %>
 <%= label :picture, :last_name, "Last Name" %>
 <%= form.text_field :last_name %>
 <%= form.submit "upload" %>
<% end %>

And add
# routes.rb
map.resources :pictures

A:     ActionController::Routing::Routes.draw do |map|
  # The priority is based upon order of creation: first created -> highest priority.

  # Sample of regular route:
  #   map.connect 'products/:id', :controller => 'catalog', :action => 'view'
  # Keep in mind you can assign values other than :controller and :action

  # Sample of named route:
  #   map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
  # This route can be invoked with purchase_url(:id => product.id)

  # Sample resource route (maps HTTP verbs to controller actions automatically):
  #   map.resources :products

  # Sample resource route with options:
  #   map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }

  # Sample resource route with sub-resources:
  #   map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller

  # Sample resource route with more complex sub-resources
  #   map.resources :products do |products|
  #     products.resources :comments
  #     products.resources :sales, :collection => { :recent => :get }
  #   end

  # Sample resource route within a namespace:
  #   map.namespace :admin do |admin|
  #     # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
  #     admin.resources :products
  #   end

  # You can have the root of your site routed with map.root -- just remember to delete public/index.html.
  map.root :controller => "pictures"

  # See how all your routes lay out with "rake routes"

  # Install the default routes as the lowest priority.
  # Note: These default routes make all actions in every controller accessible via GET requests. You should
  # consider removing the them or commenting them out if you're using named routes and resources.
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

A: It works for me in Rails 2.3.4. Did you try debugging it? I'm using Netbeans, and it'll let me set a breakbpoint on line 6 and run it and inspect the various variables etc.

A: you should have a map.resources :pictures
also its a better idea to have your form_for point to an instance of that class
<% form_for @picture, :html => {:multipart = true} do |form| %>

then in your controller make sure you set the instance
@picture = Picture.new


text:
Q: Assigning values to an object in JS I've an object as below:
default = {
    name: "",
    details: {
        age: "",
        place: ""
        country: ""
    },
    contact: {
        email: null,
        phone: null
    }
}

Now, I've another object as:
data = {
    name: "Abc",
    details: {
        age: "27,
    },
    contact: {
        email: "abc@xyz.com"
    }
}

Want to achieve:
result = {
    name: "Abc",
    details: {
        age: 27,
        place: ""
        country: ""
    },
    contact: {
        email: "abc@xyz.com",
        phone: null
    }
}

Now, I want to get the values from data and put it in default. Currently I'm checking if the key exists, then assign value, else keep default. But it's a long process. Is there a JS helper function or something that I can use for this?
Object.assign(default, data) is only copying the property values and not going deep.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I fix `LIBUSB_ERROR_PIPE` error on **Infineon FX3** I am trying to do a control transfer on the infineon fx3 but when I call libusb_control_transfer() I get LIBUSB_ERROR_PIPE.
Can anyone help with this please?
int BulkTransferLoopback::sendControl(uint8_t data[], int length, uint8_t rx[]) {
    int numdevs = cyusb_open();
    if (numdevs > 0)
    {
        int r = cyusb_open(VENDORID, PRODUCTID);
        if (r != 1) {
            // check for errors
            printf("Could not open device!\n");
        }
        _handle = cyusb_gethandle(0);
        findEndpoints();

        // Send data
        // I think error is coming from parameters 1-3.
        int err = libusb_control_transfer(_handle, 0x40, 42, 0x1234, 0, data, 2, 1000);
        printf("%s\n", libusb_error_name(err));
        cyusb_close();
    }

    return numdevs;
}

A: Will get LIBUSB_ERROR_PIPE when the control request was not supported by the device, so first you can check if The control request is handled properly in FX3 or not.
And you can check USB traces using a USB analyzer (like Wireshark) to understand the status of the USB control transfer.
also, https://community.infineon.com/ can help you to debug your FW code.


text:
Q: Getting a NullPointerException in main method I'm trying to read the value from the XML. Then, in the browser, I want to login to the Gmail application. There I'm getting NullPointerException.
The code used in Eclipse is as follows:
import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class A {

    private static WebDriver driver;
    Properties p= new Properties();
    String url=p.getProperty("url");

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {

        A a = new A();
        String url = a.readXML("logindetails","url");
        String username = a.readXML("logindetails","username");
        String password = a.readXML("logindetails","password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        //use username for webdriver specific actions
        driver.findElement(By.id("1001")).sendKeys(url);
    }

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{
        String ele = null;
        File fXmlFile = new File("D://NewFile.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(searchelement);

        Node nNode = nList.item(0);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
             ele=eElement.getElementsByTagName(tag).item(0).getTextContent();

        }
        return ele;
    }

}

The output is:
www.gmail.com
test
test123
Exception in thread "main" java.lang.NullPointerException
at A.main(A.java:33)

A: private static WebDriver driver;
....
driver.findElement(By.id("1001")).sendKeys(url);

You access driver but never initialize it.
That's what gives you the NullPointerException.

A: Initialize the driver. For eg:
If you are using firefox browser try
WebDriver driver = new FirefoxDriver();


text:
Q: Elemental Number Theory: Proving that $\pi$ is irrational, assuming the following result: if $x$ is rational, $tan(x)$ is not. Question: Prove that $\pi$  is irrational, assuming the following result: if $x$ is rational, $tan(x)$ is not.
Proof: Let $x$ $\in$ $\mathbb Q$
I have seen Lambert's proof, however I am severely confused on where to begin. Do I now suppose $tan(x)$ is rational, then proceed by contradiction? Hints would be delightful!

A: Hint: Suppose $\pi/4$ is rational.

A: $$\tan (\pi)=0\in \mathbb Q $$
$$\implies \pi \notin \mathbb Q $$


text:
Q: Cannot build VS Code from sources - Windows I cloned Visual Studio Code sources and followed the instructions for contributors from the link - https://github.com/Microsoft/vscode/wiki/How-to-Contribute but When I run yarn I'm getting the following error:
error C:\_LAB_\vscode\node_modules\native-keymap: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments:
Directory: C:\_LAB_\vscode\node_modules\native-keymap
Output:
C:\_LAB_\vscode\node_modules\native-keymap>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "" rebuild )
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@8.11.1 | win32 | x64
gyp info spawn C:\Python27\python.exe
gyp info spawn args [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'msvs',
gyp info spawn args   '-G',
gyp info spawn args   'msvs_version=2015',
gyp info spawn args   '-I',
gyp info spawn args   'C:\\_LAB_\\vscode\\node_modules\\native-keymap\\build\\config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   'C:\\Users\\Maga\\.node-gyp\\iojs-1.7.12\\common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=C:\\Users\\Maga\\.node-gyp\\iojs-1.7.12',
gyp info spawn args   '-Dnode_gyp_dir=C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp',
gyp info spawn args   '-Dnode_lib_file=C:\\Users\\Maga\\.node-gyp\\iojs-1.7.12\\<(target_arch)\\iojs.lib',
gyp info spawn args   '-Dmodule_root_dir=C:\\_LAB_\\vscode\\node_modules\\native-keymap',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'C:\\_LAB_\\vscode\\node_modules\\native-keymap\\build',
gyp info spawn args   '-Goutput_dir=.' ]
gyp info spawn msbuild
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args   '/clp:Verbosity=minimal',
gyp info spawn args   '/nologo',
gyp info spawn args   '/p:Configuration=Release;Platform=x64' ]
C:\_LAB_\vscode\node_modules\native-keymap\build\keymapping.vcxproj : error MSB4057: Target element "Build" does not exist in project.
gyp ERR! build error
gyp ERR! stack Error: `msbuild` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.16299
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\_LAB_\vscode\node_modules\native-keymap

I tried to rebuild the native-keymap project in VS2017 but then I got the similar message for two other node_modules and eventually again from native-keymap.
My PC environment:
Windows 10 and Visual Studio 2017 Community.
Python: 2.7.14
Node: 8.11.1
npm: 5.6.0
yarn: 1.6.0


text:
Q: In Google Maps API generate a Google Maps URL There is a project in which the Google Maps API is used to build the route.
Now the task for me is the following: inside the web application using the Google Maps API to create a route, after changing the route by moving the route on the map (which is in the web application) and after generating a link with which you can open google maps (https://www.google.com.ua/maps) where the route should be displayed taking into account the user's shift in the application.
In other words: through the Google Maps API generate a link that displays the changed route in Google maps.
I watched the documentation, analyzed the queries and answers of the Google Maps API and Google maps. So I did not find a solution.
I want to clarify whether it is possible to realize this task?

A: I understand you would like to generate a draggable route using Google Maps JavaScript API and open the same route in Google Maps website. Once the user dragged the way point and changed the route, you would like to update the website URL and open updated route on Google Maps website. Is it correct?
You can implement this using the following ideas:

*

*The google.maps.DirectionsRenderer can listen to the directions_changed event. Each time the route changed the API will trigger this event, so you can analyze the DirectionsResult object to extract waypoints used during the route generation.
https://developers.google.com/maps/documentation/javascript/reference#DirectionsRenderer

*You can create universal cross-platform link for Google Maps website or native app using the Google Maps URLs. There is a directions mode where you can specify origin, destination and way points and also corresponding place IDs. Please refer to the documentation for more details.

*You can extract place IDs from DirectionsResult, to get corresponding formatted addresses that are required in Google Maps URLs you can use the Geocoder service of Maps JavaScript API. Note that geocoder service is asynchronous, you might need use promises to implement this part.
I have created a small example that shows this idea. Please have a look, but be aware that this code is not production ready, it's just a proof of concept. Each time the route is changed the link 'Open in Google Maps' is updated. Also note that I used promises, so this code will work only in modern browsers.

var origin = 'Barcelona, Spain';
var destin = 'Madrid, Spain';
var geocoder;
var hashPlaces = {};

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {lat: 41.557922, lng: -0.895386},  //Spain.
    gestureHandling: 'greedy'
  });

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });
  geocoder = new google.maps.Geocoder();

  directionsDisplay.addListener('directions_changed', function() {
    computeTotalDistance(directionsDisplay.getDirections());
    prepareMapLink(directionsDisplay.getDirections());
  });

  displayRoute(origin, destin, directionsService,
      directionsDisplay);
}

function displayRoute(origin, destination, service, display) {
  service.route({
    origin: origin,
    destination: destination,
    waypoints: [{location: 'Lleida, Spain'}, {location: 'Zaragoza, Spain'}],
    travelMode: 'DRIVING',
    avoidTolls: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

function computeTotalDistance(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000;
  document.getElementById('total').innerHTML = total + ' km';
}

function geocodePlaceId (placeId) {
  return new Promise(function(resolve, reject) {
      geocoder.geocode({'placeId': placeId}, function(results, status) {
         if (status === 'OK') {
            var r = Object.create(null);
            r[placeId] = results[0].formatted_address
            resolve(r);
         } else {
            reject('Geocode was not successful for the following reason: ' + status);
         }
      });
  });
}

function prepareMapLink(result) {
  var arrWp = [];
  result.geocoded_waypoints.forEach(function (wp) {
      arrWp.push(wp.place_id);
  });

  var oplaceId = arrWp.shift();
  var dplaceId = arrWp.pop();

  var arrProm = [];
  arrWp.forEach( function (pId) {
    if (!hashPlaces[pId]) {
      arrProm.push(geocodePlaceId(pId));
    }
  });

  if (arrProm.length) {
      Promise.all(arrProm).then( function (values) {
          values.forEach(function (val) {
             for (key in val) {
                hashPlaces[key] = val[key];
             }
          });
          constructMapsUrl(oplaceId, dplaceId, arrWp);
      }).catch(reason => {
          console.log(reason)
      });
  } else {
      constructMapsUrl(oplaceId, dplaceId, arrWp);
  }

}

function constructMapsUrl(originId, destinationId, waypoints) {
    var res = "https://www.google.com/maps/dir/?api=1&";
    res += "origin="+encodeURIComponent(origin)+"&origin_place_id="+originId;
    res += "&destination="+encodeURIComponent(destin)+"&destination_place_id="+destinationId;

    var wpAddr = [];
    waypoints.forEach( function (wp) {
        wpAddr.push(hashPlaces[wp]);
    });

    var waypointsStr = encodeURIComponent(wpAddr.join('|'));
    var waypointsIds = waypoints.join('|');

    res += "&waypoints="+waypointsStr+"&waypoint_place_ids="+waypointsIds+"&travelmode=driving";

    var aElem = document.getElementById("mapLink");
    aElem.setAttribute("href", res);
}
#right-panel {
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select, #right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
  float: left;
  width: 63%;
  height: 100%;
}
#right-panel {
  float: right;
  width: 34%;
  height: 100%;
}
.panel {
  height: 100%;
  overflow: auto;
}

Total Distance:

Open in Google Maps

You can find this example on jsbin as well: http://jsbin.com/sazelo/edit?html,output
I hope this helps!


text:
Q: Is it possible to use RDF schema to define a specific Schema.org 'audience' with Microdata? I have been heavily using Microdata in my real-estate website trying to guide search engines on how to consume my website. I am trying to understand Schema.org's Audience type and see if I can use it to help to target a specific audience.
Here are examples of the audience that I would want to attract to my website:

*

*Investors from Asia that are looking to buy a home in New York

*People from New York that are looking to buy a home

*Homeowners that are looking to sell their home

How can I specify this type of audience using the Audience schema? I am thinking I would somehow need to use RDF schema to define such a thing. But if that is the case, how?

A: You can use the properties audienceType and geographicArea of Schema.org to represent your needs. audienceType is plain text, so you can add whatever you want, although it's better to have short descriptions such as "investor".
For example, with your three points I created the following snippet in JSON-LD:
{
  "@context":"http://schema.org",
  "@type":"CreativeWork",
  "audience":[
    {
      "@type":"Audience",
      "audienceType":"People that are looking to buy a home",
      "geographicArea":{
        "@type":"AdministrativeArea",
        "name":"New York"
      }
    },
    {
      "@type":"Audience",
      "audienceType":"Investors",
      "geographicArea":{
        "@type":"AdministrativeArea",
        "name":"New York"
      }
    },
    {
      "@type":"Audience",
      "audienceType":"Homeowners",
      "geographicArea":{
        "@type":"AdministrativeArea",
        "name":"New York"
      }
    }
  ]
}

It's not Microdata, but you can insert it in your main page by doing:
<script type="application/ld+json">{"@context":"http://schema.org","@type":"CreativeWork","audience":[{"@type":"Audience","audienceType":"People that are looking to buy a home", "geographicArea":{"@type":"AdministrativeArea","name":"New York"}},{"@type":"Audience","audienceType":"Investors", "geographicArea":{"@type":"AdministrativeArea","name":"New York"}},{"@type":"Audience","audienceType":"Homeowners", "geographicArea":{"@type":"AdministrativeArea","name":"New York"}}]}</script>

And it should be ready to go.


text:
Q: Python Scrapy Extract Value of aria-label I'm new to Scrapy and I'm trying to scrape a page that has an aria-label on a class:
<body>
  <div class="item-price" aria-label="$1.99">
    .....
  </div>
</body>

I'm trying to extract the label with the following parse on my spider:
def parse(self, response):
   price = circular_item.css("div.item-price > aria-label::text").extract()
   yield price

When I run the spider I get the following error:
2018-09-02 18:34:03 [scrapy.core.scraper] ERROR: Spider must return Request, BaseItem, dict or None, got 'list' in <GET https://example.com/test.html>

How do I extract the value of aria-label here?

A: You have several errors in your code:
def parse(self, response):
   item = {}
   item["price"] = response.xpath('//div[@class="item-price"]/@aria-label').extract_first()
   yield item

A: If you want to use a css extractor instead of xpath:
def parse(self, response):
    item = {response.css('div.item-price::attr(aria-label)').extract_first()}
    yield item


text:
Q: What issues might I have in opening .NET 2.0 Projects in Visual Studio 2010? The small software team I work on recently got approved to upgrade to Visual Studio 2010 (we're currently using VS 2005).  We have several ASP.NET 2.0 and WinForms (in .NET 2.0) projects in production.
I've been tasked with downloading VS 2010 and seeing how well it plays with our current projects.  What issues should I be aware of when targeting older applications in VS 2010?  If I open a VS 2005 project in VS 2010, will it still place nicely when my teammate goes back to open the project in VS 2005?  Will we have to upgrade projects to work in VS 2010 (assuming the projects themselves aren't upgraded to .NET 4)?  Can I use VS 2010 to edit legacy VB6 apps (just kidding)?
I'm excited to work with the newest software, but we're concerned about running into development snags on production applications that are already working just fine.
NOTE: I started a bounty in hopes of getting a more detailed answer to this question.  Perhaps the answer really is as simple as those already provided, but I'm interested in more feedback regarding our options to transition from using VS 2005 to VS 2010.

A: You will certainly have to "upgrade" your project and solution files. This makes it difficult to have a mixed team on VS2k5 and VS2k10. The solution file and project files can no longer be opened in previous versions of visual studio after they've been upgraded.
You can get around this by having two copies of each of your solution and project files, but this is clumsy as obviously changes made to one will need to be copied manually to the other.
In addition, it seems that you won't be able to use any pre-.NET 4.0 nit test projects with VS2010. If you use MSTest to test pre-4.0 applications, that's an argument against moving to VS2k10 at all. You'd need to port your app to 4.0, or port your tests to e.g. NUnit.
There were some bugs in Beta 1 regarding the layout of the solution explorer. All of the ones listed on Connect are "fixed", but it's worth being aware that the upgrade wizard might make mistakes that you'll have to fix manually. Assuming your whole team is migrating to vs2k10 that kind of issue isn't a big deal as it's pretty obvious if something goes wrong, pretty easy to fix, and only happens once.

A: Our company never had any problems moving our ASP.NET projects from 2005 to 2008 and so I wouldn't foresee any particular problems (though we haven't moved to 2010 yet, so bare this in mind). Most people I know have had the same experience. As others have mentioned, there is an automatic upgrade wizard that take care of upgrades for you, and it's always worked flawlessly for all projects I've upgraded . However, you won't be able to open the newly upgraded solution file in previous versions of Visual Studio (so back these up first if you want to retain them - though it may be possible to hack the .sln files to go back if really necessary).
You can, however, have multiple versions of Visual Studio installed at once (but remember that only one version can have default file extensions associated with it and this will likely be latest version you install). Incidentally, if you are interested in why you can't open older solutions in new version without conversion, then read this official VS Blog entry.
Remember, though, that Visual Studio 2010 allows you to target any previous version of the .NET Framework. So, if for some reason you wish your projects to stay at .NET 2.0 you can do so. However, in reality there is no real advantage I can see in this. Personally I think you just need to bite the bullet and upgrade everything - it's not really practical for people to use different versions for the same solutions.

A: You will have to upgrade the project.
That will change the solution file so this solution can only be opened on VS2010 after upgrading.
Other than that I wouldn't expect any problems.

A: Besides what was mentioned, take a look at .NET Framework 4 Migration Issues.

A: When you convert a project from VS 2005 to 2008, or from VS 2008 to 2010, both the solution file and the project files are modified.  But while the solution file can't then be opened with the earlier version anymore, the project files can.
Therefore, the best way to upgrade is:

*

*Navigate in the file system to your original solution (Original.sln).

*Make a copy of that solution file.

*Rename the copy so you know it's VS 2008 (e.g. OriginalVs2008.sln).

*Now do the upgrade process in VS 2010.

When the upgrade is finished, you'll be able to open your solution in VS 2010 (using Original.sln) or in VS 2008 (using OriginalVs2008.sln).
Just remember that you need to keep the solutions in sync; if you add a project to one, you'll need to add it to the other.  But I've used this technique to share projects between VS 2005 and VS 2008, and it works fine.  I've confirmed that a project created in VS 2008, then converted to VS 2010, still works in VS 2008 with a compatible solution file.

A: We are migrating our 2005 solutions to 2010, we opened the solutions and after finishing the upgraded wizard and then changed the .Net version to 4.0, when we say build, it starts throwing 100s of errors:
1. 1st Error:
An assembly with the same identity 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' has already been imported.
Solution: open your csproj file in notepad and find in the
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> and
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
 add <NoStdLib>true</NoStdLib> and
 then find Reference Tag and add <Reference Include="mscorlib" />.

2. The 2nd error:
Unable to delete file "bin\Debug\<>". Access to the path '<>' is denied.
which is not solved ... we have tried solutions present in the http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/40ed753e-47af-4638-8a72-1d607102a05c but still issue is not solved, we have to close VS 2010 then delete the files manually and then say build in the project, if we say clean or rebuild then it will give the same above error.
3. 3rd Error is:
When we executed the migration wizard in 2010 after that we saw that all the project references (not the dll references) are gone, so we have to open all the projects and again have to add the project reference for all the projects which is the most tedious work.

A: It will modify the project file and therefore in can't be opened anymore in older versions of Visual Studio without editing that file (or make sure you've copies for each VS version).

A: I moved a solution from 2005 to 2010 a couple of days ago. No issues at all, although it was a solution with a large number of small, simple, test projects. You wont be able to open the solution in 2005 though once you've done the conversion.


text:
Q: Can't start CentOS 7 "network" service I Can't start CentOS 7 "network" service after disabling and removing "NetworkManager" service.
When I check the network service status, it comes up with the following error:
#systemctl status network.service
network.service - LSB: Bring up/down networking
   Loaded: loaded (/etc/rc.d/init.d/network)
   Active: failed (Result: exit-code) since Fri 2015-01-16 22:30:46 GMT; 38s ago
  Process: 4857 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=1/FAILURE)

Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain network[4857]: RTNETLINK answers: File exists
Jan 16 22:30:46 localhost.localdomain systemd[1]: network.service: control process exited, code=exited status=1
Jan 16 22:30:46 localhost.localdomain systemd[1]: Failed to start LSB: Bring up/down networking.
Jan 16 22:30:46 localhost.localdomain systemd[1]: Unit network.service entered failed state.

In earlier CenOS it didn't seem to give any problems when switching from the "NetworkManager" service to the network service.
Any ideas as to what causes the problem and how to fix it?

Note: I used yum erase to remove network manage service.

Here is additional info as asked:
/etc/sysconfig/network-script/ifcfg-enp8s0
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
NAME=enp8s0
UUID=453a07fe-1b07-4f29-bc32-f2168e50706a
ONBOOT=yes
HWADDR=XXXXXXXXXXX
MACADDR=XXXXXXXXXX
PEERDNS=yes
PEERROUTES=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes

/etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

/etc/resolv.conf
; generated by /usr/sbin/dhclient-script
search customer.marples.midcity.lan
nameserver 10.241.128.1

A: An IP conflict will also cause this error.  Try: systemctl stop network, then ifup eth0.

A: In Centos7.0 disabling NetworkManager will leave a dhcp client running configured for NetworkManager. This causes the error message RTNETLINK answers: File exists when the network service is started.
The stale dhclient process has the additional "benefit" that when the lease expires your dhclient will choke, since it cannot reach NetWorkManager, thus removing your IP address.
If you grep for it, you will see that it points to a NetWorkManager configuration file.
[root@host ~]# ps -ef | grep dhc
root      1865   792  0 Apr28 ?        00:00:00 /sbin/dhclient -d -sf \
 /usr/libexec/nm-dhcp-helper -pf /var/run/dhclient-eno1.pid -lf\
 /var/lib/NetworkManager/dhclient-c96e56d3-a4c9-4a87-85ca-93dc0ca268f2-eno1.lease\
 -cf /var/lib/NetworkManager/dhclient-eno1.conf eno1

So what you can do is kill the dhclient and only then start your network service.

A: I too faced this today on a CentOS 7.2 cloned virtual machine. This is how I fixed  it.
systemctl disable NetworkManager
systemctl enable network

Find MAC address of the interface through command /sbin/ifconfig -a and append that in /etc/sysconfig/network-scripts/ifcfg-<interface_name>. You can use the below commands for the first interface.
nic_file=`ls /etc/sysconfig/network-scripts/ifcfg-e*`
ifconfig -a | grep ether | awk '{ print $2 }' | sed 's/.*/HWADDR=&/' >> ${nic_file}

Then fire reboot to restart the server

A: as it has been already identified - this error pops up with any issue while setting up network: IP conflict, routing issues, etc.
Look at your gateway settings to confirm your gateways are set properly and things are what they need to be with /etc/syscofig/network and each of the /etc/sysconfig/network-scripts/ifcfg-* look for duplicate IP, routes set via /etc/sysconfig/network-scripts/route-* if memory serves me right gateways now can be set in both ifcfg-* and route-* files. So confirm there's no duplication or overlap.

A: It seems this happens also if you manually configure an interface that isn't connected to the network.

A: A failure to get an IP from DNS will also give this error as I have just found. In fact it looks like any error with networking will cause this error. This appears to be a problem with CentOS 7 in that it gives a very poor error here.

A: Look into network-scripts whether there is no other interface that could crash network.service
do an ifconfig and write down the interface. Compare with the files in network-scripts. If there are more files in network-scripts than interfaces in ifconfig, you can delete the additional useless files and then do a systemctl restart network.

A: Had this error after cloning a virtual server, the clone was given a new hardware address ( MAC ) and the network adapter config still had the old one.
The line looks like: HWADDR=00:00:00:00:00:00

A: I ran into this issue, where the server keep giving me RTNETLINK answers: File exists even after removing network manager and triple check all my network configuration.
It appears that an IP was up on another server and that the server filter ICMP (so no ping), first things I tried. So don't rely on ping for testing if an IP is up or not !
When starting, the network script issue this command (change your dev and ip)
/sbin/arping -c 2 -w 3 -D -I eth0 10.196.132.206

Which tell us that a mac address is associated with this IP and fail the network script (ifup or systemctl start network)

A: I also encountered similar problems.
To modify the configuration files.(ifcfg-ensxxxx), as follows
enter image description here

*

*List Commented out "UUID=xxxx-xxxx"

*Add new option: NM_CONTROLLED=no, it indicates that this interface will be set up using this configuration file, instead of being managed by Network Manager service.

Reference: How to configure a static IP address on CentOS 7

A: I also encountered similar problems. To modify the configuration files.(ifcfg-ensxxxx), as follows:
Add new option: NM_CONTROLLED=no, it indicates that this interface will be set up using this configuration file, instead of being managed by Network Manager service.


text:
Q: Woocommerce 3.1 Add product image to order confirmation email not working I'm using the following code in my theme functions.php to add product images in order email. But the image is not showing in the email. Did I miss anything? I'm using WooCommerce 3.1
function sww_add_images_woocommerce_emails( $output, $order ) {

    // set a flag so we don't recursively call this filter
    static $run = 0;

    // if we've already run this filter, bail out
    if ( $run ) {
        return $output;
    }

    $args = array(
        'show_sku'      => false,
        'show_image'    => true,
        'image_size'    => array( 100, 100 ),
    );

    // increment our flag so we don't run again
    $run++;

    // if first run, give WooComm our updated table
    return $order->email_order_items_table( $args );
}
add_filter( 'woocommerce_email_order_items_table', 'sww_add_images_woocommerce_emails', 10, 2 );

A: Try this code in functions.php inside your theme folder.
add_filter( 'woocommerce_email_order_items_args', 'iconic_email_order_items_args', 10, 1 );

function iconic_email_order_items_args( $args ) {

    $args['show_image'] = true;

    return $args;

}


text:
Q: Speaker adaptation with HTK I am trying to adapt a monophone-based recogniser to a specific speaker. I am using the recipe given in HTKBook 3.4.1 section 3.6.2. I am getting stuck on the HHEd part which I am invoking like sp:
HHEd -A -D -T 1 -H hmm15/hmmdefs -H hmm15/macros -M classes regtree.hed monophones1eng
The error I end up with is as follows:
ERROR [+999]  Components missing from Base Class list (2413 3375)
  ERROR [+999]  BaseClass check failed
The folder classes contains the file global which has the following contents:
~b ''global''
<MMFIDMASK> *
<PARAMETERS> MIXBASE
<NUMCLASSES> 1
  <CLASS> 1 {*.state[2-4].mix[1-25]}
The hmmdefs file within hmm15 had some mixture components (I am using 25 mixture components per state of each phone) missing. I tried to "fill in the blanks" by giving in mixture components with random mean and variance values but zero weigths. This too has had no effect.
The hmms are left-right hmms with 5 states (3 emitting), each state modelled by a 25 component mixture. Each component in turn is modelled by an MFCC with EDA components. There are 46 phones in all.
My questions are:
1. Is the way I am invoking HHEd correct? Can it be invoked in the above manner for monophones?
2. I know that the base class list (rtree.base must contain every single mixture component, but where do I find these missing mixture components?
NOTE: Please let me know in case more information is needed.
Edit 1: The file regtree.hed contains the following:
RN "models"
LS "stats_engOnly_3_4"
RC 32 "rtree"

Thanks,
Sriram

A: They way you invoke HHEd looks fine. The components are missing as they have become defunct. To deal with defunct components read HTKBook-3.4.1 Section 8.4 page 137.
Questions:
- What does regtree.hed contain?
- How much data (in hours) are you using? 25 mixtures might be excessive.
You might want to use a more gradual increase in mixtures - MU +1 or MU +2 and limit the number of mixtures (a guess: 3-8 depending on training data amount).


text:
Q: Something I'm misunderstanding about rand() % i? int main() {
const int n = 5;
int A[n][n]; // value of each cell
int V[n][n]; // total value of each cell

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        V[i][j] = 0; // initialize total value of each cell equal to zero
        A[i][j] = rand() % 10; // set each cell's value equal to some number 0-9
        printf("%i ", A[i][j]);
    }
    printf("\n");
}

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        if (i == 0 && j == 0)
        {
            V[i][j] = A[i][j];
        }
        else if (i == 0)
        {
            V[i][j] = V[i][j - 1] + A[i][j];
        }
        else if (j == 0)
        {
            V[i][j] = V[i - 1][j] + A[i][j];
        }
        else
        {
            if (V[i][j - 1] > V[i - 1][j])
            {
                V[i][j] = V[i][j - 1] + A[i][j];
            }
            else
            {
                V[i][j] = V[i - 1][j] + A[i][j];
            }
        }
    }
}
printf("\n");
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        if (V[i][j] < 10) printf(" %i ", V[i][j]);
        else printf("%i ", V[i][j]);
    }
    printf("\n");
}

cin.get();

}
This outputs http://i.imgur.com/Ak3KpPr.png
What I don't understand is why V[0][2] outputs 12 when it should output V[0][1] + A[0][2], or 7+4.
Context:
At a garage sale one day, you stumble upon an old school video game. In this video game, your
character must take a journey along an n × n grid, collecting rewards along the way. Specifically,
there is an n × n matrix A with nonnegative entries, and your character collects a reward equal to
Aij if he visits the cell (i, j) of the grid. Your objective is to maximize the sum of rewards collected
by your character.
(a) [4 points]. The rules of level one of the game are as follows. Your character starts at the
top-left corner — i.e., cell (1, 1) — of the grid, and must travel to the the bottom-right corner —
i.e., cell (n, n) — in sequence of steps. At each step, your character is allowed to move either one
cell to the right or one cell down in the grid; stepping upwards, to the left, or diagonally is not
2
allowed. Show how to compute the optimal journey in O(n
2
) time.

A: Where did you get that idea about 7+4?
Your code clearly says that V[0][2] is V[0][1] + A[2][2]. But on previous iteration of your cycle V[0][1] was set to V[0][0] + A[0][1]. And on yet previous iteration of your cycle V[0][0] was set to A[0][0].
So, V[0][0] is 1. Which makes V[0][1] = 1 + 7 = 8. Which makes V[0][2] = 8 + 4 = 12.
Everything is as you implemented it.


text:
Q: Swift 4 Codable Array's So I have an API route that returns a JSON array of objects. For example:
[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]

I'm trying to envision how to use the new codable feature in Swift for to convert those into two objects in a class. So if I have a person class that is codable I would want to take that response and have it give me two person objects.
I'm also using Alamofire to handle the requests.
How can I do this? So far everything I've seen related to the codable stuff only allows 1 object. And I haven't seen any integration with Alamofire or a web framework.

A: Update regarding Alamofire 5: responseJSONDecodable.
struct Person: Codable {
    let firstName, lastName: String
    let age: Int

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
    }
}

Alamofire.request(request).responseJSONDecodable { (response: DataResponse<Person>) in
    print(response)
}

Alamofire 4 won't add Codable support for now (see #2177), you can use this extension instead: https://github.com/Otbivnoe/CodableAlamofire.
let jsonData = """
[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]
""".data(using: .utf8)!

struct Person: Codable {
    let firstName, lastName: String
    let age: Int

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
    }
}

let decoded = try! JSONDecoder().decode([Person].self, from: jsonData)

Sample: http://swift.sandbox.bluemix.net/#/repl/59a4b4fad129044611590820
Using CodableAlamofire:
let decoder = JSONDecoder()
Alamofire.request(url).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<[Person]>) in
    let persons = response.result.value
    print(persons)
}

keypath corresponds to the path where the results are contained in the JSON structure. E.g:
{
    "result": {
        "persons": [
            {"firstname": "Tom", "lastname": "Smith", "age": 31},
            {"firstname": "Bob", "lastname": "Smith", "age": 28}
        ]
    }
}

keypath => results.persons
[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]

keypath => nil (empty keypath throws an exception)

A: I managed to serialize data response to codable objects.
As all you may have been familiar with converting json object [String: String] for example. That json object need to be converted to Data by using json.data(using: .utf8)!.
With Alamofire, it is easy to get that data (or at least this kind of data worked for me, already compatible with .utf8 thing), I can just use this already available function
func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self

Then just use that data as input for the Decoder in the completionHandler
let objek = try JSONDecoder().decode(T.self, from: data)

You can also make this to some generic serialization function, with a little tweak, from the documentation
Generic Response Object Serialization
to this modification
func responseCodable<T: Codable>(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<T>) -> Void)
    -> Self
{
    let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
        guard error == nil else { return .failure(BackendError.network(error: error!)) }

        guard let data = data else {
            return .failure(BackendError.objectSerialization(reason: "data is not valid"))
        }

        do{
            let objek = try JSONDecoder().decode(T.self, from: data!)
            return .success(objek)
        } catch let e {
            return .failure(BackendError.codableSerialization(error: e))
        }

    }

    return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}

Sample struct
struct Fids: Codable {

   var Status: Status?
   var Airport: Airport?
   var Record: [FidsRecord]
}

Use the function this way
    Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse<Fids>) in
        switch response.result{
        case .success(let value):
            print(value.Airport)
        // MARK: do whatever you want
        case .failure(let error):
            print(error)
            self.showToast(message: error.localizedDescription)
        }
    }

A: to decode to array, you've your response in a type alias for clarity:
typealias ServiceResponseObject = [ResponseObject]
but then you'll have to confirm Array to codable:
extension Array: Decodable where Element: Decodable {}
that should make it all work.

A: Swift 5 Using Codable

Alamofire Generic Response

PersonModel.swift
(create with SwiftyJsonAccelerator)
import Foundation

class PersonModel: Codable {

  enum CodingKeys: String, CodingKey {
    case age
    case firstname
    case lastname   }

  var age: Int?   var firstname: String?   var lastname: String?

  init (age: Int?, firstname: String?, lastname: String?) {
    self.age = age
    self.firstname = firstname
    self.lastname = lastname   }

  required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    age = try container.decodeIfPresent(Int.self, forKey: .age)
    firstname = try container.decodeIfPresent(String.self, forKey: .firstname)
    lastname = try container.decodeIfPresent(String.self, forKey: .lastname)   }

}

Generic Get Response
func genericGET<T: Decodable>(urlString: String, completion: @escaping (T?) -> ()) {

Alamofire.request(urlString)
    .responseJSON { response in
        // check for errors
        switch response.result {
        case .success(_):

            do {
                let obj = try JSONDecoder().decode(T.self, from: response.data!)
                completion(obj)
            } catch let jsonErr {
                print("Failed to decode json:", jsonErr)
            }

            break
        case .failure(_):

            completion(nil)

            break
        }
}

}

Call this method
genericGET(urlString: "YOUR_URL") { (persons: [PersonModel]?) in
    print(persons?[0].firstname)
}


text:
Q: List of data file formats supported in QGIS including read/write support Is there a list of data file formats supported in QGIS, including information about read/write support? What I'm looking for is something like:

*

*Geopackage: r/w

*Esri Shapefile: r/w

*CSV: r

*KML: r

*etc.

The documentation has a section "Exploring Data Formats and Fields".
However, there is no simple overview over read/write support and you have to read through a lot of text that does not always mention explicitly which of the formats are editable.
In fact, the vector layer export dialog offers a list of file formats to which you can save, but a) this includes only writable formats (not readable as well) and b) it is not available outside of QGIS as a comprehensive list.

A: QGIS has some own data providers but you can check the capabilities of the OGR formats with ogrinfo.
ogrinfo --formats
Supported Formats:
  BAG -raster,multidimensional raster,vector- (rw+v): Bathymetry Attributed Grid
  JP2ECW -raster,vector- (rov): ERDAS JPEG2000 (SDK 5.5)
  FITS -raster,vector- (rw+): Flexible Image Transport System
  netCDF -raster,vector- (rw+s): Network Common Data Format
  PDF -raster,vector- (rw+vs): Geospatial PDF
  AmigoCloud -vector- (rw+): AmigoCloud
  PCIDSK -raster,vector- (rw+v): PCIDSK Database File
  PDS4 -raster,vector- (rw+vs): NASA Planetary Data System 4
  VICAR -raster,vector- (rw+v): MIPL VICAR file
  JP2OpenJPEG -raster,vector- (rwv): JPEG-2000 driver based on OpenJPEG library
  MBTiles -raster,vector- (rw+v): MBTiles
  EEDA -vector- (ro): Earth Engine Data API
  OGCAPI -raster,vector- (rov): OGCAPI
  DB2ODBC -raster,vector- (rw+): IBM DB2 Spatial Database
  ESRI Shapefile -vector- (rw+v): ESRI Shapefile
  MapInfo File -vector- (rw+v): MapInfo File
  UK .NTF -vector- (rov): UK .NTF
  LVBAG -vector- (rov): Kadaster LV BAG Extract 2.0
  OGR_SDTS -vector- (rov): SDTS
  S57 -vector- (rw+v): IHO S-57 (ENC)
  DGN -vector- (rw+v): Microstation DGN
  OGR_VRT -vector- (rov): VRT - Virtual Datasource
  REC -vector- (ro): EPIInfo .REC
  Memory -vector- (rw+): Memory
  BNA -vector- (rw+v): Atlas BNA
  CSV -vector- (rw+v): Comma Separated Value (.csv)
  NAS -vector- (rov): NAS - ALKIS
  GML -vector- (rw+v): Geography Markup Language (GML)
  GPX -vector- (rw+v): GPX
  LIBKML -vector- (rw+v): Keyhole Markup Language (LIBKML)
  KML -vector- (rw+v): Keyhole Markup Language (KML)
  GeoJSON -vector- (rw+v): GeoJSON
  GeoJSONSeq -vector- (rw+v): GeoJSON Sequence
  ESRIJSON -vector- (rov): ESRIJSON
  TopoJSON -vector- (rov): TopoJSON
  Interlis 1 -vector- (rw+v): Interlis 1
  Interlis 2 -vector- (rw+v): Interlis 2
  OGR_GMT -vector- (rw+v): GMT ASCII Vectors (.gmt)
  GPKG -raster,vector- (rw+vs): GeoPackage
  SQLite -vector- (rw+v): SQLite / Spatialite
  ODBC -vector- (rw+): ODBC
  WAsP -vector- (rw+v): WAsP .map format
  PGeo -vector- (ro): ESRI Personal GeoDatabase
  MSSQLSpatial -vector- (rw+): Microsoft SQL Server Spatial Database
  OGR_OGDI -vector- (ro): OGDI Vectors (VPF, VMAP, DCW)
  PostgreSQL -vector- (rw+): PostgreSQL/PostGIS
  MySQL -vector- (rw+): MySQL
  OpenFileGDB -vector- (rov): ESRI FileGDB
  XPlane -vector- (rov): X-Plane/Flightgear aeronautical data
  DXF -vector- (rw+v): AutoCAD DXF
  CAD -raster,vector- (rovs): AutoCAD Driver
  FlatGeobuf -vector- (rw+v): FlatGeobuf
  Geoconcept -vector- (rw+v): Geoconcept
  GeoRSS -vector- (rw+v): GeoRSS
  GPSTrackMaker -vector- (rw+v): GPSTrackMaker
  VFK -vector- (ro): Czech Cadastral Exchange Data Format
  PGDUMP -vector- (w+v): PostgreSQL SQL dump
  OSM -vector- (rov): OpenStreetMap XML and PBF
  GPSBabel -vector- (rw+): GPSBabel
  SUA -vector- (rov): Tim Newport-Peace's Special Use Airspace Format
  OpenAir -vector- (rov): OpenAir
  OGR_PDS -vector- (rov): Planetary Data Systems TABLE
  WFS -vector- (rov): OGC WFS (Web Feature Service)
  OAPIF -vector- (ro): OGC API - Features
  HTF -vector- (rov): Hydrographic Transfer Vector
  AeronavFAA -vector- (rov): Aeronav FAA
  Geomedia -vector- (ro): Geomedia .mdb
  EDIGEO -vector- (rov): French EDIGEO exchange format
  SVG -vector- (rov): Scalable Vector Graphics
  CouchDB -vector- (rw+): CouchDB / GeoCouch
  Cloudant -vector- (rw+): Cloudant / CouchDB
  Idrisi -vector- (rov): Idrisi Vector (.vct)
  ARCGEN -vector- (rov): Arc/Info Generate
  SEGUKOOA -vector- (rov): SEG-P1 / UKOOA P1/90
  SEGY -vector- (rov): SEG-Y
  ODS -vector- (rw+v): Open Document/ LibreOffice / OpenOffice Spreadsheet
  XLSX -vector- (rw+v): MS Office Open XML spreadsheet
  Elasticsearch -vector- (rw+): Elastic Search
  Walk -vector- (ro): Walk
  Carto -vector- (rw+): Carto
  SXF -vector- (rov): Storage and eXchange Format
  Selafin -vector- (rw+v): Selafin
  JML -vector- (rw+v): OpenJUMP JML
  PLSCENES -raster,vector- (ro): Planet Labs Scenes API
  CSW -vector- (ro): OGC CSW (Catalog  Service for the Web)
  VDV -vector- (rw+v): VDV-451/VDV-452/INTREST Data Format
  GMLAS -vector- (rwv): Geography Markup Language (GML) driven by application schemas
  MVT -vector- (rw+v): Mapbox Vector Tiles
  NGW -raster,vector- (rw+s): NextGIS Web
  MapML -vector- (rw+v): MapML
  TIGER -vector- (rw+v): U.S. Census TIGER/Line
  AVCBin -vector- (rov): Arc/Info Binary Coverage
  AVCE00 -vector- (rov): Arc/Info E00 (ASCII) Coverage
  HTTP -raster,vector- (ro): HTTP Fetching Wrapper


text:
Q: react-native-image-crop-picker cropping frame height fixed after a limit I am using react-native-image-crop-picker in my react naive android project to crop images. After setting freeStyleCropEnabled = true in my app I am able to do freestyle cropping but after a certain limit, I am not able to reduce the height of the frame to be cropped. Any solution regarding this?

A: You can only do free style cropping by setting freeStyleCropEnabled = true by using
react-native-image-crop-picker library for a certain extent. for more free style cropping use react-native-image-crop-tools library.

A: "freeStyleCropEnabled" is allowed for only Android.
You can use cropperToolbarTitle: 'Move and Scale' for the IOS.


text:
Q: Differences in browser scope treatment of chrome/firefox This alerts x in chrome, but not on firefox (Chrome 25.0/FF 11.0):
var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert(x)"); // Doesn't work on FF, but works on Chrome
document.body.appendChild(b);

It works on both when I use DOM (b.onclick, like the code below), but returns a "x not defined" error when using the attribute in string form, like in the code above.
var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.onclick = function(){alert(x)}; // Works on FF/Chrome
document.body.appendChild(b);

What are the differences between the two browsers that cause this?

A: This should work in FF and Chrome, but not in IE, you need to actually pass the variable ?
var x="hi.", b;
(b = document.createElement("button")).innerHTML = "click me";
b.setAttribute("onclick", "alert('"+x+"')");
document.body.appendChild(b);

In (older versions of) IE you can't set inline javascript with setAttribute as far as I know.
FIDDLE (tested in FF 19 and newest Chrome)


text:
Q: How to use datasources in Intellij IDEA Hello just starting to learn JAVA and I am trying to create a web application. So far I have managed to get the Tomcat server working and connect my Intellij IDE to my SQL sever instance creating a datasource.
My question is how to properly access this datasource in code. I want o create a method that gets the Connection object from the datasource. However I am at loss when it comes how to do it.
My basic idea is to create a class containing the Connection GetConncetion() method, that returns the connection object, this should be achieved by calling the Datasource.getConnection(), but how do I make the datasource in question the one that is created by my IDE (Intellij IDEA)? I have located the DataSources.local.xml with the datasource name so I would like use this information to access it, however I dont know how to do it.
I have quite a clear idea how to do this using DriverManager, however I would like to learn how to use this more convinient datasource method.
The database in question is created using Microsft SQL server and the driver used is jdbc.

A: IDEA is just an IDE. Your application shouldn't be IDE or editor dependent, and IDEA therefore doesn't give you such facilities (and Java doesn't depend on them). Instead, have a look at the Properties class which provides pretty much what you want.


text:
Q: customize length of lines vivagraph.js How I can customize length of lines [links] in vivagraph.js
there is a code like
graphics.link(function(link){
                return Viva.Graph.svg('path')
                           **.attr('length', 5);**

                           ...

A: I think length of the link is resulted from the layout of the graph. As far as I know you can set the layout using constant layout and calculating the node positions by yourself as shown here or set a global ideal link length (springLength) which is used while calculating the force directed layout as shown below.
var layout = Viva.Graph.Layout.forceDirected(graph, {
    springLength : 10
});

A: See this example for custom lengths per link:
https://github.com/anvaka/VivaGraphJS/blob/master/demos/other/customLinkLength.html
I'll include excerpts -- It consists of adding custom data to each link,
graph.addLink(5, 6, { connectionStrength: 0.1 });

And then using that custom data to calculate the spring length using springTransform:
var idealLength = 90;
var layout = Viva.Graph.Layout.forceDirected(graph, {
               springLength: idealLength,
               springCoeff : 0.0008,
               gravity : -10,
               // This is the main part of this example. We are telling force directed
               // layout, that we want to change length of each physical spring
               // by overriding `springTransform` method:
               springTransform: function (link, spring) {
                    spring.length = idealLength * (1 - link.data.connectionStrength);
               }
});


text:
Q: Increase network traffic between worker nodes through apache spark's shuffle process I am trying to write a (wordcount) program to simulate a use case where the network traffic would be very high because of spark's shuffle process. I have a 3 node apache spark cluster (2 cores each, 8GB RAM each) configured with 1 master and 2 workers. I processed a 5GB file for wordcount and was able to see a network traffic between 2 worker nodes raise up to 1GB in 10-15 mins. I am looking for a way where i could increase the traffic between nodes raise up to atleast 1GB within 30s-60s. The inefficiency of the program or best practices doesn't matter in my current use case as I am just trying to simulate traffic.
This is the program i have written
val sc = new SparkContext(new SparkConf().setAppName("LetterCount-GroupBy-Map"))
val x = sc.textFile(args(0)).flatMap(t => t.split(" "))
val y = x.map(w => (w.charAt(0),w))
val z = y.groupByKey().mapValues(n => n.size)
z.collect().foreach(println)

A: More shuffled data can be generated by doing operations which do not combine data very well on each node. For eg: In the code you have written, the groupby will combine the common keys ( or do groupby locally). Instead choose a high cardinality of keys (in above example its 26 only). In addition, the size of values after the map operation can be increased. In your case, its the text line. You might want to put a very long string of values for each key.
Apart from this, if you take 2 different files/tables and apply join on some parameter, it will also cause shuffling.
Note: Am assuming the contents does not matter. You are only interested in generating highly shuffled data.


text:
Q: Creating sql scripts to create table inside postgres I am trying to create a postgres container which executes .sql script while launching up. The CREATE TABLE script is working if only column names are provided. However When I add CONSTRAINT in the script, it doesn't execute in container and tables won't get created.
sql script below:
CREATE TABLE "MY_APP_DB"."ACCESS_MASTER"
(
    "ACCESS_ID" character varying COLLATE pg_catalog."default" NOT NULL,
    "ROLE_ID" character varying COLLATE pg_catalog."default",
    "RESOURCE_ID" character varying COLLATE pg_catalog."default",
    "CAN_ACCESS" character(1) COLLATE pg_catalog."default" NOT NULL DEFAULT 'N'::bpchar,
    "CAN_READ" character(1) COLLATE pg_catalog."default" NOT NULL DEFAULT 'N'::bpchar,
    "CAN_WRITE" character(1) COLLATE pg_catalog."default" NOT NULL DEFAULT 'N'::bpchar,
    "CAN_DELETE" character(1) COLLATE pg_catalog."default" NOT NULL DEFAULT 'N'::bpchar,
    "CAN_EXECUTE" character(1) COLLATE pg_catalog."default" NOT NULL DEFAULT 'N'::bpchar,
    CONSTRAINT "ACCESS_MASTER_pkey" PRIMARY KEY ("ACCESS_ID"),
    CONSTRAINT "FK_RESOURCE" FOREIGN KEY ("RESOURCE_ID")
        REFERENCES "MY_APP_DB"."IMC_RESOURCE_MASTER" ("RESOURCE_ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT "FK_ROLE_MASTER_ACCESS_MASTER" FOREIGN KEY ("ROLE_ID")
        REFERENCES "MY_APP_DB"."ROLE_MASTER" ("ROLE_ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT FK_AM_AM FOREIGN KEY ("ACCESS_ID")
        REFERENCES "MY_APP_DB"."ACCESS_MASTER" ("ACCESS_ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT FK_ROLE_MASTER_ACCESS_MASTER FOREIGN KEY ("ROLE_ID")
        REFERENCES "MY_APP_DB"."ROLE_MASTER" ("ROLE_ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT FK_RM_RES_MAS FOREIGN KEY ("RESOURCE_ID")
        REFERENCES "MY_APP_DB"."IMC_RESOURCE_MASTER" ("RESOURCE_ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

It executes till CAN EXECUTE Column but not after that. Why is this so? What's wrong.? Please help

A: It works unless the references objects are in place, See the dbfiddle might help.


text:
Q: Dynamical system with vanishing perturbation Consider the following system:
$$
\dot{x} = f(x)+h(y),\\
\dot{y} = g(y),
$$
with $x,y\in\mathbb{R}^n$, and where $f$, $g$, and $h$ are globally continuously differentiable.
We know that $y$ is asymptotically stable (i.e., for any $\epsilon>0$ there exists a $\delta>0$ such that, for any $||y(0)||\le\delta$, we have $||y(t)||\le\epsilon$ for all $t\le0$, and $y(t)\to0_n$ for $t\to\infty$).
Can we say that the solutions of $\dot{x}=f(x)+h(y)$ converge to the solutions of $\dot{x}=f(x)+h(0_n)$? Why?

A: I believe this is not the case.
Consider the following (linear) example
$$ \dot x = 3 + y,$$
$$ \dot y = -3 y.$$
All functions are smooth.
However, solving you get that $y(t) = y_0\mathrm{e}^{-3t}$; and for $x$ you get that
$$ \dot x = 3 + y_0\mathrm{e}^{-3t}$$
$$ x(t) = x_0 + 3t + y_0/3 - \mathrm{e}^{-3t}/3$$
whereas, solving $\dot x = 3$ you get
$$ \tilde x(t) = x_0 + 3t$$
and $x(t) - \tilde x(t)$ will not vanish as $t\to \infty$.


text:
Q: How to use RGB codes with the fmt library? I just installed the fmt library and I was wondering if it is possible to use RGB codes instead of color names. For example, instead of,
#include <fmt/color.h>

int main()
{
    std::string cpp = fmt::format(fg(fmt::color::yellow), "C++20");
    fmt::print("{}", cpp);
    return 0;
}

would it be possible to do something like,
#include <fmt/color.h>

int main()
{
    std::string cpp = fmt::format(fg(fmt::color::#FFFF00), "C++20");
    fmt::print("{}", cpp);
    return 0;
}

A: After hours of searching the internet, I stumbled upon the answer using the trial and error approach. In order to use RGB codes instead of color names, replace color::yellow with rgb(0xFF, 0xFF, 0x00) or rgb(255, 255, 0).
#include <fmt/color.h>

int main()
{
    std::string cpp = fmt::format(fg(fmt::rgb(255, 255, 0)), "C++20");
    fmt::print("{}", cpp);
    return 0;
}

EDIT ‒ Thanks to Wyck for the awesome suggestion in the comment.
I just discovered that the following examples also work and are 100% syntactically valid:
#include <fmt/color.h>

int main()
{
    std::string cpp = fmt::format(fg(fmt::rgb(0xFFFF00)), "C++20");
    fmt::print("{}", cpp);
    return 0;
}

and
#include <fmt/color.h>

int main()
{
    std::string cpp = fmt::format(fg(fmt::color(0xFFFF00)), "C++20");
    fmt::print("{}", cpp);
    return 0;
}

All examples in this answer have been tested and are working.


text:
Q: Calculate vacation days between dates I'm trying to get number of days between two dates. There are a number of ways to do it, but I'm not able to find one to suit my purpose to calculate vacation days!
Eg: Cell A2 dates 21/12/2016 and cell B2 dates 30/12/2016.
So the employee is on vacation from Dec 21 to Dec. 30 which is 10 calendar days, but all the formulas I know show it as 9 days.

A: Dates in Excel are simply serial numbers that start on 1/1/1900.
21/12/2016 is 42725
30/12/2016 is 42734.
The difference of the two numbers is 9.
Date difference formulas simply substract the two numbers.
9 is the number of days to get from day 21 to day 30.
One trick is to put in the sheet the returning day instead of the last day of vacation. For your example the returning day is 31/12/2016.


text:
Q: Fixing ulimit: open files: cannot modify limit: Operation not permitted I tested this on different GNU/Linux installations:
perl -e 'while(1){open($a{$b++}, "<" ,"/dev/null") or die $b;print " $b"}'

System A and D
The first limit I hit is 1024. It is easily raised by putting this into /etc/security/limits.conf:
*                hard    nofile          1048576

and then run:
ulimit -n 1048576
echo 99999999 | sudo tee /proc/sys/fs/file-max

Now the test goes to 1048576.
However, it seems I cannot raise it above 1048576. If I put 1048577 in limits.conf it is simply ignored.
What is causing that?
System B
On system B I cannot even get to 1048576:
echo 99999999 | sudo tee /proc/sys/fs/file-max

/etc/security/limits.conf:
*                hard    nofile          1048576

Here I get:
$ ulimit -n 65537
bash: ulimit: open files: cannot modify limit: Operation not permitted
$ ulimit -n 65536
#OK

Where did that limit come from?
System C
This system also has the 1048576 limit in limits.conf and 99999999 in /proc/sys/fs/file-max.
But here the limit is 4096:
$ ulimit -n 4097
-bash: ulimit: open files: cannot modify limit: Operation not permitted
$ ulimit -n 4096
# OK

How do I raise that to (at least) 1048576?
(Note to self: Don't do: echo 18446744073709551616 | sudo tee /proc/sys/fs/file-max)

A: Check that /etc/ssh/sshd_config contains:
UsePAM=yes

and that /etc/pam.d/sshd contains:
session    required   pam_limits.so

In the comment below @venimus states the 1M limit is hardcoded:

The kernel 2.6.x source states ./fs/file.c:30:int sysctl_nr_open __read_mostly = 1024*1024; which is 1048676

The 1048576 is per process. So by having multiple processes this limit can be overcome.


text:
Q: How should I structure my classes and files in python? My code is currently in one big file:
# file 1: ./mainfile.py
class Namespace:
    class This:
        ...
    class That:
        ...

mainFunc(Namespace.This(), Namespace.That())

I would like my code to look something like this:
# file 1: ./namespace/this.py
class This:
    ...

# file 2: ./namespace/that.py
class That:
    ...

# file 3: ./mainfile.py
import ???
mainFunc(Namespace.This(), Namespace.That())

What changes do I have to make so that I can still use exactly the same call to mainFunc()?

A: You need to make a package.  See the documentation.


text:
Q: sudoku solver infinite recursion I am writing a sudoku solver. It has been a long time since I have touched prolog, thus I don't remember everything regarding unification, backtracking, etc. I think that I cause the system to backtrack forever (but I don't get any stack exceptions - at least not immediately). This is what I have so far (the puzzle can be found at http://en.wikipedia.org/wiki/File:Sudoku-by-L2G-20050714.svg):
% representation of the example puzzle
puzzle([5, 3, _, _, 7, _, _, _, _],
       [6, _, _, 1, 9, 5, _, _, _],
       [_, 9, 8, _, _, _, _, 6, _],
       [8, _, _, _, 6, _, _, _, 3],
       [4, _, _, 8, _, 3, _, _, 1],
       [7, _, _, _, 2, _, _, _, 6],
       [_, 6, _, _, _, _, 2, 8, _],
       [_, _, _, 4, 1, 9, _, _, 5],
       [_, _, _, _, 8, _, _, 7, 9]).

% solve(S)
% the starting point of the program
% saves the solution in the variable S
solve(R1, R2, C1) :-
    % save the rows into variables
    puzzle(R1, R2, R3, R4, R5, R6, R7, R8, R9),
    % solve for each row
    allunique(R1), allunique(R2), allunique(R3),
    allunique(R4), allunique(R5), allunique(R6),
    allunique(R7), allunique(R8), allunique(R9),
    % the columns must be created first
    nelement(R1, 1, C11), nelement(R2, 1, C21), nelement(R3, 1, C31),
    nelement(R4, 1, C41), nelement(R5, 1, C51), nelement(R6, 1, C61),
    nelement(R7, 1, C71), nelement(R8, 1, C81), nelement(R9, 1, C91),
    C1 = [C11, C21, C31, C41, C51, C61, C71, C81, C91],
    allunique(C1).

% allunique(List)
% Succeeds if all the numbers of List are between 1-9
% and each number exists only once
allunique([]). % Recursion stops when the list is empty

% A member should be between 1-9 and not a member of the tail
allunique([H|T]) :-
    allunique(T),
    member(H, [1, 2, 3, 4, 5, 6, 7, 8, 9]),
    not(member(H, T)).

% nelement(List, N-th, X)
% Saves the nth element of a list in variable X
nelement([H|_], 1, H). % The first element is the head

% All other elements will be found in the tail
nelement([_|T], N, X) :-
    N > 1,
    N1 is N-1,
    nelement(T, N1, X).

The line allunique(C1) causes the problem. It seems that the system puts a 7 in the first empty box of the 1st column and never changes it (or at least not in the near future). An example C1 list is [5, 6, 7, 8, 4, 7, 9, 8, 6].  I am curious to find out why this is happening.

A: *

*Your example list [5, 6, 7, 8, 4, 7, 9, 8, 6] doesn't satisfy allunique since it contains 8 twice.

*solve/3 is incorrect since it checks all rows, but only one column and no "region" (the 3x3 squares).

*The solve/1 predicate promised in the comments doesn't appear, so I can't test your code; allunique/1 and nelement/3 seem fine.

*Even if you complete this program, I doubt it's ever going to return an answer. I've seen similar Prolog programs run for hours without finding the solution. Check out CLP(fd) if you want to do this fast (link is for SWI, but SICStus, GNU, and ECLiPSe have similar libraries.)


text:
Q: Man sent to a desert land joins up with rebels A movie I saw as a child;  the man is sent to a desert land, where there are rebels etc.  He falls in love with a girl, creates running water using the scrap he found, he's raided by the rebels.. I believe he becomes a fighter and takes it all back.
I think it was set on a planet or a desert island.. I don't remember!

A: I was able to find it finally -- on IMDB it is "STEEL DAWN"  possibly one of my favorite Sci-fi post apocalyptic movies ever.
Synopsis:

In a post-apocalyptic world, a warrior wandering through the desert comes upon a group of settlers who are being menaced by a murderous gang that is after the water they control.


text:
Q: SpringBoot Redis remote host I'm making an application that uses Spring Boot, MySQL and Redis on the Back End and Angular on the Front End. I want to deploy it to Heroku so I could use my front end with it but I just can't seem to configure the remote URL for Redis. I have the Redis To Go Add-on on Heroku for this with the remote URL ready. I just don't know how to configure the environment variables to access that instead of localhost and the default port 6379.
I added the following lines to my application.properties but it still did not work :
spring.redis.url= #URL
spring.redis.host= #HOSTNAME
spring.redis.password= #PASSWORD
spring.redis.port = #PORT

I keep getting the following error :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis on localhost:6379; nested exception is com.lambdaworks.redis.RedisConnectionException: Unable to connect to localhost/127.0.0.1:6379

Is there any way I could configure this to access the remote url instead of localhost?
I'm using Lettuce and not Jedis and my HttpSessionConfig file is :
@EnableRedisHttpSession
public class HttpSessionConfig {

    @Bean
    public LettuceConnectionFactory connectionFactory() {
        return new LettuceConnectionFactory();
    }

}

A: I was having a similar issue, this is how I solved it:
If you define the bean this way:
@Bean
public LettuceConnectionFactory connectionFactory() {
    return new LettuceConnectionFactory();
}

You are not allowing Spring to take the Redis values from the application.properties.
To make it work, please do the following:

*

*Remove this bean definition:

@Bean
public LettuceConnectionFactory connectionFactory() {
    return new LettuceConnectionFactory();
}

*Define the RedisTemplate bean this way:

@Bean
public RedisTemplate<String, Object> deliveryRedisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    return template;
}

*Define the following values in application.properties:

spring.redis.database=<replace-me>
spring.redis.host=<replace-me>
spring.redis.port=<replace-me>
spring.redis.timeout=<replace-me>

A: I was frustrated with the exact same issue you are facing and the spring boot documentation or examples do nothing to address what we are facing. The reason why your config entries are not being used is because you are creating a new instance of LettuceConnectionFactory with a parameter-less constructor. Digging into the source/byte code you can see that constructor is completely ignoring the spring.redis.host and spring.redis.port values and hardcoding them to localhost:6379.
What you should be doing is either:

*

*Use the LettuceConnectionFactory(hostname, port) constructor.

*Don't define the connection factory. Get rid of the entire @Bean entry for connectionFactory() and Spring will automatically wire everything up and use your config entries.

Also as a side note; to get this working with AWS Elasticache (locally via VPN) I had to add to that config class:
@Bean
public static ConfigureRedisAction configureRedisAction() {
    return ConfigureRedisAction.NO_OP;
}

A: I found the Heroku documentation for connecting to their Redis add-on (https://devcenter.heroku.com/articles/heroku-redis#connecting-in-java) contains an example using Jedis and therefore needed a little adaption. The content of the REDIS_URL added by Heroku to the environment of your running app resembles
redis://h:credentials@host:port

I parsed this using RedisURI.create and then set the host, port and password parameters of RedisStandaloneConfiguration
val uri = RedisURI.create(configuration.redisUrl)
val config = RedisStandaloneConfiguration(uri.host, uri.port)
config.setPassword(uri.password)
return LettuceConnectionFactory(config)

The code above is Kotlin rather than Java but perhaps it will help? You can find the full code at https://github.com/DangerousDarlow/springboot-redis

A: You need to choose between depending on autoconfiguration or defining your custom connection template.
First way is to remove HttpSessionConfig and then your redis properties from application.properties file will be applied. And as you have spring-redis-data-session dependency on your classpath your lettuce connection will be created implicitly.
Second solution is defining your connection properties as host, port, password inside LettuceConnectionFactory.
However it is recommended to use autoconfiguration.

A: Set the configuration in application.properties and RedisStandaloneConfiguration.
@Configuration
@PropertySource("application.properties")
@EnableRedisHttpSession
public class SpringRedisConfig {

            @Autowired
            private Environment env;

            @Bean
            public LettuceConnectionFactory connectionFactory() {

                RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
                redisConf.setHostName(env.getProperty("spring.redis.host"));
                redisConf.setPort(Integer.parseInt(env.getProperty("spring.redis.port")));
                redisConf.setPassword(RedisPassword.of(env.getProperty("spring.redis.password")));

                return new LettuceConnectionFactory(redisConf);
            }
    }


text:
Q: Objective-c Naming conventions for Methods I have a class that has the following properties:

*

*Name

*Email

*Username

I want to convert these properties to a dictionary. How can I properly name the method that does that to adhere to Apple's conventions?
I was thinking of:
- (NSDictionary *) convertToDictionary {}

A: How about just -dictionaryRepresentation, to convey the notion that you can get the data stored in the object in dictionary form? So you'd say:
NSDictionary *personDict = [person dictionaryRepresentation];

Another reasonable choice would be -properties, leaving the return type out of the name:
NSDictionary *personDict = [person properties];

A: Consider that to go from an NSString to an NSData you do:
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];

Similarly you could just do:
- (NSDictionary *)dictionary;

since you have no parameters. Or consider that to go from NSData to NSString you do:
[[[NSString alloc] initWithData:data encoding:encoding] autorelease]

The class method, if there was one, would look like:
[NSString stringWithData:data encoding:encoding]

so you could make it a category on NSDictionary. Say your class is called Account:
+ (NSDictionary *)dictionaryWithAccount:(Account *)account;

Depends on what you think looks better:
Account *account = ...;

[account dictionary];
[NSDictionary dictionaryWithAccount:account];


text:
Q: Equation box in Quill is not completely visible enter image description here
Trying to use Quill in my project. I'm using Bootstrap class 'row' with two columns. Right hand side column has Quill, everything works fine except this equation box (see in the image). Can anybody help?

A: I solved this using bounds. Here is the code snippet:
let quill = new Quill('#editor-container', {
            modules: {
            formula: true,
            syntax: true,
            toolbar: '#toolbarOptions'
            },
            placeholder: 'Compose your question here...',
            theme: 'snow',
            bounds: '#editor-container'
        });


text:
Q: node canvas not installing on docker can anyone help me to figure out this error? so I'm doing node version upgrade and dockerization tasks. we used node js 8.15.1 before now we want to update it to node js 16.15.0 the project was working on node 8.15.1 but when I tried to run npm install with node js 16.15.0 it got me node canvas error as below

npm ERR! code 1
npm ERR! path /app/node_modules/canvas
npm ERR! command failed
npm ERR! command sh -c node-gyp rebuild
npm ERR! make: Entering directory '/app/node_modules/canvas/build'
npm ERR!   SOLINK_MODULE(target) Release/obj.target/canvas-postbuild.node
npm ERR!   COPY Release/canvas-postbuild.node
npm ERR!   CXX(target) Release/obj.target/canvas/src/Canvas.o
npm ERR! make: Leaving directory '/app/node_modules/canvas/build'
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@7.1.2
npm ERR! gyp info using node@16.15.0 | linux | x64
npm ERR! gyp info find Python using Python version 2.7.16 found at "/usr/bin/python"
npm ERR! gyp http GET https://nodejs.org/download/release/v16.15.0/node-v16.15.0-headers.tar.gz
npm ERR! gyp http 200 https://nodejs.org/download/release/v16.15.0/node-v16.15.0-headers.tar.gz
npm ERR! gyp http GET https://nodejs.org/download/release/v16.15.0/SHASUMS256.txt
npm ERR! gyp http 200 https://nodejs.org/download/release/v16.15.0/SHASUMS256.txt
npm ERR! (node:19) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! gyp info spawn /usr/bin/python
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/app/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/app/node_modules/canvas/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/app/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/root/.cache/node-gyp/16.15.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/root/.cache/node-gyp/16.15.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/app/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/root/.cache/node-gyp/16.15.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/app/node_modules/canvas',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
... // C++ build log
npm ERR!                                             ^~~~~~~~
npm ERR! /root/.cache/node-gyp/16.15.0/include/node/v8.h:3060:44: note:   candidate expects 1 argument, 0 provided
npm ERR! make: *** [canvas.target.mk:149: Release/obj.target/canvas/src/Canvas.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/app/node_modules/node-gyp/lib/build.js:194:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:527:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Linux 5.4.0-107-generic
npm ERR! gyp ERR! command "/usr/local/bin/node" "/app/node_modules/.bin/node-gyp" "rebuild"
npm ERR! gyp ERR! cwd /app/node_modules/canvas
npm ERR! gyp ERR! node -v v16.15.0
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-05-13T07_10_55_542Z-debug-0.log
The command '/bin/sh -c npm install node-libcurl --build-from-source' returned a non-zero code: 1

Here is my Dockerfile

FROM node:16.15.0
WORKDIR /app
COPY package*.json ./
RUN apt-get update && apt-get install -qq build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev g++ software-properties-common
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt install python3.7 -y
RUN npm config set python /usr/bin/python
RUN npm install -g node-gyp
RUN npm i -g node-pre-gyp
RUN npm install node-libcurl --build-from-source
RUN npm i canvas@2.9.1
RUN npm install -d
COPY . .
EXPOSE 3000
CMD ["npm","start"]

so my issue is every time I try to build this container using docker build -t qr . it got me the above error. can anyone tell me why I keep getting this error and how can I resolve this. thank you.


text:
Q: Does fstack-protector linked with execstack protect against a buffer overflow attack? Im having trouble understanding what these two exactly do. And what the prevent when turned on.
Thanks

A: fstack-protector is a protection that will put some random content called stack canary before return address of your function call
Before return, it will check the random content is the same as before then return, otherwise it exited.
Because buffer overflow attack is try to overwritten the return address of function, it must overwrite stack canary.
But stack canary is generated randomly, so it could used to prevent overwrite the return address.
Buffer overflow attack also comes with shellcode.
Overwrite the return address and point to your shellcode and then generate the shell.
Execstack is a protection to prevent this happen.
The input buffer is on the stack and your shellcode is, too.
But execstack make memory area of stack non-executable.
When program return to shellcode, it will find out this memory area is non-executable.
It will cause segmentation fault.


text:
Q: Placing buttons at the center in horizontal line in QT I am new QT and trying to develop the desktop application.
Currently I am facing a issue of alignment. I am using QTCreator 3.1.2 based on qt 5.3.1
I have 3 buttons placed in the windows as

*

*After running application, If I resize the windows then buttons didn't stay in the center. like image 1  and if size is less then it is like image 2

I have tried using the hbox, but it didn't solve the problem and also scroll bar is also not visible in the window.
Would you please tell me how can I make these buttons to stay in the center only?
Thanks a lot

A: You can create QHBoxLayout passing this as its parent, which will set that layout as the layout of that widget, then add QPushButtons to that layout:
Widget::Widget(QWidget *parent) : QWidget(parent) {

    // Prepare the horizonal layout, adding buttons
    horizontalLayout = new QHBoxLayout(this);

    pushButton = new QPushButton(this);
    horizontalLayout->addWidget(pushButton);

    pushButton_2 = new QPushButton(this);
    horizontalLayout->addWidget(pushButton_2);

    pushButton_3 = new QPushButton(this);
    horizontalLayout->addWidget(pushButton_3);

    // Set the layout of the central widget
    setLayout(horizontalLayout);
}


text:
Q: Allocating untagged counts to other tags I have a quite long table that looks like this:
library(tidyverse)
x=structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), loc = c("A", "B", "?", "A", "B", "?"), count1 = c(10L, 20L, 50L, 5L, 22L, 10L), count2 = c(324L, 564L, 121L, 87L, 66L, 445L)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
x
#> # A tibble: 6 x 4
#>      id loc   count1 count2
#>   <int> <chr>  <int>  <int>
#> 1     1 A         10    324
#> 2     1 B         20    564
#> 3     1 ?         50    121
#> 4     2 A          5     87
#> 5     2 B         22     66
#> 6     2 ?         10    445

For each id, I would like to dispatch counts where loc is unknown uniformly to loc A and loc B.
For instance, for id==1 and column count1, loc A represent 1/3 of the total, therefore 1/3 of 50 is allocated to group A and 2/3 of 50 is allocated to group B, which would end on respectively 26.7 and 53.3. Rows with unknown loc should then be dropped.
There is (currently) no other possible value for loc than A, B or ?.
The ratio of A/A+B is different for every count and for every id.
I tried multiple ways of doing this, involving pivoting and transposing, but I never managed to achieve the intended result.
Here is the complete expected output:
expected=structure(list(id = c(1L, 1L, 2L, 2L), loc = c("A", "B", "A", "B"), count1 = c(26.67, 53.33, 6.85, 30.15), count2 = c(368.15, 640.85, 340.04, 257.96)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))

expected
#> # A tibble: 4 x 4
#>      id loc   count1 count2
#>   <int> <chr>  <dbl>  <dbl>
#> 1     1 A      26.7    368.
#> 2     1 B      53.3    641.
#> 3     2 A       6.85   340.
#> 4     2 B      30.2    258.

#Totals are obviously the same:
x %>% group_by(id) %>% summarise(across(count1:count2, sum))
#> # A tibble: 2 x 3
#>      id count1 count2
#>   <int>  <int>  <int>
#> 1     1     80   1009
#> 2     2     37    598
expected %>% group_by(id) %>% summarise(across(count1:count2, sum))
#> # A tibble: 2 x 3
#>      id count1 count2
#>   <int>  <dbl>  <dbl>
#> 1     1     80   1009
#> 2     2     37    598

Created on 2021-07-16 by the reprex package (v2.0.0)

A: Perhaps this helps
library(dplyr)
x %>%
  group_by(id) %>%
  mutate(across(starts_with('count'), ~ {
        tmp <- .
        i1 <- loc == '?'
        tmp[!i1] <- tmp[!i1] + tmp[!i1]/
       sum(tmp[!i1]) * tmp[i1]
      tmp})) %>%
  ungroup %>%
  filter(loc != '?')

-ouptut
# A tibble: 4 x 4
     id loc   count1 count2
  <int> <chr>  <dbl>  <dbl>
1     1 A      26.7    368.
2     1 B      53.3    641.
3     2 A       6.85   340.
4     2 B      30.1    258.

A: A bit verbose but will do the trick:
library(dplyr)

x %>%
  filter(loc != "?") %>%
  left_join(x %>%
              filter(loc == "?"), by = "id") %>%
  group_by(id) %>%
  mutate(across(ends_with(".x") & !contains("loc"), ~ prop.table(.x), .names = '{.col}_prop'),
         across(ends_with(".x") & !contains("loc"), ~
           get(gsub(".x", ".y", cur_column())) * get(paste(cur_column(), "_prop", sep = "")) + .x)) %>%
  select(1:4) %>%
  rename_with(~ gsub(".x", "", .), !id)

# A tibble: 4 x 4
# Groups:   id [2]
     id loc   count1 count2
  <int> <chr>  <dbl>  <dbl>
1     1 A      26.7    368.
2     1 B      53.3    641.
3     2 A       6.85   340.
4     2 B      30.1    258.

A: Here is an intutional solution with data.table
library(data.table)
x=structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), loc = c("A", "B", "?", "A", "B", "?"), count1 = c(10L, 20L, 50L, 5L, 22L, 10L), count2 = c(324L, 564L, 121L, 87L, 66L, 445L)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
setDT(x)
x[,`:=`(count1 = as.double(count1),
        count2 = as.double(count2))]

x[,`:=`(count1 = fifelse(loc != "?", count1 + count1[3] * count1/(count1[1] + count1[2]), count1),
        count2 = fifelse(loc != "?", count2 + count2[3] * count2/(count2[1] + count2[2]), count2)),
      by=id][loc != "?"]
#>    id loc    count1   count2
#> 1:  1   A 26.666667 368.1486
#> 2:  1   B 53.333333 640.8514
#> 3:  2   A  6.851852 340.0392
#> 4:  2   B 30.148148 257.9608

Created on 2021-07-17 by the reprex package (v2.0.0)


text:
Q: Regresar Arreglo de Caracteres Cómo Parametro o Valor en una Función de C++ Tengo una rutina que pasa de tipo de dato string a unsigned char[] que es el siguiente:
unsigned char in[20];
string str = "BABABABAAB";

for(int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
{
    std::stringstream ss;
    ss << std::hex << str.substr(aux, 2);

    int valor;
    ss >> valor;

    in[aux/2] = valor;
}

Y quiero hacer de esta rutina una función que pueda recibir como parametros un arreglo de caracteres vacío y lo regrese "lleno", ¿cómo se podría hacer eso? ¿hay alguna forma mas optimizada de hacer eso?

A:
Quiero hacer de esta rutina una función que pueda recibir como parámetros un arreglo de caracteres vacío y lo regrese "lleno"

Depende de si quieres que el arreglo sea de tamaño conocido en tiempo de compilación o de tamaño variable.
Tamaño conocido.
Para rellenar un arreglo de tamaño predefinido, debes pasarlo como referencia:
void convertir(const std::string &str, unsigned char (&in)[20])
{
    for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
    {
        std::stringstream ss;
        ss << std::hex << str.substr(aux, 2);

        int valor;
        ss >> valor;

        in[aux / 2] = valor;
    }
}

El código anterior sólo acepta formaciones de tamaño 20, si necesitas diferentes tamaños y éstos son conocidos en tiempo de compilación, puedes usar una plantilla:
template <std::size_t TAMANYO>
void convertir(const std::string &str, unsigned char (&in)[TAMANYO])
{
    for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
    {
        std::stringstream ss;
        ss << std::hex << str.substr(aux, 2);

        int valor;
        ss >> valor;

        in[aux / 2] = valor;
    }
}

Ten en cuenta que estoy siguiendo tu código en las propuestas anteriores y no se está comprobando que el arreglo de destino tenga suficientes elementos como para contener todos los datos del std::string de origen.
Tamaño desconocido.
Si el tamaño resultante depende del tamaño del parámetro entrante, lo mejor será usar un contenedor en lugar de un puntero:
void convertir(const std::string &str, std::vector<unsigned char> &in)
{
    in.reserve(str.length() / 2)

    for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
    {
        std::stringstream ss;
        ss << std::hex << str.substr(aux, 2);

        int valor;
        ss >> valor;

        in.push_back(valor);
    }
}

Pero si insistes en usar punteros (no deberías) necesitarás pasar el puntero por referencia y reservar memoria de manera acorde:
void convertir(const std::string &str, unsigned char *&in)
{
    in = new unsigned char[str.length() / 2];

    for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
    {
        std::stringstream ss;
        ss << std::hex << str.substr(aux, 2);

        int valor;
        ss >> valor;

        in[aux / 2] = valor;
    }
}

El código anterior tiene serios problemas:

*

*Debes gestionar la memoria manualmente.

*El alojado de memoria se realiza dentro de la función, no se sabe nada de cómo o cuándo será desalojada la memoria.

Para evitar estos problemas usa un puntero inteligente:
void convertir(const std::string &str, std::unique_ptr<unsigned char> &in)
{
    in = std::make_unique<unsigned char[]>(str.length() / 2);

    for (int aux = 0, tam_str = str.length(); aux != tam_str; aux += 2)
    {
        std::stringstream ss;
        ss << std::hex << str.substr(aux, 2);

        int valor;
        ss >> valor;

        in[aux / 2] = valor;
    }
}

Con el puntero inteligente te olvidas de los problemas de gestión de memoria.
A tener en cuenta.

*

*He pasado el parámetro str como referencia constante porque no va a ser modificado.

*Usar alias de tipos te puede ayudar a hacer que el código sea más claro:

*

*Arreglo de 20 elementos:
using a20 = unsigned char[20];

void convertir(const std::string &str, a20 &in);

*vector:
using vuchar = std::vector<unsigned char>;

void convertir(const std::string &str, vuchar &in);

*puntero inteligente:
using puchar = std::unique_ptr<unsigned char>;

void convertir(const std::string &str, puchar &in);

A: lo primero que se me ocurre es que la función sea de la forma
void nombre_funcion(string str, unsigned char *in){
      // rutina
}

donde el segundo parámetro es un puntero al arreglo de caracteres.


text:
Q: How to select every sixth visible LI element from list available There is list of filter Items , in UL LI format as shown below. On filter some LI with class "filter-items" will show and hide depends on filter applied.
I want to select every sixth element which is visible after filter and have class filter-items, and add clear:left css

    .
    .
    .

I have tried following jQuery selector
$(".filter-li:visible:nth-child(5n+1)").css("clear","left");

But not getting results I am looking for.

A: You can use .filter() to go through the collection of li.filter-items, and select those whose zero-based index matches the sixth element. Every sixth element will leave a remainder of zero when divided by 6, so index % 6 === 0 will work. However, remember that we are working with a zero-based index, so you will need to check if it leaves a remainder of 1:
$('li.filter-items').filter(function() {
  return $(this).index() % 6 === 1;
}).css('clear, 'left');

If this is a bit difficult to reason around, you can modify the logic to:
($(this).index() + 1) % 6 === 0

Here is a proof-of-concept example, but I have changed it so that it sets the background color to red for easy identification:

$(function() {
  $('li.filter-items').filter(function() {
    return $(this).index() % 6 === 1;
  }).css('background-color', 'red');
});

li

li

items 1

items 2

items 3

items 4

items 5

items 6

items 7

items 8

items 9

items 10

items 11

items 12

items 13

items 14

items 15

A: You may use a for loop and develop your own logic like this.
use $(obj).css("clear","left") in your case.

var count = 0;
$('.filter-items:visible').each(function(i, obj) {
  count++;
  if(count%6==0){
    $(obj).css("color","blue");
  }
});

xx

xx

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19


text:
Q: Is it possible to determine the CRC of a zip file ? I am not sure if I got the concept right, but I know that we can verify that the integrity of the files in a zip by getting the CRC values for each entry. However, my question is if I get a zip file, will there be a CRC for it and if so how can I determine that ?

A: You can use java.util.zip.CRC32 to compute CRC-32 checksum for any data stream.
BufferedInputStream bis = new BufferedInputStream(
                          new FileInputStream(new File("/path/to/file.zip")));
int read = 0;
CRC32 checksum = new CRC32();
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer)) != -1) {
    checksum.update(buffer, 0, read);
}
bis.close();
System.out.println ("CRC32 of your zip is: " + checksum.getValue());

A: You can use the checksumCRC32 method from the FileUtils class in org.apache.commons.io package.


text:
Q: Android Keys in AndroidKeyStore without encryption It is possible to store key pairs unencrypted by omitting KeyPairGeneratorSpec.setEncryptionRequired(). In this case, the key pair is presumably stored in clear, rather than encrypted with a key derived from the device lock screen credentials.
It is also known that hardware-backed keys are not in fact stored in the TEE, but rather, in /data/misc/keystore/user_0.
If keys are stored in clear, wouldn't a root user with full access to the file system then be able to extract the private key material?


text: Q: In openstack multinode setup, cinder volume cannot be created (from dashboard) or attached (from dashboard as well as command line) I recently installed openstack (xena) using kolla-ansible multinode setup on baremetal ubuntu 20.04 servers. However, I cannot create volume or instance with cinder volume from the horizon dashboard. From the cli, I can create OpenStack volume but cannot attach it with an instance. Could anyone give me some clue or help me resolve the issue?


text:
Q: Unable to access the database in the remote server from my binary if my binary is launched from the command Line(in windows 7) it is able to access the database of a remote server but if the same binary is launched by a another binary which is a service made by me it is not able to access that database.
My service is running as Local System. When i tried to change the command line to SYSTEM user then also my binary was able to access to database of the remote server.

A: Your process most likely fails because it is launched from a different user context. A process  inherits the user context of its parent process (the one that launches it). That's why it succeeds when launched from the command line, but fails when launched from your service. Your service probably runs under a different (and more limited) user account from cmd.exe.