text:
Q: Installing Devise on Engine brings route error I'm having a problem creating an Engine in Rails.
I want to create an engine that uses Devise to share over all my other applications.
I followed the Getting Started guide for Engines at rails website:
http://edgeguides.rubyonrails.org/engines.html
Created an application, required my engine... everything runs just fine.
Then, I run into Devise (I've already installed Devise direct in an application before, but not in an engine) but when I try to use it, by acessing any controller that inherits the before_action authenticate_user! I get this message:
http://i.imgur.com/dIIxgwU.jpg
I really don't understand (I'm starting in Ruby, I'm a CakePHP guy), the route is set, but it can't find it (?).
engine/config/initializers/devise.rb
Devise.setup do |config|
  ...
  config.router_name = :doisbit
  config.parent_controller = 'Doisbit::ApplicationController'
end

engine/config/routes.rb
Doisbit::Engine.routes.draw do
  ...
  devise_for :users, class_name: "Doisbit::User", module: :devise
  ...
end

engine/lib/doisbit/engine.rb
module Doisbit
  class Engine < ::Rails::Engine
    isolate_namespace Doisbit
  end
end

engine/lib/doisbit.rb
require 'doisbit/engine'
require 'devise'
...

engine/doisbit.gemspec
...
Gem::Specification.new do |s|
  ...
  s.add_dependency "devise"
end

engine/app/controllers/application_controller.rb
module Doisbit
  class ApplicationController < ActionController::Base
    before_action :authenticate_user!
  end
end

application/config/routes.rb
Rails.application.routes.draw do
  ...
  mount Doisbit::Engine, at: "/doisbit"
end

application/config/environments/development.rb
Rails.application.configure do
  ...
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end

application/Gemfile
...
gem 'doisbit', path: "C:/.../doisbit"
...

EDIT
Just noticed by accessing /doisbit/users/sign_in I get the form. (duh)
i.imgur.com/anTRK2d.jpg
But... still... by default it routes to /users/sign_in when i'm not logged in.
What I'm missing?


text:
Q: Is there a way to print a short version of the docstring for all members of a Python object? In Python dir() returns the list of names in the current local scope.
__doc__ returns the complete docstring of an object.
How can I list all names in the current local scope and print the first line of each item's docstring ?
To elaborate: for import numpy as np I would like to get a list of short descriptions of all names returned by dir(np) e.g. print(np.nonzero.__doc__.split('.', 1)[0]).
How can I do this ?

A: def print_members(obj):
    for key in dir(obj):
        value = getattr(obj, key)
        doc = (value.__doc__ or '').split('.', 1)[0]
        print('MEMBER: %s\nDOCSTRING: %s\n\n' % (key, doc))

A: I've used something like this.  It's similar but not exactly what you're looking for.  You can adjust the docstring output to your needs.
###############################################################################
def about(obj=None, text=None, capsOnly=False, noLeadingUnderScores=False):
    """
    Utility function to assist with discovery while playing in the Python
    shell.  When possible, returns the sorted dir() and values() of the
    specified object.

    * noLeadingUnderScores - toggles display filtering of items that have a
                             leading underscore; only applies to dir() not
                             values() items.

    * capsOnly - toggles display filtering of items that are uppercase only.
                 this only applies to dir() not values() items.

    * text -     toggles the display filtering of items that have 'text'
                 within their string; applies to both dir() and values() items.
    """

    print "\n*******************\n*  print __obj__  *\n*******************\n"
    if obj is None:
        print "about() is meaningless as 'obj' is None"
    else:
        # diplay help(), if possible
        try:
            if obj.__doc__:
                print "\n\n********************\n*  HELP() results  *\n********************\n"
                for x in obj.__doc__.split('\n'):
                        print x
        except:
            print "\nno __obj__ available"

        # display dir(), if possible
        print "\n\n*******************\n*  DIR() results  *\n*******************\n"
        for x in sorted(dir(obj)):
            temp = "%s" % x
            if noLeadingUnderScores and len(temp) > 0 and temp[0] == "_":
                continue
            elif capsOnly:
                if temp == temp.upper():
                    if text and text in temp:
                        print temp
                else:
                    continue
            elif text:
                if text in temp:
                    print temp
            else:
                print temp

        # display values(), is possible
        try:
            if obj.values and type(obj.values) == type({}):
                print "\n\n**********************\n*  DICT values(k,v)  *\n**********************\n"
                for x in sorted(obj.values.keys()):
                    if text:
                        if text in x or text in str(obj.values[x]):
                            print x, obj.values[x]
                    else:
                        print x, obj.values[x]
        except:
            print "\nno dictionary like obj.values available"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using String Functions (LEFT, RIGHT, MID) in Select By Attributes against a File Geodatabase using ArcMap 10 I finally (albeit reluctantly) made the switch from a personal geodatabase (pGDB) to a file geodatabse (fGDB) not too long ago.  The main reason it took so long to switch has to do with how Select by Attributes deals with string functions.
For example, I used to be able to easily select all records where the first character of a particular field starts with "A".
left([Some_Field],1 = "A")

This works without a hitch when querying against a pGDB.  However, try to do the same thing against a fGDB.
left("Some_Field",1 = "A")

This returns the following error:
There was a problem selecting
An invalid SQL statement was used.

I realize I can use the field calculator to calculate a new field equal to the first character of some other field.  But who wants to do that every time?
Is there a way to use string functions inside Select By Attributes?

A: You can use Substring("fieldname", start, length) to mimick, left(), right() and mid() functions when querying a fgdb.
Left and Mid are obvious.
To extract the right 2 characters would be Substring("fieldname", char_length("fieldname") - 1), 2).
Column numbers are 1-based.

A: Try this code:
left("Some_Field",1) = 'A'

where the comparison operator is outside the parentheses, and the string value is in single quotes.
Note that string searches are case sensitive in a file geodb. So you might also have to use the UPPER or LOWER functions, or search for 'A' or 'a'.

A: Your queries should follow the SQL format discussed here.  For what you're looking for, you can use something like this:
"Some_Field" LIKE 'A%'

The % is a wild card, so this would return records that have values in "Some_Field" that start with 'A'.

A: For anyone landing here searching for a reason why the left() function doesn't work in arcgis, this is what I found:
LEFT() and RIGHT() don't work for fgdb's.  You must use SUBSTRING(field FROM start for NumChars)
The correct syntax for the SUBSTRING function is:
SUBSTRING("Field" FROM 1 FOR 3)
 - this example returns everything from the first char to the third char (if the field value was Apple, this would return App).


text:
Q: Why does text disappear when the page is loaded? (Wordpress, CSS, HTML, JS issue) I probably would be downvoded, cause I do not even know how to describe the problem.
I have a website (on Wordpress, template was bought and modified a bit thus I am not much into it yet and do not know all staff about it).
On the left side there is menu and on the right side some "test" text.

        test

