text:
Q: Check for an array element in a string I've been doing "check string in array", but never the oposite. And that's what I need now. Currently I have this:
var Hash = 'http://example.com/place/england,
    arr = ['/place/'];

if(Hash.indexOf(arr)) {
    alert('it is')
} else {
    alert('it is not')
};

Problem is, it always returns true (alerts it is). Where I go wrong here?

A: indexOf returns -1 when not found, 0...n-1 on found. Thus, you are saying it is when ['/place/'].toString() (which evaluates to /place/) is not at the start of the string; you will get it is not only if it was found at the nullth position.
Instead, you want to test for -1. Also, if you want to test for all elements of the array instead of the concatenation of the array (because, if arr = ['/place/', '/time/'] you would end up searching for the string "/place/,/time/"), you want to do something else, like iteration or regular expression.
// iteration (functional style)
var found = arr.some(function(element) { return Hash.indexOf(element) !== -1; });

or
// regular expression approach
function escapeRegExp(string){
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var pattern = new RegExp(arr.map(escapeRegExp).join('|'));
var found = pattern.test(Hash);

(escapeRegExp from MDN)

A: You need to loop through the array to compare. Second thing your condition is not written in desired way.
if(Hash.indexOf(arr))

.indexOf() gives -1 for not found else > -1. In js 0 is false and other numbers are true hence you always get the true alert.

var Hash = 'http://example.com/place/england',
  arr = ['/place/'];
var i = arr.length;
while (i--)
  if (-1 < Hash.indexOf(arr[i]))
    alert('found, ' + arr[i]);
  else
    alert('not found, ' + arr[i]);

A: Well String.prototype.indexOf only accepts a string as an argument, and you're passing it an array. Either access the first element of the array, to get the string, or loop over the whole array if it could have more than one element.
if(Hash.indexOf(arr[0])) {
//                 ^^^ access first element

Or loop the whole array:
for(var i=0; i<arr.length; i++){
    if(Hash.indexOf(arr[i])) {
        alert('it is')
    } else {
        alert('it is not')
    };
}


text:
Q: Custom fields on custom post type archive I've run into the following problem.
I've made 2 custom post types, each, ofcourse, containing posts.
But now I've run into a situation where I would need to add a custom field at the top of the archive page.
Since I don't have a page I can access on the admin side, I can't fill these custom fields.
Should I switch to a page, or is there a other way?
I hope this is clear enough.

A: May way of doing this is to create a page and put the content in there then use the following code at the top of your archive"post-type".php to display it.
$myposts = get_posts( array('post_type'=>'page','numberposts' => 1,'include' => 45) );
foreach( $myposts as $post ) :  setup_postdata($post); ?>

    <article id="post-<?php the_ID(); ?>" <?php post_class('grid_5'); ?>>

<?php the_title(); ?>

                    <?php the_content(); ?>

         <?php endforeach; // end of the loop. ?>

All you need to do is replace the 'include' => 45 with your own page id.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gradle error in resolving react-native-reanimated dependencies I am facing the error below in the picture when I am trying to build my react-native app on android emulator.
To give more detail it gets stuck in configuring phase when performing:
(:react-native-reanimated > Resolve dependencies of :react-native-reanimated:classpath > gradle-7.3.0.pom)

(By the way, ios simulator works perfectly fine!)
Version of the packages that I am using:
"react-native": "0.70.1",

"react-native-reanimated": "^2.13.0"

Can anyone help me with this?

A: Well I am going to post the answer myself, but this will only be useful for developers who work in locations in which google services like Android are sanctioned.
The problem was simply my internet connection being unable to download the react-native-reanimated:classpath.
So to solve this issue or any other similar issue in the configuration phase, you have to use a VPN to change the source of request to be able to download the required packages to get your build.


text:
Q: drawImage on instance in Javascript I don't understand why the method drawImage doesn't work on the Canvas2D instance.
But when I put it in a setTimeout method it work, why?
function Canvas2D() {
  this._canvas = document.getElementById('screen');
  this._canvasContext = this._canvas.getContext('2d');
}

Canvas2D.prototype.clear = function() {
  this._canvasContext.clearRect(0, 0, this._canvas.width, this._canvas.height);
};

let Canvas = new Canvas2D();

let image = new Image();
image.src = './assets/sprites/spr_background.png';

// Doesn't work here
Canvas._canvasContext.drawImage(image, 33, 71);

setTimeout(() => {
  // When I put it here it works
  // Canvas._canvasContext.drawImage(image, 33, 71);
}, 1000);

A: The image has to be loaded in order to be drawn correctly.
If you'd do something like:
image.onload = function(){
  Canvas._canvasContext.drawImage(image, 33, 71);
}

it should work, I guess...
After a 1 second timeout, it is likely that the image has been loaded within that time. The above code waits for the image to be loaded and then draws it. (so it can draw it earlier if it's been loaded within less than a second, and it won't fail if it takes more than a second)


text:
Q: Not get multiple place using Google Place API I use google place api and it working fine for single type place.
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=23.0319597194644,72.5616482580887&radius=10000&type=atm&key=API_KEY

But, When set multiple place type at that time getting error. I use Alamofire class.
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=23.0319597194644,72.5616482580887&radius=10000&type=atm|cafe&key=API_KEY

Code:
Alamofire.request("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=23.032166019274,72.5615383539303&radius=10000&type=atm|hospital&key=API_KEY", method: .get, parameters: NSDictionary(), encoding: URLEncoding.httpBody, headers: [:]).responseJSON { (response) in
 print(response)
}

Error:
FAILURE: invalidURL("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=23.032166019274,72.5615383539303&radius=10000&type=atm|hospital&key=API_KEY")


text:
Q: Import CSV with semicolon separator into MongoDB database I've just try to import a CSV file (with semicolon ; separator) into a MongoDB database. I managed import with mongoimport -d mydb -c things --type csv --file files.csv --headerline but the result is not what I'm expecting.
The files have that form:

And I get the following result:

But I want to have something like:
{

   "_id": ObjectId("57b6e2654bf4a357b679305"),

   "geom_x_y" : "48.87792844925 , 2.3664591564",

   "circonfere" : "25.0",

   "adresse" : "PARIS 10E ARRDT - QUAI DE JEMMAPES",

   "hauteurnm" : "5.0",

   "espece" : "Acer platanoides",

   "varieteouc" : "'Schwedleri'",

   "dateplanta" : "31/12/2014"

}

A: mongoimport unfortunately doesn't allow you to specify your separator character. But it does work automatically with tabs as well as commas. If you know you won't ever have tabs in your input, you could replace all semicolons with tabs and that should then import correctly.
tr ";" "\t" < file.csv | mongoimport --type tsv ...


text:
Q: Reading a Micron 29F32G08QAA NAND Flash IC It would be nice if this was a shopping question - but it is 99%+ likely to be an electronic construction question :-(.
I wish to find the quickest / easiest / cheapest way to read a 4GB NAND Flash IC in a damaged USB memory stick. The onboard controller IC is dead.The Flash IC may also be dead but I will assume it isn't until it becomes otherwise obvious.
Reading it could involve
(1) Making a custom reader,
Maybe not a wholly silly idea as connections to Flash are fewish (8 data and a handful of controls.)
How likely it is that I could easily access the data if I did this I don't yet know. Obtaining a bit image is bearable worst case BUT I'd far far rather have something that "sees" the files system and files as was. Of course.
(2) soldering in a new controller IC
I do not yet know if these are in common use in other devices. Sample of 1 checked so far had 100% non-match. There may be an industry standard, part number irregardless, I know not (yet).
SK6211. QFP48. Outline description here and
Datasheet here.

Or
(3) Removing the Micron 29F32G08QAA 32 mbit NAND Flash IC.
 Datasheet not yet located.
Markings VERY dim. Here is "enhanced photo image of markings".

SO
Does anyone have any suggestions how I might BEST read this memory with original format, or at all?
Any thoughts on source of 6211, commonality with other parts, ability to use "any old" NAND Flash reading IC  etc.
Any hints.

Background:
A good friend who had been warned about the need for data backup failed to heed the warnings as has "lost access" to an extremely valuable set of files stored on a USB memory stick. She is studying to be a teacher and the files are lesson plans and other material created over a long period of time.
The USB memory stick was physically severely damaged by being knocked sideways while plugged into a USB port. Apparently attempts were made to read it by pushing it together. When it got to me 3 of the 4 connections between PCB and connector were broken. I resoldered these, expecting there to be a good chance of restoring operation.
When plugged into a USB port the memory stick draws a large current (probably port limited) and the controller gets VERY VERY hot - I first discovered this by burning myself badly on the IC. The actual memory IC is on the opposite side of the PCB. It also appears to get hot BUT this may be due to the very large Wattage going into the controller IC. Desoldering will happen.

Part number corrected to 29F32G08QAA

A: It looks like you can get the datasheet for the flash chip and thereby rig up something to read the bits.  However, that may be a long way from recovering the data.  Somewhere in the pile of bits is control information private to the flash drive, probably some wear levelling data, and then file system structures as seen by the operating system.
You should be able to get info on the file system (probably FAT32), but the private flash drive structures and how/where it actually stores the data is unlikely to be specified publicly.  I think the best bet is to get another flash drive of the exactly the same model, replace your flash chip into that drive, and hope no additional state is stored in non-volatile memory in the controller.

A: It may be this device:
http://www.micron.com/products/ProductDetails.html?product=products/nand_flash/mass_storage/MT29F32G08ABAAAM73A3WC1
Datasheets seem to be under NDA, but there's also a link to here:
http://onfi.org/specifications/
which has generic specifications.

I don't think this is really the answer to your problem, but you could...

*

*Establish enough to wire up the bare NAND chip to a favourite microcontroller (possibly via some level shifters).

*Then "bit-bang" the interface to download the whole chip over serial.  This'll take a while.

*You may then be able to run strings over that image to extract pure text content.

But there'll be all sorts of error correction and fragmentation getting in the way, so this probably isn't worth the effort.

Desoldering one or other chip and replacing it with a working one, or in a working flash drive of similar ilk is probably your best bet. good luck!

A: Olin's suggestion of transplanting the chip into another same model drive is likely fastest if it works and if you have the capability to do the soldering cleanly enough.
A fallback possibility would be to wire the chip up to something with sufficient GPIOs and access it through a software implementation of the data sheet protocol.  IIRC, this can just barely be done with a bidirectional parallel port.  A serial connected microcontroller (arduino, etc) would also be a possibility - either have it perform the access cycles and stream the data back over the serial at a few hundred kilobaud, or implement a command language for telling it what control signals to assert and get the data back really, really slowly (multiply the really by a few more if it's a USB-serial model, given the added latency).  For a one off project slow is of course relative - ie, after you spend a weekend building and debugging it, letting it run over night or even for a few days doesn't seem so bad.


text:
Q: C# : Cast from List to MyCollection : IList I have a collection object which utilises a List internally and implements IList<T
public class ModelCollection<T> : IModelCollection<T>
    where T : IModel
{  ... }

public interface IModelCollection<T> : IList, IList<T>
{  ... }

I also have model objects which may contains the collection ...
public class Article : Model, IArticle
{
    public IModelCollection<IArticleVariant> Variants { get; set; }
}

public interface IArticle : IModel
{
    IModelCollection<IArticleVariant> Variants { get; set; }
}

I'm using automapper to translate data from EF objects into the model classes, however I'm struggling to cast from List to IModelCollection as obviously List doesn't know this newly created type. I also have no access to the innerworkings of Automapper so extensibility doesn't appear to be an option. The error message is as follows ...
Unable to cast object of type

'System.Collections.Generic.List`1[IArticle]' to type 'IModelCollection`1[IArticle]'.

Any help very much appreciated.
Kind Regards,
Tim


text:
Q: Import JSON into Rails I have a data dump in a JSON file that I'm trying to pull into my app, but I think it needs some pre-processing, just not sure the best way to do this.
The format of the file is such that the data isn't one JSON array, rather each line is a complete JSON array. Looks like:
{"username": "Bob", "id": 123456}
{"username": "Jane", "id": 456123}
{"username": "Paul", "id": 789456}
{"username": "Mary", "id": 159794}

No comma delimitations at the end of a line - no brackets, etc. When I try to pull this in, say through my seed JSON.parse it throws and error - doesn't like the lack of appropriate formatting and wants it as one complete JSON dataset rather then each line being its own set.
What's the best way to pull in this data? Thanks!

A: I'm not sure what you mean to do with the data after importing it, I assume you want to insert it into a database.
I would write a rake task like this:
task :import_users do
  File.open('/path/to/your.file', 'r') do |file|
    file.each do |line|
      user_attrs = JSON.parse line
      User.create! user_attrs
    end
  end
end

A: You could always read line by line, and parse each line separately. This may not be very optimized though. An example : File.readlines('filename').each { |line| ... } (only in 1.9+)

A: If the file isn't too big, you could convert it to:
[
 {...},
 {...},
 {...}
]

Or if the speed isn't too critical, you could loop over each line and import it.


text:
Q: How to get object length Is there any built-in function that can return the length of an object?
For example, I have a = { 'a':1,'b':2,'c':3 } which should return 3. If I use a.length it returns undefined.
It could be a simple loop function, but I'd like to know if there's a built-in function?
There is a related question (Length of a JSON object) - in the chosen answer the user advises to transform object into an array, which is not pretty comfortable for my task.

A: This should do it:
Object.keys(a).length

However, Object.keys is not supported in IE8 and below, Opera and FF 3.6 and below.
Live demo: http://jsfiddle.net/simevidas/nN84h/

A: So one does not have to find and replace the Object.keys method, another approach would be this code early in the execution of the script:
if(!Object.keys)
{
  Object.keys = function(obj)
  {
    return $.map(obj, function(v, k)
    {
      return k;
    });
  };
 }

A: Can be done easily with $.map():
var len = $.map(a, function(n, i) { return i; }).length;

A: Also can be done in this way:
Object.entries(obj).length

For example:
let obj = { a: 1, b: 2, };
console.log(Object.entries(obj).length); //=> 2
// Object.entries(obj) => [ [ 'a', 1 ], [ 'b', 2 ] ]

A: For browsers supporting Object.keys() you can simply do:
Object.keys(a).length;

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:
var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {
        count++;
    }
}

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

A: Here's a jQuery-ised function of Innuendo's answer, ready for use.
$.extend({
    keyCount : function(o) {
        if(typeof o == "object") {
            var i, count = 0;
            for(i in o) {
                if(o.hasOwnProperty(i)) {
                    count++;
                }
            }
            return count;
        } else {
            return false;
        }
    }
});

Can be called like this:
var cnt = $.keyCount({"foo" : "bar"}); //cnt = 1;

A: Have you taken a look at underscore.js (http://underscorejs.org/docs/underscore.html)? It's a utility library with a lot of useful methods.  There is a collection size method, as well as a toArray method, which may get you what you need.
_.size({one : 1, two : 2, three : 3});
=> 3

A: One more answer:

var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';

obj = Object.keys(j).length;
console.log(obj)

A: For those coming here to find the item count of something that is already a jQuery object:
.length is what you are looking for:
Example:
len = $('#divID').length;
alert(len);

A: Summarizing all together, here is a universal function (including ie8 support):

var objSize = function(obj) {
    var count = 0;

    if (typeof obj == "object") {

        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() { return 1; }).length;
        } else {
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;
        }

    }

    return count;
};

document.write(objSize({ a: 1, b: 2, c: 3 }));
// 3

A: In jQuery i've made it in a such way:
len = function(obj) {
    var L=0;
    $.each(obj, function(i, elem) {
        L++;
    });
    return L;
}

A: If you want to avoid new dependencies you could make your own smart objects. Of course only if you want to do more that just get it's size.
MyNeatObj = function (obj) {
  var length = null;

  this.size = function () {
    if (length === null) {
      length = 0;
      for (var key in obj) length++;
    }
    return length;
  }
}

var thingy = new MyNeatObj(originalObj);
thingy.size();

A: You might have an undefined property in the object.
If using the method of Object.keys(data).length is used those properties will also be counted.
You might want to filter them out out.
Object.keys(data).filter((v) => {return data[v] !== undefined}).length

A: You may use something like Lodash lib and _.toLength(object) should give you the length of your object

A: You could add another name:value pair of length, and increment/decrement it appropriately. This way, when you need to query the length, you don't have to iterate through the entire objects properties every time, and you don't have to rely on a specific browser or library. It all depends on your goal, of course.


text:
Q: How do I get the value of Windows' %APPDATA% location variable in Java? I'm trying to make my program save its state in the location set by %APPDATA% when the user is using Windows. However, System.getProperty("temp.dir"); does not return that. How do I get the value of the %APPDATA% variable in Windows, for the purpose of state saving?

A: APPDATA is a Windows specific environment variable that gives you the location where application specific data is stored, so if you are not looking to write platform independent code, you can just do System.getenv("APPDATA");

A: Use System.getenv()
System.getenv("APPDATA")

But I think
System.getProperty("user.home")

should be preferred even though it's not exactly the same thing because it is more portable.


text:
Q: C/C++ preprocessor single quote?
Possible Duplicate:
How to single-quote an argument in a macro?

How can it do the following:
#define MACRO(X) ...
MACRO(a) // should give 'a'

A: I might be missing an easier way, but how about #define MACRO(X) ((#X)[0]).  The # stringtizes X and then [0] selects the first character.

A: Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:

There is no way to convert a macro
  argument into a character constant.

A: Like this:
#include <string>

std::string Macro(const std::string& s)
{
  std::string ret = "'";
  ret += s;
  ret += "'";
  return ret;
}

EDIT:
I posted this answer before it was revealed that this was needed for metaprogramming.  I don not know of a way to accomplish this for metaprogramming, but metaprogramming is not my forte.
Also, as for why I am effectively saying "don't use the preprocessor" in the first place, read the comments below.  But in short, I believe that almost everything that is commonly done using the preprocessor can and should be done using first-level constructs instead.  Using the preprocessor skirts the C++ type system and reduces safety.  Macros are difficult to debug, difficult to extend.  Extensively using macros will result in code that isn't familiar to the programmers who didn't create the macro, resulting in a kind of "secret language" only 1 person knows, decreasing maintainability of not only the macros, but the functions where they are used.
OK, I guess that wasn't so short, but there it is.


text:
Q: harvesting data via websites drop down data in R I am trying to get all data from all zip codes in pgform 2. How can I do that?
library(rvest)

url <- "https://wilottery.com/where-to-buy"
pgsession <- html_session(url)
pgform <-html_form(pgsession)[[2]]

pgform$fields[[1]]$name <- "zip"
pgform$fields[[2]]$name <- "cities"

filled_form <- set_values(form = pgform,
                          zip = "All zipcodes")

d <- submit_form(session=pgsession, form=filled_form)

y <- d %>%
  html_nodes("table") %>%
  .[[2]] %>%
  html_table(header=TRUE)

From this I am expecting to harvest all the possible data from all wisconsin's zip codes, irrespective of its cities.
UPDATE:
Thanks QHarr for your help!
I figured it out. After some adjustments to your code I have following as a final table.
get_results <- function(zip){
  r <- POST('https://wilottery.com/where-to-buy',
            add_headers(headers = c('User-Agent' = 'Mozilla/5.0')),
            body = list('action'='search', zip = zip))
  results <- jsonlite::parse_json(read_html(r)%>%html_node('p')%>%html_text())
  df.results <- do.call(rbind, do.call(rbind, results))
  return(df.results)
}

zips <- read_html('https://wilottery.com/where-to-buy') %>%
  html_nodes('#zip [value]') %>%
  html_attr('value')

df <- as.data.frame(get_results(zips[1]))

for(zip in 1:length(zips)){
  t <- as.data.frame(get_results(zips[zip]))
  df <- rbind(t, df)

}

A: The page does POST requests using the zip code to return html which containg json data inside a p tag. You can first collect the dropdown value attributes which are the zip codes; then issue post requests and parse out json from html and pass to jsonlite. Do then whatever you need to with results
library(rvest)
library(magrittr)
library(httr)
library(jsonlite)

get_results <- function(zip_code){
  r <- POST('https://wilottery.com/where-to-buy',
            add_headers(headers = c('User-Agent' = 'Mozilla/5.0')),
            body = list('action'='search', 'zip' = zip_code))
  results <- jsonlite::parse_json(read_html(r)%>%html_node('p')%>%html_text())
  return(results)
}

zips <- read_html('https://wilottery.com/where-to-buy') %>%
          html_nodes('#zip [value]') %>%
          html_attr('value')

for(zip_code in zips){
  print(get_results(zip))
  break #delete me later and decide what to do with results
}


text:
Q: Real-time patch on Linux 5.9.1 does not show fully-preemptible option for arm64 option I am trying to get my own custom Real-time Linux on a Raspberry Pi 4B. My status is this:

*

*I built the Linux 5.9.1 version, and have my own version of U-Boot, RFS with which I am able to successfully load and start the kernel, mount RFS, as well as reach the Kernel console also.

*I need to apply the Real-time patch on top of the Linux Kernel that I am building and so I used the corresponding patch for Linux 5.9.1. Since I am building a 64-bit kernel, I use the following command to get into the Kernel config and update the preemptible option:
    make ARCH=arm64 CROSS_COMPILE=aarch64-rpi3-linux-gnu- menuconfig

But I do not see the fully preemptible kernel option here:
.config - Linux/arm64 5.9.1 Kernel Configuration

General setup ─────────────────────────────────────────────────────────────────

     ┌────────────────────── Preemption Model ───────────────────────┐
     │  Use the arrow keys to navigate this window or press the      │
     │  hotkey of the item you wish to select followed by the <SPACE │
     │  BAR>. Press <?> for additional information about this        │
     │ ┌───────────────────────────────────────────────────────────┐ │
     │ │       ( ) No Forced Preemption (Server)                   │ │
     │ │       ( ) Voluntary Kernel Preemption (Desktop)           │ │
     │ │       (X) Preemptible Kernel (Low-Latency Desktop)        │ │
     │ │                                                           │ │
     │ │                                                           │ │
     │ │                                                           │ │
     │ └───────────────────────────────────────────────────────────┘ │
     ├───────────────────────────────────────────────────────────────┤
     │                    <Select>      < Help >                     │

When I run:
make menuconfig

I do see that option though for the x86 option:
.config - Linux/x86 5.9.1 Kernel Configuration

General setup ─────────────────────────────────────────────────────────────────

     ┌────────────────────── Preemption Model ───────────────────────┐
     │  Use the arrow keys to navigate this window or press the      │
     │  hotkey of the item you wish to select followed by the <SPACE │
     │  BAR>. Press <?> for additional information about this        │
     │ ┌───────────────────────────────────────────────────────────┐ │
     │ │       ( ) No Forced Preemption (Server)                   │ │
     │ │       ( ) Voluntary Kernel Preemption (Desktop)           │ │
     │ │       (X) Preemptible Kernel (Low-Latency Desktop)        │ │
     │ │       ( ) Fully Preemptible Kernel (Real-Time)            │ │
     │ │                                                           │ │
     │ │                                                           │ │

Linux Kernel: 5.9.1
Linux RT patch used: patch-5.9.1-rt19.patch.xz
I have enabled the expert mode also, as instructed in another post in unix.stackexchange
.config - Linux/x86 5.9.1 Kernel Configuration

General setup ─────────────────────────────────────────────────────────────────
┌────────────────────────────── General setup ───────────────────────────────┐
│  Arrow keys navigate the menu.   selects submenus ---> (or empty    │
│  submenus ----).  Highlighted letters are hotkeys.  Pressing  includes, │
│   excludes,  modularizes features.  Press  to exit, <?>    │
│  for Help, </> for Search.  Legend: [] built-in  [ ] excluded   module │
│ ┌────^(-)────────────────────────────────────────────────────────────────┐ │
│ │    []   Support initial ramdisk/ramfs compressed using LZMA           │ │
│ │    []   Support initial ramdisk/ramfs compressed using XZ             │ │
│ │    []   Support initial ramdisk/ramfs compressed using LZO            │ │
│ │    []   Support initial ramdisk/ramfs compressed using LZ4            │ │
│ │    []   Support initial ramdisk/ramfs compressed using ZSTD           │ │
│ │    [ ] Boot config support                                             │ │
│ │        Compiler optimization level (Optimize for performance (-O2))  --│ │
│ │    -- Configure standard kernel features (expert users)  --->         │ │
│ │    -- Enable membarrier() system call                                 │ │
│ │    -- Load all symbols for debugging/ksymoops                         │ │
│ │    --   Include all symbols in kallsyms                               │ │
│ │    [] Enable bpf() system call                                        │ │
│ │    [ ] Enable userfaultfd() system call                                │ │
│ │    [] Enable rseq() system call                                       │ │
│ │    [ ]   Enabled debugging of rseq() system call                       │ │
│ │    [*] Embedded system                                                 │ │
│ │    [ ] PC/104 support                                                  │ │
│ │        Kernel Performance Events And Counters  --->                    │ │

I see that this problem does not happen in the previous RT-patch that was released for Linux 5.6.19. Is there something missing for the 64-bit case from my side?

A: I raised it in Kernel.org, and then got a response that apparently it was intended to behave that way.
https://lore.kernel.org/linux-rt-users/20200824154605.v66t2rsxobt3r5jg@linutronix.de/
This basically meant that when we use 5.9.1 version with arm64 architecture, we need to disable KVM and then the Fully preemptible option comes up immediately. I was able to test it successfully.

A: Run,
make mrproper

Now run,
make menuconfig

The Realtime option must be visible now.


text:
Q: Clear textarea with facebook webdriver I'm using the PHP facebook/webdriver package to handle some web automation testing.
I have been unable to clear the content of a <textarea> element and have run out of options.
Given:

*

*a dom element <textarea>content</textarea>

*$element to be a Facebook\WebDriver\WebDriverElement instance

I have tried calling RemoteWebElement::clear():
// phpdoc for this method states:
// "If [is] TEXTAREA or text INPUT element, this will clear the value"

var_dump($element->getTagName()); // string(8) "textarea"
var_dump($element->getText());    // string(7) "content"

$element->clear();

var_dump($element->getText());    // string(7) "content"

I have tried sending backspace keys:
var_dump($element->getTagName()); // string(8) "textarea"
var_dump($element->getText());    // string(7) "content"

for ($i = 0; $i < mb_strlen($element->getText()); $i++) {
    $element->sendKeys(WebDriverKeys::BACKSPACE);
}

var_dump($element->getText());    // string(7) "content"

I'm at a bit of a loss. Any ideas?

A: To query the content of a textarea, use $element->getAttribute('value') instead of $element->getText().
RemoteWebElement::getText() appears only to get the text node that was present at the time the page loaded. At least that is my best guess based on observed behaviour.
RemoteWebElement::getAttribute('value') gets the current content of a texarea. I did not guess at this being the correct solution due to a texarea element not having a value attribute in HTML.


text:
Q: Facebook App FBML, fb:friend-selector get friend userid i am trying to get the current logged in user's friends, they should select one friend using the form below and then submit it to the same page.
The script is suppose to get the friend's userid (only one) and add it to the database.
The script is working fine but its not posting the right ID (Wrong ID $_POST['friend_selector_id']), it posts an id that looks like this: 2147483647 and i am not sure if this is the profile id or what but i need the id that you use with this code <fb:profile-pic uid=. i need the userid. Could somebody help me out ?
Thank You :D
<form action="<?php echo $appCanvasUrl.'challenge.php?gameid='.$_GET[gameid].'&userid='.$user.'&userid2='.$friend_selector_id; ?>" id="challenge" method="post">
<fb:friend-selector uid="<?PHP echo $user; ?>" name="userid2" idname="friend_selector_id"/>
<INPUT type="submit" value="Challenge"> </form>
<?php
    if(isset($_GET['gameid']) && is_numeric($_GET['userid']) && isset($_GET['userid2'])) {
    $gameid = am_injection($_GET[gameid]);
    $userid2 = am_injection($_POST['friend_selector_id']);
    $userid1 = am_injection($user);
    am_queries($db, "INSERT INTO `AMCMS_challenges` (`primkey` ,`userkey1` ,`userkey2` ,`gameid` ,`winner`, `score1`, `score2`) VALUES (NULL, $userid1, $userid2, $gameid, 0, 0, 0);");
    echo 'Challenge recorded.';
    } else {
    echo 'Please select a friend to challenge!';
    exit;
    }

A: My bad, it wasn't the script, it was my database. I had to set the fields to BIGINT otherwise the number recorded in the database was completely different :)


text:
Q: Error while filtering a pyspark DataFrame I am attempting to filter my DataFrame to remove entries with counts less than 100. The DataFrame results from the "COMBINED" is below:
Row(movieID=26, avg(rating)=3.452054794520548, count=73)
When I run the code below, I get the following error:

TypeError: '>=' not supported between instances of 'method' and 'int'

movieDataset = spark.createDataFrame(movies)
movieratings = movieDataset.groupBy("movieID").mean().drop("avg(movieID)")
topMovieIDs = movieDataset.groupBy("movieID").count()
combined = movieratings.join(topMovieIDs, on=["movieID"], how='inner')
filtered = combined.filter(combined.count >= 100).collect()

How can I filter the DataFrame by the count with 100 or greater?

A: Disregard, got it to work.
should looke like
filtered = combined.filter(combined[2] >= 100).collect()

A: Try this :
filtered = combined.filter(combined["count"] >= 100).collect()

count is by default a dataframe method name. Using combined.count is ambigouis and can refer to both the method or the column, so you have to be more specific.

This should work too :
from pyspark.sql.functions import col
filtered = combined.filter(col("count") >= 100).collect()


text:
Q: cheetah template importing functions So I am having some trouble trying to import functions and run them inside my cheetah templates.
So I have one file that lives at /docroot/tmpl/base.html
and then another file that is /docroot/tmpl/comments.html
inside of comments I have something that looks like this
#def generateComments($commentObj):
 code for generating comments
#end def

then inside of base.html I want to have a syntax like this
#import docroot.tmpl.comments as comments

 $comments.generateComments($commentObj)

However when I run that output I just get the contents of comments.html printed out including the #def generateComments in raw txt.'
What am I missing?

A: Cheetah compiles templates to Python classes. When you import comments module the module consists of a single class also named comments. You need to explicitly instantiate the class and call its generateComments method. So your code should be
#from docroot.tmpl import comments

 $comments.comments().generateComments($commentObj)

The first comments is a module, comments.comments is a template class in the module, comments.comments() is an instance of the class, comments.comments().generateComments($commentObj) is a call to its method. To simplify the code a bit import the class:
#from docroot.tmpl.comments import comments

 $comments().generateComments($commentObj)


text:
Q: Hausdorff distance: why can we restrict the range of supremum? According to Hausdorff distance in Wikipedia,
$$
 \sup_{w\in M}\rvert \inf_{x\in X}d(w,x)-\inf_{y\in Y}d(w,y)\lvert
=\sup_{w\in X\cup Y}\rvert \inf_{x\in X}d(w,x)-\inf_{y\in Y}d(w,y)\lvert
$$
is true. I tried to prove it and thought about a special case that $X$ and $Y$ is compact. Then, there exist $x_0\in X$ and $y_0\in Y$ such that
$\inf_{x\in X}d(w,x)=d(w,x_0),\inf_{y\in Y}d(w,y)=d(w,y_0)$.
I got
\begin{align*}
 \inf_{x\in X}d(w,x)-\inf_{y\in Y}d(w,y)
  &=d(w,x_0)-d(w,y_0)\\
  &\le d(x_0,y_0).
\end{align*}
I do not know whether this strategy is right.
Please give me its proof or hint.
By the way, I succeeded in proving below:
$$
  \sup_{w\in X\cup Y}\rvert \inf_{x\in X}d(w,x)-\inf_{y\in Y}d(w,y)\rvert
  =\max\{\max_{w\in Y}d(X,y),\max_{w\in X}d(x,Y)\}.
$$
Here, $X$ and $Y$ are compact.

A: It is the triangular inequality in disguise. Writing $d(w,X)=\inf_{x\in X} d(w,x)$ it suffices to show (I let you figure out why) that for every fixed $w\in M$ we have:
$$ d(w,X)-d(w,Y) \leq \sup_{y\in Y} d(y,X).$$
To see this let $\epsilon>0$ and pick $y_0\in Y$ so that $d(w,y_0)\leq d(w,Y)+\epsilon$. Then
\begin{align}
   d(w,X)-d(w,Y) &\leq \inf_{x\in X} d(w,x)-d(w,y_0)+\epsilon \\
                &\leq \inf_{x\in X} d(x,y_0) + \epsilon \\
                &=d(y_0,X) + \epsilon\\
                &\le\sup_{y\in Y}d(y,X) + \epsilon.
\end{align}
And $\epsilon>0$ was arbitrary.


text:
Q: Insert parent records and update linked children This is such a simple problem, but I cannot figure out the syntax to do this. I'm doing some data migration, and I have some existing records in a table that I want to link to a brand new parent table.
Let's say I have two tables:
declare @Parent table
(
    ID int identity(1,1),
    DummyField int
)

declare @Child table
(
    ID int identity(1,1),
    ParentID int, -- assume this is a new column, all nulls
    DummyField int
)

For each existing Child record, insert a new parent record and update Child to link to it.
That's it. It's so simple, but I can't figure it out without using a cursor.

A: Seudo SQL logic seems to be pretty simple ...
insert in to parent.

update childern
set ParentID = select @@IDENTITY
where ParentID = @previousParentId

unless I missed something here?

A: relation betwwen child and parent is missing
you hv to use output clause to achive so,
try like this,
declare @output table (parentid int)
insert into parent (parentid)
output inserted.parentid into @output
-- values

update c
set ParentID = o.parentid
from children c
inner join @output o on c.parentid=o.parentid


text:
Q: Common header view on top of nib files with Interface builder .Hi,
I have a nib file that contains an header that will be used in most of my views, so that I can change it's layout just once when I need. I'd like to know if it's possible to add the header nib view with interface builder, or if I need to do that programmatically and how should it be done.
I've thought about setting the subclass of the subview to a UIView subclass that automatically loads the nib file.
- (id)initWithFrame:(CGRect)frame {

    UIView *cell;

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed: @"MainHeaderView"
                                                 owner: self
                                               options: nil];

    for (id oneObject in nib)
        if ([oneObject isKindOfClass: [UIView class]])
            cell = (UIView *) oneObject;

    if ((self = [super initWithFrame: [cell frame]])) {
        // Initialization code
    }
    return self;
}

But this also doesn't seem to work.

A: It should work, at least in theory.  For that matter, it should be possible (but with rather a lot of effort) to add it via IB, from what used to be called a palette, a long time ago; I believe that option was recreated.
I would say that loading from initWithFrame: is likely not to work.  Other possible places to load would be awakeFromNib (with a caveat about multiple nib loadings causing it to be called multiple times), or viewDidLoad.  Try moving the load to viewDidLoad, and see if your cell is connected up.  You should also be testing for failure to load the nib (nil return).

A: Ok, I've solved this another way.
I've created the headerView and the controller, and a subclass of UIViewController for all views that needed the header to be displayed, loading them all with the header. Something like this:
@implementation MyDefaultViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    MyTestAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [self.view addSubview: [appDelegate.headerViewController view]];
}

