text:
Q: Symfony2 Extend Twig Block in Event Listener I'm trying to find a way to extend a known twig block in an event listener/subscriber.
The code is very basic.
Main twig:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Hello World</title>
</head>
<body>

{% block body %}{% endblock %}

{% block javascripts %}{% endblock %}

</body>
</html>

As you can see it's just a plain html with 2 blocks: body and javascripts.
Now for example I've a event listener onKernelResponse. What I want here is to be able to add new javascript to the "javascripts" block with twig's "extends".
The code could be something like:
public function onKernelResponse(FilterResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $response = $event->getResponse();

    //complete guesswork code to illustrate what I'm trying to achieve

    $content =  $this->twig->extend( //extend() function is imaginary
        $response, //pass in current response
        'AcmeBundle:Javascript:index.html.twig',
    );
    $response->setContent($content);
}

The $this->twig->extend should work like $this->twig->render, but instead of render something new, extend() should take the $response and extend it with the 'AcmeBundle:Javascript:index.html.twig' where I can add more content to the "javascripts" block.
Here is the example of the "AcmeBundle:Javascript:index.html.twig":
{% block javascripts %}
    {{ parent() }}

    <script>
        var something = "new";
    </script>
{% endblock %}

Basically I'm looking for a way to programatically extend twig block in event listeners.
Thanks for the help in advance.

A: You can register a twig global variable in the event listener to indicate wether to extend the block.
... or you can include the global variable registered in your event listener as template code somewhat similar to eval using twig's template_from_string() function.
{% block javascripts %}
    {{ parent() }}
    {{ include(template_from_string(global_variable_name|default(''))) }}
{% endblock %}


text:
Q: Image cropping in php So I am trying to write a little script to crop a users image. I would send some information (width, height, alignment properties and image url) to the script and it should return the image cropped. However, it's not working... Just an "image not found" symbol :/ Here is my script, any thoughts?
<?php
session_start();
header('Content-type: image/jpeg');
$w=$_GET['w'];
$h=$_GET['h'];
$x=$_GET['x'];
$y=$_GET['y'];
$filename="http://www.domain.com/".$_GET['src'];
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$ext='';

if($file_ext=='jpg')
{
    $image = imagecreatefromjpeg($filename);
}
else if ($file_ext=='gif')
{
    $image = imagecreatefromgif($filename);
}
else if ($file_ext=='png')
{
    $image = imagecreatefrompng($filename);
}

$crop = imagecreatetruecolor($w,$h);
imagecopy($crop, $image, 0, 0, $x, $y, $w, $h);
imagejpeg($crop);
?>

Edit: Looks like this is the error: Fatal error: Call to undefined function imagecreatetruecolor() in domainpath/crop.php on line 24 Is there anything I need to do to load this function?

A: According to your comment about the error, imagecreatetruecolor() is indeed a function, but only if you have the GD library loaded.
Make sure you have a compatible version of GD accessible to your PHP installation, and don't forget to restart your web server if you have just added it.

A: Using ImageMagick, try this;
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
    $img = new Imagick($file);
    if ($crop) {
        $img->cropThumbnailImage($w, $h);
    } else {
        $img->thumbnailImage($w, $h, TRUE);
    }

    return $img;
}
resize_image('/path/to/some/image.jpg', 150, 150);

A: I will recommend u use imagemagick instead of GD / GD2 lib. If u looking for quality, imagemagick is too good for the same. There is this link which also gives compares on the same
http://www.rubblewebs.co.uk/imagemagick/compair.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should simple SQL questions be closed as "Too localized", "Exact duplicate" or be left open? I very often find SQL beginners asking simple questions about standard SQL constructs. They often don't realize that it's a JOIN operation they are after, but it should be pretty obvious for anyone who have read at least a tutorial on the subject (Example 1: "i was having hart time finding it in exact format ... im new to sql and for example things like "users.id = emails.user_id" are still confusing for me") (Example 2).
The questions are often very precisely related to the askers' own schemas and they can't, or won't try to, understand general explanations of joins, but instead want exact answers which match their own schema. I have found that this makes it hard to find exact duplicates because other people may have other names in their schema and thus the other question may look very different (Example 3: Very standard problem, in my opinion, but how do I find duplicates?).
I'm leaning towards "Too localized" because questions where the asker want the answer to match their exact schema are often very localized. At the same time, the schema is often crucial for understanding the question at all so it must still be included in SQL questions. Maybe I'm just confused about the "Too localized" category?
So a short summary of my rather broad question:

*

*Should we close these types of questions? With what motivation?

*Can they be closed even if an exact duplicate is hard to find?

*Maybe I'm talking about two different types of problems?

*Do the experienced users have any hints on how to find duplicates?

A: All tags suffer from this, not just SQL. See The Wikipedia of Long Tail Programming Questions.
The blog post recommends that you

*

*Don't answer

*Vote to close as dup if its a dup

*Edit to make the question more general

*Create a canonical answer

Currently there is an effort to create a sql-faq tag that is supposed to help this has been attempted before on c++ see Setting up a FAQ for the C++ tag
However the reality is, its easy and rewarding to answer a question while casting a close-dupe vote is both hard and un-rewarding. The only way to overcome that tension would be to marshal the most active users in a tag and get them to stop answering these near dupe questions. If you don't you'll get a handful of tag-faq questions, a smattering of close votes and a ton of marginal questions with accepted answers.

A: How about answering the question?
We have hundreds of Regex questions of this ilk, all of which are too localized in this way, but they somehow get answers anyway.  If you close these, you're gonna have to close all of the "What is a good regex for this" questions also, including the one I asked about a month ago.


text:
Q: Alternate to using backspace in vim When I do a mistake in vim, I use backspace, because changing to command mode and use 'x' is longer, but maybe is other way to do it vim-way?

A: In insert mode ctrl+h does the same thing as the backspace key (i.e. deletes one character backwards).

A: You can use u to undo. However it tends to erase the whole last line you typed...
Depending on the situation you can use the following text objects :

*

*ciw to erase and rewrite the current word

*c$  to erase and rewrite everything to the end of the line

*c^  to erase and rewrite everything to the beginning of the line

*ci) to change the content of parentheses

See :help text-objects for more.
If you need to change a single letter, the Vim way could be to use r to replace the wrong letter.

*

*type tje home

*Put your cursor on j using fj or Fj depending if your cursor is after or before j

*Type r and then h

A: ctrl-w to erase the last word, ctrl-u to erase the entire line you're on.


text:
Q: NSLog on the iPhone device I wanted to test my app on the device, but I dont want now to buy apple licence for 99$.
I read some tutorials on the Internet and installed my app, but I cant debug it.
Xcode says that "Error launching remote program: faileds to get the task for process 731"
App works fine, but I cant debug it.
Maybe break points arent the most important for me. The worst thing is that NSLog() doesnt work when I run app on the device...
What can I do?

A: Buy an iPhone Developer Licence. 99$/Year aren't this much. If you create one paid app, you'll get more than that back. ;-)
I know it. I did that myself. ;-)

A: I am afraid that you can't do this without proper development profile. Please correct me if I am wrong.

A: The "Console" tab in the Xcode Organizer or iPhone Configuration Utility will give you device log messages. It gives messages for all apps (not just yours!) but that's not the end of the world, really.
Your app is missing the entitlement <key>get-task-allow</key><true/>. You might be able to self-sign it with this to make it work. I'm not sure, since I'm not sure what steps you're following to get it to run.

A: Instead of NSLog, write to a log file and then read it.
You can transfer it to your PC/Mac by mailing it from your application or just upload it to your computer with SSH if you have a jailbroken iPhone device.


text:
Q: how can I scrap data from reddit (in bash) I want to scrap titles and date from http://www.reddit.com/r/movies.json in bash
wget -q -O - "http://www.reddit.com/r/movies.json" | grep -Po '(?<="title": ").*?(?=",)' | sed 's/\"/"/'
I have titles but I don't know how to add dates, can someone help?

A:
wget -q -O - "http://www.reddit.com/r/movies.json" | grep -Po
'(?<="title": ").*?(?=",)' | sed 's/"/"/'

As extension suggest it is JSON (application/json) file, therefore grep and sed are poorly suited for working with it, as they are mainly for using regular expressions. If you are allowed to install tools, jq should be handy here. Try using your system package manager to install it, if it succeed you should get pretty printed version of movies.json by doing
wget -q -O - "http://www.reddit.com/r/movies.json" | jq

and then find where interesting values are placed which should allow you to grab it. See jq Cheat Sheet for example of jq usage. If you are limited to already installed tools I suggest taking look at json module of python.


text:
Q: laravel break parameter name in route after defining a simple below route into web.php:
Route::prefix('{language}')->middleware(['setLanguage'])->group(function () {
    Route::prefix('panel')->group(function () {
        Route::prefix('contactusmodule')->group(function () {
            Route::resource('contactUs', 'ContactUsController')->names('contactUs');
        });
    });
});

i try to get route name by this code:
request()->route()->parameters()

here my route parameters are: language and contactUs and when i locate this url:
http://127.0.0.1:8000/en/panel/contactusmodule/contactUs/3/edit

with this route as:
route('contactUs.edit',[app()->getLocale(),$contact->id])

i should get language and contactUs, but i get this array:
array:2 [
  "language" => "en"
  "contactU" => "3"
]

as you can see in this output problem is contactU which that should be contactUs
output of dumping route:
dd(request()->route()->getName(),request()->route()->parameters());

//output:

"contactUs.edit"

array:2 [▼
  "language" => "en"
  "contactU" => "3"
]

in our code by default we should get value from request()->route()->getName(). laravel route name is limited? how can resolve this problem?
thanks in advance

A: As lagbox says, it's caused by Laravel grammar parameterize that automatically convert plural route name to singular variable name. Laravel think contactUs is plural of contactU. If you want to use contactUs as param, just override it by adding ->parameters() method like below:
Route::resource('contactUs', 'Cms\Auth\LoginController')->names('contactUs')->parameters(['contactUs' => 'contactUs']);;


text:
Q: calculating the width of a list of loaded images using jquery I'm creating a slide show using jQuery, the images are loaded using AJAX and are put into the list using append. After all images are loaded I want to get the list width.
I'm using this code below, but the problem is that logos_counter which is supposed to contain all images width is always equal to 0.
var logos_counter = 0;
var img = new Image();
$.each(data.images, function (index, photo) {
   url = 'img/logos/' + photo;
   $('.logos ul').append($('<li>').append($('<img/>').attr('src',url).addClass('slide')));
   img.src = url;
   logos_counter = logos_counter + img.width;
});
$('.logos ul').css({width: logos_counter + 'px'});