So, everything is simple. Text on right side. However, if I open the website (http://moneyti.co/) the text on right side is seen, but then disappear. There is some *.js or something that creates this effect. The result of *.js (I am not able to say which JS does this, unfortunately) is mmm_fullwidth_container element inside the "navigation" part. This element has the following CSS:
element.style {
    width: 1841px;
    left: -128.859375px;
    right: auto;
}

As a result "text on right part" is somehow "under" this mmm_fullwidth_container.
Even if it is *.js that hides the element, I am not able to make it visible by changing CSS dynamically in browser. The element with text "test" is present in HTML markup, but I am not really able to understand why this text disappears. Why is the text not seen on the screen?


text:
Q: Can a phrasal adjective be placed AFTER a noun? If phrasal adjectives can be placed after nouns, what are some examples?

A: Yes. You can almost always move an adjective phrase around by utilizing commas. You may also have to cut or add pronouns, sometimes to make the sentence grammatical, other times for style. Notice the different patterns in the two examples below (each with three variations of the same sentence).

His razor-sharp wit cut her like glass.
His wit was razor sharp; it cut her like glass.
His wit, razor sharp, cut her like glass.
Her tar-thick apprehension cast a shadow on the wall.
Her apprehension was tar thick--it cast a shadow on the wall.
Her apprehension, tar thick, cast a shadow on the wall.

A: There are a few situations where you can put a phrasal adjetcive directly behind a noun  but they are only the cases where simple adjectives can be used in that way. The most common examples I can think of are to do with food and drink and describing the way in which the item is prepared.
For instance "I'd like a steak well done with chips please." is a perfectly acceptable alternative to "I'd like a well done steak with chips please" but "A car large black drew up to the kerb" is not an acceptable alternative to "A large black car drew up to the kerb". You will notice that the same applies to simple adjectives so we can say "I'd like a steak rare with chips please" or "I'd like a rare steak with chips please" and we can say "A black car drew up to the kerb" but "A car black drew up to the kerb" is so odd as to be incorrect.
You can put the phrasal adjective into parenthesis by using commas and say "A car, large and black, drew up to the kerb" but that is not quite the same thing.
In older English this reversal was more common and is it is sometimes used for effect, often when referring to historical or romantic subjects; you do sometimes see and hear things like "The king was held in a castle strong and secluded" but the more common and less picturesque version would be "The king was held in a strong, secluded castle".
In summary the answer is, yes it can be done but you have to be very careful how you use it unless you surround the adjective with commas to make it parenthetical.


text:
Q: Typecasting doesn't work. How to convert an object? I need to convert a custom object to a different object. How can I do that?
I know that typecasting doesn't work (the only thing is does is "shuts the compiler warnings off", but nothing more). Here is a sample code:
MyType* obj1;
MyOtherType* obj2;

obj1 = [MyType initWithData: 1];
obj2 = (MyOtherType*) obj1;

if ([obj2 isMemberOfClass: [MyOtherType class]]) { NSLog(@"OK"); }
else if ([obj2 isMemberOfClass: [MyType class]]) { NSLog(@"Nope"); }

The result is:
Nope

What can I do??

A: Typecasting (like you're doing) isn't going to change the type of the object. What you're actually doing is this:
obj1 = [MyType initWithData: 1];
"I just created a object of type MyType, now point obj1 at it. Since obj1 is a MyType pointer, it's okay."
If you were to the next line without the typecast:
obj2 = obj1;
You're saying, "point obj2 at the same thing obj1 is pointing to", which will work but the compiler know obj1 is a MyType pointer and obj2 is a MyOtherType pointer so it throws a warning telling you they are incompatible.
So when you say:
obj2 = (MyOtherType*) obj1;
All you're saying is, "point obj2 at the same thing obj1 is pointing to, OH and treat obj1 as if it were an MyOtherType object". This is cool with the compiler since as far as it is concerned it's just assigning a MyOtherType to a MyOtherType. But this doesn't actually change the object that obj1 is pointing to. So when you pass the 'isMemberOfClass' message to obj1, it's still going to be and report that it is a member of MyType.
One solution to your problem would be to write your own custom initializer or converter (something like this):
- (id)initWithMyType:(MyType*)originalType;
And then do the conversion in there

A: You can do it manually, field-by-field. Or create a method in MyType that does it manually and returns MyOtherType.


text:
Q: How do you reset a button from "clicked" to "unclicked" I have tried things like the following, but to no avail. (I am a novice programmer, so be nice.)
document.getElementById('Button1').clicked = false;
document.getElementById('Button1').value = false;
document.getElementById('Button1').value = document.getElementById('Button1').defaultValue;

A: Use CSS to do this, you could use CSS visited property to show if the link is clicked

A: Normal buttons do not behave this way. Links do, but not buttons. I'm thinking anything that has an ID of 'Button1' in Your page is actually a link Some Text, that has a CSS style (or none at all) making it appear differently once You clicked it at least once, am i right?
If so, You don't need javascript for now. You should create (or edit an existing) CSS sheet, and style your "Button1" in it. How to do it? Read here


text:
Q: Ajax post method not working shows status code 400 My ajax code for is not working. it shows error
XMLHttpRequest cannot load http://xxx.xxx.xxx No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 400.
How to solve the problem. I have tried the different headers. But not posting the data. Please to solve my issue.
my code is
$http({
       method: "post",
       dataType:'json',
        url: res,
       crossDomain : true,
        data: {
            'name': $scope.name,
            'email': $scope.email,
             'text area': $scope.query

        },
headers: { 'Access-Control-Allow-Origin': '*' }
    }).then(function success(data) {

        alert("Message sent succesfully");
        /*var success=data.data.issuccess;
        if(success==true)
        {
          var name=data.data.username;
          var userid=data.data.userid;
          alert("Name= "+name+ "UserId="+userid);
        }*/

    });

It's working postman as correct. but not in ajax.

A: You have to enable CORS on the server.
Please read this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Also check this one:
https://enable-cors.org/server.html
Note:  I am correcting this after reading the comment from SLaks. He is correct.

A: The problem is that http://xxx.xxx.xxx doesn't send the right header in its response for you to be able to access it. See https://fetch.spec.whatwg.org/#cors-protocol-examples for flow examples.

A: I have solve the problem. It is the problem face in server side. and i change the code is
$.ajax({
url: "http://xxx.xx.xx.xx/api/SendMail/SendEmail",
type: "POST",
async: false,
ContentType: "application/json; charset=utf-8",
data:  {
            'subject': "Contact us from SQU app",
            'message': msgSQU

        },
crossOrigin: true,
dataType: "json",
success: function (response) {
$resData = response;
//alert("Su");
showConfirm("Your Feedback succesfully send");

},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
//console.log(textStatus, errorThrown);
}
});

Now it is working as fine.


text:
Q: Generic class compiles in Java 6, but not Java 7 I have an interface in Java 6 that compiles correctly:
public interface IMultiMap<K, V> extends Map<K, Set<V>> {

    public int valueSize();

    public boolean put(K key, V value);

    public void clear(Object key);

    public boolean isEmpty(Object key);
}

But in Java 7, this interface doesn't compile. I get a compile error on boolean put(K, V) that it has the same erasure as V put(K, V). The full error from the compiler:
error: name clash: put(K#1,V#1) in IMultiMap and put(K#2,V#2) in Map have the same erasure, yet neither overrides the other
    public boolean put(K key, V value);
  where K#1,V#1,K#2,V#2 are type-variables:
    K#1 extends Object declared in interface IMultiMap
    V#1 extends Object declared in interface IMultiMap
    K#2 extends Object declared in interface Map
    V#2 extends Object declared in interface Map

For the record, adding any kind of overriding doesn't work. I tried explicitly overriding Map.put, but the error still comes up. Changing the return type of my put is moot since this error is blocking that potential error from ever being reached, and if this error were fixed, then the two methods wouldn't have the same name/parameter signature anyway.
I think I might try some reflection on Java 6 and see what the actual parameter types end up being in Java 6's compiled bytecode. It's clear that both Java 7 methods are being erased to put(Object, Object). I'll post the reflection results here once I do that.
In the meantime, my temporary workaround will be just to rename put to putSingle, but is this new behavior correct? Did some part of the generics specifications change for Java 7 that makes the old Java 6 behavior wrong? Or is this a bug in the Java 7 compiler?
Thanks in advance.
EDIT: I ran the reflection code. Check out my answer below.

A: I think it's a bug in 1.6 that was fixed in 1.7. Extract from this page:

Synopsis: A Class Cannot Define Two Methods with the Same Erased Signature but Two Different Return Types
Description: A class cannot define two methods with the same erased signature, regardless of whether the return types are the same or not. This follows from the JLS, Java SE 7 Edition, section 8.4.8.3. The JDK 6 compiler allows methods with the same erased signature but different return types; this behavior is incorrect and has been fixed in JDK 7.
Example:

class A {
   int m(List<String> ls) { return 0; }
   long m(List<Integer> ls) { return 1; }
}

This code compiles under JDK 5.0 and JDK 6, and is rejected under JDK 7.

A: I ran the reflection code on Java 6.
Here's the code:
public static void main(String[] args) {
    Class<IMultiMap> immClass = IMultiMap.class;
    Method[] methods = immClass.getMethods();
    for (Method method : methods) {
        if (method.getName().equals("put"))
            System.out.println(method.toString());
    }
}

Here are the method signatures for the class:
public abstract boolean IMultiMap.put(java.lang.Object,java.lang.Object)
public abstract java.lang.Object java.util.Map.put(java.lang.Object,java.lang.Object)

Or more concisely:
boolean put(Object, Object)
Object  put(Object, Object)

So they are erased to the same parameters with a different return type. I guess it's a bug an unspecified edge case in the Java 6 JLS then, as per assylias' answer. I wonder how Java 6 managed to resolve these methods correctly on runtime?
Edit: According to x4u's comment, the calling bytecode maintains a reference to the entire signature when it's compiled, so that's why the correct method was being called by the JVM. Since the compiler was probably capable of telling which method I was calling due to its access to the source (and thus to the generics information), the compiler probably linked it to the correct method via the entire signature. Interesting to know!


text:
Q: Category system for carousel? I'm using lightGallery with cycle2 plugin and I have categories for my image and when I clicked any categories my images must change with clicked category how can I do that ? any example ?
my a[data-id] is category images parents and my li#id category names
I want to share with you my structure, here you are please:

$(document).ready(function() {
  $('.mySlideShow').cycle({
    pauseOnHover: true,
    pager: "#single-pager",
    log:false,
    pagerTemplate: "",
    slides: ">a"
  });

  $(".mySlideShow").lightGallery({
    exThumbImage: "data-exthumbimage",
    download: false,
    thumbnail: true,
    loadYoutubeThumbnail: true,
    youtubeThumbSize: 'default',
    loadVimeoThumbnail: true,
    vimeoThumbSize: 'thumbnail_medium',

  });
})
.single-gallery {
  position: relative;
  width: 900px;
}

.mySlideShow {
  height: 494px;
  background: #000;
  overflow: hidden;
}

#single-pager img {
  width: 49.3px;
  border: 1px solid #fff;
  cursor: pointer;
  margin: 2px;
}

.gallery-categories {
  position: absolute;
  z-index: 20000;
  left: 0;
  top: 10%;
  list-style: none;
  padding: 0;
}

h1 {
  color: #FFF;
  padding: 0;
  margin: 0;
  font-size: 16px;
  text-align: center;
}

.gallery-categories li {
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-weight: bold;
  padding: 4px;
  margin: 2px;
  display: inline-block;
  cursor: pointer;
}
<link href="https://cdn.jsdelivr.net/lightgallery/latest/css/lightgallery.css" rel="stylesheet" />

Select a Categories

Sports

Animals

Naturel

and if you want to see on codepen please click here

A: From your question it's unclear where your skill level is and either your problem is technical or conceptual. Let's try to cover both...

Your category system could be realized as follows:
First of all we have to listen to the click event and react on that.
As you are using jQuery the following will work:
$('.gallery-categories li').on('click', function(event) {
    var category = $(event.target).attr('id');
    console.debug(category + ' selected!');
});

From now on, every time a user clicks on a li underneath your .gallery-selector the event handler is invoked. Note that this function does not check whether id is set or not.
Now we want to select all elements matching your category:
// this happens in our event handler too
var $items = $('.mySlideShow a[data-id="' + category + '"]');

...Iterate over them and change something:
$items.each(function() {
    $(this).addClass('selected');
});

There we are:
$('.gallery-categories li').on('click', function(event) {
    var category = $(event.target).attr('id');
    var $items = $('.mySlideShow a[data-id="' + category + '"]');
    $items.each(function() {
        $(this).addClass('selected');
    });
});

codepen


text:
Q: Image with max-width:100% not scaling within element with position:absolute I am currently working on a responsive carousel jquery plugin. The carousel shows 3 images on desktop devices, 2 on tablets and 1 on mobile devices. The LI items are floated left to create a strip of content and carousel-container has overflow:hidden to hide the elements within the strip not currently on show.
On mobile devices (max-width:767px) only one LI is shown and I want the image within the LI to scale as the browser size decreases. This is not currently working and I believe this may be because the UL has position:absolute. I have tried moving the image out of the carousel and it then scales as expected so I'm assuming some of the CSS applied to the carousel is affecting the CSS of the image.
Any help would be great.
The carousel consists of the following HTML:

and the following CSS:
.carousel-container{
   overflow:hidden;
   position:relative;
}

.carousel-container .carousel {
    padding: 0;
    position: absolute;
    left: 0px;
}

.carousel-container .carousel .item {
    position:relative;
}

.img-responsive {
    display: block;
    max-width: 100%;
    height: auto;
}

A: Here is an example http://jsfiddle.net/LGJ5w/ where if you specify the width of the parent then
max-width: 100%;

works fine else it fails. Try to stretch the output iframe.


text:
Q: How to combine these two regex passes into one? I have a few thousand strings that have one of these two forms:
SomeT1tle-ThatL00ks L1k3.this - $3.57 KnownWord
SomeT1tle-ThatL00ks L1k3.that - 4.5% KnownWord
The SomeT1tle-ThatL00ks L1ke.this part may contain uppercase and lowercase characters, digits, periods, dashes, and spaces.  It is always followed by a space-dash-space pattern.
I want to pull out the Title (the part before the space-dash-space separator) and the Amount, which is right before KnownWord.
So for these two strings I'd like:
SomeT1tle-ThatL00ks L1k3.this, $3.57 and
SomeT1tle-ThatL00ks L1k3.that, 4.5%.
This code works (using Perl equivalent Regular Expressions)
$my_string = "SomeT1tle-ThatL00ks L1k3.this - $3.57 KnownWord";

$pattern_title = "/^(.*?)\x20\x2d\x20/";
$pattern_amount = "/([0-9.$%]+) KnownWord$/";

preg_match_all($pattern_title, $my_string, $matches_title);
preg_match_all($pattern_amount, $my_string, $matches_amount);

echo $matches_title[1][0] . "  " . $matches_amount[1][0] . "<br>";

I tried putting both patterns together:
$pattern_together_doesnt_work = "/^(.*?)\x20\x2d\x20([0-9.$%]+) KnownWord$/";

but the first part of the pattern always matches the whole thing, even with the "lazy" part (.*? rather than .*).  I can't negative-match spaces and dashes, because the title itself can contain either.
Any hints?

A: Use this pattern
/^(.*?)\x20\x2d\x20([0-9.$%]+) KnownWord$/


text:
Q: Returning an array[] from AsyncTask back to Main Activity I am trying to return an array from my AsyncTask back to my Activity as I am trying to create a ListView from that array.
Unfortunately, the program bounds error because it wouldn't let me return an array. My codes are as below:
MainMenu Class:
public class MainMenu extends Activity {
String username;
public String[] returnValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    username ="user1";

if (checkInternetConnection()) {

    try {
        MainAsyncTask mat = new MainAsyncTask(MainMenu.this);
        mat.execute(username);
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    Toast.makeText(getApplicationContext(),"No internet connection. Please try again later",Toast.LENGTH_SHORT).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main_menu, menu);
    return true;
}

private boolean checkInternetConnection() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}}