Every view that needs the header to be there will have a controller that's a subclass of MyDefaultViewController. Seems to work, although the fact that I don't specify where to place the header scares me a bit xD


text:
Q: SSH to Ubuntu tablet over USB? I have a tablet running Ubuntu 9.04 with a USB connection to a host computer. (Ideally the host is running Windows, but if absolutely necessary I could switch the host to be Ubuntu also.)
I want to be able to SSH into the device without RS-232, WiFi, or other network connection. What software combination and setup do I need to make this happen?
Basically, I'd love the be able to have the equivalent of adb shell, but for when the tablet is running pure Ubuntu, not Android.

A: You need to set up USB networking on the tablet http://wiki.openmoko.org/wiki/USB_Networking#Debian.2C_Ubuntu_and_others
assign ip addresses to the tablet and to your pc from the same private subnet


text:
Q: Javascript Logic in Extending Search Bar I've created an expanding search bar:  You click on the magnifying glass the input extends out and to the right, click it again and it closes. (See Fiddle Below).
I'm new to the world of JS and I thought this would be a great opportunity to implement some logic.  Here's what I;m trying to do:

*

*If the search bar is open and the inner.html is empty, if you click the "search" magnifying glass, I want to prevent the default submission of the form and simply close the search bar

*If there is text, I want the form to be submitted.

