text:
Q: jQuery hover to replace the HTM hover property with fade-in effect I am in search of a jQuery technique or plugin, using which our default hover property should become the fade-in jQuery hover property. Suppose if we place the mouse cursor on any div, its background should be fade-in hovered.
Please see this image.

A: You can also use CSS3 transitions. Even though CSS3 transitions aren't supported in IE you would still get the hover effect in IE just without the fade.
The basic idea is that you use JavaScript to add and remove a class on hover. You then use CSS3 transitions to animate the background colour transition.
HTML:

     Lorem Ipsum

     Dolor Etam

     Lorem Elar

JavaScript:
$('.entry').mouseenter(function (event) {
    $(this).addClass('active');
});
$('.entry').mouseleave(function () {
    $(this).removeClass('active');
});

CSS:
.entry {
    background: #fff;
    border-bottom: 1px dotted #ccc;
    -webkit-transition:background-color 2s,-webkit-transform 2s;
    transition:background-color 2s, transform 2s;
}

.entry.active {
    background: #ddd;
}

JSFiddle demo: http://jsfiddle.net/d57BW/
Reference for CSS3 transitions usage: http://caniuse.com/css-transitions

A: JQuery does not animate colors.
If you want to replace background color, use the jquery-color plugin
(The code for changing just the opacity without plugins is at the bottom)
Now the code for replacing color:
HTML:

TEST

CSS:
#myDiv{background-color:red; width:300px; height:200px; text-align:center;}

JS:
$("#myDiv")
  .mouseover(function() {
    $(this).animate({backgroundColor: "yellow"}, 'slow');
  })
  .mouseout(function() {
    $(this).animate({backgroundColor:"red"},'slow');
  });

Example here: http://jsfiddle.net/2khZe/
If you want just to chance the opacity of the already set background color, you dont need the plugin, and just replace the above js code to this:
$("#myDiv")
  .mouseover(function() {
    $(this).animate({opacity: 0.5}, 'slow');
  })
  .mouseout(function() {
    $(this).animate({opacity: 1},'slow');
  });

Example here: http://jsfiddle.net/w2Z7x/
Hope it helps you.
Theo.

A: without javascript
//this code your test
.entry{
    border:1px solid #ddd;
    height:120px;
    line-height:120px;
    font-size:20px;
    padding-left:10px;
    margin-bottom:0.5px;
    transition:background-color 0.7s linear 0.1s;
    -moz-transition:background-color 0.7s linear 0.1s;
    cursor:pointer;
}
.entry:hover{
    background-color:#eee;
    transition:background-color 0.7s linear 0.1s;
    -moz-transition:background-color 1s linear 0.1s;
}


text:
Q: Using "this" in a callback vs external variable and the garbage collector I just stumbled on the IndexedDB example on MDN which contains the following:
function openDb() {
    var req = indexedDB.open(DB_NAME, DB_VERSION);
    req.onsuccess = function (evt) {
        // Better use "this" than "req" to get the result
        // to avoid problems with garbage collection.
        // db = req.result;
        db = this.result;
    };
    // Rest of code omitted for brevity
}

What is the problem with the garbage collector that should better be avoided?

A: This advice looks weird: the object the req variable refers to (the same the this would refer to) as well as the anonymous function objects (which are hold by onsuccess, onerror and onupgradeneeded properties) would all be garbage collectible simultaneously as soon as the query has completed and callbacks have been invoked.
Technically - req represents another reference to the object; practically it cannot cause any "problems with garbage collection".
To summarize: it's neither an "optimisation" nor "micro optimisation", both would perform equally.

A: As far as I can tell if you reference 'req', 'openDb' invocation scope is tied to 'onsuccess' (as parent scope) so you create a closure. If - on the other hand - you reference only 'this', the 'openDb' invocation scope can be discarded as soon as you exit the function.
What might be causing confusion is that the object refered to by 'req' lives beyond the lifetime of 'openDb' - it is not used exclusiveley from within that function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use AspectScaledToFitAndCenterSizeFilter in kingFisher library in swift In my project I was using AlamofireImage in swift. Now we replaced AlamofireImage with the KingFisher library.  I have created a struct using below to fit the filter
struct AspectScaledToFitAndCenterSizeFilter: ImageFilter, Sizable {
    /// The size of the filter.
    let size: CGSize

    /// Initializes the `AspectScaledToFitSizeFilter` instance with the given size.
    ///
    /// - parameter size: The size.
    ///
    /// - returns: The new `AspectScaledToFitSizeFilter` instance.
    init(size: CGSize) {
        self.size = size
    }

    /// The filter closure used to create the modified representation of the given image.
    var filter: (UIImage) -> UIImage {
        { image in
            image.imageAspectScaledAndCenter(toFit: self.size)
        }
    }
}

When we are using AlmofireImage using the below code to set image url
imageView.af.setImage(withURL: imageURL.mediaURL(), placeholderImage: #imageLiteral(resourceName: "icMissingEntreeGrid"), filter: AspectScaledToFitAndCenterSizeFilter(size: imageSize))

Now I replace the code with
imageView.kf.setImage(with: imageURL.mediaURL(), placeholder:  imageLiteral(resourceName: "icMissingEntreeGrid"))

But how to add that "AspectScaledToFitAndCenterSizeFilter(size: imageSize)" using KingFisher library. Could anyone please help me out here. Thanks in advance.

A: To create Kingfisher image processor you need to implement ImageProcessor protocol:
class AspectScaledToFitAndCenterSizeFilter: ImageProcessor {
    /// Identifier of the processor.
    /// - Note: See documentation of `ImageProcessor` protocol for more.
    let identifier: String

    /// The size of the filter.
    let size: CGSize

    /// Initializes the `AspectScaledToFitSizeFilter` instance with the given size.
    ///
    /// - parameter size: The size.
    ///
    /// - returns: The new `AspectScaledToFitSizeFilter` instance.
    init(size: CGSize) {
        self.size = size
        identifier = "com.package.AspectScaledToFitAndCenterSizeFilter(\(size))"
    }

    func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
        switch item {
        case .image(let image):
            return image.imageAspectScaledAndCenter(toFit: self.size)
        case .data:
            return (DefaultImageProcessor.default |> self).process(item: item, options: options)
        }
    }
}

Usage:
imageView.kf.setImage(
    with: imageURL.mediaURL(),
    placeholder: #imageLiteral(resourceName: "icMissingEntreeGrid"),
    options: [
        .processor(AspectScaledToFitAndCenterSizeFilter(size: .zero))
    ]
)

Check out more processor usages in documentation.


text:
Q: Systematic review of the uses of the axiom of choice Is there some systematic study of which mathematical results requires the axiom of choice? A book or a review article. I don't mean only results without which some areas of mathematics would be hard to work with (for example, that $\mathbb{R}$ is Fréchet whose demonstration relies on the axiom of choice if I am not mistaken). But also the various kind of "monster" made possible by the axiom of choice (for example, non-Lebesgue-measurable subsets of $\mathbb{R}$).

A: The book "Consequences of the axiom of choice" is excellent, but rather high level. Perhaps more accessible is Herrlich's wonderful book, which was what I learned from initially. Jech also has a book on the axiom of choice, but this focuses more on building models where choice fails/holds in specific ways, not general applications/implications of the axiom.

A: There's the book 'Consequences of the Axiom of Choice' which can be found here.
Maybe there is some pdf online or something that's cheaper or available for free, but this definitely fits the bill.


text:
Q: Checksum Exception when reading from or copying to hdfs in apache hadoop I am trying to implement a parallelized algorithm using Apache hadoop, however I am facing some issues when trying to transfer a file from the local file system to hdfs. A checksum exception is being thrown when trying to read from or transfer a file.
The strange thing is that some files are being successfully copied while others are not (I tried with 2 files, one is slightly bigger than the other, both are small in size though). Another observation that I have made is that the Java FileSystem.getFileChecksum method, is returning a null in all cases.
A slight background on what I am trying to achieve: I am trying to write a file to hdfs, to be able to use it as a distributed cache for the mapreduce job that I have written.
I have also tried the hadoop fs -copyFromLocal command from the terminal, and the result is the exact same behaviour as when it is done through the java code.
I have looked all over the web, including other questions here on stackoverflow however I haven't managed to solve the issue. Please be aware that I am still quite new to hadoop so any help is greatly appreciated.
I am attaching the stack trace below which shows the exceptions being thrown. (In this case I have posted the stack trace resulting from the hadoop fs -copyFromLocal command from terminal)
name@ubuntu:~/Desktop/hadoop2$ bin/hadoop fs -copyFromLocal ~/Desktop/dtlScaleData/attr.txt /tmp/hadoop-name/dfs/data/attr2.txt

13/03/15 15:02:51 INFO util.NativeCodeLoader: Loaded the native-hadoop library
    13/03/15 15:02:51 INFO fs.FSInputChecker: Found checksum error: b[0, 0]=
    org.apache.hadoop.fs.ChecksumException: Checksum error: /home/name/Desktop/dtlScaleData/attr.txt at 0
        at org.apache.hadoop.fs.ChecksumFileSystem$ChecksumFSInputChecker.readChunk(ChecksumFileSystem.java:219)
        at org.apache.hadoop.fs.FSInputChecker.readChecksumChunk(FSInputChecker.java:237)
        at org.apache.hadoop.fs.FSInputChecker.read1(FSInputChecker.java:189)
        at org.apache.hadoop.fs.FSInputChecker.read(FSInputChecker.java:158)
        at java.io.DataInputStream.read(DataInputStream.java:100)
        at org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:68)
        at org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:47)
        at org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:100)
        at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:230)
        at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:176)
        at org.apache.hadoop.fs.FileSystem.copyFromLocalFile(FileSystem.java:1183)
        at org.apache.hadoop.fs.FsShell.copyFromLocal(FsShell.java:130)
        at org.apache.hadoop.fs.FsShell.run(FsShell.java:1762)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:79)
        at org.apache.hadoop.fs.FsShell.main(FsShell.java:1895)
    copyFromLocal: Checksum error: /home/name/Desktop/dtlScaleData/attr.txt at 0

A: I face the same problem solved by removing .crc files