MainAsyncTask:
public class MainAsyncTask extends AsyncTask<String, Void, Integer> {
    private MainMenu main;
    private String responseText, http;
    private Ipaddress ipaddr = new Ipaddress(http);
    private Context context;

    public MainAsyncTask(MainMenu main) {
        this.main = main;
    }

    protected Integer doInBackground(String... arg0) {
        int responseCode = 0;
        try {
            HttpClient client = new HttpClient(main.getApplicationContext());
            Log.e("SE3", ipaddr.getIpAddress());
            HttpPost httpPost = new HttpPost(ipaddr.getIpAddress()
                    + "/MainServlet");

            List<NameValuePair> nvp = new ArrayList<NameValuePair>();

            JSONObject json = new JSONObject();
            json.put("username", arg0[0]);

            Log.e("SE3", arg0[0]);

            nvp.add(new BasicNameValuePair("data", json.toString()));
            httpPost.setEntity(new UrlEncodedFormEntity(nvp));

            HttpResponse response = client.execute(httpPost);

            if (response != null) {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity()
                                        .getContent()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        responseText = sb.toString();
                    } catch (IOException e) {
                        Log.e("SE3", "IO Exception in reading from stream.");
                        responseText = "Error";
                    }
                } else {
                    responseText = "Error";
                }
            } else {
                responseText = "Response is null";
            }
        } catch (Exception e) {
            responseCode = 408;
            responseText = "Response is null";
            e.printStackTrace();
        }
        return responseCode;
    }

    protected void onPostExecute(Integer result) {
        if (result == 408 || responseText.equals("Error")
                || responseText.equals("Response is null")) {
            Toast.makeText(main.getApplicationContext(),
                    "An error has occured, please try again later.",
                    Toast.LENGTH_SHORT).show();
        } else {
            JSONObject jObj;
            try {
                jObj = new JSONObject(responseText);
                String folderString = jObj.getString("folder");

                String [] folders = folderString.split(";");
                //I need to return folders back to MainMenu Activity
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

My question is how I am supposed to modify so that I am able to read my Array back on my activity with my connections remains intact.

A: I would recommend that you declare your MainAsyncTask like this:
public class MainAsyncTask extends AsyncTask<String, Void, String[]> {

Then modify doInBackground to do all the processing that you are now doing in onPostExecute (except for the Toast part) and have it return the String[] (or null if there's an error). You can store the result code in an instance variable of MainAsyncTask and return null on error. Then onPostExecute has access to the same info that it does with your current code. Finally, if there is no error, just call a method in your main activity from onPostExecute to do the UI updates, passing it the String[] result.


text:
Q: How to find the sides of a rectangle if you know the sides of a quadrilateral inside the rectangle? I'm working on an application that uses a accelerometer to measure the sides of a room, I know it will not be exact measurements but it's fine.
In reality I would like the program to be able to calculate the sides of any room shape not only rectangles and squares (and more than 4 corners), but I'm starting with something more simple (rectangle shaped rooms).
My problem is not with the accelerometer but more with the math aspect of the code. Because I measured the room by placing the phone on a wall and then going to the connected wall, I will get the measurements of a quadrilateral inside the rectangle. From there, if it's possible, I will get the measurements of the sides of the rectangle, but I don't really know how.
What I've tried so far:
Divided the quadrilateral inside the rectangle in half, to make 2 triangles. Then I calculated the diagonal using the Pythagoras theorem. Then I used the law of Cosines to calculate one of the angles, and did the same again to find another. Then found the 3rd angle using the 2 other angles (c=a+b-180). I did this for both triangles.
I don't know if this is the right approach and if I have missed something simple, or if I simply don't have enough information to solve for the sides of the rectangle. I have looked into some geometry and trigonometry math online and haven't find anything that gives me a solution. But like I said, maybe I missed something simple.
Any push in the right direction would be helpful.
 The rectangle and the quadrilateral

A: The problem lacks a unique solution. Imagine placing a pair of calipers around the quadrilateral. You'll be able to rotate the  calipers around it, and at each angle the calipers will be able to close to a different width. Each of those widths is a different possible room dimension.
You'll also never get an accurate position measurement using the inertial sensors in a phone to begin with. The accels and gyros aren't even close to accurate enough. GPS is, but only outdoors away from structures that cause multipathing artifacts. Quick and sloppy with a tape measure will win every time.


text:
Q: Angular 'Uncaught error: Zone already loaded' Errors in console
I am using a Mailchimp Ajax Submit jQuery Plugin to submit an email using a PHP file on a contact form in a website template I imported to my Angular app. When I go to enter my details on the form and submit, the page refreshes on the POST request.
The console then throws the following two errors.
[Deprecation] Synchronous XMLHttpRequest
[Deprecation] Synchronous XMLHttpRequest
on the main thread is deprecated because of its detrimental effects to the
end user's experience. For more help, check https://xhr.spec.whatwg.org/.
(anonymous) @ polyfills.c5fb4ffca9c225046d5a.js:1
polyfills.c5fb4ffca9c225046d5a.js:1

Uncaught Error: Zone already loaded.
Uncaught Error: Zone already loaded.
at polyfills.c5fb4ffca9c225046d5a.js:1
at polyfills.c5fb4ffca9c225046d5a.js:1
at Object.0TWp (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.hN/g (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.5 (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at n (<anonymous>:1:376)
at e (<anonymous>:1:248)

I am finding it difficult to understand the cause of the problem. I have tried to prevent the page from refreshing on submit using <button type="button">, this does not do a page refresh however it does not call a POST request as expected.
I have also tried un-commenting import 'zone.js/dist/zone'; in polyfills.ts
I wish to accomplish sending the email on the same page without a refresh in the Angular app unless there is a better alternative. (I am learning)
main.js
var clContactForm = function() {

    /* local validation */
    $('#contactForm').validate({

        /* submit via ajax */
        submitHandler: function(form) {

            var sLoader = $('.submit-loader');

            $.ajax({

                type: "POST",
                url: "inc/sendEmail.php",
                data: $(form).serialize(),
                beforeSend: function() {

                    sLoader.slideDown("slow");

                },
                success: function(msg) {

                    // Message was sent
                    if (msg == 'OK') {
                        sLoader.slideUp("slow");
                        $('.message-warning').fadeOut();
                        $('#contactForm').fadeOut();
                        $('.message-success').fadeIn();
                    }
                    // There was an error
                    else {
                        sLoader.slideUp("slow");
                        $('.message-warning').html(msg);
                        $('.message-warning').slideDown("slow");
                    }

                },
                error: function() {

                    sLoader.slideUp("slow");
                    $('.message-warning').html("Something went wrong. Please try again.");
                    $('.message-warning').slideDown("slow");

                }

            });
        }

    });
};

sendEmail.php
<?php

// Replace this with your own email address
$siteOwnersEmail = 'my-email';

if($_POST) {

$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));

// Check Name
if (strlen($name) < 2) {
    $error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
    $error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
    $error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }

// Set Message
$message .= "Email from: " . $name . "
";
$message .= "Email address: " . $email . "
";
$message .= "Message:
";
$message .= $contact_message;
$message .= "
 -----
 This email was sent from your site's contact form.
";

// Set From: header
$from =  $name . " <" . $email . ">";

// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

if (!$error) {

    ini_set("sendmail_from", $siteOwnersEmail); // for windows server
    $mail = mail($siteOwnersEmail, $subject, $message, $headers);

    if ($mail) { echo "OK"; }
    else { echo "Something went wrong. Please try again."; }

} # end if - no validation error

else {

    $response = (isset($error['name'])) ? $error['name'] . "
 \n" : null;
    $response .= (isset($error['email'])) ? $error['email'] . "
 \n" : null;
    $response .= (isset($error['message'])) ? $error['message'] . "
" :
null;

        echo $response;

    } # end if - there was a validation error

}

?>


text:
Q: How to add a new line into a txt file using PHP I wrote a function to insert some text into a txt file (using a foreach), but I'd like to go in a new line for each element. Any suggestiong?
This is my function:
function process_page($page) {
    $html = get_html($page);

    foreach($html->find("h1") as $div) {

        $show = $div;
        $show = strip_tags($show);

        $data = '\n' . $show;
        $ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);

        if($ret === false) {
            die('There was an error writing this file');
        }
        else {
            echo "$ret bytes written to file";
        }

    }
}

I tried to insert '\n' but it write it into text file

A: Replace '\n' with "\n". The escape sequence is not recognized when you use '.
See the manual.

A: To ensure that it's platform independant - use PHP_EOL, this ensures it's the right encoding for the platform your currently running on.
$data = PHP_EOL . $show;


text:
Q: Vagrant unable to locate Virtualbox On Ubuntu 16.04.01
Using vagrant 1.8.1 and virtualbox 5.1.12.
I have already set
VBOX_INSTALL_PATH=/usr/bin/virtualbox
VBOX_MSI_INSTALL_PATH=/usr/bin/virtualbox

Getting the following error:
$ vagrant up
No usable default provider could be found for your system.

Vagrant relies on interactions with 3rd party systems, known as
"providers", to provide Vagrant with resources to run development
environments. Examples are VirtualBox, VMware, Hyper-V.

The easiest solution to this message is to install VirtualBox, which
is available for free on all major platforms.

If you believe you already have a provider available, make sure it
is properly installed and configured. You can see more details about
why a particular provider isn't working by forcing usage with
`vagrant up --provider=PROVIDER`, which should give you a more specific
error message for that particular provider.

as also this one:
$ vagrant up --provider=VIRTUALBOX
The provider 'VIRTUALBOX' could not be found, but was requested to
back the machine 'default'. Please use a provider that exists.

Any suggestions?

A: There seems to be a compatibility issue with the particular versions of vagrant and virtualbox.
A workaround seems to be the following:
A.
cd /usr/share/vagrant/plugins/providers/virtualbox/driver
edit meta.rb and add
"5.1" => Version_5_1
under the line: "5.0" => Version_5_0, (should be around line 63)
B.
cd /usr/share/vagrant/plugins/providers/virtualbox/
edit plugin.rb and add
autoload :Version_5_1, File.expand_path("../driver/version_5_1", __FILE__)
under the line: autoload :Version_5_0, File.expand_path("../driver/version_5_0", __FILE__) (should be around line 58)
C.
cd /usr/share/vagrant/plugins/providers/virtualbox/driver
create a file named version_5_1.rb with these contents.
Hopefully this tackles the problem.


text:
Q: Compare time using Laravel In my Laravel application I want to compare times
If time was greater than 23:30 and less than 6:00 returns true
else return false
$time1 = strtotime('23:30:00');
$time2 = strtotime('06:00:00');
$time3 = strtotime('01:30:00');

if ($time3>=$time1 && $time2>$time1 ) {
    var_dump('yes');
}
else {
    var_dump('no');
}

A: I would suggest using Carbon to compare date and datetime values:
$time1 = Carbon::createFromTimeString('23:30:00');
$time2 = Carbon::createFromTimeString('06:00:00');
$time3 = Carbon::createFromTimeString('01:30:00');

if ($time3->gte($time1) && $time2->gt($time1)) {
    var_dump('yes');
} else {
    var_dump('no');
}

A: Use Carbon, it has functionality to create from a certain format, with the createFromFormat() method.
$time1 = Carbon::createFromFormat('H:i:s', '23:30:00');

$time2 = Carbon::createFromFormat('H:i:s', '06:00:00');

$time3 = Carbon::createFromFormat('H:i:s', '01:30:00');

Carbon has comparisons in built, with gt() being greater than and lt() being less than. Adding an e to the call as lte() would be less than equals. Or you can be more explicit, look through this section in the documentation.
if ($time3->gte($time1) && $time2->gt($time1)) {
    //
}
else {
    //
}


text:
Q: Change of coordinates principle for mapping class groups So I am reading Farb and Margalit's text, and his statement for the change of coordinates principle doesn't seem complete. Namely, he states that there is an orientation preserving homeomorphism of a genus g surface sending one collection of curves to another if they have the same intersection pattern. However I think we also need to stipulate that the complements of the curve have the same type of connected components. Am I mistaken? Please correct me if I'm wrong. I just want to make sure my understanding of the principle is correct or not.

A: Your intuition that cutting along these curves should not result in different surfaces is completely correct. The following two pairs of curves, $(\alpha,\beta)$ and $(a,b)$, cannot be sent to one another by any homeomorphism, for the connected components they cut off of the surface are not homeomorphic.

However, this is somewhat of a special case, as I chose a bounding pair of curves that have different genus. Note that the Primer mentions that the given statement of the change of coordinates principle is "rough." Pages 39-40 give examples of different types of pairs of curves, and mentions a few where only the intersection number is needed, e.g. when it is equal to one.


text:
Q: How can I design my database to prevent my database to update if an error is produced later in the program? I am using a DynamoDB database to store users and a running counter of missed shifts. Essentially, each month I look at each member's data, and if they were scheduled for less than 4 shifts, I query the member from my table, increment the count, and re-add it into the database. One major problem I have with this is because I tend to edit my program frequently, the program occasionally errors out. However, sometimes this error occurs after the database was updated. How can I better design my database so that if an error occurs, it does not update the table and it only updates if the program completes successfully? By the way, all of my program is in one lambda.
One possible solution I can think of is once my lambda returns a successful execution code, it can pass the data to another lambda (SNS/SQS, streams, etc.), which would simply update the database. Are there any other more efficient solutions I'm not thinking of?

A: instead of using two lambdas, a simpler approach is would be to restructure the code of your lambda such that it does the DynamoDB update as its last step. So, your code will look as follows (pseudo code):
do something
do something
...
update DynamoDB
return the result

Actually, at the same point in your code where you wanted to invoke the second lambda (via "SNS/SQS, streams, etc.") you can instead do the update of DynamoDB directly.
side note
In general, if you need one lambda to invoke another lambda, the simplest way to do that is to use AWS' Lambda API which allows you to make a call to a lambda without the need to setup SNS or a stream or any other service for that matter.
Examining the Javascript API as an example (the APIs in the other languages are quite similar) you can see that it offers an invoke() method and an invokeAsync() method. The former allows you to send a request to lambda function and get a response back. the latter just sends the request without waiting for a response.


text:
Q: Cipher suite needed for downloading from windows store Does anyone know which Cipher Suite needs to be enabled on a Win10 machine to download packages from the Windows store. I need to configure my device with a subset of ciphers and when I do it fails with error 0x80240438.
I used fiddler and i saw the connection from svchost being closed.
Note that if I disable the custom cipher list, I don't have a problem.
Here is the cypher list I have configured:
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384_P384
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384_P256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P384
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA_P384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA_P256
TLS_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA


text:
Q: change Visual Studio toolbars - customize location of comment out / uncomment out In Visual Studio 2013 Premium, I would like to add the "Comment Out" and "Uncomment Out" icons to the Text Edit Toolbar (to be near the bookmark icons).
However, when I go into Text Editor Toolbar drop down for Add or Remove Buttons. and then > Customize > Add Command, I cannot locate the Comment Out and Uncomment Out buttons in any of the Categories. (In Premium their default location is on the "Standard" toolbar).
Any suggestions on how to accomplish what I'm trying to do would be appreciated.
Thanks!

A: You can find them in the Edit category as Selection Comment and Selection Uncomment.

A:
why it is not working in your perspective !

A: Click on the Add/Remove buttons in the toolbar.  Select Customize.


text:
Q: Geometric Brownian Motion - Normal distribution I have the following formula:
Geometric Brownian Model Formula
Does anyone know if the portion highlighted in yellow, corresponds to a normal distribution with mean = 0 and standard deviation = 1? Or is it a uniform distribution between 0 and 1?

A: It refers to the former, i.e. a normal random variable with mean $0$ and standard deviation $1$.
(If you search up a proof of the solution to the geometric brownian motion stochastic differential equation, you will see a "Wiener process"/brownian motion term appearing, which is where the normal distribution comes from.)


text:
Q: python: I want to sort a list, which is in a dict In the following code test1 works, test2 does not.
I think the copy doesn't copy to where it's supposed to.
Is this a namespace problem? Can you explain to me whats going on - or even better, how to make test 2 work (items in the must_be_sorted array, so that I can make a general purpose function)?
import copy

## test 1

items = {"gi":[{"urc":2}, {"urc":1}]}

must_be_sorted = [{"l":"gi", "key":"urc"}]

for ls in must_be_sorted:
    items[ls["l"]] = sorted(items[ls["l"]], key=lambda k: k[ls["key"]])

for u in items[must_be_sorted[0]["l"]]:
  print "a:", u["urc"],
print

for u in items["gi"]:
  print "b:", u["urc"],
print

## test 2

items = {"gi":[{"urc":2}, {"urc":1}]}

must_be_sorted = [{"l":items["gi"], "key":"urc"}]

for ls in must_be_sorted:
    #ls["l"] = sorted(ls["l"], key=lambda k: k[ls["key"]])
    ls["l"] = copy.copy(sorted(ls["l"], key=lambda k: k[ls["key"]]))
    for u in ls["l"]:
      print "c:", u["urc"],
print

for u in items["gi"]:
  print "d:", u["urc"],

'''
a: 1 a: 2
b: 1 b: 2
c: 1 c: 2
d: 2 d: 1
'''

A: ls["l"] and items["gi"] in test 2 point to different objects. I can use locals()["items"] to get to the same object.


text:
Q: Add variable number of variables I need to parse a CSV file for certain fields, and based on matching a pattern I need to add fields together. I've succeeded in setting variables, but need help figuring out how to add them when there may be 1-20 variables. (Or possibly another, simpler way to approach this.)
Source file contents example:
Server-Name,Volume-Name,Vol-Size,Logical-Space-In-Use
FTWTRAQNETSQL01,FTWTRAQNETSQL01_e,2008,1989
FTWTRAQNETSQL01,FTWTRAQNETSQL01_f,106,63.698
FTWTRAQNETSQL02,FTWTRAQNETSQL02_e,2008,1989
FTWTRAQNETSQL02,FTWTRAQNETSQL02_f,106,4.155
ftwvocmpsqln01,ftwvocmpsqln01_1,1002,21.047
ftwvocmpsqln01,ftwvocmpsqln01_2,104,55.379
ftwspsqln02,ftwspsqln02_H,501,0
ftwvocmpsqln02,ftwvocmpsqln02_1,1002,20.732
ftwvocmpsqln02,ftwvocmpsqln02_2,104,55.380

Output should be one line for each each unique server name, and adding all the field 3 values and  all the field 4 values. Servers can have many volumes, some as many as 20. Desired file output would be:
Server-Name,Vol-Size,Logical-Space-In-Use
FTWTRAQNETSQL01,2114,2052.698
FTWTRAQNETSQL02,2114,1993.155
ftwvocmpsqln01,1106,76.426
ftwspsqln02,501,0
ftwvocmpsqln02,1106,76.112

I can do this in about 7 seconds in Excel, but so far haven't figured out a solution for automating with bash (or other shells.)
This is the code I have so far, only looking at field 3. It correctly sets variables for each iteration of unique servers, but I can't figure out how to do the addition with a variable number of variables.
for i in $( awk -F , '{print $1}' $REPORT | grep -v Server-Name | uniq )
do
    c=0
    for num in $( grep $i $REPORT | awk -F , '{print $3}' )
        do
        eval "var$c=$num";
        c=$((c+1));
    done
done

A: With GNU datamash:
$ datamash -t, --header-in groupby 1 sum 3,4 < file.csv
FTWTRAQNETSQL01,2114,2052.698
FTWTRAQNETSQL02,2114,1993.155
ftwvocmpsqln01,1106,76.426
ftwspsqln02,501,0
ftwvocmpsqln02,1106,76.112

A: Not a shell, but "unix way":
awk -F',' 'NR==1; NR>1{s3[$1]+=$3; s4[$1]+=$4} END { for(i in s3){printf("%s,%s,%s\n",i,s3[i],s4[i])} }' file

The order of the output will (probably) not match the input order.
Description:
awk                   # use awk.
-F','                 # set the field separator as comma (,)
'                                         # start an awk script.
   NR==1;                                 # print first line (header)
   NR>1{                                  # for lines other than first
         s3[$1]+=$3;                      # add values on third field
         s4[$1]+=$4                       # add values on fourth field
       }                                  # close the previous {
         END {                            # after all lines have been read
               for(i in s3){              # for each index of the array
                                          # (all unique values of field $1)
                             printf("%s,%s,%s\n",i,s3[i],s4[i])   # print values.
                           }              # close the for loop.
             }                            # close the END loop.
' file                                    # end script code and name the file.

A: Using Miller (mlr) to compute the sums of the two columns Vol-Size and Logical-Space-In-Use, grouping by the Server-Name field:
$ mlr --csv stats1 -a sum -f Vol-Size,Logical-Space-In-Use -g Server-Name file
Server-Name,Vol-Size_sum,Logical-Space-In-Use_sum
FTWTRAQNETSQL01,2114,2052.698000
FTWTRAQNETSQL02,2114,1993.155000
ftwvocmpsqln01,1106,76.426000
ftwspsqln02,501,0
ftwvocmpsqln02,1106,76.112000


text:
Q: jquery click, toggle one or more div block I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});

this clicked

Show this

fhslkjklsfjl

A: Try This :-

this clicked

Show this

2 nd button

fhslkjklsfjl

       $("div#toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });

https://jsfiddle.net/9oh6yqfn/9/

A: You can not use same id. ID should be unique.
Try by giving class:

  $(".toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });

this clicked

Show this

2 nd button

fhslkjklsfjl

A: You cannot have same id for both spans. Try using different id's for span.
For eg:

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});

this clicked

Show this

fhslkjklsfjl


text:
Q: how to drag the window size in wxwidgets? In the following image you can see two parts:

I want to know, what I have to do that I can grap and drag the pipe between those two windows?
main ld script    |  constants memory

If it cannot be done with wxformbuilder, I would like to know how to code it?

A: On the "Containers" page in wxFormbuilder, there is a splitter window control.  It can have 2 subwindows as children and will have a small "sash" area between them that a user can drag to resize them.


text:
Q: Unknown crash report android I have released an app on Google play store and started rolling out updates, the latest one seemed to worked fine until I received this crash report from a user
can anyone help me figure out what it is exactly, what caused it and the possible ways of fixing it ?
Device info: Asus ZenFone 2 (ZE500CL) (ASUS_Z00D), 2048MB RAM, Android 5.0
Backtrace:
native: pc 0000000000090df6  /system/lib/libc.so (tgkill+22)
native: pc 0000000000038d13  /system/lib/libc.so (pthread_kill+163)
native: pc 000000000003a5f5  /system/lib/libc.so (raise+37)
native: pc 0000000000032855  /system/lib/libc.so (abort+85)
native: pc 00000000000104da  /system/vendor/lib/libsrv_um.so.1.12.3197934 (PVRSRVDebugAssertFail+58)
native: pc 0000000000006e82  /system/vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so.1.12.3197934
native: pc 000000000001b576  /system/vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so.1.12.3197934
native: pc 000000000001b6d1  /system/vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so.1.12.3197934
native: pc 0000000000009d72  /system/vendor/lib/libIMGegl.so.1.12.3197934
native: pc 000000000000fcea  /system/vendor/lib/libIMGegl.so.1.12.3197934 (IMGeglMakeCurrent+1514)
native: pc 00000000000015a3  /system/vendor/lib/egl/libEGL_POWERVR_SGX544_115.so.1.12.3197934 (eglMakeCurrent+51)
native: pc 000000000001133f  /system/lib/libEGL.so (android::egl_display_t::makeCurrent(android::egl_context_t*, android::egl_context_t*, void*, void*, void*, void*, void*, void*)+303)
native: pc 0000000000014e3b  /system/lib/libEGL.so (eglMakeCurrent+635)
native: pc 0000000000087fce  /system/lib/libhwui.so
native: pc 000000000008247f  /system/lib/libhwui.so
native: pc 0000000000088b24  /system/lib/libhwui.so
native: pc 0000000000088623  /system/lib/libhwui.so
native: pc 000000000008b55a  /system/lib/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+154)
native: pc 0000000000016ece  /system/lib/libutils.so (android::Thread::_threadLoop(void*)+398)
native: pc 0000000000071d23  /system/lib/libandroid_runtime.so (android::AndroidRuntime::javaThreadShell(void*)+99)
native: pc 00000000000165cb  /system/lib/libutils.so (thread_data_t::trampoline(thread_data_t const*)+123)
native: pc 0000000000037cdb  /system/lib/libc.so (__pthread_start(void*)+59)
native: pc 0000000000032fba  /system/lib/libc.so (__start_thread+26)
native: pc 0000000000011df6  /system/lib/libc.so (__bionic_clone+70)

A: That's a native crash meaning a bug that was in the user's device itself not a bug in your code. I don't know what's the bug though, but that's what it means. I, personally, sometimes ignore these types of crashes if they don't occur too much. But if it occurs again and again, then you will have to see what new code you added in your new version and try to find out what was causing this issue by removing parts of your new code part by part and test it on the same device until you find it out. Unfortunately, you may not have the same device, but that's the way to fix this if it's really needed.

A: You can use CrashLet

Implementation

In your build.gradle
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

In your application's build.gradle
dependencies {
        implementation 'com.github.Collabalist:CrashLet:1.5'
}

Usage:
public class SamApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        CrashLet.with(this)
            .addRecipient("abc@gmail.com")
            .addRecipient("xyz@gmail.com")
            .showStackTrace(true)
            .init();
    }
}