Right now I've got the elements layered in such a way as to when you click the "search" button for the first time, the bar extends and the z-index of the button drops to one where the actual submit button is higher, but I want to control the functionality a little more.
What I've tried:
I tried creating a function that added an event listener that said, basically, if the bar has a width of 700px (the extended length) and the inner html is empty, bring the z-index of the extend button up back higher than the submit simply close the form.  But I can't seem to work the logic out properly.
I'm wondering how in JS you can control the z-index.
Here is the code I tried and did not work. I tried something simply like just alerting when the task I wanted to watch for was done first but it doesn't seem to be working.
Any help would be wonderful.
Code:
HTML:

<form id="myForm">
    <input id="search" name="search" type="text" placeholder="What are we   looking for?" />
    <input id="search_submit" value="" type="submit">
    </form>

CSS:
#wrap
{
margin: 50px 100px;
display: inline-block;
position: relative;
height: 60px;
float: right;
padding: 0;
}

input[type="text"]
{
height: 40px;
font-size: 35px;
border: none;
outline: none;
color: #555;
padding-right: 60px;
position: absolute;
width: 0px;
top: 0;
right: 0;
background: none;
z-index: 4;
cursor: pointer;
transition: width .4s ease-in-out;
}

input[type="text"]:focus
{
width: 700px;
z-index: 1;
border-bottom: 1px solid #bbb;
cursor: text;
}