A: You are probably hitting the bug described in HADOOP-7199. What happens is that when you download a file with copyToLocal, it also copies a crc file in the same directory, so if you modify your file and then try to do copyFromLocal, it will do a checksum of your new file and compare to your local crc file and fail with a non descriptive error message.
To fix it, please check if you have this crc file, if you do  just remove it and try again.

A: Ok so I managed to solve this issue and I'm writing the answer here just in case someone else encounters the same problem.
What I did was simply create a new file and copied all the contents from the problematic file.
From what I can presume it looks like some crc file is being created and attached to that particular file, hence by trying with another file, another crc check will be carried out. Another reason could be that I have named the file attr.txt, which could be a conflicting file name with some other resource. Maybe someone could expand even more on my answer, since I am not 100% sure on the technical details and these are just my observations.

A: CRC file holds serial number for the Particular block data. Entire data is spiltted into Collective Blocks. Each block stores metada along with the CRC file inside /hdfs/data/dfs/data folder. If some one makes correction to the CRC files...the actual and current CRC serial numbers would mismatch and it causes the ERROR!! Best practice to fix this ERROR is to do override the meta data file along with CRC file.

A: I got the exact same problem and didn't fid any solution. Since this was my first hadoop experience, I could not follow some instruction over the internet. I solved this problem by formatting my namenode.
hadoop namenode -format


text:
Q: Call async method in Office Fabric CommandBar onClick event using react hooks? I have a react hook style component in typescript. I'm using office uifabric as ui framework. I want to get the following pattern to work in a "best practice" manner:

*

*I have a component with an onClick event (in my case a CommandBar)

*User clicks on the action

*I make an async call to a backend api (the async part is whats causing me trouble here I think, and this is unfortunately a requirement).

*When the async call is complete, or fails. I want to show a MessageBar with information.

*All in all using as little code as possible, react hooks seems to have the ability to produce nice and condence code together with TypeScript. But I'm new to both things so I may be out on a limb here...

Creating a dummy fetch method that is NOT async causes my example code to work as expected. But when I have the async call, something gets lost and I do not get a re-render and visibility of the MessageBar. The api call is made though!
const UserProfile = () => {
  const [apiStatusCode, setApiResponseCode] = useState(0);
  const [showMessageBar, setShowMessageBar] = useState(false);

  const startAsync = () => {
    // With await here I get a compiler
    // error. Without await, the api call is made but
    // the messagebar is never rendered. If the call is not async, things
    // work fine.
    myAsyncMethod();
  };
  const toggleMessageBar = (): (() => void) => (): void => setShowMessageBar(!showMessageBar);

  const myAsyncMethod = async () => {
    try {
      const responseData = (await get('some/data'))!.status;
      setApiResponseCode(responseData);
      toggleMessageBar();
    } catch (error) {
      console.error(error);
      setApiResponseCode(-1);
      toggleMessageBar();
    }
  };

  const getItems = () => {
    return [
      {
        key: 'button1',
        name: 'Do something',
        cacheKey: 'button1', //
        onClick: () => startAsync()
      }
    ];
  };

  return (
    <Stack>

      <Stack.Item>
        <CommandBar
          items={getItems()}
        />
      </Stack.Item>

      {showMessageBar &&
      <MessageBar messageBarType={MessageBarType.success} onDismiss={toggleMessageBar()} dismissButtonAriaLabel="Close">
        Successfully retrieved info with status code: {apiStatusCode}
      </MessageBar>
      }

      // Other ui parts go here
    </Stack>
  )
};

export default UserProfile;

Assigning an async method to the onClick event gives compiler error:
Type 'Promise<void>' is not assignable to type 'void'.  TS2322
Not awaiting the async call causes react not re-rendering when call is complete.

A: A common pattern for this sort of thing it to update your state in the callback as you are doing, and then respond to the new data with useEffect:
useEffect(()=>{
    setShowMessageBar(!showMessageBar)
},[apiStatusCode, showMessageBar])

const myAsyncMethod = async () => {
    try {
      const responseData = (await get('some/data'))!.status;
      setApiResponseCode(responseData);
      // toggleMessageBar(); <-- delete me
    } catch (error) {
      console.error(error);
      setApiResponseCode(-1);
      // toggleMessageBar(); <-- delete me
    }
  };

A: Found the answer eventually, the key was to use reacts useEffect mechanism. This answer led me to the solution:
Executing async code on update of state with react-hooks
Key changes in my code:
Create a state to track execution
const [doAsyncCall, setDoAsyncCall] = useState(false);

Set the state in the onClick event:
  const getItems = () => {
    return [
      {
        key: 'button1',
        name: 'Do something',
        cacheKey: 'button1', //
        onClick: () => setDoAsyncCall(true)
      }
    ];
  };

Wrap the async functionality in a useEffect section that depends on the state:
  useEffect(() => {
    async function myAsyncMethod () {
      try {
        const responseData = (await get('some/data'))!.status;
        setApiResponseCode(responseData);
        setShowMessageBar(true);
      } catch (error) {
        console.error(error);
        setApiResponseCode(-1);
        setShowMessageBar(true);
      }
    }

    if (doAsyncCall) {
      myAsyncMethod();
    }
  }, [doAsyncCall]);


text: Q: How to change woocommerce default theme - hello elementor I need to stack 2 products on one product page in woocommerce. I have got template with product on the left side. Right side product I'm adding with shortcode 'product_id = x' (filled from custom fields) and it got different template, i think it's woocommerce default template. How can I change it? I'm using hello elementor and it doesn't have woocommerce folder in wp-content/hello-elementor.


text:
Q: how to open python webservice in browser I have a code for simple HelloWorld webservice in python 3 :
from werkzeug.wrappers import Request, Response

@Request.application
def application():
    return Response('Hello World!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, application)

I want to test this in a browser... I tried to open url : "http://localhost:4000/application" but it is giving an error "500".
How to solve this?

A: Issue has been solved. Change
def application(): to def application(request):


text:
Q: python script is not executed via crontab I have a python script test.py (fyi, it contains some crawling logic)
and want it to be executed every one minute.
So I write a shell script weekjob.sh( tried each all below)
python /path/test.py
/usr/bin/python /path/test.py
cd /path && /usr/bin/python test.py

and then register a job
* * * * * /bin/sh /path/weekjob.sh

But python is not executed.
When I execute the shell script like sh weekjob.sh
it worked just fine. And when I changed the contents of weekjob.sh as mkdir something cronjob also worked well, too.
what is wrong with my python cron job?
(OS is centOS)

A: I found the answer.
It was the problem of proxy thing.
cronlog shows below error.
Traceback (most recent call last):
  File "/home/deploy/crawlingScript/proxyTest.py", line 41, in <module>
    converter = xml2csv(new_url, username, password, output_file_name, encoding="utf-8")
  File "/home/deploy/crawlingScript/converterOld.py", line 13, in __init__
    response = urllib2.urlopen(request)
  File "/usr/lib64/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib64/python2.6/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/usr/lib64/python2.6/urllib2.py", line 409, in _open
'_open', req)
  File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
  File "/usr/lib64/python2.6/urllib2.py", line 1190, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib64/python2.6/urllib2.py", line 1165, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>

I set proxy in .bashrc but cron has some problem with it I think.
So, I just added some code for proxy in .py file.
and found another solution thanks to @WillemM
* * * * * . /path/.bashrc; /bin/sh /path/to/sh/test.sh

.bashrc is the file that contains proxy setting.

A: Instead of doing
* * * * * /bin/sh /path/weekjob.sh

why dont' you drop the /bin/sh like this:
* * * * * /path/weekjob.sh

And first ensure that that script is executable:
chmod +x /path/weekjob.sh


text:
Q: How to use a custom function in jquery I have been looking for sliding in different directions via jquery . I have found a custom function in stackoverflow . But I don't know how to use it .
$.fn.fadeSlideRight = function(speed,fn) {
return $(this).animate({
    'opacity' : 1,
    'width' : '750px'
},speed || 400, function() {
    $.isFunction(fn) && fn.call(this);
});

}
Please tell me where to paste it and how to use it. Thanks in advance .

A: You just need to place it before you use it (probably near the beginning of your script) and can call it like so:

$.fn.fadeSlideRight = function(speed,fn) {
  return $(this).animate({
    'opacity' : 1,
    'width' : '750px'
  },speed || 400, function() {
    $.isFunction(fn) && fn.call(this);
  });
};

$("#test").fadeSlideRight(500,function(){
    alert("fadeSlideRight callback");
  });
#test{
  opacity:0;
  width:100px;
  background-color:red;
  height:50px;
}

test


text:
Q: Can httpd check permissions of private key file used with SSL certificate? Is it possible to have httpd fail a configtest if a SSLCertificateKeyFile value exists, and points to a file with any permissions other than the minimum necessary for reading the key?  I have httpd running as root initially, and switching to a different user after startup.  The private key file should be owned by root with group root and permissions 400.  Anything more permissive should cause a warning or startup failure.
The ssh client has behavior similar to this; if you try to use a private key whose permissions are too open, it fails.

A: Depends how big is your shop. If it is a requirement, you can patch apache to have this and may be try to add it upstream. Keep the patched apache in a local repository and distribute it to the local servers.
You can also change the apache startup scripts to check the configuration and extract the filenames that have the SSL keys and do a check on their permission.
3rd option would be to create an systemtap script that checks when apache tries to open the keys logs an error and kills apache.
4th option - use inotify and check when the keys are read, check if they are opened by apache daemon, log an error, then kill apache.

