text:
Q: Executing a mysql query in regular interval? Is it possible to execute a query in regular interval?
Ex: I want a mysql query to be executed every 20 minutes

A: You should probably use a cron job which schedules a task (Google cron jobs), and that can execute and run a MySQL Query on an interval


text:
Q: MonoTouch: can't generate WCF proxy I run Win7x64 under MacOs (Lion) via VMware Fusion. On this Win7 i run simple WCF service, wich i succesful consume from client on win7.
Now i need consume this service from my MonoTouch solution, but i can't generate WCF proxy. When i try to generate proxy via MonoDevelope i get next error:

But i can succesul get WSDL from web browser:

What was my mistake?

A: I've done this recently - instead of using the MonoDevelop tools, use SlSvcUtil from the Silverlight 3, 4 or 5 SDK under Windows - then just transfer the file(s) across to the Mac
This tutorial is pretty much exactly what I did: http://wiki.ios.xamarin.com/HowTo/WebServices/Using_WCF

A: Possibly the high port number is disallowed. Try a lower port such as 81.
I have had problems like this before which have been solved by using a lower port.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image popup not display Im developed the Jquery Image upload script In MVC,My upload script is really working but my Uploaded Image not a showing popup ,its in after click uploaded Image.Please help me fix to the my problem ,Thanks in advance
Uploaded Script

Uploaded Image Display Script

View

            Add files...
            <input id="fileupload" type="file" name="files[]" multiple onchange="loadFile(event)">

                100% Complete (success)