input[type="submit"]
{
position: absolute;
height: 60px;
width: 60px;
display: inline-block;
float: right;
background:     url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAMAAABg3Am1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRFU1NT9fX1lJSUXl5e1dXVfn5+c3Nz6urqv7+/tLS0iYmJqampn5+fysrK39/faWlp////Vi4ZywAAABF0Uk5T/////////////////////wAlrZliAAABLklEQVR42rSWWRbDIAhFHeOUtN3/ags1zaA4cHrKZ8JFRHwoXkwTvwGP1Qo0bYObAPwiLmbNAHBWFBZlD9j0JxflDViIObNHG/Do8PRHTJk0TezAhv7qloK0JJEBh+F8+U/hopIELOWfiZUCDOZD1RADOQKA75oq4cvVkcT+OdHnqqpQCITWAjnWVgGQUWz12lJuGwGoaWgBKzRVBcCypgUkOAoWgBX/L0CmxN40u6xwcIJ1cOzWYDffp3axsQOyvdkXiH9FKRFwPRHYZUaXMgPLeiW7QhbDRciyLXJaKheCuLbiVoqx1DVRyH26yb0hsuoOFEPsoz+BVE0MRlZNjGZcRQyHYkmMp2hBTIzdkzCTc/pLqOnBrk7/yZdAOq/q5NPBH1f7x7fGP4C3AAMAQrhzX9zhcGsAAAAASUVORK5CYII=) center center no-repeat;
border: none;
outline:none;
top: -15px;
right: 0;
z-index: 2;
cursor: pointer;
transition: all .4s ease;
}

JS
var search = document.getElementById("myForm").search;
var search_submit = document.getElementById("myForm").search_submit;

function showOpen()
{
     if(search.style.width=="700px")
{
alert("OPEN!");
}
};

 search.addEventListener("click", showOpen);

 showOpen();

HERE IS THE FIDDLE: https://jsfiddle.net/theodore_steiner/7begmkf3/37/

A: Your issue can be solved using a few basic JavaScript elements (if you're looking to get into basic logic, these are important to know). The JS uses onsubmit, onclick, and some basic form logic. Basically, when you try to submit the form it checks if the form is empty, and if it is, the program refuses to submit the code. I added the new JavaScript to the HTML file:

    <form id="myForm" onsubmit="return check()">
        <input id="searchBar" name="search" type="text" placeholder="What are we looking for?" />
        <input id="search_submit" value="" type = "submit">
        </form>

fiddle: https://jsfiddle.net/q1L3Lstx/1/
It might also help in the future to look at the required element: http://www.w3schools.com/tags/att_input_required.asp

A: I saw a couple of issues with the code.
search and search_submit are pointing to the wrong items they can be like this:
var search = document.getElementById("search");
var search_submit = document.getElementById("search_submit");

You could call a function on submit. like this:
<form id="myForm" onsubmit="myFunction(event)">

finally you can work your code inside that function:
function myFunction(e){
    if(search.value.length <= 0){
        e.preventDefault();
        alert('empty');
    }
}


text:
Q: Extracting word document text within bullet using c# Hey I need help extracting word document text (of every style) residing in heading 1 style bullet
For example:
1. FR1:
all text in this heading 1 style bullet
2. FR2:
all text in this heading 1 style bullet
My main goal is to get text from a word document within "heading 1 style" headings and save it in a list of strings like index 1 of list should contain text residing FR1 heading and index 2 should contain text residing in FR2 heading and so on.
I don't know which is more efficient way for text extracting of specific style heading whether using  heading bullets or heading name.


text:
Q: How to create simple hello world using quartz scheduler and spring boot in clustering mode? I wanted to create a quartz job on clustering mode using spring boot I am using following quartz.properties and I have created 2 cron jobs for same time is it going to work in cluster or not ?
#===================================================
#quartz.properties
#===================================================

#===================================================
#scheduler name will be "MyScheduler"
#===================================================
 org.quartz.scheduler.instanceName=TestScheduler
 org.quartz.scheduler.instanceId=AUTO

#===================================================
#maximum of 3 jobs can be run simultaneously
#===================================================
 org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
 org.quartz.threadPool.makeThreadsDaemons = true
 org.quartz.threadPool.threadCount: 50
 org.quartz.threadPool.threadPriority: 5

#===================================================
# Configure JobStore
#===================================================
 org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
org.quartz.jobStore.useProperties=true
org.quartz.jobStore.misfireThreshold=25000
org.quartz.jobStore.tablePrefix=QRTZ_
org.quartz.jobStore.isClustered=false
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.isClustered=true

#===================================================
#Quartz dataSource
#===================================================
org.quartz.dataSource.myDS.driver=oracle.jdbc.pool.OracleDataSource
org.quartz.dataSource.myDS.URL=jdbc:oracle:thin:@localhost:1521:XE
org.quartz.dataSource.myDS.user=oracle
org.quartz.dataSource.myDS.password =oracle
org.quartz.dataSource.myDS.maxConnections=5
org.quartz.dataSource.myDS.validationQuery=select 1

A: To run quartz jobs in a clustered environment,
org.quartz.jobStore.isClustered should be set and org.quartz.scheduler.instanceId should be AUTO. I can see your quartz property file have two entries for org.quartz.jobStore.isClustered


text:
Q: Custom authentication provider - retrieving a parameter from url in initiate() method We have a working external identity provider SSO Oauth 2.0 with custom apex provider. (External app redirects to a specific SF community)
We need to extend it to accept a custom parameter from the incoming url in the initiate() Auth.AuthProviderPluginClass method to be able to redirect the user to a specific record.
URL.getSalesforceBaseUrl() and ApexPages.currentPage().getUrl() are obviously not working.
Is there any way to get the URL parameter in the initiate() method to change the redirect url?
Or is there any way to change the redirect url in the custom handler where we already have the user context? (PageRreference is returned already in the provider, before getting information about the user)

A: You cannot use a custom parameter as this flow is based on oAuth.
The stateToPropagate argument in initiate() is the way to pass information to your plugin. You can then use it to build the target URL,e.g.
public PageReference initiate(Map<String,String> config, String stateToPropagate) {

            final PageReference pageRef = new PageReference(...);
            pageRef.getParameters().put('state',stateToPropagate);
            return pageRef;
}

The value of stateToPropagate corresponds to the state query parameter in oAuth flow.

A: You'll want to see the following two sections of the Salesforce External Identity Implementation Guide:

*

*Dynamic URLs: Determine Your Brand at Run Time

*Add Dynamic Branding to Custom Login Pages
I think the latter is more specifically what you'll need to do if looking for a redirect parameter. You'll need to store it in something like the Expid, after which you can extend endpoints with either the expid_value or expid={value}.
Examples:
community-url/services/oauth2/authorize/expid_value
community-url/services/auth/oauth/authentication_provider/?expid={value}

There's much more in the document you may find helpful as well.


text:
Q: Difference between const int* ptr[] and const int (*ptr)[] Is there any difference between
const int* ptr[5];

and
const int (*ptr)[5];

?
I am trying to point to a const 5*5 2D int array, but I am not sure of the best way to do it

A: const int* ptr[5];

This is an array of five elements, each element is a pointer to const int.

const int (*ptr)[5];

This is a pointer to an array of five elements, each element is a const int.


text:
Q: How to check for the file type not based on file name/extension In my application we are uploading image/audio/video files. I have allowed some fixed set of allowed extensions of each types. If the extension does not match the list of provided extensions then it won't upload, but if the user renames the .exe, .pdf file to .jpg or .png the it would clear the UI validations and servlet will be called and upload will happen. But later that would cause a problem. Is there any way to check the same at backend and then throw an Exception accordingly.
I have tried using :
import java.net.*;

public class FileUtils{
    public static String getMimeType(String fileUrl) throws java.io.IOException {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(fileUrl);
        return type;
    }

    public static void main(String args[]) throws Exception {
        System.out.println(FileUtils.getMimeType("file:/home/kavinder/file.pdf"));
        // this is a .jpg file renamed to .pdf
    }
}

This is returning according to extension only. And
import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
    public static void main(String args[]) {
        File f = new File("/home/kavinder/file.jpg");
        System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f));
    }
}