A: It might be simpler to just deploy a cron job like this:
1 * * * * chown -R root:root /etc/apache/keys; chmod -R 400 /etc/apache/keys/*

Apache will always start without errors (unless you have just changed the permissions on the SSL files) and even if someone changes the permissions while Apache is running they will be changed back within the hour.  That job is low impact enough you could even have it run every minute on a production system with no concerns.
If you deploy your SSL keys with Puppet (or similar), you can also configure Puppet to enforce the ownership and permissions for those files.  Of course, then you have to deal with the keys being stored in Puppet.


text:
Q: AJAX Done() function with for loop I have a for loop that iterates through an array of 3 values (different report numbers), and sends an AJAX request for each one. I want the .done() function to behave differently for each report that is returned. However, I'm not sure how to make the report number available to the done function. If I don't pass in the report number as an argument to the done() function, then it always thinks the report number is '190', the last value in the array. If I do pass it in, as below, it shows up as undefined.
function runQueries(request, data) {
    var reports = ['103', '187', '190'];
    for (i=0; i < reports.length; i++) {
        var report = reports[i];
        $.ajax({
        url: request + '&reportType=' + report},
        data: data
        })
        .done(function(response, textStatus, jqXHR, report) {
            if (report === '187') {
            ...
            }
            else if (report === '190'( {
            ...
            }

A: The issue with is report is changing quicker than you requests can complete. You can avoid that with a closure. Keep in mind this won't happen in order.
var reports = [ 1, 2, 3 ];

for( var i = 0; i < reports.length; i++ ){
    var report = reports[i];
    console.log(report);
    (function(report){
        $.ajax({
            url: '/echo/html',
        }).done(function(){
            switch( report ){
                case 3: console.log('Three!'); break;
                case 2: console.log('Two!'); break;
                case 1: console.log('One!'); break;
            }
        });
    })(report);
}

Here is it in a fiddle: http://jsfiddle.net/2ArxZ/
If you don't want to create functions in your loop, you can use this then call it in the loop.
function getReport( report ){
  return function(){
    $.ajax({
        url: '/echo/html',
    }).done(function(){
        switch( report ){
            case 3: console.log('Three!'); break;
            case 2: console.log('Two!'); break;
            case 1: console.log('One!'); break;
        }
    })();
  }
}

You could also simply use $.each instead, but understanding closures helps out a lot so I went the long way!

A: closures and scope :
function runQueries(request, data) {
    var reports = ['103', '187', '190'];
    for (i=0; i < reports.length; i++) {
        (function(report) {
            $.ajax({
                url: request + '&reportType=' + report},
                data: data
            }).done(function(response) {
                if (report === '187') {
                      ...
                } else if (report === '190'( {
                      ...
                }
            });
         })(reports[i]);
    }
}

The done() method is asynchronous, so by the time that fires, the loop has long since completed.
You could also just use $.each to do the iteration.


text:
Q: How to populate a field inside array with aggregation here is the query that I used to return an object from array of elements by using the _id. It looks like this,
db.users.aggregate([
    {$match: { "business_idea._id": ObjectId('613ee10818bc570bceb1d060') }},
    {$project: {
        business_idea: {$filter: {
            input: '$business_idea',
            as: 'bi',
            cond: { $eq: ["$$bi._id", ObjectId('613ee10818bc570bceb1d060') ] }
        }}
    }}
])

This query produces output like this,
{
    "_id" : ObjectId("613e418f19968b0652bbbb24"),
    "business_idea" : [
        {
            "business_tags" : [
                ObjectId("613ee063b11cee0b7dde1086")
            ],
            "_id" : ObjectId("613ee10818bc570bceb1d060"),
            "business_id" : "613ee10818bc570bceb1d05f",
            "business_name" : "Business_2",
            "business_type" : "No type",
            "business_desc" : "desc, desc-2",
            "business_logo" : "https://neur-dev.s3.ap-south-1.amazonaws.com/logo/21091631510791555.jpeg",
            "isDeleted" : false,
            "business_name_to_lower" : "business_2"
        }
    ]
}

Now I just want to populate the real value of business_tags from businesstags collection by using _id.
can anyone help me with this,
Thanks.

A: To find related tags you must get them by $lookup aggregate like this:

{
"$lookup":{
  from: 'businesstags',
  localField: 'business_tags',
  foreignField: '_id',
  as: 'new_tags'
}
}


text:
Q: Drupal, Joomla and WordPress benchmark results So there is this benchmark at http://sven.webiny.com/benchmark-webiny-vs-wordpress-vs-drupal-vs-joomla-vs-tomatocms/
Can I really trust it? I mean it came as a surprise to me that Drupal is so much faster than Wordpress and Joomla. I always thought of it as a super heavy CPU devouring monster compared to the aforementioned.

A: That benchmark is like comparing a train with a plane. Yes, a plane is faster, but that doesn't mean that you should take a plane to commute to work.
A CMS is just a tool, and you need the tool that is most suitable for your project. There is a huge difference between a corporate brochure (5 pages, little interaction, no logged in users), a blog (100 pages, some interaction, some logged in users) and a community platform (10000 pages, lots of interaction, most users logged in). I think every CMS in that benchmark can be the top performer for a specific type of site.

A: Benchmarking stock installs of these three CMSes is useless. No one uses them without additional modules (which often have major performance implications), and anyone competent is going to set up performance enhancers like caching.
Do note, also, that the CMS that comes out on-top for every benchmark category is the blog author's own project.

A: Wordpress with a caching plugin would be just as fast.
Put NGINX in front of the webserver, and what CMS you use is immaterial. The site will be much faster.
Put your site's static assets on a CDN, and even better.
WP is easy to work with and expand. Drupal takes a gazillion modules and many queries per page. Both have excellent caching modules.
This is 2011. Not 1999. Frontend "performance" of a website to a visitor has very little to do with the backend. Movable Type would be the fastest of all of these because it writes out plain HTML files, but who wants to use the archaic CGI technology with limited plugins.

A: I have to say I'm a big fan of Joomla. If you're new to CMS, Joomla has much
less of a learning curve - and despite statements to the contrary - is just as
capable as Drupal for running large/popular sites. But choosing a proper CMS
depends on your experience level and the time you have to spend on the project.
To know more about the differences among your mentioned CMSs refer to

Comparison of Top 3 CMSs: WordPress vs Drupal vs Joomla. There you can get
the detailed info in a simple format.


text:
Q: Adding web accessibility to twitter bootstrap accordion I trying to add Keyboard Navigation to Twitter bootstrap accordion to enable web accessibility, Similar to http://hanshillen.github.io/jqtest/#goto_accordion.
I couldn't do the following:

*

*Once the focus is on Accordion Tabs, I couldn't just navigate
accordion header. When I hit tab, it navigates the all inner links
in the group, then to the next heading.

*I couldn't use up/down arrow keys

*After last accordion header tab thro', focus shifts outside the
accordion.

Link to page
<!DOCTYPE html>

<meta charset="utf-8">
<title>Getting Started</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">

Hello

                                Collapsible Group Item #1

                                    More information about Dogs on Wikipedia

                                Collapsible Group Item #2

Anim pariatur cliche...

                                    More information about Dogs on Wikipedia

A: So here is what I am going to do for lack of a better solution:
To .collapse I will add a display:none; This will hide it from sighted users as well as screen readers. Then to .in I'll add display:block;, which will make it visible to both again. So then, it skips the content in the tab order when closed, and adds it back when open.
so:
    .collapse {
       display:none;
    }

    .in{
       display:block;
    }

I haven't tested on screen reader yet, but I think it should work for down-arrow back into reading text. I'll update if not.


text:
Q: Data validation in excel 2007 I am trying to restrict the inputs of certain cells in my excel worksheet as follows:
1-7,10,12, which means that only numbers 0 to 9 and symbols - and , can appear in the cell. I would like to ideally handle it in a non-vba based Data validation manner, but even a vba based solution will be ok.
EDIT - There is one keyword which would be an exception, 'Fixed', if I see this word it would be allowed.

A: The VBA version using Regex object: I just wrote the function. You can simply call this function within the Sheet change event. (like how Siddharth has used). And one other thing, each time user enters wrong characters, the function deletes them all :D... Then again, you need to be aware that to make sure this operation happens within a particular range of your choice.. coz otherwise it can erase any cell that's being changed!!! Given Siddtharth's post for infinite loops within this `worksheet change event, I have edited the code to include that bit as well.
    Option Explicit

    '-- within sheet change event
    Private Sub Worksheet_Change(ByVal Target As Range)
       On Error GoTo Zoo
       Application.EnableEvents = False
       Call NumbersAndCommaDashOnly(Target)

       GetBack:
       Application.EnableEvents = True
       Exit Sub
   Zoo:
       MsgBox Err.Description
       Resume GetBack
    End Sub

Function NumbersAndCommaDashOnly(ByRef rngInput As Range) As String
Dim objRegex As Object
Dim strInput As String

Set objRegex = CreateObject("VBScript.RegExp")
objRegex.IgnoreCase = True
objRegex.Global = True
objRegex.Pattern = "^[-,0-9]+$|^[Fixed]$"

If Not IsNull(rngInput.Value) Then
    strInput = rngInput.Value
Else
    NumbersAndCommaDash = "Empty Range"
    rngInput.Value = ""
    Exit Function
End If

If objRegex.Test(rngInput.Value) Then
    NumbersAndCommaDash = objRegex.Replace(rngInput, "")
Else
    NumbersAndCommaDash = "No numbers found"
    rngInput.Value = ""
End If

End Function

*

*For an Excel Formula based solution, you may look into this MSDN article.

A: Here is a VBA Approach for just cell A1.
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim i As Long

    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        If Len(Range("A1").Value) <> 0 Then
            For i = 1 To Len(Range("A1").Value)
                Select Case Asc(Mid(Range("A1").Value, i, 1))
                '~~> Check for 0-9, "," and "-"
                Case vbKey0 To vbKey9, 44, 45
                Case Else
                    Range("A1").ClearContents
                    MsgBox "Invalid Value"
                    Exit For
                End Select
            Next
        End If
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

The code goes in the Sheet1 code area.

Screenshot (Code in Action)

FOLLOWUP to the recent edit in the question
Change the line
If Len(Range("A1").Value) <> 0 Then

to
If Len(Range("A1").Value) <> 0 And _
UCase(Range("A1").Value) <> "FIXED" Then


text:
Q: Reverse MemoryStream.ToArray() I am getting an httpwebresponse stream (of a flash file), and I would like to save it as binary and later access that binary and display it as flash.  Right now, I am writing the response stream to a MemoryStream and then calling ToArray() on the MemoryStream.  I get a handy byte[].
How do I reverse that function?  How do I get the stream of the flash file from the byte[] I've generated?
Thanks!

A: Super easy:
Stream s = new MemoryStream(byteArray);

More info: http://msdn.microsoft.com/en-us/library/e55f3s5k.aspx

A: You can use this:
var s = new MemoryStream(byteArray);


text:
Q: Placing JToggleButton with JPanel within into a JTable cell I need to have a JToggleButton (that has custom background) that contains a JPanel with several JLabels within itself. That part works.
This button is placed afterwards in a JTable cell and is meant to be pressed by users. The problem is that i can only press the button on the second click. Apperenty on the first click the focus first jumps to the panel with JLabels and only afterwards to the actual button.
I tried several things to try solving this issue, but the same issue persists.
A) placing the JPanel with labels directly onto the JToggleButton#add().
B) using JLayeredPane to place Button and JPanel onto different Layers where JToggleButton takes constraint Integer(-) so that the JPanel with JLabels stays visible on top
Do you have any tips? Thanks
Below is a sample code that illustrates the problem. Clicking on the button only works second time.
public class ClickableCustomButtonInTable extends JToggleButton {

public ClickableCustomButtonInTable() {
    Dimension d = new Dimension(100, 100);
    JLabel lFirst = new JLabel("1st label");
    lFirst.setPreferredSize(d);

    JLabel lSecond = new JLabel("2nd label");
    lSecond.setPreferredSize(d);

    JPanel panel = new JPanel();
    panel.setOpaque(true);

    panel.setLayout(new BorderLayout());
    panel.add(lFirst, BorderLayout.NORTH);
    panel.add(lSecond, BorderLayout.SOUTH);
    add(panel);
    addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button clicked");
        }
    });
}

private static class CustomButtonRenderer implements TableCellRenderer {

    private final ClickableCustomButtonInTable button = new ClickableCustomButtonInTable();

    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        return button;
    }
}

private static class CustomButtonEditor extends AbstractCellEditor
        implements TableCellEditor {

    private final ClickableCustomButtonInTable button = new ClickableCustomButtonInTable();

    @Override
    public Object getCellEditorValue() {
        return button.getText();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
            Object value, boolean isSelected, int row, int column) {
        return button;
    }

}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(200, 200));
    Container content = frame.getContentPane();
    TableModel model = new AbstractTableModel() {

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return null;
        }

        @Override
        public int getRowCount() {
            return 1;
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return ClickableCustomButtonInTable.class;
        }
    };

    JTable table = new JTable(model);
    // table.setBounds(new Rectangle(0, 0, content.getWidth(), content
    // .getHeight()));
    table.setRowHeight(frame.getHeight());
    table.setDefaultRenderer(ClickableCustomButtonInTable.class,
            new CustomButtonRenderer());
    table.setDefaultEditor(ClickableCustomButtonInTable.class,
            new CustomButtonEditor());

    content.add(table);
    content.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

A: When the table captures a mouse event to select a cell it passes the mouse event on to the deepest component regardless of whether that component can handle mouse events. In your example the first click ends up on one of the JLabels, bypassing the JToggleButton completely.  Once the JToggleButton has become the active cell editor, mouse clicks work upon it normally. If it was to lose the focus, it would once again require two-clicks to activate.
You can also see this if you notice in your demo you click on the button border, not on the contained panel, the button works as desired.
One way to work around this is to ensure that any mouse event that is targeted at any component within the JToggleButton. You can do this using this static method:
static void addEventBubble(final Container target, Container container) {
    for(Component comp:container.getComponents()) {
        if (comp instanceof Container) {
            addEventBubble(target, (Container) comp);
        }
        comp.addMouseListener(new MouseAdapter() {
            private MouseEvent retarget(MouseEvent e) {
                return new MouseEvent(target, e.getID(), e.getWhen(),
                        e.getModifiers(), e.getX(), e.getY(),
                        e.getClickCount(), e.isPopupTrigger(),
                        e.getButton());
            }

            public void mousePressed(MouseEvent e) {
                MouseEvent r = retarget(e);
                for(MouseListener listen:target.getMouseListeners()) {
                    listen.mousePressed(r);
                }
            }

            public void mouseReleased(MouseEvent e) {
                MouseEvent r = retarget(e);
                for(MouseListener listen:target.getMouseListeners()) {
                    listen.mouseReleased(r);
                }
            }

            public void mouseClicked(MouseEvent e) {
                MouseEvent r = retarget(e);
                for(MouseListener listen:target.getMouseListeners()) {
                    listen.mouseClicked(r);
                }
            }
        });
    }
}

and then at the end of your constructor invoke:
addEventBubble(this,this);

After this any mouse event upon any component within the button will also reach the button and hence change its state. After doing this, I found the button reacted to every click as desired.

A: http://www.coderanch.com/t/570021/GUI/java/click-event-custom-JToggleButton-JTable


text:
Q: All SharePoint dbs are recovery pending After a power outage, where everything went down, all SharePoint databases have Recovery Pending status.
It was a relatively fresh install and no backups have been made yet (don't shoot me, I'll do it myself).
When I try to open them I get not accessible like this one https://dba.stackexchange.com/questions/21817/sql-server-2008-the-database-dbname-is-not-accessible
But the permissions had been fine until the outage, so I do not think it could be that. Currently I cannot assign permissions for the non-accessible databases, because they throw not-accessible error.
I tried restarting everything from the scratch, making sure that storage, witness disk, etc. were available before SQL service kicked in - same issue.
All non-SharePoint databases on that SQL are just fine, working, responding and fully available.
SQL 2014, clustered. SP 2016.
Please advise.

A: We had a similar situation with SharePoint DBs on a volume that ran out of drive space. After expanding the volume (something you don't need to do)...
Opened SQL Server Management Studio, right-clicked each DB, select "all tasks" "Take offline. Then "Bring Online".
The databases mounted, with "Recovery Pending" message gone.

A: You won't be able to access the databases until the recovery process has completed.
You may be able to bring them back online with recovery like so:
RESTORE DATABASE YourDatabase WITH RECOVERY

During the recovery process, you can check the status/progress like so (from this article, for reference:
DECLARE @DBName VARCHAR(64) = 'databasename'

DECLARE @ErrorLog AS TABLE([LogDate] CHAR(24), [ProcessInfo] VARCHAR(64), [TEXT] VARCHAR(MAX))

INSERT INTO @ErrorLog
EXEC master..sp_readerrorlog 0, 1, 'Recovery of database', @DBName

SELECT TOP 5
     [LogDate]
    ,SUBSTRING([TEXT], CHARINDEX(') is ', [TEXT]) + 4,CHARINDEX(' complete (', [TEXT]) - CHARINDEX(') is ', [TEXT]) - 4) AS PercentComplete
    ,CAST(SUBSTRING([TEXT], CHARINDEX('approximately', [TEXT]) + 13,CHARINDEX(' seconds remain', [TEXT]) - CHARINDEX('approximately', [TEXT]) - 13) AS FLOAT)/60.0 AS MinutesRemaining
    ,CAST(SUBSTRING([TEXT], CHARINDEX('approximately', [TEXT]) + 13,CHARINDEX(' seconds remain', [TEXT]) - CHARINDEX('approximately', [TEXT]) - 13) AS FLOAT)/60.0/60.0 AS HoursRemaining
    ,[TEXT]

FROM @ErrorLog ORDER BY [LogDate] DESC

Once the process has completed, assuming no corruption, the databases should once again be accessible. If they aren't, you may want to investigate for corruption and/or other errors like so:
DBCC CHECKDB ('YourDBname') WITH NO_INFOMSGS, ALL_ERRORMSGS


text:
Q: Next/React - Loop (add 1 row per 125 data length The goal of the below code is to loop the size of the textarea depending on the length of the data extracted.
{
  logData.description.length < 125 ? (
    <>
      <FormControl
        id='descriptionFormID'
        ref={textAreaRef}
        value={logData.description}
        as='textarea'
        rows={1}
        placeholder='Comment'
        className='mr-sm-2 bg-white'
        disabled
      />
    </>
  ) : (
    <></>
  );
}
{
  logData.description.length > 125 && logData.description.length < 250 ? (
    <>
      <FormControl
        id='descriptionFormID'
        ref={textAreaRef}
        value={logData.description}
        as='textarea'
        rows={2}
        placeholder='Comment'
        className='mr-sm-2 bg-white'
        disabled
      />
    </>
  ) : (
    <></>
  );
}

I'm adding 1 row per 125 length.
Example:

*

*1 row = 125 characters

*2 row = 250 characters

A: You can use Math.ceil(logData.description.length/125) to get an integer that increments by 1 for every 125 length your description data has, then just plug that number into your rows.
<>
  <FormControl
    id="descriptionFormID"
    ref={textAreaRef}
    value={logData.description}
    as="textarea"
    rows={Math.ceil(logData.description.length/125)}
    placeholder="Comment"
    className="mr-sm-2 bg-white"
    disabled/>
</>


text:
Q: How can I loop a Keyframe css color animation? I want my css animation to loop the background color every second but I don't know how to get it to loop? I just want to know if this is possible without javascript. If it's not, then thats fine.
body {
    background-repeat: no-repeat;
    background-size: cover;
    font-family: 'Roboto', sans-serif !important;
    position: relative;
    animation-name: color;
    animation-duration: 6s;
}
@keyframes color {
    0% {background-color: white;}
    20% {background-color: green;}
    40% {background-color: aqua;}
    60% {background-color: red;}
    80% {background-color: yellow;}
    100% {background-color: purple;}
}

A: body {
    background-repeat: no-repeat;
    background-size: cover;
    font-family: 'Roboto', sans-serif !important;
    position: relative;
    animation-name: color;
    animation-duration: 6s;
    animation-iteration-count:infinite; /* add this line */
}