text:
Q: Java NoClassDefFoundError initialization error after Lotus Domino upgrade from Version 6.5.3 to 8.5.2 We have upgraded Lotus Domino upgrade from Version 6.5.3 to 8.5.2, After upgrading we are getting initialization error while calling Java methods.
The classes are kept at a location say d:\javaclasses and an entry is made in notes.ini as shown below
JavaUserClasses=.;d:\javaclasses;d:\javaclasses\lib... etc.
Everything call to java works on Version 6.5.3 however it does not work on 8.5.2.
We have not changed any java files, Just copied from older version to new version server at the same location
Note: d:\javaclasses classes are compiled using JDK1.3, Domino Version 6.5.3 uses JDK1.3 native library,
Domino Version 8.5.2 uses JDK1.6 native library inbuilt
Stack trace for reference.
java.lang.NoClassDefFoundError: com.centtric.td.cprm.AppSource (initialization failure)
 at java.lang.J9VMInternals.initialize(J9VMInternals.java:140)
 at com.centtric.td.cprm.Coverage.<init>(Coverage.java:87)
 at com.centtric.td.cprm.Coverage.find(Coverage.java:572)
 at CPRMLib.deleteCoverage(CPRMLib.java:913)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
 at java.lang.reflect.Method.invoke(Method.java:600)
 at lotus.domino.JavaConnectInvoker.invoke(Unknown Source)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
 at java.lang.reflect.Method.invoke(Method.java:600)
 at lotus.domino.JavaConnectLoader.invoke(Unknown Source)