This is always returning the mime type as: application/octet-streamThank you in advance


text:
Q: SSL certificate verification failure in Chrome, Heartbleed bug? For some reasons I'm running into SSL problems since a few days.
When trying to clone a git repository for example I receive the following error message:
fatal: unable to access 'https://someuser@bitbucket.org/somerepo.git/': SSL certificate problem: Invalid certificate chain
I was able to solve this issue by setting the following configuration option:
git config --global http.sslVerify false;
But when I try to access github.com or bitbucket.org through chrome I get the following:

Unfortunately it's in german but in short it says that the connection is affected by something. The failure type is HSTS failure. The second screen says that the certificate was signed by a unreliable deliverer.
I'm using Chrome (34.0.1847.116) on a Mac (OS X 10.9.2 (13C64)).
Any suggestions what could cause this issue or how to solve it?

A: i've got the same problem since weeks (!), exactly same setup (chrome / mac os - newest versions), also from germany. anybody an idea?
workaround: use safari or firefox.
seems to be a chrome specific problem.
- update -
here is the solution:
https://productforums.google.com/forum/#!topic/chrome/Duu4y-d-PIU

*

*delete false certificates

*will be correctly recreated by system on reboot

A: This other answer helped me: https://superuser.com/a/788547.
It's Mac OS X related, and it helps solving a problem that affects chrome in a similar way (with Github) because of a certificate that expired on July 26th 2014.
The steps that worked for me:

*

*Open Keychain (Applications / Utilities / Keychain)

*Go to Presentation -> Display expired certificates

*Find the "DigiCert High Assurance EV Root CA" certificate

*Close Chrome

*Download back this certificate from : https://www.digicert.com/digicert-root-certificates.htm

*Drag it to your "Session" keychain

*Restart Chrome

*Go to github, should be solved!

A: I've been having similar issues.
Try synchronizing your system clock with an internet time server. SSL connections check the date and time of the system so doing this fixed it for me.

A: This is what worked for me (mac, not able to open github):

*

*Open Keychain

*Select "View" -> "Show Expired Certificates"

*In the search box, type "Digi". This should be enough to show any/all DigiCert certificates.

*Delete any certificates that have a red "X" icon (these are expired).

*Navigate to / reload GitHub.  You should be allowed access.

Worth noting, I did not need a restart of Chrome or the OS.

A: The certificate of BitBucked and GitHub was recently revoked but they didn't restart their servers at the moment you were trying to connect. Just try again right now. It should be fine.

A: None of the above helped me. I tried this
export GIT_SSL_NO_VERIFY=true

Via -> http://www.uwosh.edu/ploneprojects/docs/how-tos/how-to-fix-a-git-ssl3-get-server-certificate-error


text:
Q: What is the most efficient way to update the childNodes of a DOM node with an array of DOM nodes, with the minimum number of DOM mutations? Let's say I have a DOM node parent which may or may not have child nodes. If I have an array which contains child DOM nodes, some of which may already be a child of parent, what is the best way to set the parent's children with this new array such that the minimum number of DOM mutations occur? We identify nodes which are already in the parent by simple referential identity (===), and we remove nodes which aren't found in the new children. Existing children can be reordered as well.
Note that simply setting childNodes of parent to the array doesn't do anything, but is essentially what I want to do:
// doesn't do anything
parent.childNodes = children;

Here's what I have so far:
function updateDOMChildren(el, children = []) {
    if (el.childNodes.length === 0) {
        const fragment = document.createDocumentFragment();
        for (let child of children) {
            if (typeof child === "string") {
                child = document.createTextNode(child);
            }

            fragment.appendChild(child);
        }

        el.appendChild(fragment);
        return;
    }

    let oldChild = el.firstChild;
    for (const newChild of children) {
        if (oldChild === null) {
            el.appendChild(
                typeof newChild === "string"
                    ? document.createTextNode(newChild)
                    : newChild,
            );
        } else if (typeof newChild === "string") {
            if (oldChild.nodeType === Node.TEXT_NODE) {
                if (oldChild.nodeValue !== newChild) {
                    oldChild.nodeValue = newChild;
                }

                oldChild = oldChild.nextSibling;
            } else {
                el.insertBefore(document.createTextNode(newChild), oldChild);
            }
        } else if (oldChild !== newChild) {
            el.insertBefore(newChild, oldChild);
        } else {
            oldChild = oldChild.nextSibling;
        }
    }

    while (oldChild !== null) {
        const nextSibling = oldChild.nextSibling;
        el.removeChild(oldChild);
        oldChild = nextSibling;
    }
}

This solution is suboptimal in the case where nodes are removed in the middle, because the later nodes are inserted before the to-be-removed nodes, even though they don't have to be touched. For instance:

  1
  2
  3
  4

  1
  4

In this transformation according to my current algorithm, the 4 node is inserted before the 2 node before the 2 node is removed. Is there a way to tweak the algorithm so this extra insertion does not happen?
Alternatively, is there a more efficient algorithm for implementing this function? Is there a more generic name for this algorithm (updating a linked list with an array)?


text:
Q: Laravel Model Not Saving but It Says It Is (Inside of Observer class) I have a task model and I am trying to do a simple create to test something in one of my observer classes. Here's my create code.
private function generateTasks(Event $event)
{
    $tasks = [];

    $tasks[] = [
        'event_id' => $event->id,
        'title' => 'This is a test',
        'description' => 'this is a description',
        'due_on' => Carbon::now()->addDays(14)
    ];

    dump(Task::all());
    // foreach ($tasks as $task) {
        $task = Task::create([
            'event_id' => $event->id,
            'title' => 'This is a test',
            'description' => 'this is a description',
            'due_on' => Carbon::now()->addDays(14)
        ]);

        if ($task->save()) {
            echo "Saved";
        }
        else {
            echo "NO SAVE";
        }

        dump($task);
    // }

    dd($tasks, "DONE");
}

And the output is below:

When I look at the database the table remains at 120 rows. This is really odd because it says it's saving. When I grab all the tasks you can see in the output it has 120 rows. If you look at my latest output id you'll see that I am up to 133.
Any ideas what is going on here?
UPDATE:
My fillables:
protected $fillable = [
    'title', 'description', 'due_on', 'event_id', 'completed'
];

Completed has a default of false.
My table looks like this to give you guys an idea:

A: the create does the save method you do not need to do it again you can do it as the following:
 private function generateTasks(Event $event)
{

 $tasks = [];

$tasks[] = [
    'event_id' => $event->id,
    'title' => 'This is a test',
    'description' => 'this is a description',
    'due_on' => Carbon::now()->addDays(14)
];
    $task = Task::create([
        'event_id' => $event->id,
        'title' => 'This is a test',
        'description' => 'this is a description',
        'due_on' => Carbon::now()->addDays(14)
    ]);

    if ($task) {
        echo "Saved";
    }
    else {
        echo "NO SAVE";
    }

dd($tasks, "DONE");

}

A: I ended up getting help from the laravel chat. Big shout-out to them. The problem was that I was using a dump die inside of a transaction. This was causing what appeared to be a save but then, because the die was called before the transaction commit, it was rolling everything back. It was a silly mistake. Thanks for all the help!


text:
Q: Ruby: group_by operation on an array of hashes I have an array of hashes that represent compounds stored in boxes.
database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]

I would like to select a subset of the array, minimum by the number of boxes, that covers the full inventory of compounds (i.e., 1 to 7). Thus the result would be:
database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound7", "Box"=>4}]

I can use the following to group compounds per box:
database.group_by{|x| x['Box']}

I have trouble reducing the result so that duplicate compound names are removed from the grouped operation.

A: With Ruby >= 2.4 we can use transform_values:
database.group_by { |hash| hash["Name"] }
        .transform_values { |v| v.min_by { |h| h["Box"] } }
        .values

Or if you have Ruby < 2.4 you can do:
database.group_by {|hash| hash["Name"] }.map { |_,v| v.min_by {|h| h["Box"]} }

Key methods: group_by, transform_values (Ruby > 2.4) and min_by. See Ruby Docs for more info.

A: You could try with Array#uniq:
database = [{name: "Compound1", box: 1}, {name: "Compound2", box: 1}, {name: "Compound2", box: 1}, {name: "Compound3", box: 1}, {name: "Compound4", box: 1}, {name: "Compound5", box: 2}, {name: "Compound6", box: 2}, {name: "Compound1", box: 3}, {name: "Compound2", box: 3}, {name: "Compound3", box: 3}, {name: "Compound7", box: 4}]

p database.uniq{|k,_v| k[:name]}
# =>  [
#   {:name=>"Compound1", :box=>1},
#   {:name=>"Compound2", :box=>1},
#   {:name=>"Compound3", :box=>1},
#   {:name=>"Compound4", :box=>1},
#   {:name=>"Compound5", :box=>2},
#   {:name=>"Compound6", :box=>2},
#   {:name=>"Compound7", :box=>4}
# ]