text:
Q: How do I apply only one file or two classes from a Puppet Master server? Let us say that I have a case in which I need to apply only two files from a Puppet configuration on some production servers, without touching the rest of the configuration.
/opt/aservice/myfile/thekey.conf
/opt/myfile/thekey.salt
Let's also say that these are controlled by the following Puppet manifest:
#
# author: Nathan Basanese (nathan@basanese.com)
# date: 04/17/2048
#

class keyconfig ( $cluster ){
    notify {"Deploying key config. files to $fqdn":}

    file {'/opt/aservice/key/config/thekey.conf':
                ensure => present,
                mode => '0644',
                owner => 'aservice-serv',
                group => 'aservice-serv',
                source => "puppet:///modules/keyconfig/$cluster/thekey.conf",
        }
    file {'/opt/aservice/key/config/thekey.salt':
                ensure => present,
                mode => '0644',
                owner => 'aservice-serv',
                group => 'aservice-serv',
                source => "puppet:///modules/keyconfig/$cluster/thekey.salt",
        }
}

How would I apply ONLY these two files to a given server from a Puppet Master?
Perhaps, in the puppet agent command that is run on the target server, could I specify a specific Puppet class to use?
I have used the puppet resource command before, but I'm not sure that would work, here.

A: Every resource is automatically tagged with the fully qualified name of the class or defined type in which it is declared, and with every namespace  segment of the class or type name, among other tags.  You can use those tags to filter the resources that will be applied during a given catalog run.  In the particular example you describe, you could use
puppet agent --no-daemonize --onetime --tags keyconfig