Caused by:
java.lang.NullPointerException
 at com.centtric.connectors.JDBCConnector.closeStatements(JDBCConnector.java:484)
 at com.centtric.connectors.JDBCConnector.closeAll(JDBCConnector.java:431)
 at com.centtric.td.cprm.AppSource.init(AppSource.java:70)
 at com.centtric.td.cprm.AppSource.get(AppSource.java:79)
 at com.centtric.td.cprm.AppSource.<clinit>(AppSource.java:32)
 at java.lang.J9VMInternals.initializeImpl(Native Method)
 at java.lang.J9VMInternals.initialize(J9VMInternals.java:200)

A: It's hard to say, but it looks like your new JVM either is missing some native libraries, or don't have the same classpath as your old JVM has. Are you sure the ini-file format hasn't changed?
J9VMInternals is an IBM-specific class that takes care of classloading and stuff.


text:
Q: Extending the capacity of the Hard Drive I was wondering if it is possible to substitute an internal laptop Hard Drive, with a 256 GB capacity, for another Hard Drive of 500 GB.
I was also wondering if my laptop has an SSD card. It is a Toshiba SATELLITE L745-S4210. I didn´t know what an SSD card is, and i still don´t know it very well. But someone suggested that I could replace an SSD card to increase the audio quality of my audio works.
Couldn't I replace the Hard Drive in order to increase the audio quality aswell? Sorry if my questions are a bit unclear...

A: Usually to increase the size of your HDD make your computer and you happier.
You can substitute the internal HDD.
SSD usually is for Solid State Drive.
About the connection with "Audio quality of your work" feel you free to ask again to the original prompter because it's rather unclear. The only possible reason that I can imagine is that you have to save in a low quality format the files you are processing due to lack of spaces on the HDD.
You can download the specifications of your laptop from the site of the prodicer Toshiba click on the tab Manuals & Specs.
You can read about that model, for example, on a specialized magazine too.

A: alot of stuff going on here.. First things first... what are you doing with your pc? audio processing or movie production or just simply surfing the internet and listening to music?
Improving audio does not come from changing hard drive.. changing hard drives does not change what speakers are pyshically in the computer.. to do this you should buy a decent set of desktop speakers and call it a day if you just want to improve quality.. there's more that goes into that like source of the music file and type but if your streaming then you dont have to worry about that...
Now, to clarify this SSD shenanigans... SSD means solid state hard-drive and HDD is a hard disk hard drive..  if you only have a max capacity on your hard-drive of 256 you may already have a SSD installed but I feel like you would know it if you did ... but to check you hit windows button and search for "optimize drives: and next to C:\ it will tell you what the "media type" is..
Unless you are saying you only have 256 gbs left of a stock HDD.. which.. is plenty .. you can run disk clean up and defrag and clean up the computer but you are good with over 200gbs of space.
For a 500gbs SSD you are looking to spend a couple hundred $dollars$ (USD) for something you may not need.  Check out external harddrives you can get a 1 Tera byte drive for under 100$ USD these days..
FINAL THOUGHTS
1) Run a disk clean up and defrag and possible buying a external hard drive for storage
2) Put money into desktop speakers if you want to improve audio quality - not much can be done besides replace and the internal speakers.. and thats not worth the headache...
3) if you are doing audio/video production a SSD would help with overall performance of the software youre running not sound quality though.. it would be less choppy but not cleaner ... stick to what you got if you arent though
GOOD LUCK!


text:
Q: dyld: Library not loaded: @rpath/ ... Reason: image not found with a simple Hello world applicat I am running into some trouble when trying to use SwiftCSV using CocoaPods and following the basic instructions.
After creating the simple Hello world console application for OS X from the template in XCode 7.3.1, I opened a terminal window and navigated to the project folder and issued a pod init
I then edited Podfile by adding the line below in the target section:
  pod "SwiftCSV"