Or:
p database.group_by{|k,_v| k[:box]}.each{|_k,v| v.uniq!{|k,_v| k[:name]}}

# => {
#   1=>[
#     {:name=>"Compound1", :box=>1},
#     {:name=>"Compound2", :box=>1},
#     {:name=>"Compound3", :box=>1},
#     {:name=>"Compound4", :box=>1}
#   ],
#   2=>[
#     {:name=>"Compound5", :box=>2},
#     {:name=>"Compound6", :box=>2}
#   ],
#   3=>[
#     {:name=>"Compound1", :box=>3},
#     {:name=>"Compound2", :box=>3},
#     {:name=>"Compound3", :box=>3}
#   ],
#   4=>[
#     {:name=>"Compound7", :box=>4}
#   ]
# }

A: The essence of the problem is to find a minimal-size combination of boxes that includes ("covers") all of a set of specified "components". That combination of boxes is then used to compute objects of interest, as shown below.
Code
def min_box(database, coverage)
  boxes_to_compounds = database.each_with_object(Hash.new {|h,k| h[k]=[]}) { |g,h|
    h[g["Box"]] << g["Name"] }
  boxes = boxes_to_compounds.keys
  (1...boxes.size).each do |n|
    boxes.combination(n).each do |combo| return combo if
      (coverage - combo.flat_map { |box| boxes_to_compounds[box] }).empty?
    end
  end
  nil
end

coverage is a given array of required compounds (e.g., "Compound3").
Example
Suppose we are given database as given in the question and
coverage = ["Compound1", "Compound2", "Compound3", "Compound4",
            "Compound5", "Compound6", "Compound7"]

An optimal combination of boxes is then found to be
combo = min_box(database, coverage)
  #=> [1, 2, 4]

We may now compute the desired array of elements of database:
database.select { |h| combo.include?(h["Box"]) }.uniq
  #=> [{"Name"=>"Compound1", "Box"=>1}, {"Name"=>"Compound2", "Box"=>1},
  #    {"Name"=>"Compound3", "Box"=>1}, {"Name"=>"Compound4", "Box"=>1},
  #    {"Name"=>"Compound5", "Box"=>2}, {"Name"=>"Compound6", "Box"=>2},
  #    {"Name"=>"Compound7", "Box"=>4}]

min_box explanation
Finding an optimal combination of boxes is a hard (NP-complete) problem. Some form of enumeration of combinations of boxes is therefore required. I begin by determining if a single box provides the required coverage of components. If one of the boxes does, an optimal solution has been found and the method returns an array containing that box. If no single box covers all compounds, I look at all combinations of two boxes. If one of those combinations provides the required coverage it is an optimal solution and an array of those boxes is returned; else combinations of three boxes are considered. Eventually an optimal combination is found or it is concluded that all boxes together do not provide the required coverage, in which case the method returns nil.
For the example above, the calculations are as follows.
boxes_to_compounds = database.each_with_object(Hash.new {|h,k| h[k]=[]}) { |g,h|
  h[g["Box"]] << g["Name"] }
  #=> {1=>["Compound1", "Compound2", "Compound2", "Compound3", "Compound4"],
  #    2=>["Compound5", "Compound6"],
  #    3=>["Compound1", "Compound2", "Compound3"],
  #    4=>["Compound7"]}
boxes = boxes_to_compounds.keys
  #=> [1, 2, 3, 4]
boxes.size
  #=> 4

Each of the elements 1...boxes.size is passed to the outer each block.  Consider box 3.
n = 3
e = boxes.combination(n)
  #=> #<Enumerator: [1, 2, 3, 4]:combination(3)>

We may see the objects that will be generated by this enumerator and passed to the inner each block by converting it to an array.
e.to_a
  #=> [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

The first element generated by e is passed to the block and the following is computed.
combo = e.next
  #=> [1, 2, 3]
a = combo.flat_map { |box| boxes_to_compounds[box] }
  #=> ["Compound1", "Compound2", "Compound2", "Compound3", "Compound4",
  #    "Compound5", "Compound6", "Compound1", "Compound2", "Compound3"]
b = coverage - a
  #=> ["Compound7"]
b.empty?
  #=> false

As that combination of boxes does not include "Compound7" we press on and pass the next element generated by e to the block.
combo = e.next
  #=> [1, 2, 4]
a = combo.flat_map { |box| boxes_to_compounds[box] }
  #=> ["Compound1", "Compound2", "Compound2", "Compound3", "Compound4",
  #    "Compound5", "Compound6", "Compound7"]
b = coverage - a
  #=> []
b.empty?
  #=> true

We therefore have found an optimal combination of boxes, [1, 2, 4], which is returned by the method.

A: I don't like that original data structure.  Why not just start with a hash of {CompoundX => BoxY} since "Name" and "Box" are not really useful.  But if you're married to that structure, here's how I would do it:
database = [{"Name"=>"Compound1", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound2", "Box"=>1},
            {"Name"=>"Compound3", "Box"=>1},
            {"Name"=>"Compound4", "Box"=>1},
            {"Name"=>"Compound5", "Box"=>2},
            {"Name"=>"Compound6", "Box"=>2},
            {"Name"=>"Compound1", "Box"=>3},
            {"Name"=>"Compound2", "Box"=>3},
            {"Name"=>"Compound3", "Box"=>3},
            {"Name"=>"Compound7", "Box"=>4}]

new_db_arr = database.collect{|h| h.flatten}.flatten.collect{|i| i if i != "Name" && i != "Box"}.compact!
new_db_hash = {}
new_db_arr.each_slice(2) do |a,b|
  if new_db_hash[a].nil?
    new_db_hash[a] = []
  end
  new_db_hash[a] << b
end

new_db_hash
boxes = new_db_hash.values
combos = boxes[0].product(*boxes[1..-1])
combos = combos.sort_by{|a| a.uniq.length }
winning_combo = combos[0].uniq

The bulk of the work is just transforming the data structure into the hash of :Compound => boxNumber format.  Then you generate every combination of boxes, sort by the combination's number of uniq items and take the one with the smallest number of uniq items as the answer.  Not sure how great this would scale for very large datasets.


text:
Q: Catch missing local resources in resx files I have many resource files, in many different languages.
Lets suppose for example we are supporting 3 languages (en, de, fr), and have this file:
common.resx
common.de.resx
common.fr.resx
I would like to detect occurrences when for instance a resource is requested in de, but is missing and so reverts to the default language. Is there any way of catching this? (so I can log it and later add the missing resource).
Thanks

A: If you want to catch the differences use RESX Synchronizer. It is an open source app that can synchornize all differences from main resx to localized one (it adds and/or removes keys in the localized resource).
You can use it as follows to copy all changes from common.resx to common.de.resx:
resxsync /v common.resx common.de.resx

The /v option list all changes that is all keys that were added to or removed from the de resx.

A: Assuming that all resource file changes start in development and make their way to production, this seems like a job for some form of static analysis.
I use Zeta Resource Editor because it highlights areas that are missing translations and also placeholders (e.g. {0}).

A: Resharper has this great feature http://www.jetbrains.com/resharper/features/internationalization.html#Code_Inspections_for_Resource_Files

ReSharper warns you whenever a specific resource value is not
  overridden in a specific culture

A: There's nothing in the existing resource reading API that exposes fallbacks externally.  However, System.Resources.ResourceManager is not sealed, so there's nothing stopping you from subclassing it to raise an event when fallback is required.


text:
Q: Managing model association complexity when testing Rails On several recent projects I've felt that model associations can get very complex very fast. It feels like testing is way harder than it needs to be because of this complexity. For example, I need to create an instance of model A for a test. Many times, it looks something like this (this is taken from the app I'm working on right now):

*

*Create model A, but model A relies on B.

*Model B relies on model C

*Model C relies on D, E, and F. Specifically, it needs 6 F's to be attached for it to be considered valid.

*Model D, E, and F may have a dependency or two.

Finally, A is created. I am using factories on this application and that helps a bit, but it still feels like too much when I need to satisfy so many validations in order to create a simple model that is not related to any of that.
Stubs might help, but I feel like that requirement represents something wrong with the modelling at it's core.
Are there any patterns designed to help with dependencies like this? One thing I've been thinking about is to make most of the validation conditional based on context. The controllers will save the models in that validation context but that lets my test suite create objects that would otherwise be "invalid" in the live app or full integration test suite. The problem with that is that I feel like it alters my codebase for the sake of testing and I think that is generally a bad idea.

A: Like you I'd rather not have test-specific code in my application. I'd also rather have validations in place all the time, because if I didn't who knows what test might construct invalid data and thereby pass when it shouldn't?
But it's better when tests run fast. So:

*

*I trust you've already made everything in the database a seed that should be, i.e. model instances that don't need to change more often than you deploy.

*If you're using factory_girl, rather than just defining associations and letting factory_girl create them all every time, you could make your factory reuse dependencies:
factory :a do
  before :create do |a, _|
    a.b ||= B.first || FactoryGirl.create(:b)
  end
end

(Haven't tested that but I trust the intention is clear.)

*If you need to reuse a B sometimes and make a new one sometimes, obviously you have to write some code sometimes. The most sensible thing to do is probably to create a B in the test and pass it in to the A's that should reuse it and not to the ones that don't.


text:
Q: How can I set or append different base hrefs to different links with JavaScript? I want to reduce clutter in my web page code by setting multiple base hrefs for hyperlinks. Links with the same base hrefs also have the same CSS classes. Using JavaScript, is there a way to append base hrefs to the relative links? It's very difficult to explain, but here's an example:
Sad 1
Sad 2
Angry 1
Angry 2

I want to append one base href to all the links with a blue class, and a different base href for all the links with a red class. I'll actually have several more classes in the document, but I can finish the code if someone can provide a working sample. My page has hundreds of links, which I update often, so I need the html as trim as possible. I'm solid on HTML and CSS, but I'm still trying to learn JavaScript. Thanks.

A:

function absolutizeHref(klass, base) {
  var nodes = document.querySelectorAll("." + klass + "[href]");
  Array.prototype.forEach.call(nodes, function(node) {
    var href = node.getAttribute("href");
    node.setAttribute("href", base + href);
  });
}

document.addEventListener("DOMContentLoaded", function(event) {
  absolutizeHref("blue", "http://example.com/blue/");
  absolutizeHref("red", "http://example.com/red/");
});
Sad 1
Sad 2
Angry 1
Angry 2

A: Just to give you an idea. Something like this:

var links = document.querySelectorAll('a');

for(var i = 0; i < links.length; i++) {
  links[i].href = links[i].className + links[i].pathname;
}
Sad 1
Sad 2
Angry 1
Angry 2

Update after re-reading the question and didn't notice this line at the first time so much..

I want to append one base href to all the links with a blue class, and
  a different base href for all the links with a red class.

To stick with the idea it is still quiet simple

var links = {};

links.blue = document.querySelectorAll('a.blue');
links.blue.myPath = '/custom/blue/path';

links.red = document.querySelectorAll('a.red');
links.red.myPath = '/custom/red/path';

for (var key in links) {
  for(var i = 0; i < links[key].length; i++) {
    links[key][i].href = links[key].myPath + links[key][i].pathname;
  }
}
Sad 1
Sad 2
Angry 1
Angry 2

A: Another answer here has offered the core-js solution for this.
If you are happy to use jQuery, jQuery will provided the cleanest solution for you.
If you aren't comfortable with jQuery, but are open to using it, a quickstart guide can be found here
Here's an example of solving this in jQuery. The elegance of this solution, is that all you need to do to expand it is add a key value pair to classToPrefixMap:

var classToPrefixMap = {
    green: '/path/to/green/',
    blue: '/path/to/blue/'
};

for(var key in classToPrefixMap) {
    $('.' + key).each(function(index, anchor) {
 $(anchor).attr('href', classToPrefixMap[key] + $(anchor).attr('href'));
    })
}

One
Two
Three
Four


text:
Q: How printf handles conversion I'm reading chapter 7 of C programming: a modern approach, and a bit unclear how printf handles type conversion.
Consider the following code:
int main() {
    int i = 47000; // This will overflow when squared

    int i2 = square(i);

    long l = square(i);

    printf("i2 = %ld, l = %ld, i * i = %ld, square(i) = %ld",
       i2, l, i * i, square(i));

    return 0;
}

int square(int i) {
    int j = i * i;
    return j;
}

I expected the output to be (due to overflowing):
i2 = -2085967296, l = -2085967296, i * i = -2085967296, square(i) = -2085967296

But instead I got:
i2 = 2209000000, l = -2085967296, i * i = 2209000000, square(i) = 2209000000

Could you explain:
a) why some results didn't overflow?
b) why l overflowed?