to apply only the resources declared in class keyconfig (and in any other class declared by keyconfig, recursively, but in this case there are no such other classes).
You can also declare tags manually by using the tag metaparameter in your resource declarations.  That can allow you to provide for identifying custom collections of resources.  And speaking of collections, you can use tags in the selection predicates of resource collectors, too.

A: The only way to do that is to have that node contain only the class you are wanting to have applied. In your site.pp you would have the following where the 'myhost.dns' is your fqdn. and $mycluster would be replaced by your cluster string.
node 'myhost.dns' {
    class { 'keyconfig':
      cluster => $mycluster,
    }
}


text:
Q: AMP version of e-commerce without plugin I have two product pages of an ecommerce website: one made with Woocommerce (in WordPress) and one I coded my self in AMP.
Here is the WordPress page, and here is the AMP page. Not taking into account that the two pages are on two different subdomains, how would I redirect mobile users to the AMP version of the page ?
A similar question was asked, but it only specified how to do it for simple pages, not product pages.
Does anyone know how to that?


text:
Q: Density in R plot I am trying to plot the density of the gamma distribution.
x<-seq(0,10000,length.out = 1000)
plot(density(rgamma(1000,shape = 7,scale = 120)))
plot(dgamma(x,shape=7,scale=120),col="red")

But, I don't understand why both plots are totally different.

A: Since you didn't supply x in the final call, the x coordinates defaulted to the indices 1,2,3,...1000 of the vector dgamma(x,shape=7,scale=120) rather than the intended 0,10,20,....
If you do:
x<-seq(0,10000,length.out = 1000)
plot(density(rgamma(1000,shape = 7,scale = 120)))
points(x,dgamma(x,shape=7,scale=120),type = "l", col="red")

Then the graph is:


text:
Q: Unable to access SD card on Debian Stretch I can't access my SD card, not via the internal SD card reader of my laptop, nor via an external SD card reader.
I tried to use dmesg to find the cause of the issue, but when I attach the SD card to the internal reader nothing at all happens. Attaching it externally leads to:
[140886.727796] usb 4-1.2: new full-speed USB device number 9 using ehci-pci
[140886.799854] usb 4-1.2: device descriptor read/64, error -32
[140886.975877] usb 4-1.2: device descriptor read/64, error -32
[140887.151952] usb 4-1.2: new full-speed USB device number 10 using ehci-pci
[140887.223971] usb 4-1.2: device descriptor read/64, error -32
[140887.399956] usb 4-1.2: device descriptor read/64, error -32
[140887.576009] usb 4-1.2: new full-speed USB device number 11 using ehci-pci
[140887.984099] usb 4-1.2: device not accepting address 11, error -32
[140888.056121] usb 4-1.2: new full-speed USB device number 12 using ehci-pci
[140888.464233] usb 4-1.2: device not accepting address 12, error -32
[140888.464405] usb 4-1-port2: unable to enumerate USB device

How may I resolve this problem, preferably get the internal SD card reader to work, and access my SD card?
edit: the listed daemon messages are related solely to the external card reader. I've just tried the card reader on a second system and the same errors are printed. It seems like either the device doesn't work with linux or is broken after all.
The internal card reader still doesn't work and shows no reaction, based on dmesg
edit2: the internal SD card reader works fine on windows.


text:
Q: Is it possible to put documents in the launcher? Is it possible to put documents in the launcher and if yes, how?

A: I didn't find a 'normal' way to do it, so I made a bash script do the job.
Well, here's the script:
#!/bin/bash
#This script adds to launcher a specific document that the user has selected
#After specifying the document and its icon DO NOT remove them from their original position in your disk

#THE ICON SHOULD NOT HAVE SPACES IN ITS PATH AND TO BE A PNG FILE
# VALID PATH EXAMPLE:
#  /usr/share/pixmaps/wallch.png
# INVALID PATH EXAMPLE:
# /home/alex/Pictures/MY PICS/pic.png

document=$(zenity --file-selection --title="Select the document")
if [[ "$document" == "" ]]; then
   exit #no document specified
fi

icon=$(zenity --file-selection --title="Select an icon for it")
if [[ "$icon" == "" ]]; then
   exit #no icon specified
fi
name=$(basename "$document")
desktop_name=$(echo $name | tr ' ' '_')

echo "
[Desktop Entry]
Name=$name
Comment=Open me
Exec=xdg-open \"$document\"
Icon=$icon
Terminal=0
Type=Application
Encoding=UTF-8
Categories=Utility;Application;" > ~/.local/share/applications/$desktop_name.desktop

echo "The file ~/.local/share/applications/$desktop_name.desktop has been created, pointing to $document"

To run the above script, copy and paste it into a file with Gedit, then save it as add_document_to_launcher.sh, right click on it → Properties → Permissions → Check allow executing file as program. Then (preferred way is to) open a terminal and run the script through there or double click on the file and choose 'Run'.
A dialog will pop-up asking you for the document, then another will pop-up asking you for an icon for this document. Select any icon you like BUT: It has to be PNG and its path not to contain spaces.
After this, a file will be created under ~/.local/share/applications with the extension .desktop.
If you open the DASH and search your document with its filename, it will be shown under 'Applications' (and not under Files & Folders). You can simply drag and drop your document on the launcher! That's it :)
EDIT: remember: after this, do not remove the document from its path or the icon you have selected!


text:
Q: Fastest way to add/multiply two floating point scalar numbers in python I'm using python and apparently the slowest part of my program is doing simple additions on float variables.
It takes about 35seconds to do around 400,000,000 additions/multiplications.
I'm trying to figure out what is the fastest way I can do this math.
This is how the structure of my code looks like.
Example (dummy) code:
def func(x, y, z):
    loop_count = 30
    a = [0,1,2,3,4,5,6,7,8,9,10,11,12,...35 elements]
    b = [0,11,22,33,44,55,66,77,88,99,1010,1111,1212,...35 elements]
    p = [0,0,0,0,0,0,0,0,0,0,0,0,0,...35 elements]
    for i in range(loop_count - 1):
        c = p[i-1]
        d = a[i] + c * a[i+1]
        e = min(2, a[i]) + c * b[i]
        f = e * x
        g = y + d * c
        .... and so on
        p[i] = d + e + f + s + g5 + f4 + h7 * t5 + y8
    return sum(p)

func() is called about 200k times. The loop_count is about 30. And I have ~20 multiplications and ~45 additions and ~10 uses of min/max
I was wondering if there is a method for me to declare all these as ctypes.c_float and do addition in C using stdlib or something similar ?
Note that the p[i] calculated at the end of the loop is used as c in the next loop iteration. For iteration 0, it just uses p[-1] which is 0 in this case.
My constraints:

*

*I need to use python. While I understand plain math would be faster in C/Java/etc. I cannot use it due to a bunch of other things I do in python which cannot be done in C in this same program.

*I tried writing this with cython, but it caused a bunch of issues with the environment I need to run this in. So, again - not an option.

A: I think you should consider using numpy. You did not mention any constraint.
Example case of a simple dot operation (x.y)
import datetime
import numpy as np

x = range(0,10000000,1)
y = range(0,20000000,2)
for i in range(0, len(x)):
    x[i] = x[i] * 0.00001
    y[i] = y[i] * 0.00001

now =  datetime.datetime.now()
z = 0
for i in range(0, len(x)):
    z = z+x[i]*y[i]
print "handmade dot=", datetime.datetime.now()-now
print z

x = np.arange(0.0, 10000000.0*0.00001, 0.00001)
y = np.arange(0.0, 10000000.0*0.00002, 0.00002)

now =  datetime.datetime.now()
z = np.dot(x,y)
print 'numpy dot =',datetime.datetime.now()-now
print z

outputs
handmade dot= 0:00:02.559000
66666656666.7
numpy dot = 0:00:00.019000
66666656666.7

numpy is more than 100x times faster.
The reason is that numpy encapsulates a C library that does the dot operation with compiled code. In the full python you have a list of potentially generic objects, casting, ...


text:
Q: Error when running database migration for the first time I have an ASP .Net core app which uses existing tables from a sql server database. As the tables had preexisted before I created the app, in order to build models of them within the app, I reverse engineered the tables using the command:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Using this command successfully created the models and I have been able to query from the database tables as need so far. Right now, I'm working on the User Registration system for the app and have added the necessary ASP .Net entity framework core identity service and as a part of the process, the required Application user model needs to be migrated to the database.
I tried first running (in the package manager console) the command add-migration IdentityAdded -context DBContext and there was an error saying: Add-Migration : A parameter cannot be found that matches parameter name 'context'. After this, I thought that since I hadn't yet run a migration, I needed to run the command Add-Migration InitialCreate, but after running the command, there is the error:
Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly
'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d2940a' is not marked as serializable.