A: Try this -
$.each(data.images, function (index, photo) {
   url = 'img/logos/' + photo;
   $('.logos ul').append($('<li>').append($('<img/>').attr('src',url).addClass('slide')));
   img.src = url;
   $(img).load(function(){
      logos_counter = logos_counter + $(this).width;
      $('.logos ul').css({width: logos_counter + 'px'});
   });

});


text:
Q: Custom icons for kml layer using in Google maps Api I want to display data from kml file, which is situated here http://maps.google.com/maps/ms?f=q&msa=0&output=kml&msid=201434694813577429889.0004ba2d12b7538131e5e .
It is output from MyPlaces. I want to do more stuff with it - change icons, use clustering and so on, so embedding is not good solution.
I've tried to load the file using KmlLayer in GoogleMapsApi, which works, but I don't know, how to change icons and how to get data for each marker (coordinates, description, ..).
Actually, what I need is just the access to the data in kml, I am able to do all other programming on my own. The file is continuously changing so I need to do all the stuff online.

A: You could use a 3rd party KML parser (through a proxy) like geoxml3 or geoxml-v3.  They render the KML using native Google Maps Javascript API v3 objects, you can modify those using the Google Maps Javascript API.  When you do that you lose the benefit of KmlLayer's tile based rendering, so with complex KML, you may have performance issues.
example with your KML (seems to have a character encoding issue)


text:
Q: Using proper relations for product and attribute I am about to implement a database for simple ecommerce platform. I want to implement the following:

*

*Each product belongs to one product category;

*Each product category has its own attributes;

*Each product has one value for each attribute of this products type.
What relations should I use to store this kind of information?

A: Here is the logical model -- the way I understood it; you should be able to tweak it.
From this you can derive the physical model and the SQL code. The word KEY here means UNIQUE NOT NULL and you may use them for primary keys. Should you choose to introduce integers as primary keys, make sure you keep these UNIQUE.
Note that everything should be NOT NULL, once you get to the SQL.

Category named (CAT) exists.
Category {CAT}
     KEY {CAT}

Attribute named (ATR) exists.
Attribute {ATR}
      KEY {ATR}

Category (CAT) has attribute (ATR).
Each category has more than one attribute, it is possible for the same attribute to belong to more than one category.
CategoryAttribute {CAT, ATR}
              KEY {CAT, ATR}

Product named (PRD) belongs to category (CAT).
Each product belongs to exactly one category, each category may have more than one product.
 ProductCategory {PRD, CAT}
             KEY {PRD}
             KEY {PRD, CAT} -- seems redundant here, but is
                            -- needed for the FK from the next table

     FOREIGN KEY {CAT} REFERENCES Category {CAT}

Product (PRD) from category (CAT) has attribute (ATR) that belongs to that category.
For each attribute that belongs to a category, that attribute may belong to more than one product from that category.
ProductCategoryAttribute {PRD, CAT, ATR}

        KEY {PRD, CAT, ATR}
FOREIGN KEY {PRD, CAT} REFERENCES ProductCategory   {PRD, CAT}
FOREIGN KEY {CAT, ATR} REFERENCES CategoryAttribute {CAT, ATR}

A: I don't know what database platform you are using, but for small numbers of products, and for queries that do not depend on the value of the per-category attributes, I'd use the following strategy:
CREATE TABLE "Category" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT
);

CREATE TABLE "Product" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
  "categoryId" INTEGER NOT NULL REFERENCES "Category" ("id"),
  "attributes" TEXT NOT NULL
);

In this example, the categories are used mainly to enforce referential integrity and to provide a list of categories for navigation.
The attributes are stored inside the attributes column as JSON (most modern databases tend to support this natively).
If there are any attributes common to all types of products, we'd create specific columns in Product. For example, you could add creationDate, deletionDate, price, or whatnot.
This allows you to perform the typical Select * From Product Where id = @Id to get a specific product and Select * From Product Where categoryId = @CategoryId to get all products in a category.
A creationDate could be useful to sort the products by creation date and take the top N, if necessary, when filtering by category. However with small quantities like thousands of products you might as well get all products by category and do this in code.
Regarding the code aspect, products like Dapper have specific extensions helping you deal with these discriminated unions, but writing code to support it is fairly easy. Here's an how. I'll write pseudo-C#, but I'm sure you can adapt.
We have an abstract class taking care of the Product table rows
public abstract class ProductBase
{

   // only the fields in the Product table here

   public int CategoryId { get; set; }
   protected string Attributes { get; set; }

   // serialize extra fields to JSON in Attributes
   protected abstract void Prepare();

   // load the common fields from a data row
   protected static ProductBase(DataRow dr)
   {
      CategoryId = int.Parse(dr["categoryId"]);
      Attributes = dr["attributes"] as string;
   }

   // save to DB
   public void Save()
   {
      Prepare();

      // save to SQL
   }
}

We also have specific classes per category which have the extra attributes and handle serialization and deserialization.
public class FooProduct: ProductBase
{
   public string Color { get; set; }

   protected override void Prepare()
   {
      Attributes = Json.Serialize(new { Color });
   }

   public FooProduct(DataRow dr): base(dr)
   {
      // we can only create foo products if the category is foo
      if (CategoryId != 23) throw new InvalidOperationException();

      var attr = Json.Deserialize(Attributes);
      Color = attr.Color;
   }
}