A: You get undefined behavior using %ld to print ints.
What you are actually seeing is an artifact of the X86-64 parameter passing.
When you explicitly convert the int value returned by square from 32 bit to 64 bit long, you sign extend, preserving the overflow.  So that one shows the expected overflow.
The first few ints passed to a function in x86-64 are zero extended to 64-bits (later ones may be garbage extended).  That should be an invisible effect, because only the low 32-bit should be used.  But then you used %ld causing all 64 bits to be used.  The particular value had overflowed in a way that causes zero extension to 64-bit to accidentally get back to the non overflowed value.
So the undefined behavior of passing an int that the receiving function aliases as long accidentally undid the overflow.

A: printf doesn't do type conversions. It takes its arguments (other than the format string) through an ellipsis, so it has to trust the format string to tell it what the types of the input values are.
"%ld" tells printf that the corresponding value has type long int. The values of i2, i * i, and square(i) all have type int. So the format specifier is wrong, and the displayed values are nonsense. Use "%d" for int.


text:
Q: How Get Value from multidimensional array in php I have build an RestAPI to get value from other server to my server i'm getting this value in XML format as given below
SimpleXMLElement Object
(
    [hotel-id] => XXXXX
    [room-types] => SimpleXMLElement Object
        (
            [room-type] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [room-id] => XXXXXX
                            [room-name] => XXXXXX
                            [room-status] => XXXXXX
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [room-id] => XXXXXX
                            [room-name] => XXXXXX
                            [room-status] => XXXXXX
                        )

                )

        )

    [status] => SimpleXMLElement Object
        (
            [code] => S002
            [description] => Request Executed Successfully.
        )

)

By below mention code i'm try to get value of room-type object
$value = (string) $array_data->room-types->room-type;

But every time i'm getting this error

Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in on
  line 27

Someone please help

A: Use it like this, because you indexex contains - :
$array_data->{"room-types"}->{"room-type"}


text:
Q: single line input for list I am provided with a number:
example:  12345
I'm supposed to split each digits of this number and append it to a list (list of integers).
num = list(int(input('Enter the number\n')))
print(num)

Get the error:
Exception has occurred: TypeError 'int' object is not iterable

Required output: [1, 2, 3, 4, 5]

A: Try this:
num = [int(i) for i in input("input your number")]
print(num)

A: You need to use a list comprehension to get the output [1,2,3,4,5]. It'll give you back a list as output.
The reason you are getting the error: TypeError 'int' object is not iterable
is because list() only takes objects that are iterable and an int is not iterable at all.
Here's some example code of the list comprehension that you can use:
returned_list = [int(x) for x in input("Enter your number: ")]
print(returned_list)

A: Try this
num = list(map(lambda x: int(x), input('Enter the number\n')))


text:
Q: After installing Ubuntu 13.04 and running boot-repair, Ubuntu fails to load, gets stuck with a blank screen I installed Ubuntu 13.04 on a Lenovo ThinkPad with Windows 8 preinstalled with great difficulty. To make it run, I edited the boot command by adding the following line:
acpi_osi=Linux acpi_backlight=vendor.

I was able to boot once into Ubuntu after running boot-repair. But then subsequent times onwards, I get stuck with a blank screen in spite of giving the above options. I ran boot repair a couple of times more using a live disk and a live USB. It still gets stuck.
http://paste.ubuntu.com/6339188/
I've noticed a few things. I've got a lot of partitions on my disk now. There is a partition for Windows 8, a partition for Lenovo backup files, 2 partitions (around 200GB each) for miscellaneous purposes and one more partition for Ubuntu. Everything else, I'm not sure how they've appeared. Can anyone guide me?

A: 1.First run this command on ubuntu,to know proper chaining was done or not,
sudo os-prober

IF it shows like this /dev/sda1:Windows 8 (loader):Windows:chain,then proceed to step 2.
2.Run the windows installation disk,select repair option and open the command prompt.Run    the below commands on the displayed command prompt
bootrec /fixmbr
bootrec /fixboot


text:
Q: Wordpress Pods: Find on Boolean Field I have a simple pod with a boolean called featured. I'm trying to use the find() method (using the pods() shortcut) to list all pod entries that have the featured boolean set to true on a page template but I can't get it to work. I found this answer but it's for the older version and doesn't seem to work in Pods 2.0. If there's a simpler way to do this please inform me what I'm trying something like this:
$params = array(
    'orderby' => 'date DESC',
    'where' => 'case_study.has_page = 1',
    'limit' => -1
);
$pods = pods( 'case-study', $params );

The error I receive is:
WordPress database error: [Unknown column 'case_study.has_page' in 'where clause']
SELECT DISTINCT 't'.* FROM 'wp_posts' AS 't' LEFT JOIN 'wp_postmeta' AS 'case_study' ON 'case_study'.'meta_key' = 'case_study' AND 'case_study'.'post_id' = 't'.'id' WHERE 'case_study'.'has_page' = 1 AND 't'.'post_type' = "case_study" ORDER BY 't'.'date' DESC, 't'.'menu_order', 't'.'post_title', 't'.'post_date'

Database Error; SQL: SELECT DISTINCT 't'.* FROM 'wp_posts' AS 't' LEFT JOIN 'wp_postmeta' AS 'case_study' ON 'case_study'.'meta_key' = 'case_study' AND 'case_study'.'post_id' = 't'.'id' WHERE 'case_study'.'has_page' = 1 AND 't'.'post_type' = "case_study" ORDER BY 't'.'date' DESC, 't'.'menu_order', 't'.'post_title', 't'.'post_date'; Response: Unknown column 'case_study.has_page' in 'where clause'

It appears that it's not JOINing/WHEREing to the wp_postmeta correctlyy but I can't quite figure out how to use the find params to do so. It should should be 'case_study'.'meta_key'='has_page' amongst other problems. I've tried making the field a simple relationship with a Yes/No option but still no luck.
Thank you for any help you can provide! It's much appreciated.

A: If your relationship field is named 'has_page' and it's a simple (custom) then you'll want to use this:
has_field.meta_value = 1

A: Found it! When editing the pod I went to the 'Advanced' settings tab and under 'Capability Type' I set it to 'Custom' from 'Posts.' Voila, it now works! I suppose this setting tells the find calls how to operate on the tables. My final find params were as follows:
$params = array(
    'orderby' => 'date DESC',
    'where' => 'has_page.meta_value = 1',
    'limit'   => -1
);
$casestudies = pods( 'case_study', $params );

Thank you so much Scott for being quick and an awesome help!

A: Final solution:
My original content type was an extension of post which doesn't seem to play well with relationship fields, at least basic ones, since it appears to assume they generate their own table which they don't always do. As in this case where, since it was a simple custom relationship, the data was all stored in the wp_postmeta table.
The best solution I found was to rebuild my pod as an Advanced Content Type. This way, the pod generates a table all to its own so checking booleans can be done with a simple 'where' => 'has_page' = 1 instead of all the relationship complexity. Thanks for all your help Scott.


text:
Q: Failure Behavior of Moose Role Modifier Functions Given the below code example, when running Main::main, if the eval block fails, I would assume that the 'after' block in the role would never run. However, I'm in the midst of debugging an intermittent and hard-to-pin-down error that would suggest this is not the case.
Could someone explain how the 'flattening' process works in this context, and if there are any conditions in which the eval would fail but the after block would run?
Thanks
Josh
package MyRole;
use Moose::Role;

after 'main' => sub {
    #some code that depends on main executing
};

package Main;
use Moose;
with 'MyRole';

sub main {
    eval {
        #main work
    };
    if ($@) {
        die 'what happens now?';
    }
}

A: If main dies, then the after modifier will not run.  However, it is possible for an eval to fail but $@ to be false.  It sounds like that must be what's happening here.  If the eval fails, but $@ is false, your error handling code won't run and main won't throw an exception.  Thus, the after main code will be run.
This is one of the things Try::Tiny protects you against.

A: *

*MyRole::main() would normally execute after Main::main().

*They are not exactly flattened into one method with one after the other in that what you return in Main::main() is still what gets returned and anything you return in MyRole::main() is ignored.

*If 'main work' fails, MyRole::main() will not execute since you also die in the catch (if $@) block, which means that the flow of execution dies before it reaches MyRole::main().


text:
Q: Error while building python docker container with uWSGI Here is my Dockerfile:
FROM python:3.7-alpine

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY . /usr/src/app

RUN apk --update add gcc build-base freetype-dev libpng-dev openblas-dev musl-dev
RUN apk update

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 5000

CMD ["uwsgi", "app.ini"]

When building uwsgi wheel got and error:
In file included from core/utils.c:1:
  ./uwsgi.h:238:10: fatal error: linux/limits.h: No such file or directory
    238 | #include <linux/limits.h>
        |          ^~~~~~~~~~~~~~~~

What package am i need to add to Dockerfile?+

A: Try adding apk add linux-headers, looks like uwsgi is missing some headers during the build, might be due to alpine being very bare-bones

A: I also ran in the situation that the container was not building the uwsgi.
After changing
"FROM python:3.8-alpine" to "FROM python:3.8"
everything worked fine.
Then i think you also don't need to install the linux-packages.


text:
Q: Is "labeled" an adjective or not? In most dictionaries "labeled" or "labelled" isn't recognized as an adjective but there are a few who do deem it to be an adjective. https://en.wiktionary.org/wiki/labeled Is this correct? Or is "labeled" merely the past tense of "label"?
Any input is as always greatly appreciated!