Can migrations no longer be run since I reverse engineered the database tables initially? What could be causing the problem?
Here is the startup file for reference:
startup.cs
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //using( var context = new ApplicationDbContext())
            //{
            //    context.Database.EnsureCreated();
            //}
            services.AddDbContext<DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Cn")));
            services.AddMvc();

            services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<DBContext>()
    .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequireLowercase = false;
                options.Password.RequiredUniqueChars = 6;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers = true;

                // User settings
                options.User.RequireUniqueEmail = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                // If the LoginPath isn't set, ASP.NET Core defaults
                // the path to /Account/Login.
                options.LoginPath = "/Account/Login";
                // If the AccessDeniedPath isn't set, ASP.NET Core defaults
                // the path to /Account/AccessDenied.
                options.AccessDeniedPath = "/Account/AccessDenied";
                options.SlidingExpiration = true;
            });
            services.AddPaging();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            //app.UseIdentity(); //will be deprecated
            AuthAppBuilderExtensions.UseAuthentication(app);
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=resortDeals}/{action=Index}/{id?}");

            //routes.MapRoute(
            //         name: "DetailsRoute",
            //         template: "{controller=resortDeals}/{action=Details}/{id}");
        }

            );

Edit
Application user class:
 public class ApplicationUser : IdentityUser
    {

    }

A: I believe that the parameter -Context that you pass into the Add-Migration is case-sensitive.
Also, your DBContext that you use for the AspNet Identity must inherit from IdentityDbContext

A: It seems like they have similar issue here:
Enable-Migrations Exception calling "SetData" with "2" argument(s)
Enable-Migrations installation error
Or maybe you have this issue: https://github.com/aspnet/EntityFramework6/issues/231


text:
Q: Passport: Authenticating the whole app instead of some requests I am new to web development and NodeJS. I am working on authentication using passport. It was a small app so I put check on each route request to check whether the user is authenticated or not; But I guess that technique won't be feasible for a big app.
I want to authenticate the whole app. I know that it has something to do with middleware as each request passes through middleware, but I can't figure out where. Any middleware related explanation would be appreciated.
Here is my code
const express = require('express');
const app = express();
const path = require('path');
const mongo = require('mongodb').MongoClient;
const cookieParser = require('cookie-parser');
const expressHandlebars = require('express-handlebars');
const expressValidator = require('express-validator');
const session = require('express-session');
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = require('./models/user');
const Admin = require('./models/admin');

app.engine('handlebars', expressHandlebars({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

const port = 8888;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

app.use(passport.initialize());
app.use(passport.session());

//express Validator
app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
        var namespace = param.split('.'),
            root = namespace.shift(),
            formParam = root;
        while (namespace.length) {
            formParam += '[' + namespace.shift() + ']';
        }
        return {
            param: formParam,
            msg: msg,
            value: value
        };
    }
}));

app.use(express.static(__dirname));

mongoose.Promise = global.Promise;
const url = 'mongodb://localhost:27017/userDB';
mongoose.connect(url);

Here is my login functionality.
app.get("/login", function (req, res) {
    const loginPath = path.join(__dirname, '/login.html');
    res.sendFile(loginPath);
});

passport.use(new localStrategy({
        usernameField: 'adminUsername',
        passwordField: 'password',
        session: false
    },
    function (adminUsername, password, done) {
        Admin.getAdminByAdminUsername(adminUsername, function (err, admin) {
            if (err) throw err;
            console.log('getAdmin called');
            if (!admin) {
                console.log('Admin Not Found');
                return done(null, false);
            }

            Admin.comparePassword(password, admin.password, function (err, isMatch) {
                console.log('comparePassword called');
                if (err) throw err;
                if (isMatch) {
                    return done(null, admin);
                } else {
                    console.log('Wrong Password!');
                    return done(null, false);
                }
            });
        });
    }));

passport.serializeUser(function (admin, done) {
    done(null, admin.id);
});
passport.deserializeUser(function (id, done) {
    Admin.getAdminById(id, function (err, admin) {
        done(err, admin);
        console.log('findById called');
    });
});

app.post('/login', passport.authenticate('local', {
        failureRedirect: '/login'}), function(req, res){
        console.log('login called');
        res.redirect('/');
    });

function ensureAuthenticated(req, res, next){
    console.log(req.isAuthenticated());
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/login');
    }
}

Previously, this is how I put a check on each request. Here is an example.
app.get("/update", ensureAuthenticated, function (req, res) {
    const updatePath = path.join(__dirname, '/update.html');
    res.sendFile(updatePath);
});

A: ensureAuthenticated is a middleware that you can also use standalone, like this:
app.use(ensureAuthenticated);

Express will pass requests to middleware and route handlers in order of their declaration. That means that if you add the line above in front of other middleware and route handlers, it will always be called, for each request (but read below why you might not actually want that). That way, you don't have to add it explicitly to each request handler.
Typically though, you separate "requests that require authentication" from requests that don't. For instance, requests for static resources (client-side JS, CSS, HTML, etc) typically don't require authentication. That means that you need to declare the static handler before ensureAuthenticated:
app.use(express.static(__dirname));
app.use(ensureAuthenticated);

The same goes for requests that are part of the login process: the login page and login request handler, for the simple reason that requiring a user to be logged in before they can access the login page doesn't make sense.
So the overall structure of your middleware/route handlers would look like this:

*

*Common middleware (body parser, cookie handler, passport middleware, etc)

*app.use(express.static(...))

*Login routes

*app.use(ensureAuthenticated)

*"Protected" routes