This idea works great while you don't need to get the "foo" products by Color. If you can afford to get all "foo" products and filter in code, great. If your database understands JSON and lets you query inside the Attributes field, good it will get slow with large numbers unless the server allows indexes to reference JSON-serialized values.
If all else fails, you'll need to create an index table which contains the color values and the ids of the products which have that color. This is relatively painful and you don't want to do it unless you need it (and you don't right now).


text:
Q: Can't extend the Sound object prototype I'm new to programming. I need to add new properties to the Sound object, but I can't get it to work. This is what I'm doing:
S31 = new Sound();
S31.load(new URLRequest("mp3/S31.mp3"));
Sound.prototype.correctas = 0;
trace(S31.correctas);

I get this error message:
"1119: Access of possibly undefined property correctas through a reference with static type flash.media:Sound".
I don't know what to do.
Thanks for your time.

A: The prototype class really isn't used in as3 (please someone correct me if I'm wrong here, I know its include but I'm not really sure why you would use it.)
You can create dynamic classes that allow you to add properties to them at runtime but in this case I would stick to OOP.
What you would want to do is create a class that extends Sound and holds whatever extended functionality you want to include. This new class will inherit all the functionality of the base Sound class.
Try creating a new AS3 class and having it extend Sound
package src {
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;

    public class MySound extends Sound{

    public var correctas:Number; //assuming you are using a Number here

    //sound takes two params in its constructor
    public function MySound(stream:URLRequest=null, context:SoundLoaderContext=null){
    //super passes these params to the super class
        super(stream, context);
     }
}

Now to use this you would create a new MySound object instead of Sound
 var s31:MySound = new MySound();
 s31.load(new URLRequest("mp3/S31.mp3"));
 s31.correctas = 0;
 trace(s31.correctas) //will be 0


text:
Q: progress 4gl: how link two database with foreign key relationship How to link two databases in progress 4gl with foreign key relationship?
FOR EACH jeld-wen.customer :
    FIND FIRST adm2.order WHERE adm2.order.custnum = jeld-wen.customer.custnum NO-LOCK NO-ERROR.
    IF AVAIL adm2.order THEN
    DISP jeld-wen.customer.custnum adm2.order.custnum adm2.order.ordernum.
END

A: Progress has no "foreign key" support like you might find in some SQL databases.  Relationships are maintained by application code similar to what you have shown.
Rule #1 - Progress is not SQL.

A: I cannot see a question in here although I assume you would not get the expected result from the query you have run.
The best thing you could do is refer the Data Dictionary for indexes and table relations it would give you a clear idea about the design of the Database and how are they related. In there you would find the relationship quite similar to 'foreign key relationship' in SQL if there is any.
Example Pregress DB:
           Member Table         Event Table
>          memberid             eventid
>          memberstatus         memberid
>          memberpayno          eventstatus

If you consider above example, memberid would be the foreign key equivalent in SQL.


text:
Q: Passing a shared pointer to a function argument - what is the right way to assign it to a local variable //header file
void SetLogger(const std::shared_ptr<A>& log);

//cpp file
void SetLogger(const std::shared_ptr<A>& log)
{
    std::shared_ptr<A>&  mLog;
    mLog = log;
}

What is the best way to pass a shared_ptr as a function argument such that the owner ship of the object referred to does not to change / no increment of reference count and that no body should be able to delete it accept the owner?
So how should create a local shared_ptr in the function stating the restriction above?
Caller:

SetLogger(A.get()); // A is actually a shared pointer

Header:

void SetLogger(const A& log);

CPP File:

void SetLogger(const A& log)
{
    auto mLog = std::make_shared<A>(log);
}

A: The rule of thumb for smart pointer function arguments is: if there is no notion of ownership, don't pass the smart pointer, pass the pointee

*

*as a reference, if it can't be null (preferable, see comments)

*as a pointer, if it can be null (don't forget to check, though)

In case 1, any call to delete on the argument will fail to compile, which might be desirable. Further const qualification of the argument is orthogonal. In your example:
void SetLogger(const A& log);

called like this
auto a = std::make_shared<A>(/* ... */);

SetLogger(*a);

So how should create a local shared_ptr in the function stating the restriction above?

If you need to copy the argument, there is indeed a notion of ownership. In that case, change your function signature to
void SetLogger(std::shared_ptr<A> log);

This will, however, increment the reference count, but if the object is managed by a std::shared_ptr, there is no sane solution to retain a copy without touching the reference count (for a good reason, this it what the class is about).

A: If you don't want the called function to have ownership over your object, there is nothing wrong in passing a raw pointer as stated here. Make your logger a std::unique_ptr<A> and pass the pointer using the get() method. In modern C++ it is now clear to all users of the function that they don't own that pointer and are not supposed to delete it. The owner will do that.


text:
Q: Eventbrite integration with Webflow form I have a one page Webflow site:
https://bam-training-2020.webflow.io/
The site has a form at the bottom for people to register to attend a free online streaming event. We want to use the form to capture normal information like names and emails, but also physical addresses and t-shirt size to send them a welcome box with swag. We have the form integrated with google sheets and mailchimp through Zapier zaps. Everything is working smoothly...
But the client also wants to run the event through eventbrite to also use their marketing tools. I've been able to embed the "stock" eventbrite widget, but it doesn't fit with the style of the site and it completely circumvents the registration form that we need to use in order to capture all the info we need to get.
HERE'S THE QUESTION:
Is there a way to code the current, "REGISTER" button on the form to also pass through the information in the form to eventbrite? I've looked at webhooks, but I've never used one and I don't know where to start.
I'm looking to remove the eventbrite widget completely and use the information that we'll capture on the existing form to create a (free) purchase in eventbrite.
The code for the eventbrite widget is all in JS, so I can't really see what's going on.

A: Zapier supports eventbrite also as an integration just like google sheets and mail chimp.
https://zapier.com/apps/webflow/integrations/eventbrite


text:
Q: Minify JavaScript with JavaScript? Since I've heard people whining how PHP can't handle it, how about minifying JavaScript with JavaScript itself? I want something that I can just copy and paste and use right away--my JS file is about 17KB and I know I can reduce it to about 15KB easily.
And I want to be able to do it right on the server. I don't want to have to go to  a website such as jscompress.com every time I make changes to my script.
Again, I would like something like this:
<script type="text/javascript" src="scripts.php?file_to_minify=scripts_template.js"></script>

And then I would just let JS minify it on the PHP file.
Now, I do have second thoughts...Would this even work???
Your help is appreciated. Thanks!

A: Personally, I would look to have a local version of my site, with all source/configuration files under version control. You could then have a release script that would prepare your files for upload, including minifying your javascript using a command line tool.
This ensures that you don't lose anything if you make a mistake, also it makes build of your site repeatable. This should be requirement for a production site, and is useful for a personal/hobby site (no-one likes losing changes/breaking things with no way back).


text:
Q: Time Machine Drive Failure So, I started up my computer a couple days ago, and OS X reported that my Time Machine Drive had some damage and that I could view files, but not copy anything to the drive. After verifying with disk utility, I learned that the drive has an Invalid Node structure, meaning I have to reformat the drive. But here's where the problem comes in: Before I can reformat, I need to backup all the information on the drive. Time Machine uses symbolic links, so I can't just copy with the finder. I can't use Disk Utility's restore feature to copy everything on the drive to another drive, since that will also copy the damage (I know, I tried it...). I tried using the cp -R command in terminal, which I think will not copy the hard links properly, but it started giving me permission errors.
So, does anybody have any suggestions on how to transfer my Time Machine Backups to another drive? Any help would be greatly appreciated!

A: I would suggest using rsync, which will sync all files and folders from a particular directory to another and skip over files it can't transfer because of damage. Use the following command to copy the entire root directory of your current Time Machine drive to a new drive:
sudo rsync -avxr --progress /Volumes/BadDrive/ /Volumes/GoodDrive
Due to the damage, you probably won't be able to continue using the new drive as a backup drive. It's likely that rsync will skip over some damaged files, causing OS X not to recognize it.
Another option would be to attempt to use Drive Genius to repair the existing drive. However, this probably won't work with an invalid node structure.
You could also use SuperDuper! to copy the existing files over to the new drive. However, you may run into the same problem as rsync in that it may not preserve the Time Machine file structure.
Good luck.


text:
Q: Invoke Groovy script using Groovy UI button I'm currently building a UI with Groovy Swing builder and I want to call another script on button click.
My code:
panel(alignmentX:0f) {
    flowLayout(alignment:FL.LEFT)
    button('Import KM', actionPerformed: {
    vars.dialogResult = 'Import KM'
    gshell.evaluate(new File("ImportKnowledgeModules.groovy"))
})

The new script is also in the same directory as the calling script. But nothing happens when I click the button 'Import KM'.
What am I missing here?

A: Take in account that the second script path must be relative to the path where you runs groovy command not to the path of your UI groovy script.
Example: I take the original code from http://groovy-lang.org/swing.html and I save it as swing.groovy, then I change the click me button to call swing.groovy itself using groovy.lang.GroovyShell.evaluate(java.io.File) as you do. So finally I have the follow code in swing.groovy:
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
import groovy.lang.GroovyShell

count = 0
new SwingBuilder().edt {
  frame(title: 'Frame', size: [300, 300], show: true) {
    borderLayout()
    textlabel = label(text: 'Click the button!', constraints: BL.NORTH)
    button(text:'Click Me',
         actionPerformed: {
             println "click :P"
             new GroovyShell().evaluate(new File('swing.groovy'))
         }, constraints:BL.SOUTH)
  }
}

If I run groovy swing.groovy the button evaluates correctly the script and the UI appears recursively. However if I run groovy from another path like groovy ./Scripts/swing.groovy then I have to change the path to new GroovyShell().evaluate(new File('./Scripts/swing.groovy')) from my code in order to reference it correctly.
Hope it helps,


text:
Q: Evaluate $\int_0^2\int_{y/2}^1{\frac{y^2}{1+x^4}}\,dx\,dy$ So I simplified it to $\int_0^2\int_{y/2}^1{\frac{1}{1+x^4}y^2}\,dx\,dy$
Then integrated, and got $\int_0^2(\frac{\ln(1+x^4)}{4x^3}y^2)_{y/2}^1\,dy$
Then I got: $\int_0^2((\frac{\ln(1)}{4}y^2)-(\frac{\ln(1+(\frac{y}{2})^4)}{4(y/2)^3}y^2))\,dy$
And then I figured, I must be going wrong somewhere....
I think it was in my ingration... Please someone help me!
Thanks,
Sam

A: By setting $y=2t$ then switching the order of integration we have:
$$ I = 8\int_{0}^{1}\int_{t}^{1}\frac{t^2}{1+x^4}\,dx\,dt=8\int_{0}^{1}\int_{0}^{x}\frac{t^2}{1+x^4}\,dt\,dx $$
from which:
$$ I = \frac{8}{3}\int_{0}^{1}\frac{x^3}{1+x^4}\,dx = \frac{2}{3}\left.\log(1+x^4)\right|_{0}^{1}=\color{red}{\frac{\log 4}{3}}.$$

A: You can solve this by changing the order of integration.
We have our area of integration:
$$ \Omega = \left\{ \frac{y}{2} \lt x \lt 1, 0  < y < 2\right\}$$
If you draw this out on a piece of paper, you have a shaded triangle under the line $ y = x/2$. You can see if you re-write this area in terms of x and y the original $\Omega$ is equivalent to:
$$ \Omega = \{ 0<x<1, 0<y<2x\}$$
This changes our integral bounds to:
$$\int_{0}^{1}\int_{0}^{2x}\frac{y^{2}}{1+x^4}\,dy\,dx$$
$$=\frac{8}{3}\int_{0}^{1}\frac{x^3}{1+x^4}dx$$
Which then evaluates to $\dfrac{2\log(2)}{3}$


text:
Q: C# .net chart control catching error when unsuitable series is used I have populated a combobox with a SeriesChartType list.  This allows the user to select which chart type the want to see.  This works well.
However, when there is more than one series, or if there are a different number of datapoints some chart types throw an exception.

eg. System.InvalidOperationException: 'Renko chart type - Cannot
  combine this chart type with any other charts.'

The hard part is that I cannot seem to catch the exception.  It gets thrown when i try to update the chart so I tried the following:
        try
        {
            Series1.ChartType = (SeriesChartType)Cmb_Select_Chart.SelectedItem;
            Chart.Update();
        }
        catch
        {
            foreach(Series x in Chart.Series)
            {
                x.ChartType = SeriesChartType.Line;
                MessageBox.Show("Error generating chart. Default to line.");
            }
        }

However, the try/catch doesn't work, it just throws the exception anyway. -Throws on Chart.update()
I would like to know how to catch or even just check for the error.
It would be nice to not have to chop and change the combobox list.
Can anyone shed any light on why this exception is not being caught in the try/catch block?
Thanks.
also attached below is what is hopefully the stack trace(still new never used it before)
    System.Windows.Forms.DataVisualization.dll!System.Windows.Forms.DataVisualization.Charting.Chart.OnPaint(System.Windows.Forms.PaintEventArgs e) Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.Control.PaintWithErrorHandling(System.Windows.Forms.PaintEventArgs e, short layer)    Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.Control.WmPaint(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
    System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
    [Native to Managed Transition]      Annotated Frame
    [Managed to Native Transition]      Annotated Frame
    System.Windows.Forms.dll!System.Windows.Forms.Control.Update()  Unknown No symbols loaded.

Labassist.exe!Labassist.Frm_Charts.Populate_Chart() Line 404    C#  Symbols loaded.
      Labassist.exe!Labassist.Frm_Charts.Cmb_Select_Chart_SelectedIndexChanged(object sender, System.EventArgs e) Line 435    C#  Symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.OnSelectedIndexChanged(System.EventArgs e)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.WmReflectCommand(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.WndProc(ref System.Windows.Forms.Message m)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
      [Native to Managed Transition]      Annotated Frame
      [Managed to Native Transition]      Annotated Frame
      System.Windows.Forms.dll!System.Windows.Forms.Control.SendMessage(int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ReflectMessageInternal(System.IntPtr hWnd, ref System.Windows.Forms.Message m)    Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.WmCommand(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ScrollableControl.WndProc(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Form.WndProc(ref System.Windows.Forms.Message m)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
      [Native to Managed Transition]      Annotated Frame
      [Managed to Native Transition]      Annotated Frame
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DefWndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.DefWndProc(ref System.Windows.Forms.Message m)    Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.WmCommand(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.WndProc(ref System.Windows.Forms.Message m)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
      [Native to Managed Transition]      Annotated Frame
      [Managed to Native Transition]      Annotated Frame
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DefWndProc(ref System.Windows.Forms.Message m)   Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.DefChildWndProc(ref System.Windows.Forms.Message m)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.ChildWndProc(ref System.Windows.Forms.Message m) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.ComboBox.ComboBoxChildNativeWindow.WndProc(ref System.Windows.Forms.Message m)    Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)  Unknown No symbols loaded.
      [Native to Managed Transition]      Annotated Frame
      [Managed to Native Transition]      Annotated Frame
      System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(System.IntPtr dwComponentID, int reason, int pvLoopData)  Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason, System.Windows.Forms.ApplicationContext context)    Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) Unknown No symbols loaded.
      System.Windows.Forms.dll!System.Windows.Forms.Application.Run(System.Windows.Forms.Form mainForm)   Unknown No symbols loaded.
      Labassist.exe!Labassist.Program.Main() Line 20  C#  Symbols loaded.

Thanks


text:
Q: shared_ptr compiler error invalid conversion I have a class called State which has a shared_ptr, weak_ptr and a int as its fields. I also have another class called Automata which has a shared_ptr to a state. I am using State to mimic a state in NFA. The Automata is a linked list of states in an NFA. And states are linked with shared_ptr, self loop is indicated by weak_ptr.
class State {
    public:
        // ptr to next state
        std::shared_ptr<State> nextState;
        // ptr to self
        std::weak_ptr<State> selfLoop;
        // char
        int regex;
       // Constructor
       State(const int c) : regex(c){}
       // Destructor
       ~State();
};
#define START 256

#define FINAL 257

class Automata {
    private:
       std::shared_ptr<State> start;
    public:
       // Constructor, string should not be empty
       Automata(const std::string &str);
      // Destructor
      ~Automata();
      // Determine a string matched regex
      bool match(const std::string &str);
};

The constructor of Automata basically takes in a regex and convert it into an NFA.(It works! See this if you are interested: https://swtch.com/~rsc/regexp/regexp1.html)
The compiler error happens when compiling Automata's constructor. It is implemented as follows
Automata::Automata(const string &str) {
    start = make_shared<State>(new State(START)); // Error is here, START defined above
    for (loop traversing str) {
        //add more states to start
    }
}

I got an error that states
// A lot gibbrish above
Automata.cc:7:45:   required from here
/usr/include/c++/4.8/ext/new_allocator.h:120:4: error: invalid conversion
from 'State*' to 'int' [-fpermissive]
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^
 In file included from Automata.h:4:0,
                  from Automata.cc:2:
 State.h:18:2: error:   initializing argument 1 of 'State::State(int)' [-fpermissive]
 State(const int c);
 ^

Not sure what I did wrong. I am totally new to shared_ptr, so I have no idea if it's the problem of make_shared or error with State constructor? Can you help me fix this?

A: Didn't you want to write:
Automata::Automata(const string &str) {
    start = make_shared<State>(START); // make_shared will call new internally
    for (loop traversing str) {
        //add more states to start
    }
}

?


text:
Q: javascript onclick apostrophe quotation mark issue Ok, I'm getting some data from an ajax call and need to store the value as a parameter to an onclick element via javascript.
Eg
output = " delete File ";

This behaves strangely. When I inspect the element with chrome, the output looks like this
 delete File

It should obviously look like this

The parameter is a String so I need the quotes around it. This may not be the best way to do this, but why is it making the first two quotes double quotes and then the last two single quotes?
*This is a JSP server using ajax calls to gather information. The function "deleteFileName(fileNameIn)" is an ajax call. (I don't believe this is necessary information but you never know)

A: You can not use the same kinds of quotes for the value of onclick and for the function call. You need single quotes for one and double quotes for the other (where to put which should not matter). Otherwise you are closing the onclick attribute with the first single quote of the function call.
Example:
output = " delete File ";

A: Rather than inspecting the information, I suggest that you wget or curl the page directly (or use the browser's view-source function).  These days I've found that many browsers present information subtly incorrectly in the inspector in their attempt to format everything nicely.
Removing the browser from the equation is a good first step, since that will show you exactly where the problem is occuring.


text:
Q: struts2 - how to efficiently accept a file uploaded in chunks, and maintain the chunk order A C# code is transmitting a large image file, breaking it into chunks, and it also sends the chunk order as a request parameter in each request. I wish to receive the file in a Struts2 action. Most examples I see, use Apache Commons File Upload to receive uploaded files, but its assumed that the files are transferred using <http type="file"/> as a multipart request. Even the streaming API assumes that.
Currently, I am thinking of storing each request's chunk in an array at the index received from the chunk orderNumber parameter. When all the chunks are received, I will write the file to the system. But it has some problems. I will have to maintain the state of the array across multiple requests, and action classes are stateless. Also, how will I find that the particular chunk is the last ? (I can send a request parameter with the last chunk, but if there's any other cleaner way)
Edit - image types can differ, the EOF marker is always a constant query string parameter, the image is always broken into constant-sized chunks (the buffer is 1024 bytes, can be changed) except the last one. The C# program can be altered. The user using the C# code would be already signed in, and there can be concurrent transfer of different files. After-crash-resume is not required.
Actually, the C# program is just a Silverlight plugin that is there to facilitate drag n  drop of files, and send them to the server (only for IE, as IE doesn't support drag n drop of files)


text:
Q: Is there any shortcut for removing text style in TeXStudio? I am new to the LaTex and TeXstudio, so I am not completely familiar with all the options and features.
Currently I use Cmd+B or Cmd+I for emphasizing/italicizing. But is there also a shortcut for removing these styles?
As far as I understand, a LaTeX editor doesn't work like Word that repeating the action disables it.
I know I can just undo, but when after many changes I come back to the styled text, the only way to remove it seems to manually delete the command.


text:
Q: No vertical space between Bootstrap form groups There are a few similar questions but none that really provide a solution for my issue (as far as I can see)
Here is my code:

        Quantity:
        <input type="quantity" class="form-control" min="1" max="100" ng-model="formData.quantity" required />

        Type:
        <select class="form-control" name="type" ng-model="formData.type" required>
            <option value="240" selected>240</option>
            <option value="120">120</option>
        </select>

        Type 2:
        <select class="form-control" name="typ2 ng-model="formData.typ2e" required>
            <option value="240" selected>240</option>
            <option value="120">120</option>
        </select>

    Next Section

Between the form groups there is no vertical spacing, it's all joined together one on top of the other. Not sure what to do. Any help would be appreciated!

A: You can wrap all the code with the form-horizontal

your code

Or add to your css file next code:
.form-group::before,
.form-group::after {
   content: " ";
   display: table;
}


text:
Q: Group retrieved records from a RECURSIVE query, that have the same parents, grandparents I have a table with Item(s) than are in a ManyToMany Relationship with Category.
Item
id  |  name
 1     name1
 2     name2
 3     name3

ItemCategory
id | category_id | item_id
  1     4            1
  2     5            1
  3     7            1
  4     8            1

Category (parent_id foreign key to itself)
  id | parent_id | name
   1     Null       A1
   2      1         B1
   3      1         B2
   4      2         C1
   5      3         C2
   6      1         D1
   7      6         DE
   8      1         DT

I'm trying to get the Item Categories, from child to parent, for an Item so I use:
 WITH RECURSIVE descendants(name, id, slug, parent_id, bread_order) AS (
 SELECT  name, id, slug, parent_id, 0
 FROM categories
 where id in (
 SELECT c.id FROM items AS p
 INNER JOIN items_categories AS pc ON p.id=pc.item_id
 INNER JOIN categories AS c ON pc.category_id = c.id
     WHERE p.id = 10
 )
 UNION ALL
 SELECT c2.name, c2.id, c2.slug, c2.parent_id, bread_order+1
 FROM categories AS c2
 INNER JOIN descendants AS d ON c2.id=d.parent_id
) SELECT id, name, parent_id, bread_order FROM descendants
ORDER by bread_order DESC

The problem is that two child Categories can have the same parent, or a parent for one is grand parent for the other.
C1 -> B1 -> A1
C2 ->B1  -> A1
C3 ->B2  -> A1
DE -> D1 -> A1
DT  -> A1

I tried to group them but, because have the same parents, grand_parents is not what I need, I need when I retrieve the information from database to know how to make the path(See above).
Is there any way, like using CASE with the IDs that returns from the subquery ?

A: You can aggregate the path during the query:
WITH RECURSIVE descendants(name, id, parent_id, bread_order, path) AS (
  SELECT  name, id, parent_id, 0, array[id] as path
  FROM categories
  where id in (SELECT c.id
               FROM items AS p
                 JOIN items_categories AS pc ON p.id=pc.item_id
                 JOIN categories AS c ON pc.category_id = c.id
               WHERE p.id = 1)
  UNION ALL

  SELECT c2.name, c2.id, c2.parent_id, bread_order+1, d.path||c2.id
  FROM categories AS c2
    JOIN descendants AS d ON c2.id=d.parent_id
)
SELECT id, name, parent_id, path, bread_order
FROM descendants
ORDER by path


text:
Q: How to use saddle point approximation for integrands with $e^{ix}$ I have an integral to evaluate
$I = \int_m^{\infty} \sqrt{x^2-m^2} \;e^{-ixb} dx$
where m and b is constant with b is very large as per the requirement for saddle point approximation. In saddle point method if we given the integral of the form
$I = \int_a^b g(x) \;e^{f(x)\,t} dx$
where t is a constant and very large, the soluation is
$I \approx g(x_0) \,e^{f(x_0)\,t}\int_a^b  \;e^{\frac{f''(x_0)\,t\,(x-x_0)^2}{2} } dx$
we expanded the function $f(x)$ about its maxima. $x_0$ is the point where $f(x)$ is maximum.
In this problem $f(x) = -ix$ and $ g(x)= \sqrt{x^2-m^2} $. How do I use saddle point method here? Because when $x=m \;,f(x)$ is maximum and then $g(x_0)=0$. If I am wrong please correct me.


text:
Q: row_number() from table or view? CREATE OR REPLACE VIEW public."masterx" AS
 SELECT row_number() OVER (ORDER BY st_distance(t1.geom, t2.geom)) AS rownum,
    t1.id_seq,
    t2.pars_id,
    st_distance(t1.geom, t2.geom) AS mesafe
   FROM kadas t2,v7 t1
  WHERE st_dwithin(t2.geom, t1.geom, 400::double precision) = true
  AND t1.datex > ('now'::text::date - '180 days'::interval);

It creates a view. When I use select from table it gives a result but when I select from the above view there is no result. What is the problem?
table t1 is
id_seq|field a | field b| geom|

table 2 is
id| field x  | field y | geom|

I want to join 2 tables with geom columns (both points).
__
SELECT row_number() OVER (ORDER BY st_distance(t1.geom, t2.geom)) AS rownum,
    t1.id_seq,
    t2.id,
    st_distance(t1.geom, t2.geom) AS distance
   FROM table2 t2,table1 t1
  WHERE st_dwithin(t2.geom, t1.geom, 400::double precision) = true

If I try to select:
where t2.id= 12345

gives result in 1 second.
But when i use
create view as x (
SELECT row_number() OVER (ORDER BY st_distance(t1.geom, t2.geom)) AS rownum,
        t1.id_seq,
        t2.id,
        st_distance(t1.geom, t2.geom) AS distance
       FROM table2 t2,table1 t1
      WHERE st_dwithin(t2.geom, t1.geom, 400::double precision) = true
)

hen try to query on this view there is no result.
What is the problem?
it seems rownumber is problem here but why
__
table 1 v7 has 2 milyon row.
table 2  kadas t2 has 1 milyon row.
select * from masterx.
where  pars_id =422328447

where is no solution.
what i want to do is:
select points in t1 that is in a buffer with t2 points in 400 meters and order them by distance. there is no problem to here but when I try to take row numbers by the distance for limiting the query for 100 first rows it makes db and comp mad and there is no solution**

A: Not sure, but I would simplify the CREATE statement like this:
CREATE OR REPLACE VIEW public.masterx AS
SELECT row_number() OVER (ORDER BY st_distance(t1.geom, t2.geom)) AS rownum,
       t1.id_seq,
       t2.pars_id,
       st_distance(t1.geom, t2.geom) AS mesafe
FROM   v7    t1
JOIN   kadas t2 ON st_dwithin(t1.geom, t2.geom, 400::float8)
WHERE  t1.datex > (now()::date - 180)
ORDER  BY 1;

'now' is a constant, I assume you want the function now() instead. Per documentation:

Tip: You do not want to use the third form ('now') when specifying a DEFAULT
  clause while creating a table. The system will convert now to a
  timestamp as soon as the constant is parsed, so that when the default
  value is needed, the time of the table creation would be used!

You can subtract integer from date.
And you shouldn't rely on the sort order derived from the window function. Add an explicit ORDER BY.
Call:
SELECT * FROM public.masterx

Performance
You have 1 million x 2 million rows. That's 2,000,000,000,000 possible combinations. Your condition  t1.datex > (now()::date - 180) reduces one side somewhat, but a huge number will remain. Appropriate indexes on the geom columns help a lot. That can explain why,
with the condition
where t2.id = 12345

.. it only takes 1 second. You have reduced the operation by a factor of 1 million. Without that condition it takes ~ 1 million times as long ...


text:
Q: Remove classic start menu with GPO? We are running Windows Server 2008 Standard Edition, with Windows XP Professional on our workstations.
I have created a few Organisational Units and put various levels of user in each. I have also created a GPO that I have link to each of the OU's. Everything is working exactly as it should with one exception: all users now have the classic start menu rather than the standard one. Even brand new users that are created.
I have checked that the "Force classic start menu" option is disabled, and also that the Start Menu preference hasn't had any start menu's added to it.
I did a quick search which turned up this link:
http://social.technet.microsoft.com/Forums/en-US/winserverGP/thread/fa1f33eb-0116-48a7-a4c3-114b6096d599

If I follow the guide and create a registry entry in the GPO to update the value, the start menu switches to a single column with a solid black line on the left the full height of the menu. It also adds My Computer back to the desktop which has been removed by the GPO. As soon as I delete the new registry update the start menu goes back to the classic two column menu.
When no one is logged in, the login screen appears in the standard theme - as soon as you login the theme is removed and the classic styles shows.
Any ideas?
Thanks,
Danny

A: You missing the default profile, or it's corrupt/incorrect.
MS has directions for one way to do it (there plenty of other ways too). Note that Server 2008/R2 and Vista/7 Profiles are different than 2K/XP/2003 Profiles and they are incompatible. If you need to setup your environment for both, let me know, it makes thing more complicated.
It seems like you're pretty new to this stuff, you might want to think about picking up a book.


text:
Q: eclipse checkstyle error cannot initialize module TreeWalker - TreeWalker is not allowed as a parent of RegexpHeader I am using checkstyle version 5.6.1 .I get this error when I try to use a user defined check style template :
cannot initialize module TreeWalker - TreeWalker is not allowed as a parent of RegexpHeader

A: Probably your configuration is similar to the following one:
<module name="Checker">
  <module name="TreeWalker">
    <module name="RegexpHeader">
      ...
    </module>
  </module>
</module>

You need to change it to:
<module name="Checker">
  <module name="RegexpHeader">
    ...
  </module>
  <module name="TreeWalker">
    ...
  </module>
</module>

because TreeWalker is not allowed as a parent of RegexpHeader.


text:
Q: How to post a data using Plain Javascript fetch on Laravel? I made this method on my javascript to post data into my database:
if(document.getElementById('approve_leave_request')){
    document.getElementById('approve_leave_request').addEventListener('click', ()=>{
        const urlReq = window.location.origin+"/leave/customize";
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        const leave = {
            status: 'Approved',
        };

        const request = new Request(urlReq, {
            method: 'POST',
            body: JSON.stringify(leave),
            headers: new Headers({
                'Content-Type': 'application/json',
                "X-CSRF-TOKEN": token
            })
        });

        fetch(request).then(res => res.json()).then(res => console.log(res));

    })
}

and this is my controller function:
public function customize_update(Request $request){
    return response()->json(['message'=>'Called successfully.']);
}

and on my api:
Route::post('leave/customize', 'LeaveController@customize_update')->name('api.leave.customize');

but during execution i am getting this error:
POST http://127.0.0.1:8000/leave/customize 405 (Method Not Allowed)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0


text:
Q: (Re)define a command in qutebrowser Qutebrowser has a command :close to close the current window and a command :quit, which can be shortened to :q, to quit Qutebrowser, thus closing all windows.
Since I'm used to vim and to vim's tabs, I often enter :q, accidentally confusing it with :close, thus having all windows closed at once.
What I'd like to do, is to make :q behave as :close and maybe define a :qa command which behave as the actual :quit command.
Is it possible to do this?

A: Yes, you can type in normal mode :set aliases
and then change or add aliases as you wish.
In your case you replace the command quit by close and add "qa": "quit".
B.t.w. for getting the best and fastest answers regarding the qutest browser, check out the possibilities to get help on https://www.qutebrowser.org.


text:
Q: Exibir dados numa tela de pesquisa C# ASP.NET Trazer informações para a View()
Pessoal, boa tarde.
Estou com a seguinte dificuldade: Tenho uma tela de pesquisa de um helpDesk e preciso exibir os dados do banco, que é uma lista de chamados, porém nessa mesma tela eu tenho alguns inputs que serão usados para pesquisar no banco e retornar essa mesma listagem, dentre eles alguns <selects/> como, Categoria, Status e NivelPrioridade que na minha ideia eu desejo preencher com dados do próprio banco, já que cada um é uma tabela. Consegui trazer os dados para os inputs através de uma ViewModel, porém não consigo listar os chamados a partir da ViewModel, nem criar uma ViewBag com a lista retornada do banco para fazer essa listagem e aparentemente nem trazer mais de um dado como parametro pela View().
Então minha duvida seria:

*

*Como passar mais de um parametro pra view ou

*Como listar os meus chamados e ao mesmo tempo preencher os selects com a própria viewModel

Eu não sei se estou sendo claro o suficiente, peço desculpas desde já, está confuso pra mim também.
Segue o código para exemplificar:
//Codigo referente a minha View
@model AppHelpDesk.Models.ViewModels.ChamadoViewModel

@{
   }

        <input asp-for="Chamado.Id" value="" placeholder="Id do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Titulo

        <input asp-for="Chamado.Titulo" value="" placeholder="Titulo do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Data Inicial

        <input asp-for="Chamado.DataInicial" class="form-control" type="date" value="" id="example-date-input">

            Data Final

        <input asp-for="Chamado.DataFinal" class="form-control" type="date" value="" id="example-date-input">

            Categoria

        <select asp-for="Chamado.CategoriaId"
                asp-items="@(new SelectList(Model.Categoria, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Status

        <select asp-for="Chamado.StatusId"
                 asp-items="@(new SelectList(Model.Status, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Prioridade

        <select asp-for="Chamado.NivelPrioridadeId"
                asp-items="@(new SelectList(Model.NivelPrioridade, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

        <button type="submit" class="btn btn-primary">Pesquisar</button>

        Chamados pendentes

   @*

                    @Html.DisplayNameFor(model => model.Titulo)

                    @Html.DisplayNameFor(model => model.Descricao)

                    @Html.DisplayNameFor(model => model.DataInicial)

                    @Html.DisplayNameFor(model => model.DataFinal)

            @foreach (var i in Model)
            {
                if (i.StatusId == 1)
                {

                        @Html.DisplayFor(modelItem => i.Titulo)
                        @Html.DisplayFor(modelItem => i.Descricao)
                        @Html.DisplayFor(modelItem => i.DataInicial)
                        @Html.DisplayFor(modelItem => i.DataFinal)

                }

            }

*@

...
// Codigo da minha controller
namespace AppHelpDesk.Controllers
{
    public class HomeController : Controller
    {
        private readonly DashboardService _dashboardService;

        public HomeController (DashboardService dashboardService)
        {
            this._dashboardService = dashboardService;
        }

        // GET: Dashboard
        public IActionResult Index()
        {
            var list = _dashboardService.FindAll();
            ViewBag.pedingCount = list.Where(x => x.StatusId == 1).Count();
            ViewBag.SolvedCount = list.Where(x => x.StatusId == 2).Count();
            ViewBag.priorityCount = list.Where(x => x.NivelPrioridadeId == 3).Count();
            return View();
        }

        public IActionResult Create(Chamado chamado)
        {
            _dashboardService.Insert(chamado);
            return RedirectToAction(nameof(Index));
        }

        public IActionResult Pending(Chamado chamado)
        {
            var status = _dashboardService.FindAllStatus();
            var prioridade = _dashboardService.FindAllPrioridade();
            var categoria = _dashboardService.FindAllCategoria();
            var setor = _dashboardService.FindAllSetor();

            var viewModel = new ChamadoViewModel
            {
                Categoria = categoria,
                Chamado = chamado,
                NivelPrioridade = prioridade,
                Setor = setor,
                Status = status
            };

            ViewBag.listaChamados = _dashboardService.FindAll();
            return View(viewModel);
        }

        public IActionResult Solved()
        {
            var list = _dashboardService.FindAll();
            return View(list);
        }

        public IActionResult Priority()
        {
            var list = _dashboardService.FindAll();
            return View(list);
        }
    }
}

// Codigo da minha ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppHelpDesk.Models.ViewModels
{
    public class ChamadoViewModel
    {
        public Chamado Chamado { get; set; }
        public ICollection<Categoria> Categoria { get; set; }
        public ICollection<Status> Status { get; set; }
        public ICollection<Setor> Setor { get; set; }
        public ICollection<NivelPrioridade> NivelPrioridade { get; set; }
    }
}

A: Como passar mais de um parâmetro pra View
R: Não é possível passar mais de 1 parâmetro para o método View é justamente por isso que utilizamos as ViewModels para Isso.
Como listar os meus chamados e ao mesmo tempo preencher os Selects com a própria ViewModel
R: Basicamente sua ViewModel vai possuir Um pouco mais de Responsabilidade que ela possui hoje. Pelo oque eu entendi você quer fazer um filtro e listar os registro filtrados, basicamente isso vai ficar assim.
Controller
public IActionResult Pending(ChamadoViewModel viewModel)
{
    return View(viewModel.Get());
}

View Model
public class ChamadoViewModel
{
    #region Dependency Injection

    private readonly IRepository _repository;

    public ChamadoViewModel(IRepository repository)
    {
        _repository = repository;
    }

    #endregion

    #region Handlers

    public ChamadoViewModel Get()
    {
        var query = _repository.FindAllChamados()
                                .AsQueryable();

        Categorias = _repository.FindAllCategorias();
        Status = _repository.FindAllStatus();
        Setores = _repository.FindAllSetores();
        NivelPrioridades = _repository.FindAllPrioridades();

        if (Id != null)
            query = query.Where(x => x.Id == Id);
        if (string.IsNullOrEmpty(Titulo))
            query = query.Where(x => x.Titulo == Titulo);
        if (DataInicial != null && DataFinal != null)
            query = query.Where(x => x.DataInicial >= DataInicial && x.DataFinal <= DataFinal);
        if (CategoriaId != null)
            query = query.Where(x => x.CategoriaId == CategoriaId);
        if (StatusId != null)
            query = query.Where(x => x.StatusId == StatusId);
        if (SetorId != null)
            query = query.Where(x => x.SetorId == SetorId);
        if (NivelPrioridadeId != null)
            query = query.Where(x => x.NivelPrioridadeId == NivelPrioridadeId);

        Chamados = query.ToList();
        return this;
    }

    #endregion

    #region Data

    public Chamado Chamado { get; set; }
    public ICollection<Chamado> Chamados { get; set; }
    public ICollection<Categoria> Categorias { get; set; }
    public ICollection<Status> Status { get; set; }
    public ICollection<Setor> Setores { get; set; }
    public ICollection<NivelPrioridade> NivelPrioridades { get; set; }

    #endregion

    #region Helper

    // Essa é a região de Filtro é nessas propriedades que serão feito os Binds ou Asp-For

    public int? Id { get; set; }
    public int? CategoriaId { get; set; }
    public int? StatusId { get; set; }
    public int? SetorId { get; set; }
    public int? NivelPrioridadeId { get; set; }
    public string Titulo { get; set; }
    public DateTime? DataInicial { get; set; }
    public DateTime? DataFinal { get; set; }

    #endregion
}

View
@model AspNetCore.Controllers.ChamadoViewModel

@{
}

        <input asp-for="Id" value="" placeholder="Id do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Titulo

        <input asp-for="Titulo" value="" placeholder="Titulo do chamado" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

            Data Inicial

        <input asp-for="DataInicial" class="form-control" type="date" value="" id="example-date-input">

            Data Final

        <input asp-for="DataFinal" class="form-control" type="date" value="" id="example-date-input">

            Categoria

        <select asp-for="CategoriaId"
                asp-items="@(new SelectList(Model.Categorias, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Status

        <select asp-for="StatusId"
                asp-items="@(new SelectList(Model.Status, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

            Prioridade

        <select asp-for="NivelPrioridadeId"
                asp-items="@(new SelectList(Model.NivelPrioridades, "Id", "Nome"))"
                class="custom-select" id="inputGroupSelect01">
        </select>

        <button type="submit" class="btn btn-primary">Pesquisar</button>

        Chamados pendentes

                        @Html.DisplayNameFor(model => model.Chamado.Titulo)

                        @Html.DisplayNameFor(model => model.Chamado.Descricao)

                        @Html.DisplayNameFor(model => model.Chamado.DataInicial)

                        @Html.DisplayNameFor(model => model.Chamado.DataFinal)

                @foreach (var i in Model.Chamados)
                {
                    if (Model.StatusId == 1)
                    {

                            @Html.DisplayFor(modelItem => i.Titulo)
                            @Html.DisplayFor(modelItem => i.Descricao)
                            @Html.DisplayFor(modelItem => i.DataInicial)
                            @Html.DisplayFor(modelItem => i.DataFinal)

                    }
                }

Espero que isso esclareça todas as suas duvidas, e se ficar alguma em aberto fico a disposição para tentar esclarecê-la.


text:
Q: How to parse XML values in actionscript 3? How to parse XML element using flex 4 and actionscript 3?
If my input like this
<name><first>Bill</first><last>Gates</last></name>

And I want t get output like this
<name>
  <first>Bill</first>
  <last>Gates</last>
</name>

for a button click.And I have to set ignoreWhitespace and prettyPrinting properties are false. I don't have any idea about it. But I have to do it. Please share your ideas?

A: var xml:XMLDocument = new XMLDocument('<name><first>Bill</first><last>Gates</last></name>');
xml.ignoreWhite = false;

trace(xml);
// output - <name><first>Bill</first><last>Gates</last></name>

trace(XML(xml));
// output
//<name>
//  <first>Bill</first>
//  <last>Gates</last>
//</name>

If there is a document that does not have a structure for creating structures that can convert it into XML


text:
Q: Navigate limitTo batches in Angular ngRepeat I have an ngRepeat with a limitTo in my HTML. This will show the first x number of users - essentially paginating the table. I now need to be able to show the next batch of x users. I've added a couple of anchors to go to previous or next page (with functions attached to the click)
I'm now not sure how to manipulate the ngRepeat through these functions to actually show the correct batch of users.
HTML

  {{user.name}}
  {{user.email}}

left

right

JS
$scope.users = //full users object here

$scope.paginate = {};
$scope.paginate.size = 10;

$scope.prevPage = function(){
  //load the previous 10 users
}

$scope.nextPage = function(){
  //load the next 10 users
}

A: You should add another filter (or simply a custom filter) such as

  {{user.name}}
  {{user.email}}

and then in the scope
$scope.users = //full users object here

$scope.paginate = {};
$scope.paginate.size = 10;
$scope.paginate.start = 0;

$scope.prevPage = function(){
  //load the previous 10 users
    if ($scope.paginate.start) {
        $scope.paginate.start -= $scope.paginate.size;
    }
}

$scope.nextPage = function(){
  //load the next 10 users
    $scope.paginate.start += $scope.paginate.size;
}

$scope.getList = function (user, index) {
    return (index >= $scope.paginate.start && index < $scope.paginate.start + $scope.paginate.size);
};


text:
Q: AS3 - Simple text scramble encode/decoder? I am working on the saving/loading functionality of my AS3 game. I plan to let the player save their game to their hard drive from a browser-run game. I want to scramble the text I'm saving so a human can't really read it if they open the file as text.
What is a good method to scramble text before saving, and then unscramble after opening?
I know in Java it's possible to take a char and add or subtract from it to change the char, which was an extremely simple method. What can be done simply in ActionScript 3?
Keep in mind, I'm looking for simple and easy rather than secure. All of the cryptography sites I've checked for solution are more complicated than I can understand at this point, and are focused on making the most secure encryption rather than on easy integration.

A: It is possible to do something similar to what you did in java.
Try:
var offset:int = 10;
for (i = 0; i < string.length; i++) {

string[i] = string.charCodeAt(i) + offset;

}

Where string is the text you want to change, what this does is gets the numeric unicode value of the character at each index of the string and modifies it's value by offset.
To decode you run the same code but in reverse:
for (i = 0; i < string.length; i++) {

string[i] = string.charCodeAt(i) - offset;

}

A: It may be getting a bit of the original topic with the fileReference.save() but I got here searching for this. Actually it couldn't be simpler:
var file:FileReference=new FileReference();
file.save(byteArrayData,"name you want to suggest to the user");

One thing to watch: You can only initiate inside a handler of the mouseEvent (CLICK).
So the user has to request the write.
If you try to do it automtically it will work locally, but once you put it online, it won't!
Seems to be a relatively new badly documented security feature.
So if you had trouble making it work lately, it's probably that.
Here is a working online example, where you can save a PNG with a buttonpush:
http://www.snoep.at/misc/youtube/cloud_generator/
For this to work AT ALL your user need a fairly recent version of flashplayer (I think 10.1 and up), so if it doesn't work you might try an update.

A: Why not just reverse the text? That is a simple yet effective way.
Another would be to break the text in groups of 2 characters each, and reverse them, and then join the string again.

A: rot13 would be nice and simple for this. I'm sure there are a few AS3 tutorials or libraries out there. Another common option is base64, also with existing libraries.

A: If you really wanna do this, why not use a established cryptography Cipher?
Get as3crypto from here http://code.google.com/p/as3crypto/downloads/detail?name=Crypto.zip&can=2&q=
Then here's how to use RC4 (one of the many ciphers you can use):
import com.hurlant.util.Hex;
import flash.utils.ByteArray;
import com.hurlant.crypto.prng.ARC4;

var key:ByteArray = Hex.toArray("SUPER SECRET PASSWORD THAT YOUR USER WILL FIND OUT IF HE DECOMPILES YOUR SWF ANYWAY");
var pt:ByteArray = Hex.toArray("THIS IS THE ACTUAL FILE YOU'RE ENCRYPTING OR DECRYPTING");
var rc4:ARC4 = new ARC4(key);
rc4.encrypt(pt);
var out : String = Hex.fromArray(pt);
// save out to file

// load loadedFile from file
pt = Hex.toArray(loadedFile);
rc4.init(key);
rc4.decrypt(pt);
out = Hex.fromArray(pt);
// parse out's information

This might seem a little overkill but it actually is easier to use than to make your own encryption/decryption thing, and it has been tested and used a bunch of times.

A: I don't know how you save the game, but if you use Local Shared Objects, your text is saved as binary data (while variable names remain human readable).


text:
Q: Work-Energy Theorem Problem? I found my problem on Yahoo Answers:
here.
I do not understand where $$-\Delta U =\Delta K $$ comes from. In class, we learned that
$$W_\textrm{net}=\Delta(K)$$
But we didn't see any of what the guy uses in his answer. Could someone provide an answer using the work-energy theorem, please ?

A: Work done $w$ is given (in one-dimension) by
$$w = \int_{\mathbf x_1}^{\mathbf x_2} ~\mathbf F\cdot \mathrm d\mathbf x\tag I$$
When the force is conservative, it can be expressed by scalar potential energy function $U(\mathbf x)$ viz.
$$ \begin{align}F &= - \frac{\mathrm d}{\mathrm dx}~U\\ \implies U(\mathbf x) &= -\int_{\mathbf x_0}^{\mathbf x} \mathbf F\cdot \mathrm d\mathbf x + U(\mathbf x_0) \,, \tag{II}\end{align}$$ where $U(\mathbf x_0)$ is an arbitrary constant.
Now, as OP said
$$\Delta ~\textrm{KE} = K_2 - K_1 =\int_{\mathbf x_1}^{\mathbf x_2} ~\mathbf F\cdot \mathrm d\mathbf x $$
This can be re-written as
$$\begin{align}K_2 + \left[-\int_{\mathbf x_0}^{\mathbf x_2} ~\mathbf F\cdot \mathrm d\mathbf x\right] & = K_1 +\left[-\int_{\mathbf x_0}^{\mathbf x_1} ~\mathbf F\cdot \mathrm d\mathbf x\right]\\\implies~~
K_2 + \left[U(\mathbf x_2)-U(\mathbf x_0)\right] & = K_1 +\left[U(\mathbf x_1)-U(\mathbf x_0)\right]\\
\implies~~~~~~~~~~~~~~~~~~~~~~~~~  K_2 - K_1 & = -~U(\mathbf x_2) + U(\mathbf x_1)\\ \implies~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \Delta ~\textrm{KE} &  =-~\Delta ~U\,.\tag{III} \end{align} $$

A: Your confusion is due to the fact that you have not defined the system under consideration.
If you choose the two masses as the system then the gravitational force is an external force which does work on the system equal to $mgh$ and this work increases the kinetic energy of the system.
If you choose the two masses and the Earth as the system then you have a decrease in the gravitational potential energy of the system equal to $mgh$ and this work increases the kinetic energy of the masses.
Note here that one should really include the kinetic energy gained by the Earth but because the mass of the Earth is so much greater than that of the masses it is almost always not included.
If you are not sure about this point remember that when a mass falls down due the gravitational attraction of the Earth on the mass the Earth is also fall "up" due to the equal magnitude force on the Earth due to the gravitational attraction of the Earth.
A very important thing to remember about gravitational potential energy is that a system which comprises of just one mass cannot have any potential energy.
Again this point is usually ignored because the Earth is so large and so a statement that a mass has gravitational potential energy is used for convenience although it can lead to confusion like in this case.


text:
Q: Symfony2 customize form choice labels I want my choice labels rendered unescaped
here my FormType code:
$builder
    ->add('banner', new BannerType())
    ->add('runtime', 'entity', array(
        'class' => 'AdvertisingBundle:Runtime',
        'expanded' => true,
        'property' => 'label'
    ))

here the label property:
public function getLabel()
{
    return "
".$this->description.
    "

".$this->hint."
";
}

I want the label rendered raw, which form_theme fragment I need to override?

A: here my solution:

            {% for option in form.runtime %}

                        {{ form_widget(option) }}

                    {{ option.vars.label |raw}}

            {% endfor %}


text:
Q: How to set a JComboBox's selected item from my JTable? i'm having trouble trying to set values on a JComboBox while i click the row on my JTable.
The Problem is: the code seems pretty correct to me, but still, it doesn't set any value to the JComboBox.
Here's what i'm using to try it:
    String s = Table.getValueAt(Table.getSelectedRow(),1).toString();

    Object a = s;

    ComboBox.setSelectedItem(a);

But first, allow me to give you some detail about the code:
I'm using MySQL as database to store the values, and filling the JTable from objects that i get from the database, that's why i have set the JComboBox to use < Object > as parameter.
That's it guys, thanks in advance. Looking forward to solve this.

A: No! this is not correct because TableModel::getValueAt return an Object and not a String, so you should to get the value like this :
Object obj = table.getValueAt(table.getSelectedRow(), 1);
comboBox.setSelectedItem(obj);

If the valueAt cell (table.getSelectedRow(), 1) is of a String type then you can cast it like this :
String str = (String) obj;


text:
Q: javascript async await not waiting Here are the functions I have.
async function check_saved_url() {
  $.get("https://ipinfo.io/json", function (response) {
    current_ip = response.ip;
    location_here = response.country;

    var ajax_get_url_prefix = base_url + 'getDomain.php?ip=';
    var key_ip = current_ip + '@@@' + domain_permanent;
    var url = ajax_get_url_prefix + key_ip;

    $.get(url, function(data, status) {
      console.log("Data: " + data + "\nStatus: " + status);
      if (data.includes('0 results')) {
        return 'unknown';
      } else {
        return data;
      }
    });
  }, "jsonp");
}

const func1 = async() => {
  return await check_saved_url();
}

const func2 = async() => {
  let domain_preference = '';
  domain_preference = await func1();
  console.log("domain_preference: ",domain_preference);
}
func2();

This method is from this answer.
As you can see, there are two jquery ajax to get data from server.
The problem is, the func1 and func2 never waits until check_saved_url returns value.
This is what I see in console.

The top red line is the output of func2, which must wait until check_saved_url runs, whose result is the following 2 circles.
I am not sure why this persists to happen and hours of copying answers from everywhere didn't help me.

A: You probably need to develop your understanding of promises and how async JavaScript works a little.
If you have to use jQuery, you could promisify the jQuery $.ajax  method (which appears to use a very old version of the promise API?), and then use that with modern JS constructs like async/await.

const pGet = (url, dataType = 'jsonp') =>
  new Promise((success, error) => $.ajax({url, dataType, success, error}))

const IP_URL = 'https://ipinfo.io/json'
const PREFERENCE_URL_PREFIX = 'https://www.example.com/getDomain.php?ip='

const go = async () => {
  try {
    const { ip } = await pGet(IP_URL)
    const preference = await pGet(`${PREFERENCE_URL_PREFIX}${ip}`)
    //do something with the preference
  } catch(err) {
    // handle errors
  }
}

go()
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you don't have to use jQuery, I'd avoid it and use the fetch API provided by modern host environments.

const IP_URL = 'https://ipinfo.io/json'
const PREFERENCE_URL_PREFIX = 'https://www.example.com/getDomain.php?ip='

const go = async () => {
  try {
    const { ip } = await (await fetch(IP_URL)).json()
    const preference = await fetch(`${PREFERENCE_URL_PREFIX}${ip}`)
    //do something with the preference
  } catch(err) {
    // handle errors
  }
}

go()
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

A: You need to return a Promise from check_saved_url. Inside of the Promise, you then need to use resolve to replace return. You can also use reject(new Error("error")) if there was an error.
async function check_saved_url() {
  return new Promise((resolve, reject) => {
    $.get("https://ipinfo.io/json", function (response) {
      current_ip = response.ip;
      location_here = response.country;

      var ajax_get_url_prefix = base_url + 'getDomain.php?ip=';
      var key_ip = current_ip + '@@@' + domain_permanent;
      var url = ajax_get_url_prefix + key_ip;

      $.get(url, function(data, status) {
        console.log("Data: " + data + "\nStatus: " + status);
        if (data.includes('0 results')) {
          // Instead of return, use resolve()
          //return 'unknown';
          resolve('unknown');
          // You can also pass an error with `reject(new Error("error"))`
        } else {
          // Instead of return, use resolve()
          //return data;
          resolve(data);
        }
      });
    }, "jsonp");
  });
}

const func1 = async() => {
  return await check_saved_url();
}

const func2 = async() => {
  let domain_preference = '';
  domain_preference = await func1();
  console.log("domain_preference: ",domain_preference);
}
func2();

You can read more about promises on MDN

A: There is no promise returned by check_saved_url nor is $.get returning a promise. You need to wrap it all in a promise
async function check_saved_url() {
    return new Promise((resolve, reject) => {
        $.get("https://ipinfo.io/json", function (response) {
            current_ip = response.ip;
            location_here = response.country;

            var ajax_get_url_prefix = base_url + 'getDomain.php?ip=';
            var key_ip = current_ip + '@@@' + domain_permanent;
            var url = ajax_get_url_prefix + key_ip;

            $.get(url, function(data, status) {
                console.log("Data: " + data + "\nStatus: " + status);
                if (data.includes('0 results')) {
                    resolve('unknown');
                } else {
                    resolve(data);
                }
            })
                .fail(reject);
        }, "jsonp")
            .fail(reject);
    })
}

Clean the code
To have a cleaner and reusable code you can wrap $.get in a Promise
async function async_get(url) {
    return new Promise((resolve, reject) => {
        const jqxhr = $.get(url);
        jqxhr.done(() => resolve({ json: jqxhr.responseJSON, status: jqxhr.status }));
        jqxhr.fail(() => reject(jqxhr));
    })
}

async function check_saved_url() {
    const { json: response } = await async_get("https://ipinfo.io/json");
    current_ip = response.ip;
    location_here = response.country;
    var ajax_get_url_prefix = base_url + 'getDomain.php?ip=';
    var key_ip = current_ip + '@@@' + domain_permanent;
    var url = ajax_get_url_prefix + key_ip;

    const { json: data, status } = await $.get(url);
    console.log("Data: " + data + "\nStatus: " + status);
    return data.includes('0 results') ? 'unknown' : data;
}

A: Your function check_saved_url does not return a promise - this is why await is not working for it.
The solution would be to return a promise in check_saved_url.
Suppose I have a function create_promise which I want to await (this mimics your 'get' request):

function create_promise() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Done!"), 500);
  });
}

const func1 = async() => {
  const result = await create_promise();
  return result + " <- result";
};

func1().then(console.log);

A: I will suggest you to use fetch API check_saved_url(). It return promise. You can read more about it here. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Code will go like this :
async function check_saved_url() {
    let connect = await fetch("https://ipinfo.io/json")
    let response = await connect.json()
    current_ip = response.ip;
    location_here = response.country;

    var ajax_get_url_prefix = base_url + 'getDomain.php?ip=';
    var key_ip = current_ip + '@@@' + domain_permanent;
    var url = ajax_get_url_prefix + key_ip;

    //   $.get(url, function(data, status) {
    //     console.log("Data: " + data + "\nStatus: " + status);
    //     if (data.includes('0 results')) {
    //       return 'unknown';
    //     } else {
    //       return data;
    //     }
    //   });
    // }, "jsonp");
  }


text:
Q: How to add consumerGroup for a topic in kafka using Shopify/sarama golang library? In the sarama library there is an option to initialize NewConsumerGroup but how to hook it hook i t up to NewConumer?

A: NewConsumerGroup creates its own Consumer, so there's nothing for you to hook it to
Source: https://github.com/Shopify/sarama/blob/main/consumer_group.go#L105


text:
Q: return a ajax output I have a question.
How to change the ajax function so that it returns the value of output variable.
function ajax(url, data)
        {
            const http = new XMLHttpRequest();
            http.open('post', url, true);
            http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            http.onload = function()
            {
                if(http.status === 200 || http.status == 0)
                {
                    var output = http.responseText;
                }
            }
            http.send(data);
            // return the value of output
        }

A: For that you can use addEventListener method. It depends on what event you are waiting for. If you are waiting for a click, you need to find an element at first document.querySelector('#some-button').addEventListener('click', myFunction). If it is a custom event, you can add event listener to the document and then dispatch this event on document


text:
Q: css3 and jquery load page slider effect Hi I´m trying to create a full page load slider effect with css3 and jquery. For this I´m using two divs where I load the pages. I have buttons for previous, close and next. I´m having problem with next effect. When I click the next button I load the new page into div 2 at the moment with  translateX ('100%'). Then I add  translateX ('-100%') to div1(at the moment on screen  translateX ('0%')). The effect should be translateX ('-100%') div1, and then translateX('0%') for div2. All translates with a transition of 1.0s.
This is working.
But when I click again the next button the div1 is with translateX('-100%'), (on left, out of screen), so I remove the class with  translateX ('-100%') and  add another class with translateX('100%') with out transition. Then I remove this class and add another class with translateX('0%') with transition of 1.0s. I remove class with translateX ('0%') for div2 and add another with translateX ('-100%') to movet to the left. But this is not working. The div1 is entering by the left instead of the right of the screen. Any Idea?
the CSS
.to-next {
    transform: translateX(100%);
}

.to-screen {
    transform: translateX(0%);
    transition-duration: 1.0s;
}

.to-left {
    transform: translateX(-100%);
    transition-duration: 1.0s;
}

The HTML

The JavaScript
$('#ajax-inserted2').removeClass('to-screen').addClass('to-left');
$('#ajax-inserted1').removeClass('to-left').addClass('to-next').removeClass('to-next').addClass('to-screen');

A: This is most likely happening because you are not giving the browser time to update between adding the translateX(100%) and then changing it to translateX(0%). This causes it to only run the translateX(0%) with animation (causing it to come from the left). If you instead move the translateX(0%) to a setTimeout of 0, it should work correctly because it gives the browser time to refresh the CSS. (Note there are better ways instead of setTimeout but it will work to test it)
setTimeout(function() {
    $('#ajax-inserted1').removeClass('to-next').addClass('to-screen');
    $('#ajax-inserted2').removeClass('to-screen').addClass('to-left');
}, 100);

jsFiddle here


text:
Q: White output dialog box in Fortran trouble with reading file I am trying to read a file cs251_1.dat in Fortran and then trying to create a new file using the data from cs251_1.dat. The file cs251_1.dat was written by another Fortran program and the data inside this file is two spaces followed by a three digit number followed by two spaces with a total of four numbers on a line. However, I get the following error
C:\Users\Cornelius\Documents\~Source5.f:3:
open(5, File = 'C:cs251_1.dat')
1
C:\Users\Cornelius\Documents\~Source5.f:6: (continued):
Integer A
2
Statement at (2) invalid in context established by statement at (1)

This is the program:
      open(5, File = 'C:cs251_1.dat')
      open(6, File = 'C:cs251_2.out')

      Integer A, B, C, D
      total = 0.
      E = 1
      Integer Selection = 1
      total = Selection + 1
      Print *, 'Let''s do some math!!'
    *  16  continue
      Read(5, 65) A, B, C, D
  65  Format(I4, I4, I4, I4)
      write(6,66)
  66  Format(4(2x, I4))

A: You can't have a declaration after an active statement.     That is what your compiler means by "Statement at (2) invalid in context established by statement at (1)".   So change the order of the statements.


text:
Q: Change attribute value programmatically I have created product programmatically but when i try to update attribute value with code:
$product->setData($attributeCode, '')->save();

It won't change. The update will work only after i have saved the product in Magento admin GUI. What might be the reason of that?
Code I use to create product:
  $_product->setName($productName)
    ->setId($productID)
    ->setAttributeSetId($attributeSetId)
    ->setStoreId($storeId)
    ->setVisibility(4)
    ->setStatus(1)
    ->setWebsiteIds(array(1))
    ->setSku($Sku)
    ->setPrice($price)
    ->setDescription($description)
    ->setShortDescription($shortDescription)
    ->setStockData(array(
         'use_config_manage_stock' => 0,
         'is_in_stock' => $stock,
         'qty' => $qty
    ))
    ->setUrlKey($urlKey)
    ->setCategoryIds(array($CategoryId))
    ->setTypeId("simple")
    ->setData($attributeCode, 5)
    ->save();

Editing script
`$_product->load($productID)->setStoreId($storeId)->setData($attributeCode, 'Blue')->save();`

$_product is an instance of \Magento\Catalog\Model\Product.

A: The reason for that may your attribute code isn't correct. You should check the attribute code again: STORES > Attributes > Product. You also need to reindex the database and clear your Magento Cache to see the result after updating the attribute.


text:
Q: Log4j2 - Cannot write logs to a file I'm attempting to use log4j2 to write log statements to both console and log files. However, when I check the log folder, nothing is being created.
The idea is to use the RoutingAppender to have all the test classes of each package in one folder.
Here is the log4j2.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="LOG_PATTERN">%d{HH:mm:ss.SSS} [%t] %-5level [%5X{tId}] %logger{36} - %msg%n</Property>
    </Properties>
    <Appenders>
        <Routing name="MyRoutingAppender">
            <Routes pattern="$${ctx:threadName}">
                <Route>
                    <RollingFile
                            fileName="logs/${ctx:testGroupName}/${ctx:threadName}.log"
                            name="appender-${ctx:threadName}"
                            filePattern="logs/${date:yyyy-MM}/${ctx:threadName}-%d{yyyy-MM-dd}-%i.log.gz">
                        <PatternLayout pattern="${LOG_PATTERN}"/>
                        <Policies>
                            <TimeBasedTriggeringPolicy interval="6" modulate="true" />
                            <SizeBasedTriggeringPolicy size="10 MB" />
                        </Policies>
                    </RollingFile>
                </Route>
            </Routes>
        </Routing>
        <Console name="LogToConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="TestCases" level="info" additivity="false">
            <AppenderRef ref="LogToConsole"/>
            <AppenderRef ref="MyRoutingAppender"/>
        </Logger>
        <Logger name="PageObjects" level="info" additivity="false">
            <AppenderRef ref="LogToConsole"/>
            <AppenderRef ref="MyRoutingAppender"/>
        </Logger>
        <Root level="info">
            <AppenderRef ref="LogToConsole"/>
        </Root>
    </Loggers>
</Configuration>

Here is what I'm having in my java class:
    package TestCases.Groups;

    public class AddDeleteGroup extends TestInit {
        private final Logger logger = LogManager.getLogger(AddDeleteGroup.class.getName());

        @BeforeClass
        public void beforeClass() {
            String threadId = String.valueOf(Thread.currentThread().getId());
            ThreadContext.put("tId", threadId);
            ThreadContext.put("testGroupName", "TestCases.Groups");
            ThreadContext.put("threadName", AddDeleteGroup.class.getName());
        }

        @Test(groups = "test")
        public void setUp(){
            logger.info("SetUp method for {}", AddDeleteGroup.class.getName());
            // do stuffs
        }

        @Test(dependsOnMethods={"SetUp"})
        public void testRunner(){
            logger.info("TestRunner method for {}", AddDeleteGroup.class.getName());
            // do stuffs
        }

The console shows the log statements being printed out, but when I check the logs folder, I do not see anything.
If anyone has any idea what I'm doing wrong, please help me out. Thanks in advance.

A: Here is for you. I've tried and it works.
JAVA - Separate log files for threads using log4j2

A: It turns out the "*.log" file wasn't being recognized in IntelliJ. When I tried changing the file type to "*.txt", the log files are being displayed in the folder.
The configuration works as expected.


text:
Q: Client certificate browser prompt in IIS I need to read the certificate off a smart card reader from a web browser.
The certificate will then be used in a subsequent API call to an external service.
I have setup an asp net api project.
[HttpGet]
public async Task<ActionResult> Get()
{
    var cert = await HttpContext.Connection.GetClientCertificateAsync();
    // call external service
    return Ok();
}

I have added the following in applicationHost.config
<section name="iisClientCertificateMappingAuthentication" overrideModeDefault="Allow" />

<security>
    <access sslFlags="Ssl, SslNegotiateCert, SslRequireCert" />
    <authentication>
        <anonymousAuthentication enabled="false" />
        <basicAuthentication enabled="false" />
        <clientCertificateMappingAuthentication enabled="true" />
        <digestAuthentication enabled="false" />
        <iisClientCertificateMappingAuthentication enabled="true">
        </iisClientCertificateMappingAuthentication>
</security>

When I call the endpoint from a browser, I get the error
 HTTP Error 403.7 - Forbidden
 The page you are attempting to access requires your browser to have a Secure Sockets
 Layer (SSL) client certificate that the Web server recognizes.

How can I get the browser to prompt for the client certificate from my smart card ?
Do I need to install a certificate on my machine ?

A: You could try the below workaround :

*

*Install the certificate under the root CA folder.

*Set up clientCertificateMappingAuthentication to false.

*Set the certificate hash and username password in is client certificate mapping authentication.


text:
Q: Unity script stops working when scene is reloaded I am trying to create an infinite runner.
My scene have a "road creator" object that is just a trigger and a script attached to my road prefab.
Every time a piece of road leaves the road creator trigger, a new piece of road is created.
Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class roadGenerator : MonoBehaviour
{
    public GameObject road;

    private void OnTriggerExit(Collider other) {
        if(other.gameObject.tag == "roadGenerator"){
            Instantiate(road, new Vector3(200, 0, 0), Quaternion.identity);
        }
    }
}

My issue is that once the player loses and the level reloads the script stops working.
Everything gets loaded properly (the trigger object and the first piece of road with the script attached) but for some reason the script doesn't get triggered...

A: Hey I think I'll need some more context to understand your problem:
You have a "roadGenerator" with a trigger and the Script attached + a "Road" Prefab with the Tag "roadGenerator" right?
I suppose by "realoading the level" you mean reloading the Scene with something like SceneManager.LoadScene(...)
It would also be good to know what you already tried out to fix it. :)