I then executed pod install, which completed successfully.
After loading the resulting .xcworkspace in XCode, when I run the application, I get the following error:
dyld: Library not loaded: @rpath/SwiftCSV.framework/Versions/A/SwiftCSV
  Referenced from: /Users/paolomarini/Library/Developer/Xcode/DerivedData/BundleGeneratorSwift-egsxgxpdiuvqrfddzyzcxnwltulk/Build/Products/Debug/BundleGeneratorSwift
  Reason: image not found
Program ended with exit code: 9

Note that I didn't specify a platform in Podfile as I can't figure out what the correct value is for OS X. The Podfile is as below:
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'BundleGeneratorSwift' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for BundleGeneratorSwift
  pod "SwiftCSV"
end

Thanks,
Paolo


text:
Q: Cannot write ă symbol in name during Windows 10 setup I am starting a brand new PC with Windows 10 pre-installed for the very first time. Now I am stuck because I cannot write the user name with this special character ă.
I try to use the Alt + ASCII code (259=ă), nothing happens, but it is working for Ā ("Alt" + 256).

System region: Switzerland
Keyboard layout: Swiss-German
Installed language packages: Maybe the one which I could select a few steps before: German - English (UK) - French - Italian

Does anyone know a solution or restriction about this character?

A: For the moment, you can write the name without the breviated 'a' (ă).
Later, you will be able to change the user account name through Control Panel by copying and pasting the character.
Once the account is set up as an admin, go to "Control Panel\User Accounts\User Accounts", click "Manage User Accounts", and click "Properties".
Now you can change the username to include the breviated 'a'.
Good luck!