text:
Q: MySQL LEFT JOIN I have a table structure as follows:
registered (1 to 0/1) cobuy (1 to 0/*) cobuy_area_instance (0/* to 1) area
A search on a registered user list must return users from left to right, e.g it must return registered users with no cobuy profile, those with a cobuy rofile but no area, and those with all three.
I know this should be achieved by a left join, but am unclear as to how best to approach. I need fields from the registered table, cobuy table and area table, depending on what exists.
Any help appreicated...

A: SELECT R.FIELD_1, C.FIELD_2, CAI.FIELD_3
FROM REGISTERED R
LEFT OUTER JOIN COBUY C ON R.UID=C.UID
LEFT OUTER JOIN COBUY_AREA_INSTANCE CAI ON C.CID=CAI.CID

Should give you every item from the REGISTERED table plus any existing items from the COBUY table and any existing items from the COBUY_AREA_INSTANCE table.
Note that I deal with MSSQL so the syntax may not be correct.
Edited for WHERE clause on joins.
SELECT R.FIELD_1, C.FIELD_2, CAI.FIELD_3
FROM REGISTERED R
LEFT OUTER JOIN COBUY C ON (R.UID=C.UID AND C.DATE > '2011-02-14')
LEFT OUTER JOIN COBUY_AREA_INSTANCE CAI ON C.CID=CAI.CID

Seems like the solution to me.


text:
Q: How to save data in database by using ASP.NET Identity (Web Form)? This question is the next chapter of:
How to add custom table in ASP.NET IDENTITY?
In the first chapter I asked how to create a custom table in ASP.NET Identity.
In this chapter I'm asking how to save data in database. I tried many ways but I wasn't successful.
After the successful login, system should store some data like:

*

*[AccountLogID] PK

*[IPv4]

*LoginDate

*[UserId] FK (From User.ID)

My codes look like this:
IdentityModels.cs
namespace Web_WebApp.Models
{
    // You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {

        public virtual ICollection<AccountLog> AccountLogs { get; set; }

        public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            return Task.FromResult(GenerateUserIdentity(manager));
        }

    }

    public class AccountLog
    {
        [Key]
        public Guid AccountLogID { get; set; }

        public string IPv4 { get; set; }
        public DateTime LoginDate { get; set; }
        public string UserId { get; set; }

        [ForeignKey("UserId")]
        public virtual ApplicationUser User { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

    {
        public ApplicationDbContext()
            : base("Web_Identity", throwIfV1Schema: false)
        {
        }

        public System.Data.Entity.DbSet<AccountLog> AccountLog { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

    }
}

Login.aspx.cs
namespace Web_WebApp.Account
{
    public partial class Login : Page
    {

        string GuidToken = System.Guid.NewGuid().ToString();

        public static string GetExternalIP()
        {
            try
            {
                string externalIP;
                externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
                externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                             .Matches(externalIP)[0].ToString();
                return externalIP;
            }
            catch { return null; }
        }

        protected void LogIn(object sender, EventArgs e)
        {
            // Validate the user password

            //var AccountLogs = Context.GetOwinContext().GetUserManager<AccountLog>();
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

            // Require the user to have a confirmed email before they can log on.
            var user = manager.FindByName(username.Text);

            if (IsValid)
            {

                if (user != null)
                {

                    {
                        // This doen't count login failures towards account lockout
                        // To enable password failures to trigger lockout, change to shouldLockout: true
                        var result = signinManager.PasswordSignIn(username.Text, Password.Text, RememberMe.Checked, shouldLockout: true);

                        if (!user.EmailConfirmed && result == SignInStatus.Success)
                        {

                            Response.Redirect("/Account/Confirmation?UserConfirmationID=" + user.Id);
                        }

                        switch (result)
                        {
                            case SignInStatus.Success:

                                var AccountLog = new AccountLog()
                                {

                                    IPv4 = GetExternalIP(),
                                    LoginDate = DateTime.Now,
                                    UserId = user.Id,

                                };

                                user.AccountLogs.Add(AccountLog);

                                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

                                break;
                            case SignInStatus.LockedOut:
                                //Response.Redirect("/Account/Lockout");

                                FailureText.Text = "This account has been locked, please try again later.";
                                ErrorMessage.Visible = true;
                                return;

                            case SignInStatus.RequiresVerification:
                                Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                                Request.QueryString["ReturnUrl"],
                                                                RememberMe.Checked),
                                                  true);
                                break;
                            case SignInStatus.Failure:
                            default:
                                FailureText.Text = "Invalid password";
                                ErrorMessage.Visible = true;
                                break;

                        }

                    }

                }
                else
                    FailureText.Text = "Account not found.";
                ErrorMessage.Visible = true;
            }
        }
    }
}

With these codes my application runs, I can login but it doesn't save anything as I've mentioned in my code. I don't get any error or warning.
I'm sure something like "SaveChanges()" is missing but I don't know where to put that.
I appreciate your efforts in reaching a solution for my problem.

A: You are getting the user through the ApplicationUserManager, and after adding a new AccountLog entry to the collection user.AccountLogs, you'll need to save the user back to the database. AFAIK you can get the Entity framework context (ApplicationDbContext?) from OWIN the same way as you get other instances.
switch (result)
{
    case SignInStatus.Success:

        var AccountLog = new AccountLog()
        {

            IPv4 = GetExternalIP(),
            LoginDate = DateTime.Now,
            UserId = user.Id,
        };

        user.AccountLogs.Add(AccountLog);

        // get the entity framework context.
        var dbContext = Context.GetOwinContext().Get<ApplicationDbContext>();
        // save the changes to objects tracked by this context
        dbContext.SaveChanges();

        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

        break;
case SignInStatus.LockedOut:
 // removed for brevity.
    break;

}

Note: You might have to get the user again straight from the context, but I don't think that it's necessary, depends on whether or not the user is detached or not.


text:
Q: How to slice a double cone to get a pair of parallel lines? There are four possible types of degenerate conics (Wikipedia): a point, a single straight line, a pair of intersecting lines, and a pair of parallel lines.
I am however unable to see how one can use a 2D plane to slice a double cone to get a pair of parallel lines. Googling, I'm also unable to find any image showing how this can be done and I was hoping someone here could show me (if this is indeed possible).
I did find this decades-old discussion claiming that the "solution" is to treat a cylinder as a "degenerate cone". Is that the correct solution?


text:
Q: Flutter Provider showing results ONLY after Hot Reload I am a beginner, and I am building an app following a tutorial using provider. The logic is that, when You click the "Categories" widget, it should lead you to a page with products in that category. The logic works as expected except I have to first refresh the code for results to show. I frankly do not know what I am doing wrong.
From the Homepage, the Categories widget is rendered using a listview builder
Container(
                height: 75,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: categoryProvider.categories.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () async {
                        await productProvider.loadProductsByCategory(
                            categoryName:
                                categoryProvider.categories[index].name);
                        changeScreen(
                            context,
                            CategoryScreen(
                                categoryModel:
                                    categoryProvider.categories[index]));
                      },
                      child: CategoriesWidget(
                          category: categoryProvider.categories[index]),
                    );
                  },
                ),
              )

Main.Dart
I am listening to providers like this
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: AppProvider()),
        ChangeNotifierProvider.value(value: UserProvider.initialize()),
        ChangeNotifierProvider.value(value: CategoryProvider.initialize()),
        ChangeNotifierProvider.value(value: MarketProvider.initialize()),
        ChangeNotifierProvider.value(value: ProductProvider.initialize()),
      ],
      child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Akatale',
          theme: ThemeData(
            primaryColor: Colors.black,
          ),
          home: ScreenController())));
}

class ScreenController extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<UserProvider>(context);

    switch (auth.status) {
      case Status.Uninitialized:
        return Loading();
      case Status.UnAuthenticated:
      case Status.Authenticating:
        return SignInScreen();
      case Status.Authenticated:
        return MainScreen();
      default:
        return SignInScreen();
    }
  }
}

Product Service
With this, I fetch products from firestore by the name of the category and add them to a List
class ProductService extends ChangeNotifier {
  String collection = "products";
  Firestore _firestore = Firestore.instance;

  Future<List<ProductModel>> getProductsByCategory({String category}) async {
    List<ProductModel> products = [];
    _firestore
        .collection(collection)
        .where("category", isEqualTo: category)
        .getDocuments()
        .then((result) {
      for (DocumentSnapshot product in result.documents) {
        products.add(ProductModel.fromSnapshot(product));
      }
    });
    return products;
  }
}

Product Provider
Here I have public methods to be called in widgets
class ProductProvider with ChangeNotifier {
  ProductService _productService = ProductService();
  List<ProductModel> products = [];
  List<ProductModel> productsByCategory = [];

  ProductProvider.initialize() {
    _loadProducts();

  }

  //Private method Load products to List
  Future _loadProducts() async {
    products = await _productService.getProducts();
    notifyListeners();
  }

  //public method to Load products to List by category
  Future loadProductsByCategory({String categoryName}) async {

    productsByCategory =
        await _productService.getProductsByCategory(category: categoryName);

    notifyListeners();
  }
}

Categories Page
This is where products are rendered based on the chosen category
class CategoryScreen extends StatelessWidget {
  final CategoryModel categoryModel;

  const CategoryScreen({Key key, this.categoryModel}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final productProvider = Provider.of<ProductProvider>(context);
    return Scaffold(
      body: SafeArea(
          child: ListView(
        children: [
          Text(categoryModel.name),
          Column(
            children: productProvider.productsByCategory.map((item) {
              return GestureDetector(
                  onTap: () {
                    //Load details page
                  },
                  child: ProductWidget(
                    product: item,
                  ));
            }).toList(),
          ),
        ],
      )),
    );
  }
}

A blank page is displayed

But on hitting Hot reload, the products appear

A: In getProductsByCategory in your ProductsService you are not awaiting getDocuments.
So while the documents will get loaded it already calls notifyListeners in the model before it is actually done loading them.
And thus when you rebuild using hotreload they show up
To fix this simply await the getDocuments in the service


text:
Q: Facebook SDK cURL 7.34.0 fails, 7.19.7 works I got a strange problem here at our CentOS 6.4 box (2.6.32-431.3.1.el6.i686) running PHP 5.5.8.
All Facebook apps stopped working since we upgaded cURL / libcurl to version 7.34. It just times out when trying to execute ´curl_exec($ch)´.
Using yum downgrade and yum install curl libcurl, I was able to reproduce the error (and always works), see the differences of phpinfo() here:

Tried to run curl in verbose mode and catch the data sent and recieved.
If someone other wants to know how to catch this cURL data (wasn't to easy to find):
$opts[CURLOPT_VERBOSE] = true; // enable verbose logging
$verbose = fopen('php://temp', 'rw+');
$opts[CURLOPT_STDERR] = $verbose;
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>". htmlspecialchars($verboseLog), "</pre>\n";

This works with 7.19.7:
* About to connect() to graph.facebook.com port 443 (#0)
*   Trying 173.252.101.48... * connected
* Connected to graph.facebook.com (173.252.101.48) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using SSL_RSA_WITH_RC4_128_SHA
* Server certificate:
*   subject: CN=*.facebook.com,O="Facebook, Inc.",L=Palo Alto,ST=California,C=US
*   start date: Oct 28 00:00:00 2013 GMT
*   expire date: Aug 05 23:59:59 2015 GMT
*   common name: *.facebook.com
*   issuer: CN=VeriSign Class 3 Secure Server CA - G3,OU=Terms of use at https://www.verisign.com/rpa (c)10,OU=VeriSign Trust Network,O="VeriSign, Inc.",C=US
> POST /me HTTP/1.1
User-Agent: facebook-php-3.2
Host: graph.facebook.com
Accept: */*
Content-Length: 232
Content-Type: application/x-www-form-urlencoded

< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Cache-Control: private, no-cache, no-store, must-revalidate
< Content-Type: application/json; charset=UTF-8
< ETag: "a4238b670d50df51506644bd20277a7cffbfaa80"
< Expires: Sat, 01 Jan 2000 00:00:00 GMT
< Last-Modified: 2014-01-15T13:20:35+0000
< Pragma: no-cache
< X-FB-Rev: 1097933
< X-FB-Debug: ekyERaUVGaiB7H+tLQn1m6sll33KkF8CUhlHGd9/lGs=
< Date: Tue, 28 Jan 2014 09:51:40 GMT
< Connection: keep-alive
< Content-Length: 253
<
* Connection #0 to host graph.facebook.com left intact

When trying to do the same with 7.34.0, httpd runs with 100% and gets a timeout after 30 seconds (or whatever is set in php.ini). No verbose output at all, just times out. Nothing to find in Apache error_log.
Any ideas how to debug any further?
Regards,
Max

A: Its very hard to tell you without being on your position. But still here are few suggestion from my end. Not sure how much it will help you.
First write a basic curl code and run it for the site example.com(for example). And see what does it return.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);

If above code doesn't work for you, then its the issue of curl.
Now, run the same code by changing the url into https://www.google.com/ and also adding the other curl options for ssl/certificate things(use from your existing code). And check what it does. If it doesn't work, then its the issue of ssl with curl.
If it works then change the url into your graph api url. And check what it does. If it doesn't then its the problem of CURLOPT_SSLVERSION for curl that you are using.
Finally, you can also try to run my above code with the below option for both https://www.google.com and https://graph.facebook... sites. And see how they react.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);


text:
Q: State changing but not rendering
I want to render a settings menu onclick when an element is added to my list and disable all other setting menus when one is active. I also have a sample element in a different state and would like to deactivate all setting menus when it is on and have it disabled if a settings menu is on. I am storing the setting states of all elements in an array and in my update function the copy of my setting state is changing but my actual settings state isn't. I think it has to do with my useeffect and when I comment it out my settings state does change but it isn't rendered. It was working before I mapped my chart data, but I am not sure what caused it to stop working as commenting it out still does not render settings.
const [settings, setSettings] = useState([]);
const [sampSettings, setSampSettings] = useState(false);

const updateSettings = (val, index) => {
if(val){
    let copySettingsFalse = [...settings]
    copySettingsFalse[index]=false;
    return setSettings(copySettingsFalse);
}
let copySettingsTrue = settings.fill(false);
copySettingsTrue[index] = true;
console.log(copySettingsTrue)
return setSettings(copySettingsTrue);

};
useEffect(() => {
if (stockList.length>0){
stockList.map((val,index) => {
  // Chart
  setLineData([
    ...lineData,
    {
      labels:trimLineDataHistory[index],
      datasets: [
        {
          label: val.Tick,
          data: trimLineDataHistory[index].reverse(),
          pointRadius: 0,
          fill: false,
          backgroundColor: day ? "#e9dfd4" : "#141e28",
          borderColor: "#52ad59",
        },
      ],
    },
  ]);
  // Settings
  setSettings([...settings, false]);
})}
  return;
},[stockList]);