text:
Q: Double.MIN_VALUE - 1.0D Есть код:
System.out.println(Double.MIN_VALUE - 1.0D);

Почему его результатом будет -1.0?

A: Согласно стандарту IEEE-754 числа с точкой можно записывать в экспоненциальной форме. Этот формат дает боле-менее фиксированную точность (например, для 32бит - около 7 знаков), но в очень широком диапазоне (около +/-10 в 38 степени).
Так вот, MIN_VALUE это то минимальное, отличное от нуля, число (без учета знака), которое можно записать в этом формате (для 32бит - около 10^-38).
Соответственно, если вы берете очень малое число (Double.MIN_VALUE), и отнимаете от него единицу, то вы получите минус единицу и очень малую часть, которая будет утеряна, т.к. она не попадает в "точность" 7 знаков вокруг единицы.
То есть, грубо говоря у вас получается что-то типа -1.0000000000000000000000000000123, которое будет "округлено" и записано как -1.0000000.
Дополнительно: Почему при записи большого числа во float меняются цифры на конце?

A: Потому что Double.MIN_VALUE - это на самом деле не самое маленькое число, которое можно записать в double, а значение максимально близкое к нулю. Самое маленькое значение, которое вы можете сохранить в double является -Double.MAX_VALUE.

A: Потому что в java нет нуля. Это связано с тем, что невозможно представить 2 в такой степени, чтобы был 0. Для решения это проблемы ввели MIN_VALUE. Это наиболее близкое к нулю число (а не минимальное).
Более подробно можете почитать про представление чисел тут


text:
Q: Proof that the function on $C[0,b]$ is a contraction Question :
Let  $a$,$b$  be  real  numbers  with  $0\lt b\lt 1$ . Consider  the  subset  $X\subset C[0,b]$  consisting  of  the  functions  $f$  s.t $f(0)=a$ .Then  $X$  is  closed  in  $C[0,b]$.  Define , $$Tf(x) := a+\int_0^x  |f(t)|dt ,(0\le x\le b).$$
Prove  that $T$  is    contraction of $x$ and  there  is  a  unique  $f\in X$  satisfying  $$f'=|f| $$  on  $(0,b)$
My attempt :
$$T \ :\ X\subset C[0,b]  \rightarrow \mathbb R$$
 To  prove  contraction ,  I  have  to  show $$|Tf(x)-Tg(x)|\lt ||f(x)-g(x)||_{\infty}$$  where  $||\ .\ ||_{\infty}$  is  the  supremum norm  on  $C[0,b]$.
$$|Tf(x)-Tg(x)|=|(\int_0^x |f(t)|dt-\int_0^x |g(t)|dt)|$$
$$= |\int_0^x(|f(t)|-|g(t)|)dt\ \  |$$
$$\le |\ \int_0^x |f(t)-g(t)|dt\ |$$
$$\le \int_0^x |f(t)-g(t)|dt $$
$$\le sup_{t\in [0,x]} |f(t)-g(t)|.x$$
$$\lt ||f(t)-g(t)||_\infty ;\ \ as\ \ x\le b\lt 1\ $$
So  this  is  a  contraction .  But  I  don't  know  what  "contraction of x  "  means .
As  for  the  second  part  ,  by  Banach Contraction Principle   , there  is  a  $f\in X$  s.t  $$f(x)=a+\int_0^x  |f(t)|dt,(0\le x\le b)$$
 $$or \ \ ,\ \ f'(x)=|f(x)|$$
Is  my  proof  allright  $?$
I  am  a  little  skeptical  about  the  last  step  ,if  it  is  correct  or  not  . Correct  me  if  I  have  made  other  mistakes  also.
Thanks  for  any  help.


text:
Q: Grant "Network Service" Read Only Permissions to Cert for RDP via Batch I'm securing RDP by adding my SSL cert to my Windows host and of course, I'm working on scripting everything. I've got it 99% complete, the only step I can't figure out how to script is relating to permissions.
Eg: https://superuser.com/questions/1093159/how-to-provide-a-verified-server-certificate-for-remote-desktop-rdp-connection/1093160#1093160
1.Start > Run > mmc
2.File > Add Remove Snap-in > Certficates > Add > Computer Account > Local Computer > OK
3.In the left-hand window right-click on Certificates (Local Computer)Personal, choose All Tasks/Import…
4.Locate the pfx file and import it, I suggest that for security reasons you don't make it exportable.
5.Expanding your Personal/Certificates you should now see 3 certificates, one of which is your site certificate (e.g. mysite.com). Right-click on this site certificate and right-click, choose All Tasks / Manage Private Keys…
6.Add user 'NETWORK SERVICE' with Read permission only (not Full Control), then Apply
7.Close mmc
I'm trying to script step 6 in this guide. Does anybody have any ideas where to start?

A: There are 2 methods actually that I found to get this working. Of course the better answer came from StackOverflow and not Microsoft.
You can use winhttpcertcfg.exe which must be downloaded separately as it doesn't come with Windows. Another issue was it granted Full Control permissions when only Read was needed. I found no way to rectify this, but in my search I found a better way.
This command will grant NETWORK SERVICE READ Permissions to all files in the SSL Cert directory:
icacls.exe "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\*" /grant "NETWORK SERVICE":R

https://docs.microsoft.com/en-us/microsoft-desktop-optimization-pack/appv-v4/how-to-modify-private-key-permissions-to-support-management-server-or-streaming-server
https://docs.microsoft.com/en-us/windows/win32/winhttp/winhttpcertcfg-exe--a-certificate-configuration-tool
https://blogs.technet.microsoft.com/operationsguy/2010/11/29/provide-access-to-private-keys-commandline-vs-powershell/
https://stackoverflow.com/questions/1678584/winhttpcertcfg-giving-access-to-iis-user-in-windows-7


text:
Q: Closure of a Manifold is a Manifold with Corners? Is there a general theorem that shows that if you have a manifold $S$ then its closure $\overline{S}$ is a manifold with corners?  I am dealing with a specific set $S$ (I would rather not say which set it is) which is an open subset of a vector space, but really I'm much more interested in $\overline{S}$.  The only methods I know that I can use to show that $\overline{S}$ is a manifold with corners is either to construct coordinate charts (which seems rather daunting to me), or to find a clever group action $G \times X \to X$ of a group $G$ on some manifold with corners $X$ that will yield the quotient manifold $X/G \approx \overline{S}$.  This question might be rather vague, but I'm wondering if there is a general theorem for showing that the closure of a manifold is a manifold with corners (obviously with or without corner points).
For reference I'm reading some material out of Differential Topology by Margalef-Roig/Outerelo-Dominguez for the necessary background.
Edit: Thank you for the cool counterexamples that you're all contributing.  I'd like to augment my post to ask of potentially good methods, suggestions, and references to read up on manifolds with corners, specifically dealing with group actions.  Constructing coordinate charts seems like my best option, but if there are theorems involving group actions in addition to those presented in Roig/Dominguez I'd really like to know of them.


text:
Q: Amazon AWS S3 SDK for iOS drops connection (Error -1005) When running the AWSiOSDemoTVM project, the async S3 demo code will start uploading data, but the connection will be dropped after a couple of seconds.

AWSiOSDemoTVM: didFailWithError : Error Domain=NSURLErrorDomain
  Code=-1005 "The network connection was lost."UserInfo=0xb54e850
  {NSErrorFailingURLStringKey=https://BUCKETNAME.s3.amazonaws.com/asyncDemoKey,
  NSErrorFailingURLKey=https://BUCKETNAME.s3.amazonaws.com/asyncDemoKey,
  NSLocalizedDescription=The network connection was lost.,
  NSUnderlyingError=0xb5527f0 "The network connection was lost."}

Small uploads without using the asynchronous delegate will succeed.

A: I didn't set the correct endpoint for the bucket. The default endpoint only works for US buckets.
In AmazonClientManager.m, add the correct endpoint for your bucket region.
    s3  = [[AmazonS3Client alloc] initWithCredentials:credentials];
    s3.endpoint = @"https://s3-eu-west-1.amazonaws.com";

A list of regional endpoints for S3 and other AWS services can be found here


text:
Q: how to get an image from gallery or take from camera and insert it into an edittext? I'm new to Android programming.
What I'm trying to do is get a image from the gallery or take it from the camera, and insert into the edittext which might have texts on it. (e.g., text....text...text.. [IMAGE])
How should the code for getting a image and insert it into the selected cursor point of the edittext?

A: You can do this with 2 methods
1)With SpannableString
 SpannableString ss = new SpannableString("abc\n");
    Drawable d = img.getDrawable();
    d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
    ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    editText.setText(ss);

2) With CompoundDrawablesWithIntrinsicBounds
editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.image, 0, 0, 0);

A: Try this to do programmatically:
EditText et_EditImage = (EditText)findViewById(R.id.et_EditImage);
et_EditImage.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.tick), null);

Try this to do it in XML file:
<FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:id="@+id/search"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/search_bar"
                android:drawablePadding="8dp"
                android:paddingLeft="30dp"
                android:paddingRight="10dp"
                android:singleLine="true" >
                <requestFocus />
            </EditText>

            <Button
                android:id="@+id/searchBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left|center_vertical"
                android:layout_margin="10dp"
                android:background="@drawable/icon_magnify" />

            <Button
                android:id="@+id/delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right|center_vertical"
                android:layout_margin="8dp"
                android:background="@drawable/icon_remove" />
        </FrameLayout>

I found that on Here


text:
Q: first argument to append must be slice (struct and golang) hello i am a begginer in golang and i am working on a shopping cart app, every time i try to excute the code it shows  "first argument to append must be slice" here is the code
package cart
type Cart struct {
    items map[string]Item
}

type Item struct {
    id       string
    name     string
    price    float32
    quantity int
}

func NewItem(i string, n string, p float32) Item {
    return Item{
        id:       i,
        name:     n,
        price:    p,
        quantity: 0,
    }
}

func NewCart() Cart {
    return Cart{
        items: map[string]Item{}}
}

func (box *Cart) AddItem(item Item) []Item {
    box.items = append(box.items, item)
    return box.items
}

func main() {
    utils.CreateLogger("shopping-cart")
    shoppingCart := cart.NewCart()

    item1 := cart.NewItem("potato121", "Potato", 10)

    err := shoppingCart.AddItem(item1)
}

A: You get the error because you tried to add an object into a map using append(), on this line of code:
box.items = append(box.items, item)

Meanwhile the box.items type is a map[string]Item.
type Cart struct {
    items map[string]Item
}

The append() built in function can only be used on a slice data type.

I'm not sure what you are trying to do, whether to use a map or a slice as the type of .items. But if you want the .items property to be a slice, then change your code into this:
type Cart struct {
    items []Item
}

func NewCart() Cart {
    return Cart{
        items: make([]Item, 0)}
}

If you want the .items property to be a map, change your code into this:
func NewCart() Cart {
    return Cart{
        items: map[string]Item{}}
}

func (box *Cart) AddItem(item Item) map[string]Item {
    box.items[item.id] = item
    return box.items
}