text:
Q: (Countable) partition generated $\sigma$-algebra I am working on exercise 1.9 b) in the book "Probability and Stochastics" by Erhan Çınlar to  practice my understanding of $\sigma$-algebras (although this might possibly be future homework in my classes).
Anyway, here's the exercise:
Let $\mathcal{C}$ be a (countable) partition of E. Show that every element of $\sigma \mathcal{C}$ is a countable union of elements taken from $\mathcal{C}$.
So, $\mathcal{C} = \{ C_n: n \in \mathbb{N}\}$ is a partition of $E$.
To prove the exercise, I have introduced $\mathcal{E} = \{\cup_{i \in I} C_i: I \subseteq \mathbb{N}\}$ and am trying to show that $\mathcal{E}$ is a $\sigma$-algebra.
For this, I have to show the following three parts/properties (correct me if I'm wrong):

*

*E $\in \mathcal{C}$: $\mathcal{C}$ is a partition of E, so $\cup \mathcal{C}=E.$ Since $\mathcal{C}$ is countable, $\cup \mathcal{C}$ is the union of countably many members of $\mathcal{C}$.

*Show that $\mathcal{E}$ is closed under countable unions: Since $\mathcal{E}$ consists only of sets which are countable unions of elements of $\mathcal{C}$, $\mathcal{E}$ is closed under countable unions.

*Show that $\mathcal{E}$ is closed under complement: Let $A \in \mathcal{C}$, so there exists a countable $\mathcal{C}_A \subseteq \mathcal{C}$ such that $A = \cup \mathcal{C}_A.$ Let $\mathcal{D} = \mathcal{C} \setminus \mathcal{C}_A$; then $\mathcal{D}$ is a countable subset of $\mathcal{C}$, and if $D =\cup \mathcal{D},$ then $D \in \mathcal{C}.$ Since $\mathcal{C}$ is a partition on E, $D = E \setminus A = A^c$, and so $A^c\in \mathcal{C}$.
Now, in the last part I want to show that $\mathcal{E} = \sigma\mathcal{C}$, but I'm not sure how exactly this is done.

A: Here's a proof using only the material covered in Çınlar before your exercise. As you showed, $\mathcal{E}$ is a $\sigma$-algebra containing $\mathcal{C}$. It is obviously contained in $\sigma(\mathcal{C})$ : to see that, all we have to say is that $\sigma(\mathcal{C}$ must contain all the countable unions of elements in $\mathcal{C}$, so it contains all the elements of $\mathcal{E}$. Therefore, $\mathcal{E} \subset \sigma (\mathcal{C})$.
But,  $\sigma(\mathcal{C})$ is defined as the intersection of all the $\sigma$-algebras containing $\mathcal{C}$. Therefore, as $\mathcal{E}$ is a $\sigma$-algebra containing $\mathcal{C}$, it is clear that $\sigma(\mathcal{C})$ is contained in $\mathcal{E}$.
So, $\mathcal{E} = \sigma (\mathcal{C})$.
This kind of reasonning is very very common in measure theory, analysis, probability. Make sure you understand all the things here. It works like this : to prove that two $\sigma$-algebras are equal, you write one as the $\sigma$-algebra generated by a collection, and you show that the other is a $\sigma$-algebra containing this collection and contained in the first one.
Have a nice time with Çınlar's excellent textbook :)


text:
Q: Div changes depending on a  menu I'm trying to do something similar to this: http://jsfiddle.net/JSyLV/1/
But I can't get that code to work in dreamweaver, simply from copy and paste.
I put the javascript code in my header using  and
and directly copied the html to my body, but all the divs show and its not applying the javascript to the drop down menu. Am I implementing the javascript code incorrectly?

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>TEST</title>

asdf

kljh

zxcv

qwerty

    <select id="selectMe">
        <option value="option1">option1</option>
        <option value="option2">option2</option>
        <option value="option3">option3</option>
        <option value="option4">option4</option>
    </select>

A: It's more likely that you got JQuery loaded incorrectly into your dreamweaver project. A quick fix would be to add this in the header before the first script tag :

Which leads to : http://pastebin.com/gtLyVcU2

A: This will work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 2</title>

asdf

kljh

zxcv

qwerty

<select id="selectMe">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>


text:
Q: What could be wrong with my code so that instead of printing all the subsequences of a string it is printing an empty subsequence? Hi I have tried to print all subsequences of a string but it is not giving the output please help me if there is an error in my code
I couldn't figure what's wrong with my code as I am still learning please help me out
Here I am passing two inputs to a function string and empty string and after that I am doing recursion where it will push the results into vector v after the input size of string becomes 0 and it return the vector back to the main function. But it is not printing my string subsequence...
'''
#include<iostream>
#include<vector>
using namespace std;

vector<string> gss(string ip, string op)
{
    vector<string> v;
    if(ip.length()==0)
    {
        v.push_back(op);
        return v;
    }

    string op1, op2;
    op1 = "";
    op2.push_back(ip[0]);
    ip.erase(ip.begin()+0);

    gss(ip, op1);
    gss(ip, op2);

    return v;

}

int main()
{
    string str;
    cin >> str;

    vector<string> ans = gss(str, "");

    cout<<"[";
    for(auto it: ans)
        cout<<it<<" ";
    cout<<"]";

    return 0;
}
'''


text:
Q: How to target first element from list for guide in into.js I am trying to use intro.js-react for website onboarding in ReactJs.
i am facing issue when trying to target first element from a list.
my code-
const [tour, setTour] = useState({
    steps: [
           {
            element: '#tourqty2',
            intro:
Add number of product to  order
,
            position: 'left',
           },
      ]
    })

inside return
<Steps enabled={stepsEnabled} steps={tourSteps} initialStep={initialStep} onExit={onExit} />
<Hints enabled={hintsEnabled} hints={tourHints.hints} />

and i want to target below element
<Col md="2" >
    <input type="text"
    id={`tourqty${key+1}`}
    className="tour-qty"
    value={row.adjustedQty}
    onFocus={e => resetInput(e)}
    placeholder={"0"}
    style={{width: '80px', textAlign:'right', border: '1px solid #89D329', borderRadius: '2px'}}
    onChange={e => changeAdjQty({row,key, e})}
    onBlur={e => updateStock({row, key, e})}/>
</Col>

for other element where i am using static id, it is working fine there

for dynamic id-
it is not highlighting input field

Please help.
Any help will be appreciated.
Thanks in Advance


text:
Q: How to test certificate validation with OCSP address in powershell I have certificate and when I try to test my digital signature code one error raised for OCSP validation. Now I want to check OCSP address and my certificate validation with powershell to test and find my error.
I need the powershell command to check validation of my certificate with OCSP address.

A: We have certutil tools in cmd for test a certificate validity with ocsp or crt file
Certutil -path 'address of csertificate'
When you run this command windows open a little tools for test your certificate
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/certutil


text:
Q: Is a finite convex function subdifferentiable everywhere? Let $X$ be a (infinite-dimensional) Hilbert space and $f:X\to\mathbb{R}$ be convex. Then is $f$ subdifferentiable everywhere in $X$?
I have looked at Non-subdifferentiable convex function on a normed space and it is clear that there are counterexamples when $f$ can take value $+\infty$. However, what about finite convex functions?
The answer by Tom suggests that convex functions should be subdifferentiable on their relative interior - does someone have a reference and/or proof for this?

A: Let $\tilde{\mathbf{x}}\in\text{ri}(\text{dom}(f))$. Since the vector $(\tilde{\mathbf{x}}, f(\tilde{\mathbf{x}}))\subseteq\mathbb{R}^n\times\mathbb{R}$ is on the relative boundary of $\text{epi}(f)$, it follows by the supporting hyperplane theorem that there exists a separating hyperplane between $(\tilde{\mathbf{x}}, f(\tilde{\mathbf{x}}))$ and $\text{epi}(f)$, meaning that there exists a nonzero vector $(\mathbf{p},-\alpha)$ for which \begin{equation}\tag{1}
\mathbf{p}^T\tilde{\mathbf{x}}-\alpha f(\tilde{\mathbf{x}})\geq\mathbf{p}^T\mathbf{x}-\alpha t,\quad \forall (\mathbf{x},t)\in\text{epi}(f).
\end{equation}
Since $(\tilde{\mathbf{x}}, f(\tilde{\mathbf{x}}))$ is on the boundary of $\text{epi}(f)$ it follows that $(\tilde{\mathbf{x}}, f(\tilde{\mathbf{x}})+1)\in \text{epi}(f)$ as well. Hence we can plug $\mathbf{x}=\tilde{\mathbf{x}}$ and $t=f(\tilde{\mathbf{x}})+1$ to the equation above and get
$$\mathbf{p}^T\tilde{\mathbf{x}}-\alpha f(\tilde{\mathbf{x}})\geq\mathbf{p}^T\tilde{\mathbf{x}}-\alpha(f(\tilde{\mathbf{x}})+1 )\quad \iff \alpha\geq 0. $$
After showing that $\alpha\geq 0$ we need to prove that $\alpha\neq 0$. Denote $A_f=\text{aff}(\text{dom}f)$. Since $\text{epi}(f)\subseteq A_f\times\mathbb{R}$ and a supporting hyperplane $(\mathbf{p},-\alpha)$ by definition does not contain $\text{epi}(f)$, it does not contain $A_f\times\mathbb{R}$ as well. Now consider the affine combination $\mathbf{y}_{\lambda}=(1-\lambda)\tilde{\mathbf{x}}+\lambda\mathbf{y},\;\lambda\in\mathbb{R}$. The points in this line all lie in the affine set $A_f$ and $\mathbf{y}_{\lambda}\to\tilde{\mathbf{x}}$ as $\lambda\to 0$. Since $\tilde{\mathbf{x}}\in\text{ri}(\text{dom}(f))$, for small values of $|\lambda|$ the points $\mathbf{y}_{\lambda}$ lie in $\text{dom}(f)$. Hence we can plug $\mathbf{y}_{\lambda}$ into $(1)$ and get (after some  algebra)
$$\lambda\mathbf{p}^T(\tilde{\mathbf{x}}-\mathbf{y})-\alpha(f(\tilde{\mathbf{x}})-f(\mathbf{y}_{\lambda}))\geq 0.\tag{2}$$
Inequality $(2)$ must hold for sufficiently small positive and negative values of $\lambda$. As long as $\alpha>0$ there is no problem and the inequality still holds$^\textbf{**}$. Assume in contradiction that $\alpha=0$. Then $(2)$ becomes $\lambda\mathbf{p}^T(\tilde{\mathbf{x}}-\mathbf{y})\geq 0$ which cannot hold for both positive and negative values of $\lambda$.
Take a deep breath, we're almost done :)
After establishing that $\alpha>0$ we can divide $(1)$ by it to get
$$f(\mathbf{x})\geq f(\tilde{\mathbf{x}})+\mathbf{g}^T(\mathbf{x}-\tilde{\mathbf{x}}),\quad \forall \mathbf{x}\in\text{dom}(f)$$
where $\mathbf{g}=\mathbf{p}/\alpha$. Thus $\mathbf{g}\in\partial f(\tilde{\mathbf{x}})$, establishing the non-emptiness of $\partial f(\tilde{\mathbf{x}})$.
$^\textbf{**}$If you analyze $f(\mathbf{y}_{\lambda})$ you notice it's monotone decreasing in $\lambda<0$ (it increases as $\lambda$ moves away from zero in the negative direction), hence offsetting the change of sign from $\lambda\mathbf{p}^T(\tilde{\mathbf{x}}-\mathbf{y})$.


text:
Q: h2o4gpu Dockerfils - CentOS vs Runtime and Starting Image I have been working with building the h2o4gpu Docker image, and after getting through the build process for the CentOS image, have found myself with a few more questions:

*

*What is the difference between the Dockerfile_runtime, and Dockerfile-build-centos.x86-64-centos7-cuda9.0? Near as I can tell, the Dockerfile_runtime is intended for an Ubuntu image, but is there a preferred one to use?

*After building the Centos Dockerfile, I have been using the below code to try and run it:
Docker run -it --rpm -p 8888:8888 dockerimage
When I do, I get the error:
Error response from daemon: oci runtime error: container linux.go:247: starting container process caused "exec \"./run.sh\": stat ./run.sh: no such file or directory

I did try adding in the included run.sh file, partially since I saw that it was included in the Dockerfile_runtime:
COPY run.sh /run.sh
ENTRYPOINT ["./run.sh"]
CMD ["/run.sh]

However, this didn't have any visible changes on the output, so I've been scratching my head what to do next.
I appreciate any insight or thoughts offered!
Thank you!

A:
What is the difference between the Dockerfile_runtime, and Dockerfile-build-centos.x86-64-centos7-cuda9.0?

The build dockerfiles (we have 2) are intended to only contain things required to build the project, whereas the runtime one also contains stuff required by the project during runtime, adds some sample data and starts a Jupyter notebook. The Centos one was added as the binaries generated by the Ubuntu image cannot run on quite a few Linux distros easily (due to high glibc version used by Ubuntu). We have a PR which rewrites all our dockers as Centos based but still need to test it more before merging.

but is there a preferred one to use?

For building the whl either Dockerfile-build or the Centos one are ok. If you want a runtime docker then Dockefile-runtime is prefered.

After building the Centos Dockerfile

How are you building it? You can have a look at our docker building scripts how we do it https://github.com/h2oai/h2o4gpu/blob/master/scripts/make-docker-runtime.sh There should be no need to add that run.sh file as it's being copied in the dockerfile. The Centos docker file does not start Jupyter, expose 8888 nor contain run.sh.


text:
Q: Can I get a C# Visual studio program to control a raspberry pi? I am working on a project that combines a visual studio application and a raspberry pi.
Is there an easy way to run a terminal program (like "python script.py") on a raspberry pi through a C# Visual Studio Program and retrieve the results?

A: IF YOU RUN Windows 10 ON YOUR Raspberry .
You can use a remote Powershell on a Raspberry running Windows 10 with the following :
# Start WinRM on the local Windows OS
net start WinRM

# Vérify RaspBerry PI3 access
Test-Connection jpbraspbpi3-1

# Allow accesss to Raspberry PI3
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'jpbraspbpi3-1'

# Etablish the connexion
Enter-PSSession -ComputerName 'jpbraspbpi3-1' -Credential (Get-Credential -UserName 'administrator' -Message 'Mot de passe !')

# You can allow a pseudo cmd.exe command line on the Windows 10 of your Raspberry
reg.exe ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\EmbeddedMode\ProcessLauncher" /v AllowedExecutableFilesList /t REG_MULTI_SZ /d "c:\windows\system32\cmd.exe\0"

Then you can use developp using .NET core on Raspberry.
IF YOUR RUN RASPBIAN, you can deploy Mono and develop with visual studio or visual Code (.net core).


text:
Q: Scala string pattern match regex a star multiple findallin I want to parse this string: "er1r2r3" with: """(e|w|n|s)(r[1-3])*""".r
  val SideR = """(e|w|n|s)""".r

  val PieceR = """(r)([1-3])""".r

  def parseSidedPieces(str: String): (Char, List[Char]) = {
    val side = str(0) match {
      case SideR(s) => s
    }

    val pieces = parsePieces(str.tail)

    (side, pieces)
  }

  def parsePieces(str: String): List[Char] = {
    PieceR.findAllIn(str).toList map {
      case PieceR(c, n) => n
    }
  }

But this throws on empty string "" because str(0).
Fix this, regex only.

A: I don't think this can be fixed 'regexes only' (whatever that is supposed to mean), because the code fails before the first regex is used.
It fails because you call apply(index: Int) on an empty String. So, either you do an isEmpty check before calling str(0) or even parseSidedPieces, or you change the code and match the whole String:
val PieceR = """(r)([1-3])""".r
val CombinedR = "(e|w|n|s)((?:r[1-3])*)".r

def parseSidedPieces(str: String): (Char, List[Char]) = {
  str match {
    case CombinedR(side, pieces) =>
      (side(0), parsePieces(pieces))
    case "" =>
      // hmm, what kind of tuple would be a good return value here? maybe:
      throw new IllegalArgumentException(s"Unexpected input: $str")
    case _ =>
      // handle unmatched strings however you like, I'd do:
      throw new IllegalArgumentException(s"Unexpected input: $str")
  }
}

def parsePieces(str: String): List[Char] = {
  PieceR.findAllIn(str).toList map {
    case PieceR(c, n) => n(0)
  }
}

parseSidedPieces("er1r2r3") |-> res0: (Char, List[Char]) = (e,List(1, 2, 3))


text:
Q: Windows server and ddns which binding and sql hostname do i use? i'm trying to connect to websites on this server from outside the network. i've opened ports in router and firewall and can ping the ports using portchecker. let's pretend i want to use wordpress or dotnetnuke(but not the web platform versions as i have sql 2014) . I signed up for a free ddns at no-ip.com
example.ddns.net
installation screen for any normal cms/blog wants your sql/mysql hostname & iis binding needs hostname as well

*

*on normal first-time installation page...localhost? example.ddns.net? the static ip i setup for this server?

*in the iis settings what do i use for the binding? i added one for
each of what i thought most likely. 192.168.1.141, example.ddns.net,
and localhost. (see below for which worked)
note: if i go into iis, right click the project i want to expose to internet, and set the 'physical path credentials' to an admin account and pw...it lets me see all 3 of them, and lets me use example.ddns.net from outside the network. so this may be a file permission problem?
second note: if i try and use IUSR or IIS_IUSRS as the anonymous credential(instead of app pool identity) or as physical path credential it says i need a password??
Third note: i had never heard of RFC1918, so i don't know if the static ip i setup for ipv4 is a valid ip to use for this server. 192.168.1.141 (and reserved that on routers dhcp)
fourth note let windows server do a standard install and then added a bunch of roles and then removed them. added a whole lot of certification/AD roles because i thought it'd be nice to let all my old home pc's connect and do backups and such. I then  removed AD (cert, domain, directory rights), application serv, dhcp server, dns server, deployment services, and maybe a few others i had originally added

A: When you set up a CMS using its Install page, it wants this information to know where your website lives, and what to call it - So all links it creates on your Backend are pointing in the right place.
So if your website is example.ddns.net then that will be your hostname on your CMS as well as in IIS.
Your IP address in IIS will be your local IP address which you have assigned to that server or public if you are connecting a server directly to the internet using DMZ or other setup where your Public IP is directly assigned to that server.
As long as your CMS is on the IIS server and your DB is on the same server then localhost will be just fine, however you will need to change this if you are remotely connecting to the DB over the internet or LAN - In which case you will need to allow remote connections for that other specific IP address so your CMS can talk to your DB.
I hope I have made my answer clear enough for you and that it answers your questions, I can elaborate on/edit my answer if necessary.


text:
Q: Django crispy form fields is not saving Im trying formatting with Django crispy forms, but its not possible to save.
first some code:
forms.py
class CreateForm_test(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name'}))
    street = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Street'}))
    number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Number'}))
    comment = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Comment'}))
    phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone'}))
    status = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Status'}))

class CrispyAddressForm(CreateForm_test):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(
                Column('name', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            'street',
            'number',
            Row(
                Column('comment', css_class='form-group col-md-6 mb-0'),

                Column('phone', css_class='form-group col-md-2 mb-0'),
                Column('status', css_class='form-group col-md-2 mb-0'),

                css_class='form-row'
            ),

            Submit('submit', 'Submit')
        )

views.py
class CreateRegisterView(CreateView):
    model = Register
    message = _("saved")
    form_class = CrispyAddressForm

    template_name = 'register_form.html'
    def form_valid(self, form):
        if self.request.user.is_authenticated:
            form.instance.user = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        messages.success(self.request, self.message)
        return reverse('home')

register_form.html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  {% crispy form %}
{% endblock %}

When I open the form in my Browser, I got this error
forms.py", line 36, in __init__
    super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'instance'
[29/Feb/2020 18:40:13] "GET /Register/create/ HTTP/1.1" 500 115893

I tried also with
 class CreateRegisterView(FormView):
but then I get the same error to the views in this line  form.instance.user = self.request.user

A: The problem is that you used a Form, not a ModelForm. A simple Form has no .instance, and does not know anything about .save(), since the task of a Form is simply to process the GET or POST data, and do validation and cleaning. The ModelForm that is built on top of a Form can load, update and save model objects. You thus should subclass from a ModelForm, and provide a Meta:
class CreateForm_test(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name'}))
    street = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Street'}))
    number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Number'}))
    comment = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Comment'}))
    phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone'}))
    status = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Status'})

    class Meta:
        model = Register
        fields = ['name', 'street', 'number', 'comment', 'phone', 'status']
Furthermore as specified in the documentation, you need to specify the action in the helper:
class CrispyAddressForm(CreateForm_test):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_action = 'name_of_createview'
        self.helper.layout = Layout(
            Row(
                Column('name', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            'street',
            'number',
            Row(
                Column('comment', css_class='form-group col-md-6 mb-0'),

                Column('phone', css_class='form-group col-md-2 mb-0'),
                Column('status', css_class='form-group col-md-2 mb-0'),

                css_class='form-row'
            ),

            Submit('submit', 'Submit')
        )

A: I think, the main issue is I defined the fields twice. One time in models and one time in my forms.
Now this is working:
forms
class CreateForm_test(forms.ModelForm):
    class Meta:
        model = Register
        fields = ['name', 'street', 'number', 'comment', 'phone', 'status']

class CrispyAddressForm(CreateForm_test):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
             Row(
                 Column('name', css_class='form-group col-md-7 mb-0'),
                css_class='form-row'
            ),
            Row(
                Column('street', css_class='form-group col-md-6 mb-0'),
                Column('number', css_class='form-group col-md-1 mb-0'),
                css_class='form-row'
            ),

            Row(
                Column('comment', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            Row(
                Column('phone', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            Submit('submit', 'Submit')
        )

views
class CreateRegisterView(CreateView):
    model = Register
    message = _("saved")
    form_class = CreateForm
    template_name = 'register_form.html'
    def form_valid(self, form):
        if self.request.user.is_authenticated:
            form.instance.user = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        messages.success(self.request, self.message)
        return reverse('home')

models
class Register(models.Model):
    CREATED = "C"
    DELETED = "D"
    STATUS = (
        (CREATED, _("Created")),
        (DELETED, _("Deleted")),
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL, default=1)
    timestamp = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(default=datetime.now)
    status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
    comment = models.CharField(max_length=42, null=True, unique=False, blank=True)
    edited = models.BooleanField(default=False)
    objects = ArticleQuerySet.as_manager()
    name = models.CharField(max_length=35, null=True, unique=False)
    street = models.CharField(max_length=42, null=True, unique=False, blank=True)
    number = models.CharField(blank=True, null=True, max_length=6)
    phone = models.CharField(max_length=15, blank=True, null=True)
    zip = models.CharField(max_length=42, null=True, unique=False, blank=True)
    city = models.CharField(max_length=42, null=True, unique=False, blank=True)
    class Meta:
        verbose_name = _("Register")
        verbose_name_plural = _("Register")
        ordering = ("-timestamp",)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  {% crispy form %}
{% endblock %}

To understand, with crispyforms I have two options to formatting the form. First is this with the forms and the second direct in html.
When I change in the views to form_class = CreateForm_test and in html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <form method="post" novalidate>
    {% csrf_token %}

        {{ form.name|as_crispy_field }}

    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
{% endblock %}

Then is not longer working, the first example formatting in forms is working.In the second html I added only the field name, because only this is a mandatory field.
what is the difference that the html-formatting does not work? The form is visible in the browser but is not saving, no errors.


text:
Q: DMZ vs Port-Forwarding In some ISP(s) new routers the DMZ option is absent
In this cases I sometimes solve the problem
Redirecting all ports (1-65535) as VirtualPorts
to the intended DMZ machine (Port-Forwarding)
What problems can this promote (DMZ-vs-PortRedirection)
Why do you think ISP(s) are removing the DMZ feature...
it is clearly a most valuable feature for gamers
network administrators and power users

*

*PS: I put first this question in "Network Engineering" and opted to post also here just to prevent some dude there claiming this is not about network engineering

A: Using DMZ is a big security risk unless you have a router behind your modem/router.
Usually when this is the case, the modem/router is placed in bridged mode and DMZ is not necessary.
However, opening every single port is only a good thing if all ports forward to a router. If they forward to your pc, then you basically invite hackers to install virusses on your computer and it won't take long before a crypto virus is installed.
ISP's usually don't remove DMZ, but switch to hardware where DMZ simply doesn't exist. DMZ is a good way to test a port forwarding problem, but it is really bad to just work around not being able to open the correct ports.
In the past, people who don't know what DMZ really do and how bad it is to use in a live environment for a longer period of time (unless all DMZ does is forward the modem/router's traffic to a second router) manufacturers have started to disable DMZ because misuse basically causes people who don't know what they're doing to open their ports, which then causes their name to go down because people say: that brand is bad because you get hacked easily with them.
Sometimes it is done to be able to provide a cheaper alternative.
Do note, DMZ is only present in a router. So if an ISP ships a device, the device itself will have to be a modem/router, and not just a modem. A plain modem will do this already, forward everything from the WAN port to the LAN port.


text:
Q: Joomla 2.5 - How to fix 404 Not Found error after restoration using akeeba kickstart After kickstarting a Joomla 2.5.22 on a new server in a sub-folder, the only page that works well is the home page, the rest give me (404 Not Found).
Tried many solutions found on the web even on Akeeba website here but still can't solve this issue.
I know that it's a path issue as if I add the sub-folder name in the address of the page that gives 404 error, the page displays properly.
Eg : www.testing.ca/mysub-folder/contact.html  = Works well !!!
How do I dynamically add the sub-folder name for the entire site? or a best solution to solve this?

A: In your .htaccess file, replace the following:
# RewriteBase

With:
RewriteBase /mysub-folder/

Open your configuration.php file, and change:
$live_site = ''

to:
$live_site = 'http://www.[yourdomain].com';

Also in the configuration.php file, change the tmp and the log paths to the correct physical location.


text:
Q: Show that $\dfrac{x^2-6x+9}{\sqrt{x^2-6x+13}-2}=\sqrt{(x-3)^2+4}+2$ and hence find the limit as x tends to 3. Show that $\dfrac{x^2-6x+9}{\sqrt{x^2-6x+13}-2}=\sqrt{(x-3)^2+4}+2$ and hence find the limit as x tends to 3.
How do I start with this question? Rationalising the denominator? But how would I expand it?

A: $$\frac{x^2-6x+9}{\sqrt{x^2-6x+13}-2}=\frac{(x-3)^2}{\sqrt{(x-3)^2+4}-2}$$ $$\frac{(x-3)^2}{\sqrt{(x-3)^2+4}-2}*\frac{\sqrt{(x-3)^2+4}+2}{\sqrt{(x-3)^2+4}+2}$$ $$\frac{(x-3)^2}{\sqrt{(x-3)^2+4}-2}*\frac{\sqrt{(x-3)^2+4}+2}{\sqrt{(x-3)^2+4}+2}=\frac{(x-3)^2\sqrt{(x-3)^2+4}+2(x-3)^2}{(x-3)^2}$$ $$\frac{(x-3)^2\sqrt{(x-3)^2+4}+2(x-3)^2}{(x-3)^2}=\sqrt{(x-3)^2+4}+2$$

A: Yes, you are right. You want to use the identity $$a^2-b^2=(a+b)(a-b)$$ In your case $a:=\sqrt{x^2-6x+13}$ and $b=2$. The expansion is $$\left(\sqrt{x^2-6x+13}-2\right)\cdot\left(\sqrt{x^2-6x+13}+2\right)=x^2-6x+13-4=x^2-6x+9$$ Now, this simplifies significantly with the term in the numerator (but do not forget to multiply the numerator with the conjugate as well).


text:
Q: How to read in n columns of CSV fie to check they are null? I'm trying read in a spreadsheet that has this format
username,   lastname,   firstname,    x1,      x2,       x3,      x4
user1,       dudette,    mary,         7,       2,                 4
user2,       dude,       john,         6,       2,        4,
user3,       dudest,     rad,
user4,       dudaa,      pad,          3,       3,        5,       9

basically, it has usernames, the names those usernames correspond to, and values for each x. What I want to do is read in this from a csv file and then find all of the blank spaces and fill them in with 5s. My approach to doing this was to read in the whole array and then substitute all null spaces with 0s. This is the code so far...
The solution I got, thanks to another respondent on stackoverflow, was
n=5
while IFS=, read username lastname firstname x1 x2 x3 x4; do
    ! [[ $x1 ]] && x1=$n
    ! [[ $x2 ]] && x2=$n
    ! [[ $x3 ]] && x3=$n
    ! [[ $x4 ]] && x4=$n
    echo $username,$lastname,$firstname,$x1,$x2,$x3,$x4
done < something.csv > newfile.csv && mv newfile.csv something.csv

For the last several hours, I have been now trying to figure out how I can expand this to an n column case. So in the example above, I know that I have 7 columns and so I have seven variables I read in. What I'm trying to do now is figure out how to expand that to the n column case. In the even that another column is added, I still need the code to work.

A: awk is better suited for this type of csv parsing and formatting.
awk -F '[, ]+' -v n=7 '{for (i=1; i<=n; i++) printf "%10s%s", $i, (i<n)?OFS:RS}' OFS=, x
  username,  lastname, firstname,        x1,        x2,        x3,        x4
     user1,   dudette,      mary,         7,         2,         4,
     user2,      dude,      john,         6,         2,         4,
     user3,    dudest,       rad,          ,          ,          ,
     user4,     dudaa,       pad,         3,         3,         5,         9

A: The answer by Anubhava should be faster (since it's awk, not bash). I am adding an answer just to answer your question about how to extend read to n columns.
n=5
while IFS=, read -a columns; do
    for i in ${!columns[@]}; do # * NOTE1
        [ "${columns[$i]}" ] || columns[$i]=$n
    done
    printf "%s" ${columns[0]}; printf ",%s" ${columns[@]:1} # * NOTE2
done < something.csv > newfile.csv && mv newfile.csv something.csv

NOTE1: If the entries are blank, but placeholders are present, use the for loop as is.
If the number of columns in the csv file is not fixed (e.g. check user3 row), then change the inner for loop to for ((i=0;i<$max_columns;i++)); do
NOTE2: In the printf commands, change %s to %10s if desired.