// Settings
// useEffect(() => {
//   if (settings.includes(true)) {
//     setSampSettings(false);
//   }
//   if (sampSettings === true) {
//     setSettings(settings.fill(false));
//   }
//   return;
// }, [settings,sampSettings]);

  if(stockList.length>1)
  return(
  <>
  {stockList.map((val, index) => {
   const { Tick, Name } = val;
   return(

        <BsFillGearFill
         className="gearIcon"
         onClick={() => updateSettings(settings[index], index)}></BsFillGearFill>

)}
            </>)

A: You try to add the "Key" attribute BsFillGearFill tag and also set & update value for it. it may be any value


text:
Q: Prevent PHP thumbnail generator response as in ajax I am trying to upload an image through ajax and needs to get the image URL as response.
code below..
$(".filupldt").on('change',function(){

    var file_data=$(this).prop("files")[0];
    var form_data=new FormData();
    form_data.append("file",file_data);
    form_data.append("type",$(this).prev().prev().val());
    form_data.append("primerkey",$(this).prev().val());
    var element = this;

    $.ajax({
        type:'POST',
        mimeType: 'multipart/form-data',
        url:'includes/dealerimg.settings.php?operation=savedealerimgeqtype',
        dataType:'json',
        async:false,
        processData: false,
        cache: false,
        contentType: false,
        data:form_data,
        success:function(response){
          console.log(response);
          //$(element).parent().prev().prev().attr('src',response);
        },
    });
  });

PHP Ajax function
        $createthumb = new createthumb();
        $todburl =  $this->url;
        $ajaxtype = $_POST['type'];
        $uploads_dir = "../assets/equipmenttype/";
        $uniid = uniqid();
        $now =date('Y-m-d H:i:s');
        $pkid = $_POST['primerkey'];
        $ext =pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

        $filename = $pkid."_".$DealerID."_dealerupdate";
        $thumbnamer = $pkid."_".$DealerID."_thumb_dealerupdate_".$uniid.".".$ext;

        $tmpname = $_FILES['file']['tmp_name'];
        $imagename = $_FILES['file']['name'];

        $loc_thumb = $uploads_dir.$thumbnamer;

        $createthumb->create_thumb_with_ratio($tmpname,300,300,$loc_thumb);  //CREATING THUMB
        $createthumb->upload_original(1,$filename,$imagename,$tmpname,$uploads_dir);//for upload original

        $thumnametodb = $thumbnamer;
        $orinametodb = $filename."_".$imagename;

        $data = ['dddd'=>$todburl."assets/equipmenttype/".$thumbnamer];
        header('Content-Type: application/json');
        echo json_encode($data);

This function working perfectly and creating thumb in my required folder.
But this is an ajax page and I want to show the image name as response.
In this case the ajax response is like below attached image.

How can i solve this issue ?
Thanks

A: You said that you want to show the image name as response :
Then just
echo $_FILES['file']['name'];

then in your script you get the image name as response with :
 success:function(response){
          console.log('Image Name = '+response);
 }

Your current response is JSON representation (json_encode($data)) & not the image's name.

A: Probably some output is braking the response data. To be sure that nothing prints on the response page try putting ob_start() and ob_end_clean()
ob_start();
//...
// your code here
//...
$data['dddd'] = $todburl."assets/equipmenttype/".$thumbnamer;
ob_end_clean();
echo json_encode($data);


text:
Q: Awaiting for two methods that return observables in angular I have two methods that make api calls and return observables.
private method1(): Observable<Home> {
  return homeService.call.get();
}

private method2(): Observable<User> {
  return userService.call.get();
}

Then I have the following two methods:
private method3(): void {
  this.method1().subscribe();
  this.method2().subscribe();
}

and one last one
private method4(): void {
 // does things
 this.method3();
}

I want the method4 to wait for the method3 to finish all is requests in order to proceed, but I have no idea how to achieve it in angular 8. Any tips?

A: You are probably looking at a term called flattening observables - having nested observables. (Unless you care only about the final response - forkJoin)
You have variety of operators that can help you achieve what you need. Here are only some of them. Take a look and you will see which of them applies to your code the best way.
switchMap - Has the canceling effect.
mergeMap - "This operator is best used when you wish to flatten an inner observable but want to manually control the number of inner subscriptions."
forkJoin - "This operator is best used when you have a group of observables and only care about the final emitted value of each."


text:
Q: PHP page not hiding a DIV using visibility:none or display:none A PHP page I am working on can be loaded in several states, in the default state I need one DIV layer to be visible and another one to not be visible - and vice versa.
The script has javascript backup to do the same things, BUT I need the css to work for persons viewing the page with javascript disabled.
The code for the first DIV works fine:

<
div name="MoreDiv" ID="MoreDiv" style="position: absolute;top: 10px; left: 15px;  width: 95%; font-size:1.3em;
<?php
if(isset($_GET['page']))
{
$ipi = getenv("REMOTE_ADDR");
$u = getenv ("HTTP_REFERER");
$httpagenti = getenv ("HTTP_USER_AGENT");

$page = $_GET['page'];
switch($page)
{
case 404:
{echo '';
break;}

default:
{ ?>

<?php }

break;}
}
else { //
?>visibility:none; display:none;<?php }
?>">

... So you'd think that for the other DIV, that needs to be hidden when the ?page variable is set in the URL, putting the "visibility:none; display:none;" attributes inside the default for the php output would work - a bit like this:
div name="PhotoText" ID="PhotoText" style="position: absolute;top: 15px; left: 15px; width: 400px; font-size:1.3em; background: rgb(0, 0, 0); background: rgba(0, 0, 0, 0.7); padding:10px; -webkit-border-radius: 10px;  -moz-border-radius: 10px; border-radius: 10px; -khtml-border-radius: 10px; <?php
if(isset($_GET['page']))
{$page = $_GET['page'];
switch($page)
{
case "test":
{?>
visibility:none; display:none;

<?php
break;}

default:
{ ?>
visibility:none; display:none;

<?php }

break;}
}

else { //
?><?php }
?>">

And yet for some strange and really bizarre reason the DIV STILL SHOWS!... and it stays visible until the page has fully loaded and the javascript within the "body onload" tag kicks in to hide it. I cannot use the PHP to keep the DIV layer blank for the default URL variable, as there are javascript links which require it to be there in order to load content.... so I need a non-JS way of hiding this layer, but in such a way that JS can be used to make it visible again!!

A: There's really several ways of accomplishing this. First of all, never, ever, interpolate an if and a switch type of logic within an attribute's value as you have it in your question. Recipe, meet disaster.
On the visibility vs display question, this QA actually depicts it pretty well:
http://webdesign.about.com/od/css/f/blfaqhidden.htm
More or less, visibility still maintains it's "space" in the flow of the document, whereas display affects it's flow (including removing it entirely). Easy to mix up, totally different concepts.
Here's a demo, and the source markup and CSS.

Visiblity
Will you see me?
Will I still be "there"?

Block
Will you see me?
Will I disappear?

        <button type="button" id="visibility">Toggle Visibility</button>
        <button type="button" id="display">Toggle Display</button>

#wrapper.hide #nodisplay {
    display: none;
}
#wrapper.invisible #novisibility {
    visibility: hidden;
}

The Javascript is toggling the .hide and .novisibility classes on the #wrapper.
I would suggest a template pattern, where you separate the logic from the markup/display layer. For instance:
page.php
<?php

// ... other stuff

if (isset($_GET['page'])) {
    $page = $_GET['page'];

    switch($page) {
        case "test":
           $cls = " NoDisplay";
        break;
        default:
           $cls = " Highlight";
        break;
    }
}

// ... other stuff

?>

Where you hae this defined in your CSS (not in a style attribute if you can help it):
/assets/css/site.css
.PhototextContent.NoDisplay {
    display: none;
}
.PhototextContent.Highlight {
    background: yellow;
    display: block;
}

docPagePhotoInline.tpl

<div id="PhotoText" class="PhotoTextContent<?php echo $cls; ?>">Your content

I also wonder if you're reusing that id value; you should (can) only have one unique id per page. If you need something to cover several elements, use class names to group elements by class. Also note, name in divs are still valid I think, but rarely used by anyone. Use id to uniquely identify an element.
So which do you think is easier to read? I don't think it's hard to see what I'm up to here, but it takes a double look with what you've got, followed by some head-scratching. Your code should be expressive of intent; code that feels well-tended and that feels right when you look at it isn't always great code, but inelegant, whiplash formatting is often an indicator the code could be problematic. Think of it like a garden; a well tended and organized garden is much more appealing than one that's, well, not.
So I'd implement at least a basic templating approach. There's several decent tutorials out there, like this one. I'd like to try out Mustache for PHP soon, but there's others like Smarty, Flexy, Twig, and Dwoo. Keep in mind PHP itself may be used as a templating system, and most template system compile the templates into PHP or bytecode. You just need to be careful to separate the logic from the view or display layer.
You should pair them with an approach, though, so I'd suggest a framework using the MVC pattern. There's a lot out there, like CodeIgniter, TinyMVC, Kohana, Cake, etc. This looks reasonable:
http://phpsavant.com/
Try not to hang out there on your own too much, though.


text:
Q: how to set value of a class property in react How can I access and set a dynamic e.target.value of a class with setState?
I've tried this.setState({fields[e.target.name]: e.target.value});

class App extends Component  {
  constructor() {
    super();
    this.state = {
      data: [],
      fields: {
        name: ''
      }
    }
  }

  handleChange = e => this.setState({fields[e.target.name]: e.target.value});

  render() {
    const { fields } = this.state;

    return (
      <>
        <input type="text" name="name" placeholder="name" onChange={this.handleChange} value={fields.name} />
      </>
    )
  }
}

export default App;

A: You can't access a state property like this. A possible solution is to create a copy from the fields, modify the value and then set the new state, like below:
handleChange = e => {
    // The line below creates a copy of the state, using the spread operator
    let fields = { ...this.state.fields };
    fields[e.target.name] =  e.target.value
    this.setState({fields});
}

A: This is a slightly similar to this question. There are two ways to update the object. And as others have said, nesting state like this is an antipattern. This is a good read-up on why.
1- Simplest one:
First create a copy of fields then do the changes in that:
let fields = Object.assign({}, this.state.fields);    //creating copy of object
fields[e.target.name] =  e.target.value               //updating value
this.setState({fields});

Instead of using Object.assign we can also write it like this:
let fields = {...this.state.fields};

2- Using spread operator:
  handleChange = e => {
    e.persist(); //need to make the values persist because of event pooling
    this.setState(prevState => ({
      ...prevState,
      fields: {
        [e.target.name]: e.target.value
      }
    }))
  }