A: You could use:
done: function (e, data) {
      var canvas = data.files[0].preview;
      var dataURL = canvas.toDataURL();
      $("#light").css("background-image", 'url(' + dataURL +')');
      //other stuff

And then avoid the loadFile() function, in this way, is all 'unified' in the same function. I guess you should set a width and height to '#light' div and remove the img tag.


text:
Q: Android: how to run AsyncTask at regular interval in background service How do I run an AsyncTask at regular interval of 2 mins sleep for 10 times in the background service?
As VM stops my service at any time, my AsyncTask is also getting closed.
I have tried ScheduledThreadPoolExecutor, Timer, TimerTask all gets stopped once Service gets stopped.
Is there a good option start with?
Any help is appreciated.

A: Your service will never get stopped but you should show notification. Try implementing foreground service. foreground service
Foreground service displays notification and is never stopped.
Implement this code snippet in your service
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

A: Have you tried the Handler? U can read more about this in this link


text:
Q: Attribute must be readwrite while its primary must be read only I added a UITextView to storyboard that I created a property for and connected in a subview of UIView (called FieldView) in this case. The property was like this
@property (strong, nonatomic) UITextView * instructions;

That FieldView is a property of the viewController
@property (strong, nonatomic) IBOutlet FieldView *fieldView;

When I wanted to hide the UITextView *instructions with code in the viewController, I declared the property in the .h file so that I could eventually do this when a button was pressed
 self.fieldView.instructions.hidden = YES;

However, xCode's giving me an error
 illegal redeclaration of property in class extension FieldView, attribute must be readwrite while its primary must be readonly

When I added readwrite in both the .h and .m files
@property (weak, nonatomic, readwrite) IBOutlet UITextView *instructions;

it said `perhaps you intended this to be a readwrite redeclaration of a readonly public property

What is the correct way to do what I am trying to do?

A: I Also got same issue,
If same name property is declared in .h file and you are again declaring it in extension then you will get this error.
So renaming property name will resolve the issue.

A: To resolve your issue you need declare readonly property in .h file and readwrite property in .m file:
//FieldView.h
@interface FieldView
@property (nonatomic, readonly, strong) UITextView *instructions;
@end

// FieldView.m
@interface FieldView()
@property (nonatomic, readwrite, strong) IBOutlet UITextView *instructions;
@end

A: For me, I had to remove one of the properties in AppDelegate.h
Before:
@property (nonatomic, strong) UMModuleRegistryAdapter *moduleRegistryAdapter;
@property (nonatomic, strong) UIWindow *window;

After:
@property (nonatomic, strong) UIWindow *window;


text:
Q: Redirect HTTP to HTTPS with ldirectord/LVS We're using LVS for load balancing and want to do a 301 redirect for http://example.com to https://example.com
LVS is enabling https without issue, but the http real servers are not being added to the pool (weight of 0).
Does LVS not follow 301 redirects? If not, how do I configure ldirectord to send all HTTP traffic to HTTPS?
Here is the nginx config:
server {
    listen      80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

server {
        listen       443;
        ssl on;
        ssl_certificate         server.crt;
        ssl_certificate_key     server.key;
        server_name  example.com;

# more here

}

And ldirectord.cf looks like this:
virtual=VIP:80
        fallback=127.0.0.1:80
        real=10.0.0.7:80 masq 5
        real=10.0.0.8:80 masq 5
        service=http
        request="lvs.htm"
        receive="lvs"
        virtualhost=example.com
        scheduler=wlc
        protocol=tcp
        checktype=negotiate

virtual=VIP:443
        fallback=127.0.0.1:443
        real=10.0.0.7:443 masq 5
        real=10.0.0.8:443 masq 5
        service=https
        request="lvs.htm"
        receive="lvs"
        virtualhost=example.com
        scheduler=wlc
        protocol=tcp
        checktype=negotiate

I also tried setting my VIP to port 80 and my RIP ports to 443 which resulted in the servers being added to the pool, but nginx then returns a 400 "The plain HTTP request was sent to HTTPS port" error.

A: I was making this harder than it needed to be.
I modified my nginx.conf as so:
server {
    listen      80;
    server_name example.com;

    root    /var/www;

    location = /lvs.htm {
        #do nothing
    }

    location / {
        return 301 https://example.com$request_uri;
    }
}

lvs.htm resides in /var/www so the location is matched, searching stops and lvs.htm is served with a 200 response code. LVS adds the server to the pool and when it is hit, nginx correctly redirects to https with a 301.


text:
Q: Parsing DateTime in Java for previous OS versions I've been practicing on parsing JSON for android apps using The Guardian's API, and I'm having trouble formatting the date into a better looking format.
This is what my adapter looks like so far:
    public class ArticleAdapter extends ArrayAdapter {
public ArticleAdapter(MainActivity context, ArrayList<Article> article){
    super(context,0, article);
}

/**
 * Return the formatted date string
 */
private String formatDate(String dateObject) throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        return formatter.parse(dateObject).toString();

}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(R.layout.article_list_item, parent, false);
    }
    Article currentArticle = getItem(position);

    TextView header = (TextView) listItemView.findViewById(R.id.header);
    header.setText(currentArticle.getHeader());

    //Creates the date view and object and passing it through the function to format properly
    TextView date = (TextView) listItemView.findViewById(R.id.date);
    Date DateObject = new Date(currentArticle.getDate());
    try {
        date.setText(formatDate(currentArticle.getDate()));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return listItemView;
}
}

I've tried both using a String as or a Date object as the input to formatDate(), as well as many different formatting techniques -
using an input and output date format
using .formatter rather than .parse
several other solutions I found from similar questions, can't honestly remember them all.
The app keeps crashing with "IllegalArgumentException". Through enough trial and error I was able to trace the failure to be certain it's coming from here.
Note: The getDate() method returns a String
Small example of the JSON being parsed:
[{"id":"technology/2018/jul/05/privacy-policies-facebook-amazon-google-not-gdpr-compliant","type":"article","sectionId":"technology","sectionName":"Technology","webPublicationDate":"2018-07-04T23:01:14Z","webTitle":"Privacy policies of tech giants 'still not GDPR-compliant'","webUrl":"https://www.theguardian.com/technology/2018/jul/05/privacy-policies-facebook-amazon-google-not-gdpr-compliant","apiUrl":"https://content.guardianapis.com/technology/2018/jul/05/privacy-policies-facebook-amazon-google-not-gdpr-compliant","isHosted":false,"pillarId":"pillar/news","pillarName":"News"}

The date I'm using is webPublicationDate
This is the first time I've posted a question so I hope I didn't miss anything in the description. Appreciate any direction because I'm kind of lost atm.

A: Ok so after some more work I was able to find out what caused the failures:
Date DateObject = new Date(currentArticle.getDate()); //currentArticle.getDate() is a string

As soon as I commented this line out everything worked as expected. I fixed it but I'm still not sure as to why, could anyone explain this to me maybe?
Thanks in advance!

A: the reason is that the date "webPublicationDate":"2018-07-04T23:01:14Z" is already formatted in UTC timezone so you need to deconstruct it first using SimpleDateFormat
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'");

Date myDate = null;
        try {
            myDate = dateFormat.parse(currentArticle.getmDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }

// Define a new SimpleDateFormat object to reconstruct the date into the desired format.
        DateFormat newDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
        // Convert the Date object into a String.
        String formattedDate = newDateFormat.format(myDate);


text:
Q: laravel 8 : send email verification after registration laravel I'm building a laravel API. I want when i register , email verify will be sent activation code to user email automatically.
the problem is when i create a new activation code , i create a new record in tokens table too, this record has user_id field , so for store it , i use JWTAuth::user()->id but i have this error:
Trying to get property 'id' of non-object
i know why this happens , because I did not enter any tokens and i don't know how handle it and where to create  a new record in tokens table
for more details I have :
AuthController : Login and register
 public function register(Request $request) {

        $validator = Validator::make($request->all(), [
            'name'=>'required|string|min:3|max:30',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)],
                ));

        $token = JWTAuth::fromUser($user);

        dd($this->sendNotification());

        $user->$this->sendNotification();

        return response()->json([
            'message' => 'successfully created',
            'user' => $user,
            'token' => $token,
        ], 201);
    }

EmailVerifyController  : for verify user email and validate activation code
public function emailVerify(Request $request){
        $data = $request->validate([
            'code' => 'required|size:10|numeric',
        ]);
        $interedCode = (int)$data['code'];//convert code from string to integer

        $userCode = Token::where('user_id' , JWTAuth::user()->id)->first();//find user from tokens table
        $activationCode = $userCode->code; //get activation code of user in tokens table
        $expires_in = (int)$userCode->expires_in; //get expire time of code

        $now = Carbon::now()->timestamp;

        if($interedCode == $activationCode) {
            if ($now < $expires_in) {
                    $user = JWTAuth::user()->id;
                    $findUser = User::find($user);
                    $findUser->email_verified_at = Carbon::now()->timestamp;
                    $findUser->save();

                    $token = Token::where('user_id', JWTAuth::user()->id)->first();
                    $token->status = 1;
                    $token->save();

                    return response()->json('email verified successfully', 200);
            } else {
                return response()->json('code expired', 400);
            }
        }else{
            return response()->json('wrong activation code' , 400);
        }
    }

SendNotificationTrait : for send email and create a new record in token table
trait EmailVerifyTrait
{
    public function sendNotification(){

        $random = $this->generateVerificationCode(6);

        $details = [
            'title' => 'Mail from ItSolutionStuff.com',
            'body' =>$random,
        ];

        Mail::to('*****@gmail.com')->send(new VerifyMail($details));

        return response()->json([
            'message'=>'your email verification code sent to your email'
        ] , 201);
    }

    public function generateVerificationCode($length = 6) {
        $characters = '0123456789';
        $charactersLength = strlen($characters);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[rand(0, $charactersLength - 1)];
        }

            $token = new Token();
            $token->user_id = JWTAuth::user()->id;
            $token->code = $code;
            $token->status = 0;
            $token->save();

        return $code;
}

tokens tables : has this fields : user_id , code , created_at , expires_in
so how can i handle creating new Token record in tokens table ?
or should i use event listener ?
thank you for your help and sorry for my language.

A: for handle this email verification , i used laravel Notification : https://laravel.com/docs/8.x/notifications
and i used $user->id for getting id and use it for user_id field in tokens table.
codes:
Register method
   use ActivationCode;

  public function register(Request $request) {

        $validator = Validator::make($request->all(), [
            'name'=>'required|string|min:3|max:30',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }

        //create user
        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)],
                ));
        //create token
        $token = JWTAuth::fromUser($user);

        //create a new activation code
        $activationCode = $this->generateVerificationCode();

        //create a new token
        $newToken = new Token;
        $newToken->code = $activationCode;
        $newToken->status = 0;
        $newToken->user_id = $user->id;
        $newToken->save();

        //email details
        $details = [
            'greeting' => 'Hi'.$request->name,
            'body' => 'use this activation code for verify your email address',
            'activation_code'=>$newToken->code,
            'thanks' => 'thank you',
            'order_id' => 101
        ];

        //send email verify to user email
        Notification::send($user, new EmailVerification($details));

        return response()->json([
            'message' => 'use created successfully and activation code sent to email',
            'user' => $user,
            'token' => $token,
        ], 201);
    }

Activation code trait:
trait ActivationCode
{
    public function generateVerificationCode($length = 6) {
        $characters = '0123456789';
        $charactersLength = strlen($characters);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[rand(0, $charactersLength - 1)];
        }
        return $code;
    }

}

EmailVerify Notification :
class EmailVerification extends Notification
{
    use Queueable;
    private $details;

    public function __construct($details){
        $this->details = $details;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                ->greeting($this->details['greeting'])
                ->line($this->details['body'])
                ->line($this->details['thanks'])
                ->line($this->details['activation_code']);
    }

    public function toArray($notifiable)
    {
        return [
            'order_id' => $this->details['order_id']
        ];
    }
}


text:
Q: C++ vector Base class and inheritance For my project I have this class structure :
class Base
{
        enum class type
    {
        Derived1,
        Derived2
    }

    int getType() {return type;};

    type        type;
    //general methods & attributes
}

class Derived1 : public Base
{
    //specific methods & attributes
    void        uniqueSpecificMethodOfDerived1();
}

class Derived2 : public Base
{
    //specific methods & attributes
    void        uniqueSpecificMethodOfDerived2();
}

class Core
{
    vector<unique_ptr<Base>>        tab;
    void                            iterate();
}

void        Core::iterate()
{
    tab.emplace_back(new Derived1());
    tab.emplace_back(new Derived2());

    vector<unique_ptr<Base>>::iterator it;

    for (it = tab.begin(); it != tab.end(); ++it)
    {
        if ((*it)->getType())
            (*it)->uniqueSpecificMethodOfDerived1(); //unknow function Can't resolve 'uniqueSpecificMethodOfDerived1()'
        if ((*it)->getType())
            (*it)->uniqueSpecificMethodOfDerived2(); //unknow function Can't resolve 'uniqueSpecificMethodOfDerived1()'
    }
}

My problem is I can't reach the specific methods of derived class in this vector. And I do not want to use polymorphism because this functions are totally different and not needed by other derived classes.
How I can do that ?

A:
My problem is I can't reach the specific methods of derived class in this vector. And I do not want to use polymorphism because this functions are totally different and not needed by other derived classes.
How I can do that ?

The language provides two mechanisms to access functions in a derived class given a pointer/reference to base class.

*

*Through polymorphism.

*Through dynmaic_cast and accessing the derived class function directly.

You can build layers of functions that allow you to access the direct interface of a derived class without the client code explicitly using dynamic_cast but they must use dynamic_cast at some point if use of polymorphism is not an option.
Here's an updated version of your code that uses dynamic_cast directly.
class Base
{
   public:
      virtual ~Base() {}
};

class Derived1 : public Base
{
   public:
      void uniqueSpecificMethodOfDerived1() {}
};

class Derived2 : public Base
{
   public:
      void uniqueSpecificMethodOfDerived2(){}
};

class Core
{
   vector<unique_ptr<Base>>        tab;
   void                            iterate();
};

void Core::iterate()
{
   tab.emplace_back(new Derived1());
   tab.emplace_back(new Derived2());

   vector<unique_ptr<Base>>::iterator it;

   for (it = tab.begin(); it != tab.end(); ++it)
   {
      Base* ptr = (*it).get();
      Derived1* ptr1 = nullptr;
      Derived2* ptr2 = nullptr;
      if ( (ptr1 = dynamic_cast<Derived1*>(ptr)) != nullptr )
      {
         ptr1->uniqueSpecificMethodOfDerived1();
      }

      if ( (ptr2 = dynamic_cast<Derived2*>(ptr)) != nullptr )
      {
         ptr2->uniqueSpecificMethodOfDerived2();
      }
   }
}


text:
Q: Highcharts piechart with slice animation and drilldown on click together throws exception in chart and breaks the pie chart I have a pie chart here. On click event it drills down and on mouseover it does the slice animation. The slice animation is copied from an answer here from Pawel Fus
The events I have on pie chart point are as below,
mouseOut: function () {
    setTranslation(this, false);
},
mouseOver: function() {
    setTranslation(this, true);
},
click: function() {
    var drilldown = this.drilldown;
    if (drilldown) { // drill down
        setChart(drilldown.name, drilldown.categories, drilldown.data, drilldown.color);
    } else { // restore
        setChart(name, categories, data);
    }
}

and the functions used in them are
function setChart(name, categories, data, color) {
    chart.xAxis[0].setCategories(categories);
    chart.series[0].remove();
    chart.addSeries({
        name: name,
        data: data,
        pointPadding: -0.3,
        borderWidth: 0,
        pointWidth: 15,
        shadow: false,
        color: color || 'white'
    });
}

function setTranslation(p, slice){
    p.sliced = slice;
    if(p.sliced){
        p.graphic.animate(p.slicedTranslation);
    } else {
        p.graphic.animate({
            translateX: 0,
            translateY: 0
        });
    }
}

The problem I have is it throws following exception:
Uncaught TypeError: Property 'select' of object #<Object> is not a function highcharts.src.js:12364
It breaks the chart when clicking on it for drilldown.
I am not sure what I am doing wrong but I guess the mouseover event is getting messed up on drilldown.
It would be great if I can get both these features working together.

A: The problem is with actual running animation. I advice to not use setting translation to a pie chart until all animations for a slice are don, see: http://jsfiddle.net/5H675/5/
function setTranslation(p, slice) {
    p.sliced = slice;
    if (!$(p.graphic).is(':animated')) {
        if (p.sliced) {
            p.graphic.animate(p.slicedTranslation);
        } else {
            p.graphic.animate({
                translateX: 0,
                translateY: 0
            });
        }
    }
}


text:
Q: How to safely run User-generated SOQL query strings Background Context:
I'm building a small feature similar to Andrew Fawcett's Declarative Lookup Rollup Summary tool. We will allow users to enter in details for their own WHERE clauses for the Aggregate queries, which are very likely to include string literals; a typical clause is expected to resemble:
WHERE Status__c = 'Complete' OR Status__c = 'In Progress'
SFDC security standards dictate that I should escape single quotes before running the query to mitigate risks of SOQL injection, but that of course causes the queries to explode around these String literals.
What I need
A way to safely run these queries without breaking the literal expressions
What I've tried
I was hoping to pull out all the literals into a collection, substituting them for :collection[index] expressions, but Dynamic SOQL does not support brackets or parenthesis in bind expressions. Here is what I currently have:
String[] criteriaValues = new List<String>();
String criteria = rule.Relationship_Criteria__c;//example: Status__c = 'Complete' OR Status__c = 'In Progress'
Matcher m = Pattern.compile( '\'(.+?)\'').matcher(criteria);
while(m.find()){//iterate through the Criteria string to carefully separate and encode String literals
    criteriaValues.add(  m.group()  );
    criteria = criteria.replace(m.group(), '{'+ (criteriaValues.size()-1) +'}');
}
/**  0 -> aggregate selections;  1 -> WHERE conditions;  2 -> GROUP BY  **/
String qry = 'SELECT {0} FROM '+objectType.getDescribe().getname()+ ' WHERE {1} GROUP BY {2}';
String[] fmtArgs = new List<String>{
    'COUNT(Id), '+rule.Relationship_Field__c,
    String.format(criteria, criteriaValues),
    rule.Relationship_Field__c
};
//Executed query string should read (or perform identically to)
//'SELECT COUNT(ID), Related__c FROM Custom__c  WHERE Status__c = 'Complete' OR Status__c = 'In Progress' GROUP BY Related__c'
return (AggregateResult[])Database.query(String.escapeSingleQuotes(String.format(qry, fmtArgs)));

A: The easiest option is to use the REST/SOAP API. The API enforces CRUD/FLS and sharing, so js clients can run their own SOQL safely and your Apex code isn't involved. The risk of SOQL injection is just the risk of permissions bypass, as Salesforce SOQL is not like SQL and cannot result in anything other than a query on SOQL objects.
But if you want to make the query in Apex, then you need to not only escapeSingleQuotes the string literals in where fields, but also do full CRUD/FLS checks.
Remember the client does not know the allowed sObjects, nor the fields belonging to those objects, nor the server's schema, yet somehow the client is supposed to be generating the queries. All of the key information lives on the server and has to be passed to the client by the server, then information is lost when the client does not pass enough structure back to the server to unambiguously parse the SOQL query.
That means that you can always design this so that the server never sends any real field names or object names to the client, and the client never sends any strings to the server (except for string literals to be used in WHERE clauses), but only tokens (references), and the client returns a combination of the tokens together with commands to combine them with string literals into queries. Then the server has enough information to properly generate the SOQL query the client wants and perform all necessary escaping and CRUD/FLS checks: server side, you automatically escapeSingleQuote any string literals, and interpret all the tokens and commands as map keys, putting the corresponding value into the query after doing an isAcccessible() check on the field value. You map the commands (e.g. parenthesis, AND, etc) to the corresponding lookup value string.
Now, no strings are being passed from the client to the server that go into a SOQL query unescaped and without any CRUD/FLS checks.
It is, however, a lot of work whereas using the REST API is easy.


text:
Q: Creating a folder titled with a user's input In PHP, I need use a user's input as the title of a folder.
For example:
$foldername = $_REQUEST["foldername"];
mkdir("./userfolders/".$foldername);

Because, one problem I see with this is that the input could contain a "../" which would cause the folder to be written in the parent directory, which I don't want. My solution to this was to str_replace away all forward slashes from the string.
Are there any other vulnerabilities that I've missed?

A: The ideal way would be not to accept user input for this at all IMO. Apart from other vulnerabilities depending on the file system (what about Windows's backslashes, for example?) you may run into a world of other problems like character set trouble - think about ♥♥♥♥♥♥♥♥♥♥♥, for example: it's a perfectly valid UTF-8 string....
If you have a database at hand, a more secure way would be storing the user input there, and naming the directories after the database record's unique ID for example.
If that's not practical: one acceptable compromise that I've always liked is urlencode()ing the user input, which will guarantee you won't get problematic characters in the file system. You still need to be clear about which encoding you use (otherwise the urldecode() that you use afterwards to display the directory name will return broken data) but otherwise, this should work okay. The directories created this way will also be accessible through a browser, as special characters in a URL get urlencode()d anyway.

A: Is there a possibility you can use the urlencode function on the folder name variable.
When showing the folder to the user you can then use urldecode.
$foldername = urlencode($_REQUEST["foldername"]);
mkdir("./userfolders/".$foldername);

// Show folder name
echo urldecode($foldername);


text:
Q: Returning to "sender" from a future inside an actor I want to do something like this -
class MyActor extends Actor {
....
override def receive = {
  case msg =>
     .... // do something
     Future {
       ... // calculate response
       sender ! response
     }
}
}

// in some other code -
val future = myActorRef ? msg
future.onSuccess {
    ....
}

Would this work? In other words, does Akka's "ask" implementation care if the response was sent back before the "receive" method finishes or not?

A: Yes it would work, and there is even a built-in akka pattern for it - pipe:
import akka.pattern.pipe

override def receive = {
  case msg =>
    .... // do something
    Future {
      ... // calculate response
      response
    } pipeTo sender()
}

There are, however some caveats in your code you should note:
sender is a function, therefore, when the code inside your Future{...} block executes, the actor may be handling a message from another sender, so you may reply to the wrong sender. To avoid this, evaluate your sender outside the closure:
val mySender = sender()
Future {
  ... // calculate response
  mySender ! response
}

You don't however need to worry about this if you use pipe.

You are wrapping a future into an actor and calling that actor with ask, which again gives you a future. You should really consider calling the future directly, without actors.
If you really need the actor, e.g. because you're isolating some mutable state or message ordering is important, you should be aware that computing the Future will not happen on the actor's thread, so you are losing your state consistency and message ordering - another reason to consider losing the actor, and calling the future directly.

A: The problem is, that sender may no longer be valid, when the future is performed. You have a couple of options, here are two from the top of my head:
You can capture the sender before the future:
override def receive = {
  case msg =>
     .... // do something
     val replyTo = sender

     Future {
       ... // calculate response
       replyTo ! response
     }
}

Or you can use the pipeTo pattern:
override def receive = {
  case msg =>
     .... // do something
     import akka.pattern.pipe

     Future {
       ... // calculate response
     }.pipeTo(sender())
}


text:
Q: How can I secure Jenkins port 8080 with SSL under apache2 in ubuntu 18.04 Server? I have been able to successfully install and configure Apache2 server to served on HTTPS. I have been having issues getting Jenkins to use the same SSL certificates and run on Secured port 443. This is my configurations and please, any help will be appreciated. Thank you.
I have the server currently serving a static WordPress site which launches successfully on https port 80 or 443. I also have Jenkins serving successfully on the route of the server but with port 8080.
Is there any way I can get Jenkins to serve right under the Apache2 server like
jenkins.server.com/jenkins instead of jenkins.server.com:8080?
    <VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerName jenkins.server.com
        ServerAlias www.jenkins.server.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        <Directory /var/www/html>
            Options +FollowSymlinks
            AllowOverride All
            Require all granted
        </Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
RewriteEngine on
RewriteCond %{SERVER_NAME} =jenkins.server.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

<VirtualHost *:443>

        SSLEngine on
        SSLProxyEngine on

        # SSL certificate and keys. Edit paths to whereever your SSL files are located
        SSLCertificateFile /etc/letsencrypt/live/jenkins.server.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/jenkins.server.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf

        ProxyRequests Off
        ProxyPreserveHost On
        RewriteEngine On
        RequestHeader set X-Forwarded-Proto "https"
        AllowEncodedSlashes NoDecode

        ProxyPass / http://jenkins.server.com:8080 nocanon
        ProxyPreserveHost On
        RewriteEngine On
        RequestHeader set X-Forwarded-Proto "https"
        AllowEncodedSlashes NoDecode

        ProxyPass / http://jenkins.server.com:8080 nocanon
        ProxyPassReverse / http://jenkins.server.com:8080

        <Proxy http://jenkins.server.com:8080/*>
                Order deny,allow
                Allow from all
        </Proxy>

</VirtualHost>

A: I was able to fix this problem by modifying the generated file by Apache2 with the name 000-default-le-ssl.conf under /etc/apache2/sites-available/000-default-le-ssl.conf
This file was generated automatically and I modified the proxy settings.
I also had to maintain "localhost" instead of jenkins.server.com even though localhost will not launch Jenkins in the browser.
This is my updated and working file...
<IfModule mod_ssl.c>
<VirtualHost *:443>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerName jenkins.server.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

        ProxyPass         /jenkins  http://localhost:8080/jenkins nocanon
        ProxyPassReverse  /jenkins  http://localhost:8080/jenkins
        ProxyRequests     Off
        AllowEncodedSlashes NoDecode
        RequestHeader set X-Forwarded-Proto "https"
        RequestHeader set X-Forwarded-Port "443"

        # Local reverse proxy authorization override
        # Most unix distribution deny proxy by default (ie /etc/apache2/mods-enabled/proxy.conf in Ubuntu)
        <Proxy http://localhost:8080/jenkins*>
          Order deny,allow
          Allow from all
        </Proxy>

SSLCertificateFile /etc/letsencrypt/live/jenkins.server.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/jenkins.server.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>


text:
Q: monitoring plugin check_http cert expiration check [root@chi plugins]# '/usr/lib64/nagios/plugins/check_http' '-C' '15,30' '-I' '99.830.700.184' '-S' '-p' '443'
SSL OK - Certificate 'localhost' will expire on 2018-12-14 02:20 +0000/UTC. HTTP WARNING: HTTP/1.1 404 Not Found - 226 bytes in 0.156 second response time |time=0.155850s;;;0.000000 size=226B;;;0
I need to suppress The HTTP 404 warning. If there's another plugin that can do this, I'd like to know about it. (I can't change anything on the webserver.)

A: You can use the same plugin, but add -e 404, so it will look like:
[root@chi plugins]# '/usr/lib64/nagios/plugins/check_http' '-C' '15,30' '-I' '99.830.700.184' '-S' '-p' '443' '-e' '404'

The -e 404 flag suppress 404 error code.

A: I used the tcp command (check_tcp plugin) instead. I should have been using check_tcp all along.
In my /etc/icinga2/zones.d/global-templates/global-commands.conf file I added
apply Service "HTTPS/8443: Secure Management Interface" {
  import "generic-service"
  check_command = "tcp"
  vars.tcp_port = "8443"
  vars.tcp_ssl  = true
  vars.tcp_timeout = 60
  vars.tcp_ipv4 = true
  vars.tcp_ipv6 = false
  vars.tcp_timeout = 30

  assign where host.vars.devtype == "dadada"


text:
Q: Move a section from one config file to another with configparser I have two files:
test1.conf:
[1414]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

test2.conf:
[1415]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

I just want to put the section [1414] from test1.conf under the section from test2.conf, and then delete from test1.conf
I tried converting the section into a dictionary and then adding it to the test2, but it didn't include the section name, just the configs, and I need all the configs to move (section name and it's configs).
I just need something to work with, then I'll see what I can do to insert it in my code. I have read the documentation of course, but I couldn't find anything that paste a full section.
Here is what I tried (the file is large so I got pieces of it):
config = configparser.ConfigParser(strict=False,comment_prefixes='/',allow_no_value=True)
with open('test1.conf', "r") as f:
    config.readfp(f)

for general_queue_id in config.sections():
    general_id_arr.append(general_queue_id)

for key in general_id_arr: # Array with all sections from test1.conf
    with open('teste2.conf'):
        items = {k:v for k,v in config.items(key)}
        for x in items.items():
            f.write(x[0] + '=' + x[1] + '\n')

A: If you already know the section that you are looking for it will be easier to use the builtin functions found in configParser that you can build into a wrapper class.
For example, I use the following to create my parser and then grab all of the items in a section as a list.
from configparser import ConfigParser, ExtendedInterpolation

class MyConfigParser(object):

    def __init__(self):
        """
        initialize the file parser with
        ExtendedInterpolation to use ${Section:variable} format
        [Section]
        option=variable
        """
        self.config_parser = ConfigParser(interpolation=ExtendedInterpolation())

    def read_ini_file(self, file):
        """
        Parses in the passed in INI file.

        :param file: INI file to parse
        :return: INI file is parsed
        """
        with open(file, 'r') as f:
            self.config_parser.read_file(f)

    def add_section_toFile(self, section):
        """
        adds a configuration section to a file

        :param section: configuration section to add in file
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.config_parser.add_section(section)

    def add_configurations_to_section(self, section, lst_config):
        """
        Adds a configuration list to configuration section

        :param section: configuration section
        :param lst_config: key, value list of configurations
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.add_section_toFile(section)

        for option, value in lst_config:
            print(option, value)
            self.config_parser.set(section, option, value)

    def get_config_items_by_section(self, section):
        """
        Retrieves the configurations for a particular section

        :param section: INI file section
        :return: a list of name, value pairs for the options in the section
        """
        return self.config_parser.items(section)

    def remove_config_section(self, section):
        """
        Removes a configuration section from a file
        :param section: configuration section to remove
        :return: void
        """
        self.config_parser.remove_section(section)

    def remove_options_from_section(self, section, lst_options):
        """
        Removes a list of options from configuration section
        :param section: configuration section in file
        :param lst_options: list of options to remove
        :return: void
        """
        for option, value in lst_options:
            self.config_parser.remove_option(section, option)

    def write_file(self, file, delimiter=True):
        with open(file, 'w') as f:
            self.config_parser.write(f, delimiter)

I added functions that wrap functions from the configParser api that will help accomplish what you are attempting found in these api sections add_section & set along with remove_section & remove_option
To use it you can create your instance and call it with something such as:
from config_parser import MyConfigParser

def main():
    lst_section = []

    fileIn = './test1.conf'
    fileOut = './test2.conf'

    parser1 = MyConfigParser()
    parser2 = MyConfigParser()

    parser1.read_ini_file(fileIn)
    parser2.read_ini_file(fileOut)

    lst_section = parser1.get_config_items_by_section('1414')

    parser2.add_section_toFile('1414')
    parser2.add_configurations_to_section('1414', lst_section)

    parser1.remove_config_section('1414')

    parser1.write_file(fileIn)
    parser2.write_file(fileOut)

if __name__ == "__main__":
    main()

The MyConfigParser class was a quick build, so if you are going to use it in a production type environment, you will want to add in more robust error handling to catch things like if the section option already exist. The configParser api will typically show what error will occur that you can but try/except to handle that exception type. Unless I made a mistake in the copy paste, i ended up putting together something that I was able to test that it ran for you. I hope this helps.


text:
Q: Combining jQuery scripts to make it smaller I have written a jQuery script which does same task but on different events say

*

*On page load

*On change of dropdown selections

*On click of swap button

*On keyup in a text field

But I had to write the scripts for all of them separately. I am new to jQuery. I want to combine the scripts to work same but making it smaller. Is it possible?
Script
<script type="text/javascript">
        // Fire this function when page loads
        $(document).ready(function () {
            $.getJSON(
                    'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
                    function(data){
                            if(typeof fx !== "undefined" && fx.rates){
                                    fx.rates = data.rates;
                                    fx.base = data.base;
                var amount = $("#amt").val();
                                    var from   = $("#from").val();
                                    var to     = $("#to").val();
                                    $("#res").val( fx(amount).from(from).to(to));
                                    $("#result").show();
                            }
                    }
            );
        });

        // Fire this function when value is entered in the field
        $(document).keyup('#amt', function(){
        $.getJSON(
            'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
            function(data){
                if(typeof fx !== "undefined" && fx.rates){
                    fx.rates = data.rates;
                    fx.base = data.base;
                    var amount = $("#amt").val();
                    var from   = $("#from").val();
                    var to     = $("#to").val();
                    $("#res").val( fx(amount).from(from).to(to));
                    $("#result").show();
                }
            }
        );
    });

        // Fire this function on swap button click
        $("#swap").click(function(e) {
        e.preventDefault();
        var fromVal = $("#from option:selected").val();
        var fromText = $("#from option:selected").text();
        var toVal = $("#to option:selected").val();
        var toText = $("#to option:selected").text();

        $("#from option:selected").val(toVal);
        $("#from option:selected").text(toText);
        $("#to option:selected").val(fromVal);
        $("#to option:selected").text(fromText);

            $.getJSON(
                    'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
                    function(data){
                            if(typeof fx !== "undefined" && fx.rates){
                                    fx.rates = data.rates;
                                    fx.base = data.base;
                var amount = $("#amt").val();
                                    var from   = $("#from").val();
                                    var to     = $("#to").val();
                                    $("#res").val( fx(amount).from(from).to(to));
                                    $("#result").show();
                            }
                    }
            );
        });

        // Fire this function on change of "FROM" dropdown selection
        $("#from").change(function () {
            $.getJSON(
                    'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
                    function(data){
                            if(typeof fx !== "undefined" && fx.rates){
                                    fx.rates = data.rates;
                                    fx.base = data.base;
                var amount = $("#amt").val();
                                    var from   = $("#from").val();
                                    var to     = $("#to").val();
                                    $("#res").val( fx(amount).from(from).to(to));
                                    $("#result").show();
                            }
                    }
            );
        });

        // Fire this function on change of "TO" dropdown selection
        $("#to").change(function () {
            $.getJSON(
                    'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
                    function(data){
                            if(typeof fx !== "undefined" && fx.rates){
                                    fx.rates = data.rates;
                                    fx.base = data.base;
                var amount = $("#amt").val();
                                    var from   = $("#from").val();
                                    var to     = $("#to").val();
                                    $("#res").val( fx(amount).from(from).to(to));
                                    $("#result").show();
                            }
                    }
            );
        });
</script>

A: It's more like a general question, but here it is. You can reuse your code! Just put your code into a function like that.
function hello(){ console.log('hi!')}

And then you can pass it to another function
anotherFunction(hello)

Or simply call it
hello()

In your example you can do like this
function someFunction() {
    $.getJSON(
        'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5',
        function (data) {
            if (typeof fx !== "undefined" && fx.rates) {
                fx.rates = data.rates;
                fx.base = data.base;
                var amount = $("#amt").val();
                var from = $("#from").val();
                var to = $("#to").val();
                $("#res").val(fx(amount).from(from).to(to));
                $("#result").show();
            }
        }
    );
}
function passItToSwap(e) {
    e.preventDefault();
    var fromVal = $("#from option:selected").val();
    var fromText = $("#from option:selected").text();
    var toVal = $("#to option:selected").val();
    var toText = $("#to option:selected").text();

    $("#from option:selected").val(toVal);
    $("#from option:selected").text(toText);
    $("#to option:selected").val(fromVal);
    $("#to option:selected").text(fromText);

    someFunction();
}

$(document).ready(someFunction);
$(document).keyup('#amt', someFunction);
$("#swap").click(passItToSwap);

etc

A: You could divide the code in functions and create a separate file (filename.js) to include it in your HTML.

A: You could reuse the same function for each handler, since you seem to have the same code in each of them:
var fx = {
        'base' : null,
        'rates' : true
    },
    getRates = function() {
        $.getJSON( 'https://openexchangerates.org/api/latest.json?app_id=2e946db1e3fc4888b61330e505a804e5', function(data) {
            var amount,
                from,
                to;
            if (typeof fx !== "undefined" && fx.rates) {
                fx.rates = data.rates;
                fx.base = data.base;
                amount = $("#amt").val();
                from = $("#from").val();
                to = $("#to").val();
                $("#res").val( fx(amount).from(from).to(to));
                $("#result").show();
            }
        });
    };
// Fire this function when page loads
$(document).ready(getRates);
// Fire this function when value is entered in the field
$(document).keyup('#amt', getRates);
// Fire this function on swap button click
$("#swap").click(function(e) {
    e.preventDefault();
    var fromVal = $("#from option:selected").val(),
        fromText = $("#from option:selected").text(),
        toVal = $("#to option:selected").val(),
        toText = $("#to option:selected").text();

    $("#from option:selected").val(toVal);
    $("#from option:selected").text(toText);
    $("#to option:selected").val(fromVal);
    $("#to option:selected").text(fromText);
    getRates();
});
// Fire this function on change of "FROM" and of "TO" dropdown selection
$("#from, #to").change(getRates);


text:
Q: Replace a character with another in python I am using the following code in python to receive data from a device.
from socket import *

HOST = 'localhost'
PORT = 30003    #our port from before
ADDR = (HOST,PORT)
BUFSIZE = 4096

sock = socket( AF_INET,SOCK_STREAM)
sock.connect((ADDR))

def readlines(sock, recv_buffer=4096, delim='\n'):
    buffer = ''
    data = True
    while data:
        data = sock.recv(recv_buffer)
        buffer += data

        while buffer.find(delim) != -1:
            line, buffer = buffer.split('\n', 1)
            yield line.strip('\r\n')

    return

for line in readlines(sock):
    print line

And I am getting the output in following format:
MSG,2,0,0,8963AB,0,2015/02/06,15:03:27.380,2015/02/06,15:03:27.380,,0,7.5,343.0,10.152763,76.390593,,,,,,-1    MSG,2,0,0,8963AB,0,2015/02/06,15:03:28.630,2015/02/06,15:03:28.630,,0,7.5,348.0,10.152809,76.390593,,,,,,-1

I should get the output in following format:
'MSG','2','0','0','8963AB','0','2015/02/06','15:03:27.380','2015/02/06','15:03:27.380','','0','7.5','343.0','10.152763','76.390593','','','','','','-1'

A: Split the string with , as delimiter. Then append the elements to a list
appended_list = [x for x in original_list.split(',')]

Now the appended list will contain the strings like you wish


text:
Q: Make laptop fans always run at maximum speed I have a Dell Precision M90 laptop, which has two fans. I just want both the fans to run at maximum speed all the time. I have installed and tried i8kmon.conf file.

A: I have found the solution. This video really helped me:
https://www.youtube.com/watch?v=pNVPkkmnsWI
Now I'm able to make both fans run at maximum speed (12000RPM).


text:
Q: Dynamic Widget creation based of configparser file I am trying a piece of python based tkinter code with following objective:
(Please go through the objective, then I will take an example to explain what exactly i require and then in the end will post the script I have written)

*

*Reads from a config file, which is implemented using configparser module.

*Based on options read from this file it automatically generates widget.

*These widgets are restricted to only labels and entry box as of now.

*Every entry box is associated with a variable. It is hence needed to generate a variable
automatically whenever a entry box is declared.

*Now when the user enters any value in the entry box, and presses calculate button a list is
generated with combination of values entered by user( in a specific format).

Example:
Let the configparser file has following content:

[widget]
label = ani_label,sham_label
entry = ani,sham

The list generated for this case will be like this:

out_list = ['-ani','< ani >','-sham','< sham >']

< ani > means value stored in ani variable
And below is the code that i have tried.
from Tkinter import *
from Tkinter import Tk
import Tkinter as tk
import ttk
import ConfigParser
import sys
############ Initialize ###############################
parser_read = ConfigParser.ConfigParser()
parser_read.read('option_read.config')
config_list = {}
config_list['label'] = parser_read.get('widget','label').split(',')
config_list['entry'] = parser_read.get('widget','entry').split(',')

######
def calculate():
    #Will include the list generation part
    pass

#######
root = Tk()
root.title("NRUNTEST GUI VERSION 1")
#
menuframe = ttk.Frame(root)
menuframe.grid(column=0,row=0)
menuframe.columnconfigure(0,weight=1)
menuframe.rowconfigure(0,weight=1)
#
mainframe_label = ttk.Frame(root)
mainframe_label.grid(column=1,row=0)
mainframe_label.columnconfigure(0,weight=1)
mainframe_label.rowconfigure(0,weight=1)
#
mainframe_entry = ttk.Frame(root)
mainframe_entry.grid(column=2,row=0)
mainframe_entry.columnconfigure(0,weight=1)
mainframe_entry.rowconfigure(0,weight=1)

#
general_label= Label(menuframe,text="Please Enter the Values Below").grid(column=1,row=0,sticky=(E))
compiler_label= ttk.Label(menuframe,text="Compiler")
compiler_label.grid(column=1,row=1,sticky=W)
#
calculate_button = ttk.Button(menuframe, text="Calculate", command=calculate).grid(column=1,row=2,sticky=(W,E))
#Automatic Widget declaration ###
for x in config_list['label']:
    x = ttk.Label(mainframe_label,text=x).grid()

for x in config_list['entry']:
    #print x
var = lambda: sys.stdout.write(x)
x = ttk.Entry(mainframe_entry,textvariable = x).grid()

root.mainloop()

The content of option_read.config is
[widget]
label : animesh_label,sharma
entry : animesh_entry,sharma

STATUS:
I can create the required widgets automatically. But I am not able to create the variables dynamically to store the entry box values.
Once the variable has been calculated, I can write the calculate function on my own.
Please advice how i can proceed.
If you have any better way to meet my requirements, please do suggest.
Also do ping me if you require any more inputs or my query is not clear.

A: The easiest way to do this, IMO, is to use a dict to store the references to the dynamically created variables. You could use the label as the key. For example:
vars = {}
for x in config_list['entry']:
    vars[x] = StringVar()
    entry = ttk.Entry(mainframe_entry, textvariable=vars[x])
    entry.grid()

By the way... are you aware that if you do something like x=ttk.Entry(...).grid(...), x does not contain a reference to the widget? It contains the result of the call to grid, which is None.


text:
Q: Type mismatch when creating List of objects I am trying to part the mainListarraylist to 3 sublist Arraylist and then add it as sublist in other arraylist mainSublist but I am getting this error:
 How can I fix it?
I appreciate any help.

1)-Type mismatch: cannot convert from List to ArrayList
2) -The method add(RootCreator) in the type ArrayList is not applicable for the arguments (ArrayList)

Code:
    ArrayList<RootCreator> mainList = new ArrayList<RootCreator>();
    for (String key : names) {
        RootCreator rootcreat = join_line(path, key);
        mainList.add(rootcreat);
    }
    ArrayList<RootCreator> mainSublist = new ArrayList<RootCreator>();

    for(int i= 0 ; i < mainList.size(); i++){
        int index = i*3;
        //the error 1 is here
        ArrayList<RootCreator> sublist = mainList.subList(0, index);
         //error 2 is here
        mainSublist.add(sublist);
    }

A: All List are not ArrayList, so when you use sublist you get a generic List. On the other hand, the method to add a collection to another collection is addAll instead add.
List<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
    RootCreator rootcreat = join_line(path, key);
    mainList.add(rootcreat);
}
List<RootCreator> mainSublist = new ArrayList<RootCreator>();

for(int i= 0 ; i < mainList.size(); i++){
    int index = i*3;
    //the error 1 is here
    List<RootCreator> sublist = mainList.subList(0, index);
     //error 2 is here
    mainSublist.addAll(sublist);
}

A: The subList method returns a List, not an ArrayList, and you cannot assign a List to an ArrayList.  In fact, the List returned by the subList method is not an ArrayList.
If it needs to be an ArrayList, then create an ArrayList out of the sub list.
ArrayList<RootCreator> sublist = new ArrayList<>(mainList.subList(0, index));

If you just need a List, then make sublist a List instead.
List<RootCreator> sublist = mainList.subList(0, index);

You can't add an ArrayList<RootCreator> to an ArrayList<RootCreator>; you must add a RootCreator.  If you want to add the elements of sublist to another list, then use the addAll method.
mainSublist.addAll(sublist);

A: OK, let's look at the two errors here:
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);

This is telling you that you're trying to assign something of the type List to a variable that's declared as an ArrayList. While an ArrayList is a subtype of List, it doesn't work both ways - you can assign an ArrayList to a List, but not vice versa. So let's change your declaration:
//the error 1 was here, but fixed.
List<RootCreator> sublist = mainList.subList(0, index);

The second one is slightly different:
//error 2 is here
mainSublist.add(sublist);

Here, you've got a list defined to hold items of the type RootCreator - but you're not adding RootCreator items, you're adding a list of them. So if you want to have the list hold other lists, you need to specify that when you create it:
ArrayList<List<RootCreator>> mainSublist = new ArrayList<List<RootCreator>>();

But, if you're trying to just keep a single list and want to add everything from the sublists, then instead, change your code to:
//error 2 was here, but Fixed
mainSublist.addAll(sublist);


text:
Q: Trying to automate channel permissions but it updates all the roles in the room with either read or write together I've been trying to make it so the Host role on my discord server can use either a !host or !stophosting command to unlock or lock their channel.  !host is correctly opening the channel back up, but !stophosting is locking everyone except admins out of the channel.  I want hosts to still have access to it.
    const Discord = require('discord.js');
    const { prefix, token } = require('./config.json');
    const fs = require('fs');

    const client = new Discord.Client();
    client.commands = new Discord.Collection();

    const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

    client.once('ready', () => {
    console.log('Ready!');
    });

    client.on('message', message => {
    if (message.content.includes(`${prefix}stophosting`)) {
    let channel = message.channel;
    let roles = message.guild.roles; // collection
    const memberRole = message.guild.roles.cache.find(r => r.name === 'member');
    const defaultRole = message.guild.roles.cache.find(r => r.name === 'default');
    const hostRole = message.guild.roles.cache.find(r => r.name === 'Host');
    channel.overwritePermissions([
    {
    id: defaultRole.id,
    deny: ['VIEW_CHANNEL'],
    },
    ], 'Lockdown')
    channel.overwritePermissions([
    {
    id: memberRole.id,
    deny: ['VIEW_CHANNEL'],
    },
    ], 'Lockdown')
    channel.overwritePermissions([
    {
    id: hostRole.id,
    allow: ['VIEW_CHANNEL'],
    },
    ], 'Lockdown')
    .then(console.log)
    .catch(console.log);
    }
    });
    client.login(token);


text:
Q: How do I set my AWS S3 Rails 5.2 ActiveStorage to public? According to the Rails guide, I can set the files to be public. However, when I tried it, I get this error:
Cannot load `Rails.config.active_storage.service`
invalid configuration option `:public'):

If I remove the public: true in my storage.yml file, it works. But then the file itself is private and so my Cloudflare CDN cannot serve it.
# config.storage.yml
amazon_dev:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['AWS_SECRET_KEY'] %>
  region: us-west-2
  public-read: true
  bucket: xxxxxx

# config/environments/development.rb
config.active_storage.service = :amazon_dev

Also set the AWS S3 to public:
S3 bucket settings
Can't embed yet so this will be a link.
Thank you,

A: It has to do with your AWS settings, not Rails.
When creating a bucket, UNTICK "block all public access":

See the difference of a public and a private bucket in the dashboard:

For adding a policy:

it can be something like
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::awsexamplebucket1/"
            ]
        }
    ]
}


text:
Q: How to build a dictionary with a key and value being a list of list containing a list and matched to a value within a list I need help building a dictionary which has a key and then values being a list of a list which has a list, in which the keys value matches the third item of list the list and then places it under that key
(I will try show by example cause its difficult to word)
#This is the score users achieve and needs to be the keys of the dictionary)
keyScores = [5,4,3,2,1]

# The data represents at [0] =user_id , [1] = variables for matching,[2] = scores
#      (if its score == to a dictionary key then place it there as a value )

fetchData = [
             [141, [30, 26, 7, 25, 35, 20, 7], 5],
             [161, [36, 13, 29], 5],
             [166, [15, 11, 25, 7, 34, 28, 17, 28],3]
            ]

#I need to build a dictionary like this:

    {5: [[141, [30, 26, 7, 25, 35, 20, 7],[161, [36, 13, 29]],
     3:[[166, [15, 11, 25, 7, 34, 28, 17, 28]
     }

I was thinking of using defaultdict as expressed in
Python creating a dictionary of lists
I cant get the unpacking right.
Any help would be great.
Thank you.

A: Prob not the best way but this worked for me:
dictList=OrderedDict((k,[]) for k in keyScores)

    for k in dataFetch:
        for g in keyScores:
           if k[2] == g:

               dictList[g].append(k)

A: defaultdict makes it easy to append items to a list without having to check if the key is already present.  The parameter to defaultdict is the default item to construct.  In this case, an empty list.  I also use a set on the keyScores to make to in lookup a little more efficient.  pprint just helps pretty print the resulting dictionary.
from collections import defaultdict
from pprint import pprint

D = defaultdict(list)
keyScores = set([5,4,3,2,1])
fetchData = [
             [141, [30, 26, 7, 25, 35, 20, 7], 5],
             [161, [36, 13, 29], 5],
             [166, [15, 11, 25, 7, 34, 28, 17, 28],3]
            ]
for id,data,score in fetchData:
    if score in keyScores:
        D[score].append([id,data])
pprint(D)

Output:
{3: [[166, [15, 11, 25, 7, 34, 28, 17, 28]]],
 5: [[141, [30, 26, 7, 25, 35, 20, 7]], [161, [36, 13, 29]]]}


text:
Q: Vb.net - Cross-threading exception when opening the form I have created two forms, in which one form to display the last modified record and another form which gives search result of current form. But some times when searching records "No result can happened" , in that situation i am closing the search form and opening the "Last record showing form"
Searching :
Menu find click
 frmSearch.Show()
 frm.Hide()

if no records find then, i am invoking "Begin invoke method" to close and show "Form Last record"
Me.BeginInvoke(New MethodInvoker(AddressOf CloseMethod))

Sub CloseMethod()
     frmSearch.Close()
     frm.Show()
end sub

But in "Frm.show" i am getting Error - Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
Also when i change the method as
 Sub CloseMethod()
         frmSearch.Close()
         frm.Close()
         frm.Show()
 end sub

i am not getting the error. Please any one help me understand why i am getting error.


text:
Q: Getting started with unit testing in VS2010? I'm new to both unit testing and Visual Studio 2010 (just upgraded from 2008). I'm interested in using VS2010's new built-in unit testing tools, but would like to get the lay of the land first. I haven't been able to find any resources or tutorials on unit testing with VS2010 specifically - has anyone found a good walk-through?
I'm also open to persuasion that we should stick with NUnit or the like, if anyone knows a reason to avoid the built-in tools.

A: PEX and PEX Tutorial

A: Here's a Channel9 video titled "TestDriven Development with Visual Studio 2010".
She goes through the basics of the Test Project, and it seems a good intro, Channel9-style!
Aside:
This is vintage 2008 material, and the GUI of Visual Studio doesn't look like RTM. You can see though, when she selects text, that it appears to highlight ala 2010.

A: I prefer using open source tools such as NUnit, the reason is, if you use the built-in testing tools in your projects, those will not be available to developers running express versions of Visual Studio. This might not be a good enough reason for you but it is for me, specially when you work with .NET open source projects.
Good luck!


text:
Q: Implementing SSO in sharepoint 2013 with SAP I am looking for a solution that will connect SAP from SharePoint. What is best way to create SSO in SharePoint 2013 to SAP.
I am completely unaware of this type of requirement. Any one could explain in plain way and steps to implement my requirement.
Requirement

*

*Create a SSO in Sharepoint 2013 with SAP

*Create a Login in Sharepoint 2013

*How to take care of SAP users in Sharepoint 2013

*How can i maintain the user authorization for all applications.


text:
Q: How to deploy multiple Lambda's in CFN Template through Codepipeline? Usecase
I have a cloudformation Stack with more then 15 Lambdas in it. I can able to deploy the stack through Codepipeline which consists of two stages CodeCommit and CodeDeploy. In this approach all my lambda code is in cloudformation template(i.e.inline code). For Security concerns i want to change this Inline to S3 which inturn requires S3BucketName and S3Key.
As a temporary workaround
As of now i am zipping each lambda file and passing manually S3keyName and bucketname as a parameters to my stack .

Is there any way possible to do this step via Codepipeline ?

My Assumption on CodeBuild
I Know we can use the CodeBuild for it. But upto now i have seen CodeBuild is only used to build package.json file. But in my usecase i dont have any . And also i can see it is possible to specify cloudformation package command to wrap my lambda from local to S3 this command will generate S3 codeuri`, but this is for Serverless Applications where there will be single lambda but in my case i have 15.
What i had tried
I know that as soon as you give a git push to codecommit it will keep you code in S3. So what i thought is to get the S3BucketName and S3KeyName from the codecommit pushed file and pass these parameters to my CFN template. I can able to get the S3BucketName but S3KeyName i dont know how to get that ? And i dont know whether this tried apporach is a workable one ?
BTW i know i can use shell script just to automate this process. But is there a way possible to do it via CODE PIPELINE ?
Update--Tried Serverless Approach
Basically i run two build actions with two different runtimes(i.e.Nodejs,Python) which runs independently. So when i use serverless approach each build will create a template-export.yml file with codeuri of bucketlocation , that means i will have two template-export.yml files . One problem with Serverless approach it must have to create changeset and then it trigger Execute changeset. Because of that i need to merge those two template-export.yml files and run this create changeset action followed by execute changeset. But i didn't know is there a command to merge two SAM templates.Otherwise one template-export.yml stack will replace other template-export.yml stack.
Any help is appreciated
Thanks

A: There's documentation on deploying multiple Lambda functions via CodePipeline and CloudFormation here: https://docs.aws.amazon.com/lambda/latest/dg/build-pipeline.html
I believe this will still upload the function code to S3, but it will leverage AWS tooling to make this process simpler.

A: If I'm understanding you right, you just need an S3 Bucket and Key to be piped into your Lambda CF template. To do this I'm using the ParameterOverrides declaration in my pipeline.
Essentially, the pipeline is a separate stack and picks up a CF template located in the root of my source. It then overrides two parameters in that template that point it to the appropriate S3 bucket/key.
        - Name: LambdaDeploy
          Actions:
          - Name: CreateUpdateLambda
          ActionTypeId:
            Category: Deploy
            Owner: AWS
            Provider: CloudFormation
            Version: 1
          Configuration:
            ActionMode: CREATE_UPDATE
            Capabilities: CAPABILITY_IAM
            RoleArn: !GetAtt CloudFormationRole.Arn
            StackName: !Join
              - ''
              - - Fn::ImportValue: !Sub '${CoreStack}ProjectName'
                - !Sub '${ModuleName}-app'
            TemplatePath: SourceOut::cfn-lambda.yml
            ParameterOverrides: '{ "DeploymentBucketName" : { "Fn::GetArtifactAtt" : ["BuildOut", "BucketName"]}, "DeploymentPackageKey": {"Fn::GetArtifactAtt": ["BuildOut", "ObjectKey"]}}'

Now, the fact that you have fifteen Lambda functions in this might throw a wrench in it. For that I do not exactly have an answer since I'm actually trying to do the exact same thing and package up multiple Lambdas in this kind of way.


text:
Q: Now to normalize table when position in group uniquely identifies entity I need to model charts such as the one displayed below...

... and came up with the following:

For the sample chart I originally showed..

*

*charts.name is "Custom transactions", charts.y_legend is "Amount", x_legend is "Customer Group"

*series.name is "2007" for position 0 and "2006" for position 1, categories.name is "Foreign" for position 0, "Specialty Stores" for positions 1, etc.

*chart_values.value will be the value for a given series and category such as $14,000,000 for series "2007" and category "Foreign".

As seen, the unique series can be identified solely on idSeries and position, (and similarly for categories, however, I will no longer be saying so), and thus series.idseries is redundant.  Does this violate the 1st, 2nd, 3rd, or Boyce and Codd Normal Form?
Regardless of normalization purity, I am also concerned (yet don't know why) with the implications of using composite key charts_idcharts/position as series primary key.  For my application, a backend configuration page will allow the user to add/remove categories and series, rename them, change the position order, etc.  To change a series name, the client can provide the chart ID and series position along with the new desired value.  To change position, the client could provide an array of the previous positions in a given order [2, 0, 1, 3].  Are there any negative implications of using position in a group in an entities primary key (other than needing to change the primary key upon changing position)?

A: Which happens more often?  Renaming/reordering versus fetching?
If you are fetching most of the time, then make that more efficient (PK order), while letting the other be more costly.
If you are renaming/reordering most of the time, then normalize to simplify that -- at the cost of ordering during fetching.
If the two tasks are the same (or even remotely similar in frequency), the do whichever is easier to code.


text:
Q: How to sort by defined order in sas, not alphabetically? Say I have a dataset for a supermarket,  with a product category, price product name etc. I want to sort by the category but with a defined order as opposed to alphabetically.
For instance if the categories are: canned, dairy, meat,  vegetable,  and I want to sort by when they may expire (I'll it's likely we'd have that information, so just play along please).  This means I want to sort in this order: Dairy, Meat, Vegetable, Canned.
I wrote a macro with this signature:
key_sort(ds=, keys='canned, dairy, meat,  vegetable', field =category, sort_by=)

This parses the keys so that the can be put in a macro loop,  then I use that much loop to write out a select statement like so:
Select(&field. ) ;
    %do i=1 %to &number_of_keys. ;
    %let current_key= %scan(&keys., &I., &delim.) ;
    When(&current_key. ) &field._key=&i. ;
    %end;
End;

I then sort by the  &field._key
Is this the best method to take? Can this be done more succinctly or efficiently?

A: If you had a separate dataset that contained the ordering then you could utilise that and provide it as input a PROC FORMAT, or apply one that's only a few bits as simply as possible.
proc format;
    value $EXPIRES
        'canned'= 4
        'dairy' = 1
        'meat' = 2
        'vegetable' = 3
        other = 5
        ;
run;

proc sql;
    CREATE TABLE output_set AS
    SELECT * FROM foods ORDER BY put(produce_type, $expires.);
quit;


text:
Q: What does it mean when two voids are in a parameter name in C? I have a method I need to fill in and one of the parameters is: "void (*destructor)(void*)".  Can anyone tell me what this is?

A: It is a Function pointer.
It stores address of an function which takes a void *(pointer to void) as an input parameter and returns no parameter.

A: That's a function pointer. The function given should have the signature:
void funcname(void*)

The first void is the return type, the second is a pointer to void (in other words, a pointer to who knows what, which the underlying function will presumably cast to some useful type later).

A: The void (*destructor)(void*) is a function pointer. This means, that you can use it to point to any function, which has void as return value (returns nothing) and expects an generic pointer (void*), which can point to anything.

A: It's pointer to a function that takes a void* as its only argument, and returns nothing.


text:
Q: How to shut down when only at the encryption password page? Possibly a silly question. I have my hard drive encrypted so on turning on my laptop I have to enter my hard drive password. There is nothing else on this screen. If I wish to shut down my computer at this point what is the safest way of doing it?
I would hope there is a way of doing it without having to log in and then having to shut down.
Running 14.04 on my machine. It has 2 hard drives; one for Ubuntu and the other for /home. There is only full disk encryption on the OS Hard Drive.

A: As you are using full-disk encryption on the OS drive, and you have not yet entered the password to decrypt that disk, you may be sure that nothing is being written there. You can also know that nothing is being written to the disk containing /home, as without decrypting the OS drive the system can't access /etc/fstab and thereby discover that it needs to mount /home, let alone actually mount it.
As such, it should be entirely safe to power off the machine in any reasonable way. While pulling the plug seems unnecessary, an ACPI power-off (by holding the power button) should be fine.
As a side note, if the system were booted to such a point that disk writes were a possibility, but login (or display-manager shutdown) wasn't, my first instinct (though probably not the best answer) would be a Magic SysRq sequence, probably REISUO, with appropriate multi-second pauses between commands.

A: LVM Encrypted Ubuntu 18.04 could be shut down from the boot-time decrypt page by escaping to grub (example 2.04) command line then commanding to halt.
[Ctrl] + [Alt] + [Delete]      (Escape to grub menu)
[Esc]                          (Escape to grub command line)
grub> halt     + [Enter]       ("The command halts the computer")

A: It seems as if You have some FULL drive/disk encryption, and need to "unlock" to boot further than the bootloader (either BIOS/UEFI, or a GNU/Linux bootloader (like GRUB))...?
If above is the case, I agree with earlier posters - it's safe to do a hard shutdown by pressing down the power button for the seconds needed (usually 3-6 s. depending on model).
Elaborations below...
Even IF any other file system is mounted (or  encryption backing FS/partition), the system is basically running in a pre-boot environment with extremely little writing going on (if any)...
Hardly any fairly modern file system would fail patching up the few bytes that could disappear due to a shutdown.
(And if You're using spinning disks (mechanical hard drives) and worry about read/write-heads falling to disk surfaces and scratching them because of power down, that won't happen, they "auto park" safely.)


text:
Q: Choose between multiple devices in XCode I've 2 devices (iPhone + iPod) connected to my Mac and both are available as developper devices in XCode. How can I choose which one to use for testing purpose and switch from one to the other when I want ? For the moment the only way I found is to unplug the unwanted one in order for the other to be available. Am I missing something obvious ?
Rgd
--GQ.

A: What you need to do is use the Overview drop-down in Xcode.  When you have multiple provisioned devices attached and have chosen to deploy to a Device (not the simulator), the drop-down will give you a choice under "Active Executable", listing the devices by name.

A: I have multiple devices but don't have enough USB ports to plug them both in at the same time. So I switch between them the same way you do...

A: You use Project > Set Active Executable, and pick the device you want.  In order for a device to show up, it has to be provisioned with a copy of the OS and the provisioning file that corresponds to the target OS and signing certificate for the app you built.


text:
Q: Exit code is not bubbled up Outer.ps1:
& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& '.\Inner.ps1'; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode"
Write-Host "OUTSIDE: $LastExitCode"

Inner.ps1:
exit 3

Executing Outer.ps1 outputs:
BLOCK: 1
OUTSIDE: 1

What, why? Inner.ps1 clearly exited with exit code 3. What's the problem?
Note: If I change Inner.ps1 to return 0, I receive the following output:
BLOCK: 0
OUTSIDE: 0

Somehow, all other codes than 0 are defaulted to 1, why?

A: You have quoting problem:
& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command '& ''.\Inner.ps1''; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode'
Write-Host "OUTSIDE: $LastExitCode"


text:
Q: Print is invalid Syntax? [Python 3] I'm trying to write a program that will do some simple math for a video game, however I am encountering multiple errors.
the string after Print IS in brackets, because of Python 3.
I also get "Calculation error" if I try to enter 1.5 or a value similar for 'FCS'
import decimal
print("ARMORED CORE V - FCS SIMULATION")
print("This program will calculate lock times for weapons combined with their FCS in           Armored Core V")
print("----------------------------------------------------------------------------")

#Base Weapon Lock/FCS Lock Percentage (150=1.5)/60
#Seidenbaum at 421 Base Lock
#421/1.5/60 is lock time (4.67 seconds)
#Subcomputer: Base Weapon Lock/FCS Lock Percentage/Subcomp Lock Percentage  (320=3.02)/Second Subcomp/60
#Subcomps: 421/1.5/3.02/60 (1.54 Seconds)
#Dual Subcomps: 421/1.5/3.02/3.02/60 (0.5 Seconds)

while (1 == 1):
    command = input("\nTo begin, type 'compute'\nThen enter your weapon's Base Lock Time\nThen your FCS' Lock Computation\nAnd then how many Subcomputers you have\nyou can also type help [ compute // help ]")
    if command == "help":
        print("\nFollow the instuctions as prompted\n\nI will also display the Lock Times and Subcomp Acceleration for FCSes and Subcomputers")
        print("--FCSes--\nUFC-11 GLANCE - 1.7 Lock Computation\nFCS-09 YASAKANI - 1.05 Lock Computation\nKV-1T2/OTKRYT - 0.75 Lock Computation\nFCS-07/Lr UZUME - 1.8 Lock Computation\nSEHER FCS199 - 1 Lock Computation\nPREDIRE FCS190 - 1.5 Lock Computation\n--SUBCOMPUTERS--\nSUBCOMPUTER USC-1 DHANBAD - 3.02 Lock Improvment\nSUBCOMPUTER SBC-9 TSUKUYOMI - 3.06 Missile Lock Improvement [Enter Normally]")
    if command == "compute":
        baselock = input("\n\nEnter your weapon's Base Lock Time >> ")
        fcs = input("\nEnter your FCS' Lock Computation as a Percentage >> ")
        subcompone = input("\nEnter your first Subcomputer's lock improvment\n Enter '1' if you don't have any subcomps >> ")
        subcomptwo = input("\nEnter your second Subcomputer's lock improvment\n Enter '1' if you don't have a second subcomputer >> ")
        try:
locktime = float(int(baselock)//int(decimal.decimal(fcs)//int(decimal.decimal(subcompone)//int(decimal.decimal(subcomptwo)//60)
                return(locktime)
                print("Seconds")
        except ValueError:
            print("error in calculation")

A: You forgot a closing parantheses on the line
locktime = float(int(baselock)//int(decimal.decimal('fcs')//int(subcompone)//int(subcomptwo)//60))

Also, I'm assuming this is in the function and that return is needed, but print('seconds') won't be executed if the return is hit. It is unreachable.


text:
Q: how to parse remote xml file with javascript/jQuery and phonegap? For phonegap development:

*

*is it possible to fetch remote data for phonegape?

*is it possible to fetch remote json/xml file using ajax/jquery ?

*XmlHttpRequest can fetch remote xml file ?

also any suggestion for it or important link.

A: Ajax works no different that it does else where execept that cross domain calls are ok with phonegap,
see my other answer
Example of jquery ajax call @ http://api.jquery.com/jQuery.ajax/
Parsing xml with javascript @ http://www.w3schools.com/xml/xml_parser.asp

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});

Example of native javascript call

Ref from phonegap about ajax
(see question:

Q. I want to create an application for phonegap to access externally deployed web services via AJAX. How can i resolve the issue with the cross-domain security policy of XmlHttpRequest?)
True to life example on this site

This should be enough to get you started.
Let me know if you have any other questions.


text:
Q: Phone gap camera - is there a more powerful option? I'm looking to build a companion photo capture app for my photo capture website.  I was planning to do this with phone gap.
Upon triggering the camera I want to grab a frame (a still, really) up to five times a second and send it to the server (barring any surprises, The sending part should already be dealt with in code I have).  I suppose the realtime video from the camera itself should be displayed to the user as well, though I could just use the stop motion frames for that part.
Unfortunately, according to the phone gap docs, one can only launch the phone's cam app, manually take a picture, then return the user to the app.
I am looking into plugins, but I don't see any massive phonegap plugin repository out there, so I am not sure where to begin.  I am just rambling now, so here is a list of bulleted questions:

*

*Is there a plugin out there that does something like this already?

*Is there a giant repository of phone gap plugins that I am too foolish to find?

*If I try to roll my own java plugin (this is for an android app), what am I really getting myself into?  Will I need to know enough to just make the damned thing native?  I am pretty exclusively in the JS world at the moment, and am trying to get this out the door asap.

*Am I missing something and there is a way to to this with vanilla phone gap?

*Any other suggestions?

Thanks!

A: The phonegap plugins are here:
https://github.com/phonegap/phonegap-plugins


text:
Q: Strategies for parallelising neural networks When it comes to parallelising a problem, it involves the division of routines and subroutines between a number of nodes, namely; the master node and the slave nodes. Once each of these nodes completes its respective task, all the results from all the nodes are concatenated together to give the final output, hopefully in a shorter time than when using sequential computing methods.
My question is, is there a standard strategy which migrates this method over to the realm of neural networks? For example, my initial reasoning was that what would be "parallelised" in this case would be the feature vector, and each portion of this vector is computed simultaneously, and then concatenated together into one again and the final result will be classified.
Would this strategy make sense or would it be better to parallelise the neurons themselves instead?

A: What's the distinction between parallelizing the feature vector and parallelizing the neurons? I assume that the neurons of the input layer are features of a training instance.
Suppose the feature vector of an instance is a 1 by n1 matrix, the weights between the input layer and the first hidden layer is a n1 by n2 matrix, and there are m training instances. Then a feed-forward pass from the input to the hidden layer is just a matrix multiplication, the multiplication of the m by n1 matrix and the n1 by n2 matrix. The training process is made up of many matrix multiplications, so the problem is essentially about parallelizing matrix multiplication.
In machine learning, researchers more often parallelize training examples instead of parallelize features. There are three types of learning (1) batch learning (2) mini-batch learning (3) stochastic learning, and mini-batch algorithms are often considered for parallelization speedup. The parallelization can be seen as decomposing (m by n1) * (n1 by n2) to many (b by n1) * (n1 by n2) matrix multiplications where b is the batch size.
In comparison, parallelizing features is less conceptually sensible. Particularly, for deep neural network learning, the features are considered interconnected with each other, and the connections are what the algorithms try to learn. When performing unsupervised pre-training, if features are paralleled, then different parts of features are separated and their connections cannot be learned.

A: Typically parallel versions do some form of stochastic gradient descent, in which SGD steps for different data instances are spread across nodes (map) and then the partial results are summed up (reduce). This simple strategy can be used to parallelize many algorithms.
This NIPS paper is a very good read on parallelizing machine learning algorithms (including NN) using MapReduce. Quoting from this paper:

By defining a network structure (we use a three layer network with two output neurons classifying the data into two categories), each mapper propagates its set of data through the network. For each training example, the error is back propagated to calculate the partial gradient for each of the weights in the network. The reducer then sums the partial gradient from each mapper and does a batch gradient descent to update the weights of the network.


text:
Q: How far could you theorically get with the one shot demo? There was the one shot demo that you could play last week.
In that demo, you had half an hour to get as far as you could in the police station.
I would imagine that even if you could speedrun pretty far in the game, you did not download the whole game in case you got that far. So it must hard block you at some point, even if there's still time on the clock.
So if you were to remove the time limit (or go really fast), how far could you theorically go in the one shot demo?

A: Funny how you may find the answer to your own question later in the day.
The GameGrumps played the 1-shot demo, and the game ended right after the cutscene where you see Claire on the surveillance camera.

And it ended with a splash screen saying complete, that I don't think I saw in other playthroughs.

So I guess that is where the Oneshot demo forces you out of the game, even if there is still time on the clock.
Fun fact, earlier in the video there were 6 minutes left, so the completion timer must not count some things (even if the oneshot timer seems to continue) I would guess the completion timer pauses in cutscenes and the one shot doesnt; because the only other place I can think of is when you pause the game, but that also pauses the oneshot timer.


text:
Q: openSSL and gnuTLS can't connect to OpenWRT web interface, why not? I have some weirdness securely connecting to OpenWRT from IceWeasel (debian Firefox).  I find recent Firefox's error messages less useful for troubleshooting.
So I want some HTTPS tool to run tests on the connection.  But my usual command-line tools were failing completely.  Why?  Is this a known bug?
$ curl --insecure https://mortar.local
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

$ wget --no-check-certificate https://mortar.local
--2014-10-02 10:42:53--  https://mortar.local/
Resolving mortar.local (mortar.local)... 10.209.37.18
Connecting to mortar.local (mortar.local)|10.209.37.18|:443... connected.
GnuTLS: An unexpected TLS packet was received.
Unable to establish SSL connection.

The above is on Debian 7.6.  wget and curl were respectively using gnutls26 2.12.20-8+deb7u2`and openssl 1.0.1e-2+deb7u12.
If I switch to Fedora 20, curl works but not wget.  On Fedora wget still uses openssl, but curl uses NSS 3.16.2, so I can use that for the tests I originally wanted to run.  IceWeasel/Firefox uses NSS, so it explains why IceWeasel doesn't always fail.  But I don't like that there's an incompatibility with the other two SSL libraries.
OpenWRT 12.09
uhttpd-mod-tls 2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd
libcyassl 1.6.5-1

Update: also applies to OpenWRT 14.07

A: Update x2: I retested from Debian 7 system, and both curl and wget work now.  I haven't seen a weird problem with IceWeasel (Firefox) yet either.  Crypto libraries are now openssl 1.0.1e-2+deb7u14 and gnutls 2.12.20-8+deb7u2.  That's no change in gnutls (and OpenWRT doesn't do automatic updates).
So I really don't know why curl (using gnutls) is working now.  Nor do I have anything to troubleshoot.
The strongest hypothesis is: perhaps there was a bug which OpenWRT 14.07 fixed - however I know my upgrade to 14.07 wasn't very smooth, so that could have left a weird problem.
Gory details - I had managed to upgrade the squashfs image (read-only base filesystem), while leaving the package source configured for 12.09 & a bunch of packages installed from there on the JFFS overlay.  That took a bunch of fixing.  I should probably save my config files and package list and re-flash, in case there's anything else lurking :).


text:
Q: Database schema to map Hotel Amenities from different sources into a uniform format to remove duplicates I am creating a hotel application that fetches hotel feeds from different sources and store it to database to form a uniform structure and expose API to the mobile application. I am fetching hotels from 3 different sources using python/django app.
Now every hotel source has different sets of amenities for example:
Source 1 [Expedia]
    - Free WiFi
    - Hairdryer In Room
    - Cable TV
    - Double Bed
    - Single Bed
    - Fireplace

Source 2 [SomeHotelProvider]
    - WiFi
    - Hairdryer
    - Television
    - and so on

So here we have same amenity name with different name (Free WiFi and WiFi ) for example. The only problem is that at the Mobile screen it will display two filter [Free WiFi, Wifi] to filter out the result set. So what is best approach to deal with these duplicate values.
Need a solution to create a mapping table that maps all duplicates to one amenities master table.
Thanks in advance.

A: I would use a JSONB column so you can accept any type of data. in a hash format.  Then you will have to find duplicate keys and consolidate them.
https://www.postgresql.org/docs/9.4/static/datatype-json.html
Then you will have to go through and consolidate duplicate keys (wifi, free wifi, etc).  Unfortunately this can't be done programatically as even if you wrote a perfect program to do this, in the future there might be a new form you did not account for like "included Wifi".


text:
Q: composer require (normal) and require --dev in one single CLI command How can I use composer require vendor/normal_package and composer require vendor/dev_package --dev in one single command? I want one CLI command that requires 2 packages, one into "normal" require and one into require-dev section.
Background info: I've a composer.json file like this:
{
    "require": {
        "drupal/core": "^8.6.7"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "^8.6.7"
    }
}

Those two packages always need to be updated the same time. Usually I just do a composer update drupal/core webflo/drupal-core-require-dev --with-dependencies which works fine.
But sometimes I explicitly want to require a new minimum version, and I want to do it in a shell script in order to update multiple projects at once (no manual editing of composer.json). I can't run the two commands
composer require drupal/core:^8.6.10
composer require webflo/drupal-core-require-dev:^8.6.10
consecutively, because they depend on each other.
How can I require a normal and a dev package in one single command?

A: If you have got a circular dependency in your composer.json and that dependency is split across require and require-dev, then it currently is not possible to update and set a new min version with just one command. But I've found a workaround that saves a lot of time by using the require-command with --no-update option.
Below is the code I'm currently using (drupal/core is the normal package, webflo/drupal... is the dev package, version ^8.7.1 is the new minimum version I want to enforce):
# include both packages in the require section, but don't update
# this is much faster than normal require with update
composer require --no-update drupal/core:^8.7.1 webflo/drupal-core-require-dev:^8.7.1

# move the dev package back into the require-dev section
composer require --dev --no-update webflo/drupal-core-require-dev:^8.7.1

# now run the update, this will take some time (you can not use --no-dev here)
composer update drupal/core webflo/drupal-core-require-dev:^8.7.1 more_stuff/*

# optional: remove the dev-packages again (this is quite fast too)
composer install --no-dev

I won't mark the question as answered though, because this is just a time-saving workaround and not a real solution.