text:
Q: Why is my Bootstrap Toggle Navbar disappearing? So the "hamburger" toggle navbar icon seems to be invisible after I collapse the page to the point that it's supposed to appear.  Both the 3 icon bars and the actual button are invisible.  However, it still seems to work in that it drops down when clicked on.  I have gone through the styles effecting it using the 'Inspect Element' function in Google Chrome, toggling and changing numerous styles to no avail.
Can anyone help me understand why it's doing this?

Here's a picture illustrating the problem, and my code:

    <title> Bootstrap Testing </title>

      <button type="button" class="btn btn-lg btn-primary visible-lg">Sign In</button>

      <button type="button" class="btn btn-lg btn-primary" style = "visibility: hidden;">ButtonToTakeUpSpace</button>

            <button type = "button" class = "navbar-toggle" data-toggle = "collapse" data-target = "#mainNavbarInfo">
               Toggle navigation

            </button>
             EdViewRate

 Home

 SLO Generator

 SLO Tutorial

 Sign up

               Sign In

                  <form action="[YOUR ACTION]" method="post" accept-charset="UTF-8">
                    <input id="user_username" style="margin-bottom: 15px;" type="text" name="user[username]" size="30" />
                    <input id="user_password" style="margin-bottom: 15px;" type="password" name="user[password]" size="30" />
                    <input id="user_remember_me" style="float: left; margin-right: 10px;" type="checkbox" name="user[remember_me]" value="1" />
                     Remember me

                    <input class="btn btn-primary" style="clear: left; width: 100%; height: 32px; font-size: 13px;" type="submit" name="commit" value="Sign In" />
                  </form>

A: The problem is that you haven't specified the "theme" to use for the navbar. You must a class of navbar-default or navbar-inverse along with the navbar class on your nav element.
http://jsfiddle.net/65KdX/1/
In doing this, all the Bootstrap CSS appears to do to the navbar-toggle is apply a border-color of #ddd to it. You could probably omit the navbar-default class, but there's no telling what other styling problems with the navbar you're likely to run into. Better to apply that class and then override the specific things you don't want/need.


text:
Q: How to show the modal dialog based on label type I'm trying to show a open modal dialog based on the label click, but it is showing the same(All Recommendations) modal dialog even if i clicked on other label(Entities By type) . How to handle this , please help me thanks in advance
const ExportTypes: Array<{ label: string; id: string }> = [
 { label: 'All Recommendations', id: 'AllRecommendations' },
 { label: 'Entities By type', id: 'EntitiesBytype' },
];

const handleModalExport = useCallback(
() => {
  if (ExportTypes.some(e => e.id === 'AllRecommendations')) {
      openModalDialog({
        title: t('Export all recommendations'),
        renderContent: () => <RecommendationExportModel />,
      });
    }
   else if(ExportTypes.some(e => e.id === 'EntitiesBytype')) {
      openModalDialog({
        title: t('Export all'),
        renderContent: () => <RecommendationExportEntitiesModel />,
      });
    }
  },
 [openModalDialog, t],
);

{ExportTypes.map((objType) => (
  <MenuItem key={objType.id} onClick={handleModalExport}>
     {t(objType.label)}
  </MenuItem>
))}

A:
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

In this case, when you run handleModalExport(), it's checking your ExportTypes constant for if it has an item with an id equal to AllRecommendations. Since it always has that, anytime you click the MenuItem, it will always pass the first conditional since that item id is always present in your constant.
You're basically not using the clicked item's id which is the problem. Your MenuItem needs to pass in the id that you are clicking and that you want to do a check on.
Try using this instead:
<MenuItem key={objType.id} onClick={() => handleModalExport(objType.id})}>

Then update your callback to use this dynamic id from your onClick event:
const handleModalExport = useCallback(
(id) => {
  switch (id) {
    case 'AllRecommendations':
      openModalDialog({
          title: t('Export all recommendations'),
          renderContent: () => <RecommendationExportModel />,
        });
      }
    break;
    case 'EntitiesBytype':
      openModalDialog({
        title: t('Export all'),
        renderContent: () => <RecommendationExportEntitiesModel />,
      });
    break;
    default:
      // handle this, throw? do nothing?
  },
 [openModalDialog, t],
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Catch route with .html constraint and menupath(*) in .net Core I am struggeling to achive the same routing in my .net core project, as i have in my mvc projects.
In my mvc projects i have the following routes caching menuPath and menuPath with pageurl. But as you can see im using a class named greedyroute in order to have 2 routes with (*).
  routes.Add(
                new GreedyRoute("{*menuPath}/{pageUrl}",
                new RouteValueDictionary(new { controller = "Page", action = "Index" }),
                new RouteValueDictionary(new { pageUrl = @"[0-9a-zA-ZøæåØÆÅ+_-]+.html" }),
                new MvcRouteHandler()));

            routes.Add(
                new GreedyRoute("{*menuPath}",
                new RouteValueDictionary(new { controller = "Page", action = "List" }),
                new MvcRouteHandler()));

How can i achieve the same result in a asp .net core project?
I did try the following:
routes.MapRoute(
    name: "page",
    template: "{*menuPath}/{pageUrl}",
    constraints: new { pageUrl = @"[0-9a-zA-ZøæåØÆÅ+_-]+.html" },
    defaults: new { controller = "Page", action = "Index" });

routes.MapRoute(
    name: "listpage",
    template: "{*menuPath}",
    defaults: new { controller = "Page", action = "List" });

but that gives me this error:
Additional information: A catch-all parameter can only appear as the last segment of the route template.
Examples of paths when the routing actually works:
/stars/jupiter.html routes to index method and menupath = /stars and pageurl = jupiter.html
/stars/randomname/jupiter.html routes to index method and menupath= /stars/randomname and pageurl = jupiter.html
/stars/all-stars routes to list method and menuPath = /stars/all-stars.
And, menuPath is dynamic.


text:
Q: Как написать ножницы на C#? Ищу конкретную статью либо видеоурок, может быть кто то уже видел и я теряю время в поисках?
Я про ножницы из win7. Просто программа, полностью повторяющая функционал. Хочу разобраться.
A: Так проще самому написать. Там функционала-то почти нет:

*

*Получаешь DC рабочего стола.

*Помещаешь картинку на созданную форму без заголовка, растянутую на всю рабочую область (хотя ножницы возможно действуют по-другому)

*Реализуешь выбор области (на мауз даун событие, мауз мув и мауз ап). По мауз ап, берешь выбранную область и помещаешь ее в виде картинки в буфер обмена.


text:
Q: Flutter arkit_plugin 0.6.0 pods fail to install I am trying to use arkit_plugin 0.6.0 and pods fail to install. Pods fail because "'ARWorldTrackingConfiguration' is only available in iOS 11.0". I need to update my AppDelegate.swift file in order for plugin to work. Below is my Podfile. How do I fix this?
Podfile
platform :ios, '12.0'
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
      config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '9.0'
      config.build_settings['OTHER_SWIFT_FLAGS'] = '-DDISABLE_TRUEDEPTH_API'
  end
end
end


text:
Q: How to use the Mongo aggregation method to join on one collection filed name to another collection filed value? I'm on Spring boot 2 and Spring Data MongoDB.
At the front side, In user form, all the fields are displayed dynamically from the DB.
I have the "Filed" collection for all the fields.
So my Field collection looks like:
{
    "_id" : ObjectId("5f05a51dc9e77c00014bb3b5"),
    "fieldName" : "name",
    "fieldType" : "text"
},
{
    "_id" : ObjectId("5f05a51dc9e77c00014b4523"),
    "fieldName" : "address",
    "fieldType" : "text"
}

User Collection
{
    "_id" : ObjectId("5f058db405c9fc60965ce243"),
    "name" : "john",
    "address" : "US"
}

Now I want to join these two collections based on fileName filed of the Field collection and user collection.
I expect result:
{
   "_id" : ObjectId("5f058db405c9fc60965ce243"),
   "fileds":[
   {
       "_id" : ObjectId("5f05a51dc9e77c00014bb3b5"),
       "fieldName" : "name",
       "fieldType" : "text",
       "value":"John"
   },
   {
       "_id" : ObjectId("5f05a51dc9e77c00014b4523"),
       "fieldName" : "address",
       "fieldType" : "text",
       "value":"US"
   }]
}

Any Idea?

A: Here is a quick example how to achieve this using $objectToArray and then doing a $lookup on the fields name.
db.users.aggregate([
  {
    $addFields: {
      userFields: {
        $objectToArray: "$$ROOT"
      }
    }
  },
  {
    $unwind: "$userFields"
  },
  {
    $lookup: {
      from: "fields",
      let: {
        field: "$userFields.k"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$$field",
                "$fieldName"
              ]
            }
          }
        },
        {
          $addFields: {
            value: "$$field"
          }
        }
      ],
      as: "fields"
    }
  },
  {
    $unwind: "$fields"
  },
  {
    $group: {
      _id: "$_id",
      fields: {
        $push: "$fields"
      }
    }
  }
])

Mongo Playground


text:
Q: Why does Android Emulator show black screen with Android flashing on it? I have installed Eclipse Helios and Android Sdk. The problem is that when I launch an Emulator I get a black screen with android text flashing on it. I get the following errors in the Log.Can anyone please suggest a step by step solution to this problem.
Here are the errors:
02-27 05:59:50.070: E/logwrapper(920): executing /system/bin/e2fsck failed: No such file or directory
02-27 05:59:51.130: E/cutils(932): Failed to read /data/.layout_version: No such file or directory
02-27 05:59:51.130: E/installd(932): Could not create directories; exiting.
02-27 05:59:51.790: W/InterfaceController(925): Warning (dlopen failed: library "/system/lib/libnetcmdiface.so" not found) while opening the net interface command library
02-27 05:59:51.920: E/keystore(933): chdir: /data/misc/keystore: No such file or directory
02-27 05:59:52.250: D/Vold(923): Volume sdcard state changing 0 (No-Media) -> 1 (Idle-Unmounted)
02-27 05:59:53.270: E/SurfaceFlinger(928): hwcomposer module not found
02-27 05:59:53.270: W/SurfaceFlinger(928): getting VSYNC period from fb HAL: 1536001
02-27 05:59:53.280: W/SurfaceFlinger(928): no suitable EGLConfig found, trying a simpler query
02-27 05:59:53.280: W/SurfaceFlinger(928): EGL_SLOW_CONFIG selected!
02-27 05:59:53.320: W/SurfaceFlinger(928): power module not found
02-27 05:59:54.910: E/SurfaceFlinger(928): ro.sf.lcd_density must be defined as a build property
02-27 05:59:54.940: D/libEGL(993): Emulator without GPU support detected. Fallback to software renderer.
02-27 05:59:55.860: E/cutils(1010): Failed to read /data/.layout_version: No such file or directory
02-27 05:59:55.860: E/installd(1010): Could not create directories; exiting.
02-27 05:59:56.030: E/keystore(1011): chdir: /data/misc/keystore: No such file or directory
02-27 05:59:57.230: E/AudioFlinger(931): int android::load_audio_interface(const char*, audio_hw_device_t**) couldn't load audio hw module audio.r_submix (No such file or directory)
02-27 06:00:05.810: E/cutils(1060): Failed to read /data/.layout_version: No such file or directory
02-27 06:00:05.810: E/installd(1060): Could not create directories; exiting.
02-27 06:00:06.040: E/keystore(1061): chdir: /data/misc/keystore: No such file or directory
02-27 06:00:06.840: E/memtrack(929): Couldn't load memtrack module (No such file or directory)
02-27 06:00:06.840: E/android.os.Debug(929): failed to load memtrack module: -2
02-27 06:00:10.220: I/installd(1085): installd firing up
02-27 06:00:10.220: E/cutils(1085): Failed to read /data/.layout_version: No such file or directory
02-27 06:00:10.220: E/installd(1085): Could not create directories; exiting.
 02-27 06:00:10.570: E/keystore(1086): chdir: /data/misc/keystore: No such file or directory
02-27 06:00:15.720: E/cutils(1109): Failed to read /data/.layout_version: No such file or directory
02-27 06:00:15.720: E/installd(1109): Could not create directories; exiting.
02-27 06:00:16.230: E/keystore(1110): chdir: /data/misc/keystore: No such file or directory
02-27 06:00:29.190: E/EmojiFactory_jni(929): Failed to load libemoji.so: dlopen failed: library "libemoji.so" not found

A: While creating emulator check the option "Use Host GPU" at the bottom

A: The "flashing android text" means the emulator is booting. That can take a while depending on how fast your machine is.
Sometimes it just gets stuck and you have to deleed it and start over,  but it sounds you have already tried that.
When booting the emulator from Eclipse, look at the Console tab, not the log tab. Console may show error messages. The Log tab only shows logcat, which are messages from Android itself
When you create a new emulator it warns you about assigning it too much RAM if you try anything above 768M the emulator may not start according to the error message at the bottom of the virtual device setup.
Do try with 512M of RAM and see if it starts.

A: I've found this same issue.  The same error messages display over and over again, in a loop.  It occurs when I upgrade the emulator to API version 19.  (I waited overnight, but the emulator never started up.)
BUT, if I run the emulator with API version 17, it started up fine after about five minutes.  (By the way, I allocated 512 megs both times.)


text:
Q: Find the velocity of $v$ In the arrangement shown in the figure the ends P and Q of an inextensible string moves downward with uniform speed u. Pulleys a and b are fixed. The mass M moves upwards with what speed?

How can v be u/cos(theta) as v should be vertical component of velocity u hence v should be u cos(theta)


text:
Q: why fill in a matrix with a vector by matrix() is not working as expected?
As shown in the picture, it showed me "numeric 48" instead of actual numbers from the vector. Why is that and how to fix it? Thank you in advance!

A: The 'x' is a data.frame, so we may need to either convert to matrix with as.matrix
x1 <- as.matrix(x)

Or unlist the data.frame and convert to matrix with new dimensions
x1 <- matrix(unlist(x), 8, 6)

Reproducible example with
data(iris)
x1 <- matrix(iris, 150, 5)
head(x1)
#     [,1]        [,2]        [,3]        [,4]        [,5]
#[1,] Numeric,150 Numeric,150 Numeric,150 Numeric,150 Numeric,150
#[2,] Numeric,150 Numeric,150 Numeric,150 Numeric,150 Numeric,150
#[3,] Numeric,150 Numeric,150 Numeric,150 Numeric,150 Numeric,150
#[4,] Numeric,150 Numeric,150 Numeric,150 Numeric,150 Numeric,150
#[5,] factor,150  factor,150  factor,150  factor,150  factor,150
#[6,] Numeric,150 Numeric,150 Numeric,150 Numeric,150 Numeric,150


text:
Q: difference between Kendo DropDownList for server binding and ajax binding using kendoUI http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/dropdownlist/overview
difference between Kendo DropDownList for server binding and ajax binding.

A: You can see for example this answer : https://stackoverflow.com/a/10542545/1127669.
Basically, server binding will refresh the whole page every time an action changes the list whether the ajax binding sends an ajax request which only changes the dropdownlist...


text:
Q: How do I correctly randomly assign a port to a test HTTP server using boost asio? I am using boost asio to create a test server to test an http client. This will run on the same machine as the client. Now what I want to do is create a server with a randomly assigned port. I have looked at this thread here: Using boost::asio is there a portable way to find out free port number but I'm frankly still a little baffled.
My code looks something like this:
boost::asio::io_service service;
tcp::acceptor acceptor(service);
unsigned short port(0);
tcp::endpoint endPoint(tcp::endpoint(tcp::v4(), port);
acceptor.open(endPoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endPoint);
port = endPoint.port();

std::cout<<port<<std::endl; // prints 0

My thoughts were that by creating an endpoint with 'port 0' and then trying to bind to that port, it should cause an available port to be randomly assigned but this doesn't seem to be the case. Any idea what I'm doing wrong?
Cheers.

A: boost::asio::io_service service;
boost::asio::ip::tcp::acceptor acceptor(service);
unsigned short port(0);
boost::asio::ip::tcp::endpoint endPoint(tcp::endpoint(tcp::v4(), port);
acceptor.open(endPoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endPoint);

m_acceptor.listen();

boost::asio::ip::tcp::endpoint le = acceptor.local_endpoint(); //THIS LINE SOLVES IT
port = le.port();

// port = endPoint.port(); // This is didn't work for me

Helpful answer
Similar question

A: You can shorten this by using a different constructor for the acceptor:
using boost::asio;
io_service service;
ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), 0));
unsigned short port = acceptor.local_endpoint().port();

This constructor calls open(), bind() and listen() on the acceptor.

A: Fixed. I needed to do:
boost::asio::io_service service;
tcp::acceptor acceptor(service);
unsigned short port(0);
tcp::endpoint endPoint(tcp::endpoint(tcp::v4(), port);
acceptor.open(endPoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endPoint);
m_acceptor.listen();        // NEEDED TO ADD THIS BIT!
port = endPoint.port();

std::cout<<port<<std::endl; // prints 0


text:
Q: Hibernate unidirectional OneToMany delete violates constraint ( optional=false at parent side?) I use Hibernate 3.6 and I have something like this:
@Entity
public class Parent {
    @OnyToMany( fetch = FetchType.LAZY, cascade = { ascadeType.ALL } )
    @Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE )
    @JoinColumn( name="Parent_ID" )
    public List<Child> getChildren() { return children; }
public void setChildren( List<Child> children ) { this.children = children; }
private transient List<TitleMetadataCategory> children;
...
 }

@Entity
public class Child {
....
}

Association is unidirectional for several reasons and I don't want to change it . In addition orphan children don't exist, so there is DB constraint that CHILD.PARENT_ID is not null.
All works fine, except removing child. When I do
parent.getChildren().remove(child);
 session.saveOrUpdate(parent).
it fails.
Since I don't have
@ManyToOne( optional=false )

at the child side Hibernate tries to update child with PARENT_ID=NULL and fails due to DB constraint.
Is there any way to fix it?

A: Have you tried
@JoinColumn(name = "Parent_ID", nullable = false)

?
Also, note that attached entities are automatically persistent. You don't need to call saveOrUpdate().

A: The answer of JB Nizet is working, but with one correction. Since I also have Child.getParentId() method ( not getParent() ), its Column annotation should have nullable=false, insertable=false, updateble=false parameters in addition to nullable=false, updatable=false in Parent.getChildren() association.

A: With the current configuration Hibernate doesn't know that the Child has to be deleted when you remove it from children collection (it's called orphan removal). You need @OneToMany(orphanRemoval=true) in the parent. org.hibernate.annotations.CascadeType.DELETE only specifies that child should be deleted too when the entire parent is deleted.


text:
Q: how to can convert hard coded values list of lists to use Add() method c#? I want to convert hard coded values list of lists to use Add() method but, i  can't do it.i am writing a little bit code for it but it doesn't work.
i put original code for understand better. actually,*pictureBox1_MouseClick* is original code.
 private List<List<Node>> graph = new List<List<Node>>();
        private List<Node> ListNode = new List<Node>();
        private Node node = new Node();
 private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {

        if (e.Button != MouseButtons.Right)
        {
            var result = circleManager.HitTest(e.Location);
            if (result != -1)
            {
                circlesSourceAndDestination.Add(circleManager.Circles[result]);
                if (Count == 1)
                {
                    node.Id = result;
                }
                else if (Count == 2)
                {
                    var weigth = CalculateLengthSourceAndDestination(circlesSourceAndDestination);
                    if (weigth < 0)
                    {
                        weigth *= -1;
                    }
                     ListNode.Add(node);

                    graph.Add(ListNode);

                    Count = 0;
                }
                Count++;
            }
        }
        else
        {
            var result = circleManager.HitTest(e.Location);
            if (result != -1)
            {
                circleManager.Circles[circleManager.HitTest(e.Location)].Selected = true;
                circleManager.Circles[result].SelectFillColor = Color.Red;
            }
        }
        pictureBox1.Invalidate();
    }

List<Node> graph = new List<Node>() {
            new Node() {
                Id = 0, Neighbors = new List<KeyValuePair<int,int>>() {
                   new KeyValuePair<int,int>( 1,127),
                   new KeyValuePair<int,int>( 2,100),
                   new KeyValuePair<int,int>( 4,139),
                   new KeyValuePair<int,int>( 6,117),
                   new KeyValuePair<int,int>( 7,156)
                }
            },
            new Node() {
                Id = 1, Neighbors = new List<KeyValuePair<int,int>>() {
                   new KeyValuePair<int,int>( 0,127),
                   new KeyValuePair<int,int>( 2,102),
                   new KeyValuePair<int,int>( 3,108),
                   new KeyValuePair<int,int>( 7,53)
                }
            }

    public class Node
{
    public Node()
    {
        Neighbors = new List<KeyValuePair<int, int>>();
    }

    public int Id { get; set; }
    public List<KeyValuePair<int, int>> Neighbors { get; set; }
}
}

A: You can declare a new Node and .Add() to your graph like this:
Node newNode = new Node();
//Assign Node Id
newNode.Id = 2;
//Declare a new List for Neighbors in Node
List<KeyValuePair<int, int>> neighborList = new List<KeyValuePair<int, int>>();
//Add members to neighborList
neighborList.Add(new KeyValuePair<int, int>(1, 1)); //Assign these values dynamically;
neighborList.Add(new KeyValuePair<int, int>(2, 2));
neighborList.Add(new KeyValuePair<int, int>(3, 3));
//Assign neighborList to Neighbors
//Note that this could have been done without declaring a separate List
newNode.Neighbors = neighborList;
//Add newNode to your List
graph.Add(newNode);

A: You may use Dictionary<int, int> instead of List<KeyValuePair<int,int>>. Then you can do the following:
public class Node {
    ...
    public Dictionary<int, int> Neighbors { get; set; }
}

Neighbors.Add(0,127);
Neighbors.Add(3,108);
...


text:
Q: Downloading HTML files without opening a browser I have a URL which I don't want to open up in a browser. The servlet which my URL points to is able to download the JPEG image of the rendered HTML document using html2canvas library based on specific params.
How can I download the HTML as JPEG even without rendering the HTML on the client side. Is that possible?


text:
Q: Reset selected file input in JQuery Is there a way to write a jQuery method to delete the selected file to clear it out? How can I pass the file name to jQuery to reset the file input?
I don't want to clear all the files at once.
Here are my files:

    <form:label path="file" cssClass="fieldLabel">
    Attach Competitor:
    </form:label>

    <form:input path="file" type="file" cssClass="fileInput" accept="application/pdf"/>  Remove

            <form:label path="file2" cssClass="fieldLabel">
                Attach 2
            </form:label>
            <form:input path="file2" type="file" cssClass="fileInput"/>  Remove

            <form:label path="file3" cssClass="fieldLabel">
                Attach Additional Information:
            </form:label>
            <form:input path="file3" type="file" cssClass="fileInput" accept="application/pdf"/>  Remove

            <form:label path="file4" cssClass="fieldLabel">
                Attach Additional Information (If Needed):
            </form:label>
                <form:input path="file4" type="file" cssClass="fileInput" accept="application/pdf" />  Remove

In my JS:
How can I pass the name to my JS file and reset the selected link?
function RemoveFile(name) {
    $('input[type=file]').val('');
}

A: This code works, please ignore the changes I made to the html, that is for generating the HTML in the editor.
Explanation: If you add an event handler to all the a tags in the form with classes field fieldTEXT the function will get called, the event will provide us a this which is basically the clicked element. Then using the jquery function prev(), I access the element before the a tag, which is the input element, then we clear the field using val('')

$('.field.fieldTEXT a').on('click', function(){
     $(this).prev().val('');
});

            <form:label path="file2" cssClass="fieldLabel">
                Attach 2
            </form:label>
            <input path="file2" type="file" cssClass="fileInput"/>  Remove

            <form:label path="file3" cssClass="fieldLabel">
                Attach Additional Information:
            </form:label>
            <input path="file3" type="file" cssClass="fileInput" accept="application/pdf"/>  Remove

            <form:label path="file4" cssClass="fieldLabel">
                Attach Additional Information (If Needed):
            </form:label>
                <input path="file4" type="file" cssClass="fileInput" accept="application/pdf" />  Remove

A: Get all the elements and check each object if they have file. and clear if file is exist
$('input[type=file]').each(function(i, obj) {
    if(obj.files.length){
        obj.val('');
     }
});


text:
Q: Filter array with JSONS with more than one conditions in javascript I have the following array
 let tableA=[{id:'1', name:'name1',age:'31',gender:'male',class='B'},
             {id:'2', name:'name2',age:'38',gender:'male',class='A'},
             {id:'3', name:'name3',age:'35',gender:'male',class='C'},
             {id:'4', name:'name4',age:'20',gender:'female',class='B'},
             {id:'5', name:'name5',age:'19',gender:'female',class='A'},
             {id:'6', name:'name6',age:'31',gender:'male',class='A'}
            ];

and this array for filters
 let filters = [{type:'gender',value:"male"}, {type:'age',value:"31"}];

I'm trying to filter tableA with the values of table filters, all filters must match. Filters are not static, it means that filters can include json files for all table keys.
So far I'm trying to filter table_A with the code above.
 let filtered_table=[];
 tableA.forEach(row => {
    filters.map((item) => {
        if(row[item.type]==item.value){
           filtered_table.push(row);
         }
     });
});
console.log(filtered_table);

the result of the code above is:
 [ { id: '1', name: 'name1', age: '31', gender: 'male', class: 'B' },
   { id: '1', name: 'name1', age: '31', gender: 'male', class: 'B' },
   { id: '2', name: 'name2', age: '38', gender: 'male', class: 'A' },
   { id: '3', name: 'name3', age: '35', gender: 'male', class: 'C' },
   { id: '6', name: 'name6', age: '31', gender: 'male', class: 'A' },
   { id: '6', name: 'name6', age: '31', gender: 'male', class: 'A' } ]

How I can get back only the row that match for all of the filters_table items combined? For this example I'm expecting this:
[ { id: '1', name: 'name1', age: '31', gender: 'male', class: 'B' },
  { id: '6', name: 'name6', age: '31', gender: 'male', class: 'A' } ]

A:
let filtered_table=[];
 tableA.forEach(row => {
    const flag = filters.map((item) => {
        if(row[item.type]==item.value){
           return 1;
         } else {
           return 0;
         }
     });
     if(flag.filter(el=>el != 1).length==0) {
        filtered_table.push(row);
     }
});
console.log(filtered_table);

A: Its simple with js .filter(). Check this out
Its looping every element in tableA and filter out the gender and the age

 let tableA = [{
     id: '1',
     name: 'name1',
     age: '31',
     gender: 'male',
     class: 'B'
   },
   {
     id: '2',
     name: 'name2',
     age: '38',
     gender: 'male',
     class: 'A'
   },
   {
     id: '3',
     name: 'name3',
     age: '35',
     gender: 'male',
     class: 'C'
   },
   {
     id: '4',
     name: 'name4',
     age: '20',
     gender: 'female',
     class: 'B'
   },
   {
     id: '5',
     name: 'name5',
     age: '19',
     gender: 'female',
     class: 'A'
   },
   {
     id: '6',
     name: 'name6',
     age: '31',
     gender: 'male',
     class: 'A'
   }
 ];

 let fil = [{
   type: 'gender',
   value: "male"
 }, {
   type: 'age',
   value: "31"
 }];

const data = tableA.filter((ele,index) => {
    return ele.gender == fil[0].value && ele.age == fil[1].value
})

console.log(data)

A: The thing you're after is the .every method See Docs.
var filters = [
  { type: "gender", value: "male" },
  { type: "age", value: "31" },
];

var tableA = [
  { id: "1", name: "name1", age: "31", gender: "male", class: "B" },
  { id: "2", name: "name2", age: "38", gender: "male", class: "A" },
  { id: "3", name: "name3", age: "35", gender: "male", class: "C" },
  { id: "4", name: "name4", age: "20", gender: "female", class: "B" },
  { id: "5", name: "name5", age: "19", gender: "female", class: "A" },
  { id: "6", name: "name6", age: "31", gender: "male", class: "A" },
]

var result = tableA.filter(item =>
  filters.every(filter => item[filter.type] === filter.value)
);

console.log(result)

//  [ { id: '1', name: 'name1', age: '31', gender: 'male', class: 'B' },
//    { id: '6', name: 'name6', age: '31', gender: 'male', class: 'A' } ]

Below is a more verbose way, not using the ES6 Syntax:
var result tableA.filter(item => {
  //ensure every filter has been matched against
  var everyFilterMatched = filters.every(filter => {
    return item[filter.type] === filter.value;
  });
  return everyFilterMatched
});

N.B: Edit is use every as I am assuming you may not know how many filters you will have, just that there is an array of the given shape, and you want to match *all of them.


text:
Q: Best place to store config and log files for a Windows service I am wondering what is the best folder to use to store config files (ini, xml) and log files for a Windows service.
According to the special folders list on msdn, it seems that CommonApplicationData (= C:\ProgramData on Windows Vista/7/Server 2008 (R2)) is the best suited place :

CommonApplicationData = The directory that serves as a common repository for application-specific data that is used by all users.

Any other advice?

A: the .NET config file generated from Visual Studio, called myService.exe.config should be saved in the same location as the exe. and it's an XML not an ini file.
Log files can be saved in a folder like C:\Logs\ServiceName or anything else you like, we usually create a network share on such folder so we can check log files also from other machines without need to connect to the server where the Windows Service is running.

A: For logging, I think the Windows Event Log is the most suitable. If you use Enterprise Library it's pretty easy to set up :)
Edit: Also, I would agree that using CommonApplicationData for config files is a good choice.

A: Without much answers, I am just resuming in the following what I think and heard/read it's best:

*

*Configuration files (ini, xml) should be stored with the exe file of the service.

*Logs: The more modular way is to use a third-party logger (such as log4net or NLog - this thread is interesting for comparison). The folder where you will store your log file doesn't really matter, as long as it meets your needs (the service should have the sufficient rights to write in the folder, think who need to access to the log file and from where).


text:
Q: Return json of validations with laravel 5.4 i have the following request ajax:
$("#btnSave").click(function()
{
    var Url = 'http://localhost/Projetos-Laravel/Sibcomweb/public/panel/client/save';

    var Dados = $('#FormClient').serialize();

    $.ajax({
             type:'POST',
             url:Url,
             dataType: 'JSON',
             data: Dados,
             success:function(data){
                  if($.isEmptyObject(data.error)){
                     alert(data.msg);
                  }else{
                     alert('have errors');
                    }
                },
                error:function(e){
                  alert('Error !');
                  log.console(e);

                },
            });
        });

error log.console(e)
POST http://localhost/Projetos-Laravel/Sibcomweb/public/panel/client/save 500 (Internal Server Error)
send @ jquery.js:9566
ajax @ jquery.js:9173
(anonymous) @ create:431
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014
create:446 Uncaught ReferenceError: log is not defined
    at Object.error (create:446)
    at fire (jquery.js:3317)
    at Object.fireWith [as rejectWith] (jquery.js:3447)
    at done (jquery.js:9274)
    at XMLHttpRequest.<anonymous> (jquery.js:9514)

the request ajax go to the controller but have some error in method of validation ...
I think the problem is in the validator method, am I doing something wrong?
public function store(Request $request)
{
    $dataForm = $request->all();

    $rules =[
    'name'=>'required|min:3|max:100',
    'number'=>'required|numeric',
    ];

    $valida = validator($dataForm, rules);
    if($valida->fails())
    {
        return $valida;
    }
    else
        return 'Ok';
}

how i do for return the var valida in type json?

A: log is not a fuction. Change log.console to console.log

A: To see the response error:
Change your callback function on fail to:
  error: function(e){
    var errors = e.responseJSON;
    alert(errors);
    // Render the errors with js ...
  }

A: have two problems.
first it was: log.console(e), but is console.log(e).
and the second problem is in controller, the method of return  not is correct.
that way it's correct:
public function store(Request $request)
{
    $dataForm = $request->all();

    $rules =[
    'name'=>'required|min:3|max:100',
    'number'=>'required|numeric',
    ];

    $valida = validator($dataForm, $rules);

    return response()->json(['error'=>$valida->errors()->all()]);
}


text:
Q: Bank cards: the same as debit card, or catch-all for debit and credit card? I've been asked by a student whether 'bank card' is a common synonym for debit card.
I started by checking wikipedia whose article on bank cards points towards it including both debit, credit and other cards. However, the article on debit cards seems to imply that bank card is indeed a synonym of debit card.
While searching EL&U, I found an answer to the question that clearly states that, at least in Canada, bank card is a synonym for debit card.
So...
Is bank card a general synonym for debit card, or is this true only in some English-speaking countries? And if so, which countries? In the countries where this is true, which term is preferred in everyday speech?

A: A debit card is a card issued by a bank, therefore it qualifies as a bank card.
A bank card is not necessarily a debit card, because it could be a credit card etc., as explained in one of the answers to the question you linked to.
debit card -> bank card
bank card -> debit card, credit card, etc.
Because of the relationship, I would say that a debit card is a type of bank card, but not a synonym. The best way to check if bank card works as a synonym of debit card is a simple substitution. If someone said:
Please give me your bank card

Someone who had both a debit or credit card in their pocket might hand the person a credit card, instead of a debit card. Sometimes, you would know based on context which card they wanted you to give them, but it is not explicit.  It is however, very obvious which card the person wants if they say:
PLease give me your debit card

A: In the US bank card is rather ambiguous therefor not really used much unless there is some context.
If someone told me that they had a "bank card" I would think it was just an ATM card.  If you open a bank account in the US you get an ATM card from the bank to get your money out.  Some of these have a debit card function.
Although it is not wrong to declare your credit or debit card a "bank card" (especially when one is backed by a local bank) but it generally isn't used for that purpose.  You would normal say you credit card or debit card and sometimes these two terms are affixed to whatever said person uses the most.
This question has variance because the standards outside the US are for the most part much higher as far as security and because of this cards are wrapped up into one.  I still find it ridiculous that people would even use a debit card in the US meaning an informed person probably has an ATM card with various credit cards.

A: To add to the ambiguity, and the history of the term: the first widely used credit card in Australia and New Zealand, introduced in 1974, was called Bankcard.


text:
Q: Lipschitz Constant for Equation System I'm would like to compute the region of convergence from Newton-Rapson Method for a multivariate system of equations by a theorem that states:
Let $\vec{F}: \mathbb{R}^N \rightarrow \mathbb{R}^N$ be continuously differentiable in an open convex set $D \subset \mathbb{R}^N$. Assume

*

*there exists $x^*$ with $r,\beta > 0$ such that $N(x*,r) \subset D$. ($N$ ist the disk around $x^*$ with radius $r$)

*$\vec{F}(x^*)=0$

*$\Vert J^{-1} \Vert \leq \beta$

*and J is Lipschitz continuous with Lipschitz constant $\gamma$
Then there exists $\epsilon>0$ such that for all $x_0 \in N(x*,r)$ the sequence $x_1, x_2 ,...$ converges to $x^*$ by applying the Newton-Rapson Method and obeys:

*

*$\Vert x_{k+1} - x^* \Vert \leq \beta \gamma \Vert x_{k} - x^* \Vert^2$
I found an example within a book. Within this book, there is a Jacobian J
$: \begin{bmatrix}
   2 x_1 & 2 x_2\\
   -1 & 2 x_2\\
\end{bmatrix}$
given to the underlying equation system F $: \begin{bmatrix}
   x_1^2 x_2^2 - 9\\
   -x_1 x_2^2 - 3 \\
\end{bmatrix} = 0$
and a solution $x^*= [2, \sqrt5]$. The Lipschitz constant is said to be $\gamma=4$.
How can one compute the Lipschitz constant in general for multivariate system of equations and how do they determine $\gamma=4$?


text:
Q: Circular Path Animation not working with Pulsating Movement I'm trying to achieve a kind of pulsating moon effect with canvas in HTML5. I have the pulsating effect, but my requestAnimation function does not seem to be updating the frame along the circular path that I have defined. Here's the javascript.
window.requestAnimFrame = function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame
||
window.mozRequestAnimationFrame || window.oRequestAnimationFrame
|| window.msRequestAnimationFrame ||
  function(a) {
   window.setTimeout(a, 1E3 / 60)
  }
}();

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

 function Ball(radius, color) {
  if (radius === undefined) {
   radius = 40;
   }
  if (color === undefined) {
  color = "#ff0000";
   }

  this.x = 0;
  this.y = 0;
  this.radius = radius;
  this.rotation = 0;
  this.scaleX = 1;
  this.scaleY = 1;
  this.lineWidth = 1;
  }

  Ball.prototype.draw = function(context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.rotation);
  context.scale(this.scaleX, this.scaleY);
  context.lineWidth = this.lineWidth;
  context.fillStyle = "#e50000";
  context.beginPath();
  //x, y, radius, start_angle, end_angle, anti-clockwise
  context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
  context.closePath();
  context.fill();
 if (this.lineWidth > 0) {
  context.stroke();
  }
  context.restore();
  };

  window.onload = function() {
  var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        ball = new Ball(),
        angle = 0,
        centerScale = 1,
        range = 0.5,
        speed = 0.02,

pathX = canvas.width / 2,
pathY = canvas.height / 2,
pathRadius = 150,
pathAngle = 0;
ball.x = Math.cos(pathAngle) * pathRadius + pathX;
ball.y = Math.sin(pathAngle) * pathRadius + pathY;

   (function drawFrame() {
   window.requestAnimationFrame(drawFrame, canvas);
   context.clearRect(0, 0, canvas.width, canvas.height);
  ball.scaleX = ball.scaleY = centerScale + Math.sin(angle) * range;
  angle += speed;
  pathAngle += speed;
  ball.draw(context);
  }());
};

A: You're rotating a circle around it's own centerpoint so it's not orbiting relative to it's centerpoint.
// offset the circles rotation by 100px off its centerpoint
context.arc(100, 0, this.radius, 0, (Math.PI * 2), true);

Example code ad a demo:

window.requestAnimFrame = function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame
||
window.mozRequestAnimationFrame || window.oRequestAnimationFrame
|| window.msRequestAnimationFrame ||
  function(a) {
   window.setTimeout(a, 1E3 / 60)
  }
}();

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

 function Ball(radius, color) {
  if (radius === undefined) {
   radius = 40;
   }
  if (color === undefined) {
  color = "#ff0000";
   }

  this.x = 0;
  this.y = 0;
  this.radius = radius;
  this.rotation = 0;
  this.scaleX = 1;
  this.scaleY = 1;
  this.lineWidth = 1;
  }

  Ball.prototype.draw = function(context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.rotation);
  context.scale(this.scaleX, this.scaleY);
  context.lineWidth = this.lineWidth;
  context.fillStyle = "#e50000";
  context.beginPath();
  //x, y, radius, start_angle, end_angle, anti-clockwise
  context.arc(50, 0, this.radius, 0, (Math.PI * 2), true);
  context.closePath();
  context.fill();
 if (this.lineWidth > 0) {
  context.stroke();
  }
  context.restore();
  };

  window.onload = function() {
  var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        ball = new Ball(),
        angle = 0,
        centerScale = 1,
        range = 0.5,
        speed = 0.02,

        pathX = canvas.width / 2,
        pathY = canvas.height / 2,
        pathRadius = 50,
        pathAngle = 0;
        ball.x = canvas.width/2;  // Math.cos(pathAngle) * pathRadius + pathX;
        ball.y = canvas.height/2; //Math.sin(pathAngle) * pathRadius + pathY;

   (function drawFrame() {
   window.requestAnimationFrame(drawFrame, canvas);
   context.clearRect(0, 0, canvas.width, canvas.height);
  ball.scaleX = ball.scaleY = centerScale + Math.sin(angle) * range;
  angle += speed;
  pathAngle += speed;
  ball.rotation+=Math.PI/180;
  ball.draw(context);
  }());
};
body{ background-color:white; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>


text:
Q: Extract only begining and end script tag with preg_match_all Html:
<script type="text/javascript"> ..code.. </script>
<script type="text/javascript"> ..code.. </script>
<script> ..code.. </script>
<script type="text/javascript"> ..code.. </script>

What i would like to see:
<script type="text/javascript"></script>
<script type="text/javascript"></script>
<script></script>
<script type="text/javascript"></script>

My expression:
preg_match_all('/<script.*> (<\/script>)/i',$html, $result);

I cant get it work.

A: From Here:
function stripscript($code) {
  $code = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/i', '<script type="text/javascript"></script>', $code);
  return $code;
}

Codepad example: here

A: You can use this:
$html = preg_replace('~<script[^>]*>\K[^<]*(?=</script>)~i', '', $html);

or this for more performances:
$html = preg_replace('~<script[^>]*+>\K[^<]*+(?=</script>)~i', '', $html);

Note that if you are sure of the lowercase, you can remove the i.
\K reset the start of the match from match result.(?=</script>) is a zero-width assertion that means "followed by </string>". It's not a part of the match result. It's only a check.


text:
Q: How to call Service location I need to get user location each 5 minutos, I found this class:
Link
I changed the line:
private static final int LOCATION_INTERVAL = 30*1000*60;

to
private static final int LOCATION_INTERVAL = 1000;

But I tried to call on my activity :
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(MainActivity.this, MyLocationService.class);
    startService(intent);
  }

But dont show anything. How can I show the location on Toast for example?

A: Do you have service definition in your manifest:
<service android:name=".MyLocationService"></service>

And also added permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

You may request these permissions in runtime beginning Android 6.


text:
Q: i need __NSCFArray convert to an array. is it possible? I need to get values from "readers" to an array,
 where readers :
@"readers":[NSString stringWithFormat:@"%@",[readersIds componentsJoinedByString:@","]],

where readersIds is an NSArray.
NSArray *test =[[[e.response objectForKey:@"acls"] objectAtIndex:0] objectForKey:@"readers"];

Actually i need to get back readers values into another NSArray, when i try
     NSString *test =[[[e.response objectForKey:@"acls"] objectAtIndex:0] objectForKey:@"readers"];

it shows __NSCFArray. Is there any way to get back as array ?

A: You don't need to do anything to convert __NSCFArray into NSArray. Just assume it's plain NSArray and use it like regular. Actually, I believe it's the way it's implemented behind the scenes.


text:
Q: How can I check if a file contains a string or a variable in JavaScript? Is it possible to open a text file with JavaScript (location like
http://example.com/directory/file.txt) and check if the file contains a given string/variable?
In PHP this can be accomplished easily with something like:
$file = file_get_contents("filename.ext");
if (!strpos($file, "search string")) {
    echo "String not found!";
} else {
    echo "String found!";
}

Is there a way to do this? I'm running the "function" in a .js file with Node.js, appfog.

A: You can not open files client side with javascript.
You can do it with node.js though on the server side.
fs.readFile(FILE_LOCATION, function (err, data) {
  if (err) throw err;
  if(data.indexOf('search string') >= 0){
   console.log(data) //Do Things
  }
});

Newer versions of node.js (>= 6.0.0) have the includes function, which searches for a match in a string.
fs.readFile(FILE_LOCATION, function (err, data) {
  if (err) throw err;
  if(data.includes('search string')){
   console.log(data)
  }
});

A:
Is there a, preferably easy, way to do this?

Yes.
require("fs").readFile("filename.ext", function(err, cont) {
    if (err)
        throw err;
    console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});

A: You can also use a stream. They can handle larger files. For example:
var fs = require('fs');
var stream = fs.createReadStream(path);
var found = false;

stream.on('data',function(d){
  if(!found) found=!!(''+d).match(content)
});

stream.on('error',function(err){
    then(err, found);
});

stream.on('close',function(err){
    then(err, found);
});

Either an 'error' or 'close' will occur. Then, the stream will close since the default value of autoClose is true.

A: OOP way :
var JFile=require('jfile');
var txtFile=new JFile(PATH);
var result=txtFile.grep("word") ;
 //txtFile.grep("word",true) -> Add 2nd argument "true" to ge index of lines which contains "word"/

Requirement :
npm install jfile

Brief :
((JFile)=>{
      var result= new JFile(PATH).grep("word");
})(require('jfile'))

A: From the client side you can definitely do this :
var xhttp = new XMLHttpRequest(), searchString = "foobar";

xhttp.onreadystatechange = function() {

  if (xhttp.readyState == 4 && xhttp.status == 200) {

      console.log(xhttp.responseText.indexOf(searchString) > -1 ? "has string" : "does not have string")

  }
};

xhttp.open("GET", "http://somedomain.io/test.txt", true);
xhttp.send();

If you want to do it on the server side with node.js use File System package this way :
var fs = require("fs"), searchString = "somestring";

fs.readFile("somefile.txt", function(err, content) {

    if (err) throw err;

     console.log(content.indexOf(searchString)>-1 ? "has string" : "does not have string")

});


text:
Q: how to broadcast data to clients in java I am writing a small desktop application which is about showing notifications to the client who is using this application.so my application should get notifications from a server where all the notifications are stored.so if there are 100 clients using this app and if I add some notifications to server how can I send these data to 100 clients...please give me some idea what APIs or which technology I can use to get this functionality implemented.this application is a desktop application

A: There are some possibilities:
1. Via Sockets, ServerSocket/Socket/Multicast
Push-Notification: Open a listening socket on every client and open a connection from server to send a notification from server to client.
Pull-Notification: Open a listening socket on the server and open e.g. every 10 seconds or so a connection from the clients to the server to look for new notifications on the server.
Multicast: Send the same message to multiple clients with one API call.
2. JDBC/JPA: Transfer messages over the database, if you have one.
3. JMS: Use a message topic
...
The best method depends on your needs.

A: Its simple ...
1) Make Arraylist of socket that has socket of all clients. // i.e when new client connected then add its socket into th ArrayList.
2) When ever there is any update just iterate through the ArralyList and send notification to all the connected clients.

A: There are two (maybe more but I know those two. :) ) patterns to deal with those types of scenarios. Observer and publish-subscriber
They are very similar with the difference that for the Observer pattern, the "standard" implementation might create memory leaks while in a publish-subscriber scenario, neither the publish or subscriber knows about each other.
Have a look a the links below that might give you a better idea.
http://en.wikipedia.org/wiki/Observer_pattern
http://www.oodesign.com/observer-pattern.html
http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
http://www.eaipatterns.com/PublishSubscribeChannel.html


text:
Q: Proper way to make a Spark Fat Jar using SBT I need a Fat Jar with Spark because I'm creating a custom node for Knime. Basically it's a self-contained jar executed inside Knime and I assume a Fat Jar is the only way to spawn a local Spark Job. Eventually we will go on submitting a job to a remote cluster but for now I need it to spawn this way.
That said, I made a Fat Jar using this: https://github.com/sbt/sbt-assembly
I made an empty sbt project, included Spark-core in the dependencies and assembled the Jar. I added it to the manifest of my custom Knime node and tried to spawn a simple job (pararellize a collection, collect it and print it). It starts but I get this error:

No configuration setting found for key 'akka.version'

I have no idea how to solve it.
Edit: this is my build.sbt
name := "SparkFatJar"

version := "1.0"

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "1.3.0"
)

libraryDependencies +=  "com.typesafe.akka" %% "akka-actor" % "2.3.8"

assemblyJarName in assembly := "SparkFatJar.jar"

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}

I've found this mergestrategy for Spark somewhere on the internet but I can't find the source right now.

A: I think the issue is with how you've setup assemblyMergeStrategy. Try this:
assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case "application.conf"            => MergeStrategy.concat
  case "reference.conf"              => MergeStrategy.concat
  case x =>
    val baseStrategy = (assemblyMergeStrategy in assembly).value
    baseStrategy(x)
}


text:
Q: insert value into one to one mapping annotation using ebeans or hibernate Hi I am trying to implement ebeans one-to-one mapping with ebeans with  user and user_profile details. I have done annotation marking  with each key but not able to insert the value at run time.
UserProfile.java
@Entity
public class UserProfile extends Model{

    @Id
    public Long userProfileId;

    public String empId;
    public String name;
    public String emailId;

    @OneToOne
    @JoinColumn(name = "email")
    public User user;

    //inserting filled form into database
    public static Long create(UserProfile userProfile)
    {
        //save leave into database
        userProfile.save();
        return userProfile.serial_id;
    }

User.java
@Entity
public class User extends Model {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static Finder<String, User> find = new Finder<String, User>(String.class, User.class);

    @Id
    public String email;
    public String name;
    public String password;
    public String permission;
    public int userProfileId;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch= FetchType.LAZY)
    public UserProfile profile;

    public User(long id,String email, String name, String password,String permission,
                int user_id) {
        //this.id=id;
       this.email = email;
       this.name = name;
       this.password = password;
       this.permission = permission;
       this.user_id = user_id;
    }

I want to insert userprofile table's userprofile_id into user's userProfileId.

A: Try following:
@Entity
public class UserProfile extends Model{

    @Id
    public Long userProfileId;

    public String empId;
    public String name;

    @OneToOne
    public User user;

    //inserting filled form into database
    public static Long create(UserProfile userProfile)
    {
        //save leave into database
        userProfile.save();
        return userProfile.serial_id;
    }

@Entity
public class User extends Model {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static Finder<String, User> find = new Finder<String, User>(String.class, User.class);

    @Id
    public String email;
    public String name;
    public String password;
    public String permission;

    @OneToOne(cascade = CascadeType.ALL, fetch= FetchType.LAZY)
    public UserProfile profile;

    public User(long id,String email, String name, String password,String permission,
                int user_id, UserProfile profileIn) {
        //this.id=id;
       this.email = email;
       this.name = name;
       this.password = password;
       this.permission = permission;
       this.user_id = user_id;
       this.profile = profileIn;
    }

The difference is that you don't need emailId in UserProfile entity and userProfileId in User entity. Simply use the entity instance and hibernate will do its job. If you at all need to expose the userProfileId in User entity to allow services to access just the id then amend User class with following changes:
@Column(name = "profileId", insertable = false, updatable = false, nullable = false)
private Long profileId;

@OneToOne(cascade = CascadeType.ALL, fetch= FetchType.LAZY, nullable = false)
@JoinColumn(name = "profileId")
private UserProfile profile;

Last but not the least please do not expose the properties like you have done in your classes. Make them private and implement getter/setter methods.


text:
Q: Is it possible to print monochrome with System.Diagnostics.ProcessStartInfo? I want to have two functions on my program but I can only print color. I also want to have an option "monochrome".
I have my code right here, can you tell me what I am missing?
Private Sub prntbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles prntbtn.Click

        Dim psi As New System.Diagnostics.ProcessStartInfo()

        Dim filepath = OpenFileDialog1.FileName
        psi.UseShellExecute = True
        psi.Verb = "printto"
        psi.WindowStyle = ProcessWindowStyle.Hidden
        psi.FileName = filepath

        Dim myProcess As System.Diagnostics.Process
        myProcess = System.Diagnostics.Process.Start(psi)
        myProcess.WaitForInputIdle()

        Dim localProces As Diagnostics.Process = Diagnostics.Process.GetProcessById(myProcess.Id)
        localProces.CloseMainWindow()
        localProces.Close()
    End Sub


text:
Q: Using blur with text fields I have two input text fields. One is for entering the title of the article and one is for the permalink of the article. What I'm wanting to do is have the permalink field disabled until text is inserted into the title field and when the user takes focus out of the title field then it runs a custom regex to replace spaces with hyphens and lowercases any uppercase letters.
<input type="text" id="title" name"title" />
<input type="text" id="permalink" name="permalink" />

A: It's real easy with jQuery...
var permalinkInput = $('#permalink');

$('#title').change(function() {
    permalinkInput.prop('disabled', !$(this).val());
}).change().blur(function() {
    $(this).val(function(i, value) {
        return value.replace(/\s+/g, '-').toLowerCase();
    });
});

jsFiddle.
If you don't have jQuery but only need to support standards-compliant modern browsers, it'd be...
var permalinkInput = document.querySelector('#permalink'),
    titleInput = document.querySelector('#title');

permalinkInput.disabled = true;

titleInput.addEventListener('change', function() {
    permalinkInput.disabled = !titleInput.value;
}, false);

titleInput.addEventListener('blur', function() {
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase();
});

jsFiddle.
If you didn't have jQuery and had to support our old IE friends, it'd look like...
var permalinkInput = document.getElementById('permalink'),
    titleInput = document.getElementById('title');

var addEvent = function(element, type, callback) {
    if (element.addEventListener) {
        element.addEventListener(type, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + type, callback);
    } else {
        element['on' + type] = callback;
    }
}

permalinkInput.disabled = true;

addEvent(titleInput, 'change', function() {
    permalinkInput.disabled = !titleInput.value;
});

addEvent(titleInput, 'blur', function() {
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase();
});

jsFiddle.
Note that the old fallback for event registration is to assign the on* property. This will overwrite any previous property assigned there.
If you really wanted to register multiple events for these ancient browsers, you'd modify the property assignment to use a custom handler which registered and then triggered multiple events when required.


text:
Q: Set transparent background - Action Bar I'm trying to set the background of the actionbar to be transparent
Is it possible? if possible can someone show me how?
Here are my codes:
public class MainMenu extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar actionbar = getSupportActionBar();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main_menu);
        LinearLayout v = (LinearLayout) findViewById(R.id.layout);
        //v.setBackgroundColor(0xffECECEC);
        v.setBackgroundResource(R.drawable.background);

        actionbar.setDisplayShowTitleEnabled(false);
        actionbar.setDisplayShowHomeEnabled(false);

        LayoutInflater mInflater = LayoutInflater.from(this);
        View mCustomView = mInflater.inflate(R.layout.action, null);
        TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.actiontitle);
        mTitleTextView.setText("HADI");

        actionbar.setCustomView(mCustomView);
        actionbar.setDisplayShowCustomEnabled(true);

        BitmapDrawable background = new BitmapDrawable (BitmapFactory.decodeResource(getResources(), R.drawable.actionbar));
         background.setTileModeX(android.graphics.Shader.TileMode.REPEAT);

         actionbar.setBackgroundDrawable(background);

    }

A: fixed by setting the alpha in actionbar style


text:
Q: Python interpreter launch time I am writing a package that automatically collects program execution metadata including the time program execution began and terminated.
The Python standard library exposes a hook to have code run automatically at interpreter termination via atexit.register. Using this to record a termination time is sufficient for my needs.
Since this approach will record, approximately, the time interpreter execution terminates, I would like the corresponding begin time to be approximately the time interpreter execution begins.
Is it possible to determine this time within a Python module?

A: I found a package psutil that provides a way to get the start time of the Python process in this answer https://stackoverflow.com/a/4559733 to the question How to retrieve the process start time (or uptime) in python. Usage is given in the answer.
This has the advantage of being cross-platform, but the disadvantage of introducing a dependency. That is acceptable for my use case. My package can first try to use psutil, and failing that, fall back on the current time as an approximation.
I am writing this answer because I think this solution can be helpful to others, but I'd still love to know whether or not there is a way to get the Python interpreter start time through the Python built-ins or standard library.


text:
Q: Flask-sqlalchemy temporary session/context variable I'm exposing an API that allows users to do various CRUD operations.
The underlying classes of my SQLAlchemy data model are derived from a single declarative base, which include a "insert_uuid" field that (as the name implies) should register the  UUID of the user triggering every insert.
In every API call, I'd like to set a 'temporary' session/context/whatever variable that I can use to set a default value. However, without having to rely on Flask's request module, because this declarative base resides in a 'data package' that does not need Flask in any way.
I.e. something like:
db.session.set_variable(user-uuid='aaaa-bbbb-etc')
db.session.add(object1)
db.session.add(object2)
db.session.add(object3)
db.session.remove_variable(user-uuid)

I've looked at setting the execution option on the SQLAlchemy engine. However this is an immutable dict, initialized upon creating the engine.
def get_user_uuid(context):
    return context.engine.get_execution_options().get('user_uuid', None)

class BaseTableDefinition(object):
    insert_uuid = Column("insert_uuid", UUIDType(), default=get_user_uuid)
    ....

BaseTable = declarative_base(cls=BaseTableDefinition)

And then, upon initializing the engine:
engine = create_engine(self._cn_string, echo=False, execution_options={'user_uuid': 'aaaa-bbbb-etc'})

In a 'static' back-end with a single-user-per-engine setup this could work, but it does not for my API use case.
What's the best way to achieve the above in a flask-sqlalchemy context, ideally relying on some functionality of the underlying SQLAlchemy core?
Thanks!

A: SQLAlchemy sessions have an info attribute, a user-modifiable dictionary, so something like this would work:
db.session.info['user-uuid'] = 'aaaa-bbbb-etc'
db.session.add(object1)
db.session.add(object2)
db.session.add(object3)
db.session.info.pop('user-uuid')

Session and sessionmaker accept an info keyword argument to set the contents of the dictionary at creation time.  To set the value dynamically at session creation time in Flask-SQLAlchemy you might want to subclass SQLALchemy and override / extend create_session or create_scoped_session.


text:
Q: Hamiltonian vector field vs Heisenberg picture, from a view point of geometric quantization Let $(M,\omega)$ be a symplectic manifold, and let $X_f$ denote the Hamiltonian vector field for $f\in C^{\infty}(M)$. I know that the integral curve
$$(X_H)_{\gamma (t)}=\dot{\gamma}(t)$$
means the Hamiltonian equation. If the symplectic form $\omega$ is exact, that is, $\omega=d\theta$ for some $1$-form $\theta$ on $M$, then we can find the prequantization $Q$ defined by
$$Q(f)=i\hbar \left(X_f-\frac{i}{\hbar}\theta(X_f) \right)+f$$
for each $f\in C^{\infty}(M)$. And it satisfies the relation
$$\frac{i}{\hbar}[Q(f),Q(g)]=Q(\{f,g\})$$
(see the page469 of Brain.C.Hall), where $\{f,g\}=\omega(X_f,X_g)$ is the Poisson bracket.
On the other hand, in the quantum mechanics, we consider the Heisenberg equation
$$\frac{i}{\hbar}[\hat{H},A(t)]=\frac{d}{dt} A(t).$$
Since $X_H(f)=\{H,f\}$ holds, it seems likely that the Heisenberg picture would be quantized by applying the prequantization $Q$ to the Hamiltonian equation, but it is not rigorous. Are there any relation between them?
My attempt. For a curve $\gamma(t)$, we consider the Dirac delta function $\delta_{\gamma(t)}$. If the operator $X_H$ can act distributions and if the Poisson bracket $\{\cdot,\cdot\}$ can be also defined for delta functions, then it might be true that
$$(X_H)_{\gamma(t)}=X_H(\delta_{\gamma(t)})=\{H,\delta_{\gamma(t)} \}.$$
If it holds, then the Hamiltonian equation might turn into
$$\{H,\delta_{\gamma(t)}\}=\frac{d}{dt}\delta_{\gamma(t)}.$$
Letting $A(t)=Q(\delta_{\gamma(t)})$ and applying $Q$ to the previous equation, then we could have the Heisenberg picture
$$\frac{i}{\hbar}[Q(H),A(t)]=\frac{d}{dt}A(t).$$
Will it be mathematically justified? In addition, the $Q(H)$ is just self-adjoint? Furthermore, would the Heisenberg picture induce the classical mechanics $(X_H)_{\gamma(t)}=\dot{\gamma}(t)$?

A: The bracket equation gives us a straightforward way to quantize into the Heisenberg picture. If $Q$ has $\{f,g\}=-\frac{i}{\hbar}[Q(f),Q(g)]$ then for  Heisenberg picture if $H,f\in C^\infty(M)$ and $H$ is the Hamiltonian, $$\frac{d}{dt}Q(f)=\frac{i}{\hbar}[Q(H),Q(f)]=Q(\{f,H\})$$ Recall that in Hamiltonian mechanics, $\frac{d}{dt}f=\{f,H\}$ meaning that in this case we have $$\frac{d}{dt}Q(f)=Q\left(\frac{d}{dt}f\right)$$ This tells us that the time evolution commutes with the quantization, and that in any system which satisfies the quantization condition the time evolution of quantized observables corresponds to the quantization of their time evolution.
In your discussion, I believe you can make most of the equations and notions rigorous through weak derivatives and functional analysis, but it is not clear that what you have written gives any indication to the correspondence between the classical observable picture and the quantized Heisenberg picture.


text:
Q: convert epoch time to readable time foramt I wrote a code which convert epoch time to readable time
sd=`date -d '1970-01-01 UTC '$SDATE' seconds' +"%d-%m-%Y"`

the output is : 27-12-2002 but I want the output to be : 27/Nov/2002
how should i change my code?

A: sd=`date -d '1970-01-01 UTC '$SDATE' seconds' +"%d/%b/%Y"
I believe

A: There's a shortcut for "time from unix stamp": date -d @$STAMP. For the output, read man date

A: Use %b instead:
sd=`date -d '1970-01-01 UTC '$SDATE' seconds' +"%d/%b/%Y"`

Read man date for more details:


text:
Q: if na tela antes da consulta ser realizada Estou tentando criar um consultor com PHP que faz uma requisição em um formulário com um e-mail do cliente e me retorna se ele é cadastrado no serviço. O problema é que quando inicio minha página diretamente o if me imprime na tela o valor true (ele só deve me passa os valores do if depois da consulta feita).
Código HTML:

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

    <title>.::Cliente Consultor::.</title>

<form method="POST">

.::Consulta::.<img src=""

<input type="text" name="bin">
<input type="submit">

</form>

Código PHP:
<?php

 error_reporting(0);

$bin = $_POST['bin'];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://minhaconta.payleven.com.br/forgot-password");
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

           curl_setopt( $ch, CURLOPT_POSTFIELDS, "password_token_type[email]=$bin" );
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            $s = curl_exec($ch);

$mensagem = ' ';

if ($1 == $2)

{

            $q = explode('</title>', $s);
            $1 = $q[1];
            $2 = $q[1];
            $binchecker = " [".$bin."] ";

$mensagem = 'cliente encontrado';

}

else

{

$mensagem= 'cliente não cadastrado';

}

   echo "

".$mensagem."";

?>

A: *

*Para executar um código PHP apenas quando o formulário é submetido, você precisa fazer uma verificação do método HTTP da requisição tratada e os campos presentes nessa requisição.
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Código aqui...
}

*Não utilize error_reporting(0) sem saber o que está fazendo. Ao meu ver, você jamais deveria utilizar esta linha de código. Isso ocultará qualquer mensagem de erro no seu código, mas as mensagens de erro são suas melhores amigas.

*O PHP não permite variáveis com nomes iniciando com números, apenas com letra ou sublinhado. Leia a documentação para mais detalhes.

*Não faz sentido você verificar o valor de duas variáveis antes de definí-la. Você está definindo o valor de $1 e $2 apenas dentro do if, então na condição $1 == $2 nenhuma das duas existe.

Lembrando que $1 e $2 não são nomes válidos para variáveis.

*Também não faz sentido você fazer o echo de um elemento HTML fora da tag html e body. A mensagem deveria ser devidamente exibida no corpo da página.


text:
Q: Lines not visible on a KML file I have a set of points that are joined by using kml.linestring . But,  I want to colour code those lines   based on the speeds at those lines (  which I have available)> The problem is that my kml file, when rendered on google maps,  doesn't  render the lines at all :(
If I do the same thing for a different set of co-ordinates, which are polygons, it works totally fine. Infact, if I do not colour code the lines and just use the default colour, it renders the lines perfectly. But, I need the colour coding. I am attaching the code below:
public static void drawKML(File f) throws IOException
    {
        final  Kml kml= KmlFactory.createKml();
        final  Document document = kml.createAndSetDocument().withName("Document.kml").withOpen(true);

        final LineStyle style1=document.createAndAddStyle().withId("linestyleExample1").createAndSetLineStyle().withColor("ff000000");
        final LineStyle style2=document.createAndAddStyle().withId("linestyleExample2").createAndSetLineStyle().withColor("ff008cff");

        final LineStyle style3=document.createAndAddStyle().withId("linestyleExample3").createAndSetLineStyle().withColor("ff008000");
        FileInputStream fstream=new FileInputStream(f);
        DataInputStream in=new DataInputStream(fstream);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String line=br.readLine();
        Placemark placemark1;

        while(line!=null)
        {
            String[] alpha=line.split(" ");
            double speed=Double.parseDouble(alpha[4])*3.6;
            String description="";
            description=description+"Speed="+speed+"\n";

            if(speed>=0 && speed<=15) {
                document.createAndAddPlacemark().withStyleUrl("#linestyleExample1").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
                logger.error("In black range");
            }
            else if(speed>15 && speed<=35) {
                document.createAndAddPlacemark().withStyleUrl("#linestyleExample2").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
                logger.error("In orange range");
                }
            else {
                document.createAndAddPlacemark().withStyleUrl("#linestyleExample3").withDescription(description).createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
                logger.error("In green");
            }
            //placemark1.createAndSetLineString().withExtrude(true).withTessellate(true).addToCoordinates(Double.parseDouble(alpha[1]), Double.parseDouble(alpha[0])).addToCoordinates(Double.parseDouble(alpha[3]),Double.parseDouble(alpha[2]));
            line=br.readLine();

        }
        kml.marshal(new File(path/to/file));
    }

This is how it looks:

This is how it should look:

Fragment from the faulty kml file ( which doesn't represent any points ) :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
    <Document>
            <name>Document.kml</name>
        <open>1</open>
        <Style id="linestyleExample1">
            <LineStyle>
                <color>ff000234</color>
                <width>0.0</width>
            </LineStyle>
        </Style>
        <Style id="linestyleExample2">
            <LineStyle>
                <color>ff008cff</color>
                <width>0.0</width>
            </LineStyle>
        </Style>
        <Style id="linestyleExample3">
            <LineStyle>
                <color>ff006400</color>
                <width>0.0</width>
            </LineStyle>
        </Style>
        <Placemark>
            <description>Speed=0.0
</description>
            <styleUrl>#linestyleExample1</styleUrl>
            <LineString>
                <extrude>1</extrude>
                <tessellate>1</tessellate>
                <coordinates>78.48419,17.38463 78.48302,17.38328</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=0.0
</description>
            <styleUrl>#linestyleExample1</styleUrl>
            <LineString>
                <extrude>1</extrude>
                <tessellate>1</tessellate>
                <coordinates>78.48302,17.38328 78.48244,17.38264</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=0.0
</description>
            <styleUrl>#linestyleExample1</styleUrl>
            <LineString>
                <extrude>1</extrude>
                <tessellate>1</tessellate>
                <coordinates>78.48244,17.38264 78.48173,17.38204</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=51.4415867904
</description>
            <styleUrl>#linestyleExample3</styleUrl>
            <LineString>
                <coordinates>78.48173,17.38204 78.48068,17.38264</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=51.4415867904
</description>
            <styleUrl>#linestyleExample3</styleUrl>
            <LineString>
                <coordinates>78.48068,17.38264 78.47993,17.3829</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=90.72
</description>
            <styleUrl>#linestyleExample3</styleUrl>
            <LineString>
                <coordinates>78.47993,17.3829 78.47677,17.38331</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=76.46400000000001
</description>
            <styleUrl>#linestyleExample3</styleUrl>
            <LineString>
                <coordinates>78.47677,17.38331 78.47521,17.38359</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=61.56000000000001
</description>
            <styleUrl>#linestyleExample3</styleUrl>
            <LineString>
                <coordinates>78.47521,17.38359 78.47506,17.38353</coordinates>
            </LineString>
        </Placemark>
        <Placemark>
            <description>Speed=0.0
</description>
            <styleUrl>#linestyleExample1</styleUrl>
            <LineString>
                <extrude>1</extrude>
                <tessellate>1</tessellate>

Fragment from one which does represent it correctly :
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
    <Document id="feat_1">
        <Style id="stylesel_0">
            <LineStyle>
                <color>ff000000</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_1">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_2">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_3">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_4">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_5">
            <LineStyle>
                <color>ff008000</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_6">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_7">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_8">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_9">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_10">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_11">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_12">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_13">
            <LineStyle>
                <color>ff008000</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_14">
            <LineStyle>
                <color>ff008000</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_15">
            <LineStyle>
                <color>ff008cff</color>
                <colorMode>normal</colorMode>
            </LineStyle>
        </Style>
        <Style id="stylesel_16">

They are different as the second one has been generated using Python ( which  generates a lot of linestyles first and then assigns them one by one to the points . )

A: The reason is that in the 'faulty' kml your linestyles have a explicit width definition of 0.0 Change it to a positive number (5.0 or so) and you'll see your lines or remove it completly to use the default width
Codewise I don't know the lib you are using but I would guess something like this should do the trick
final LineStyle style2=
    document.createAndAddStyle()
            .withId("linestyleExample2")
            .createAndSetLineStyle()
            .withColor("ff008cff")
            .withWidth(5.0d);


text:
Q: How can I escape null check when call a API? When I write RestController in Spring, all time I check whether object is null or not. How can I escape this check?
In below example, there is null check and later return notFound or Http status 404. So I don't want to check it all time.
  @GetMapping(path = "/api/member/{member-id}")
  public ResponseEntity<Member> getMemberById(@PathVariable(name="member-id", required=true) final Long memberId) {
    final Member member = memberService.findById(memberId);
    if (member != null) {
      return ResponseEntity.ok(member);
    }
    return ResponseEntity.notFound().build();
  }

A: Although you cannot avoid the null-check itself, you can move it out of the Controller into the service (also, use Optional). If you are looking for a general strategy to handle negative response scenarios, I'd suggest using Spring's RestControllerAdvice annotation that will enable global exception handling for all your APIs:
Let's first move the check to the service and raise a custom exception MemberNotFoundException in case no record is found.
DefaultMemberService.java
public Member findById(final String memberId) {
  Optional<Member> member = memberRepository.findById(memberId);
  return member.orElseThrow(() -> new MemberNotFoundException("Invalid member Id"));
}

In the Controller, just make a call to the service method, and return the response.
MemberController.java
@GetMapping(path = "/api/member/{member-id}")
public ResponseEntity<Member> getMemberById(@PathVariable(name="member-id", required=true) final Long memberId) {

  return ResponseEntity.ok().body(memberService.findById(memberId));
}

As you can see, we're not handling the exception explicitly. Instead we'll let RestControllerAdvice do it for us by mapping the exception class to the response (error message, response code):
ExceptionHandlerControllerAdvice.java
@RestControllerAdvice
public final class ExceptionHandlerControllerAdvice {

  @ExceptionHandler({ MemberNotFoundException.class })
  @ResponseStatus(HttpStatus.NOT_FOUND)
  ResponseEntity<ErrorDto> handleRecordNotFound(MemberNotFoundException ex) {
    return ResponseEntity.status(HttpStatus.NOT_FOUND)
        .body(new ErrorDto(ex.getMessage));
  }
}

where, ErrorDto (simplified) is:
public class ErrorDto {
  private String message;

  public ErrorDto(String msg) { this.message = msg; }

  public String getMessage() { return this.message; }
}

Ref: RestControllerAdvice, ExceptionHandler

A: That is perfectly fine.
Alternatively, memberService.findById can return an Optional<Member> instead, then you can do something like:
memberService.findById(memberId)
  .map(it -> ResponseEntity.ok(member).build())
  .orElse(ResponseEntity.notFound().build());

You can also "encode" the return type in an exception type, and whenever you are searching for the requested resource at the database tier/layer, if not present you can throw that exception that gets translated into an HTTP Not Found downstream – in some exception handler. In that case you wouldn't need to worry about the different return types in the controller – but all that magic also comes with some drawbacks, for instance, it wouldn't be quite clear (for newcomers) what's going on just by inspecting the code, unless you've been working on it for a while.
Moreover, if you are looking not to repeat the same null check, you can wrap that in a generic/common method.


text:
Q: HTML print > instead of </> I set text in a html Element with JQuery like that
$('#xmlTextArea').text(prepareXML(response))

I want to replace all < and > with > and < as I use a prettify Lib, that doesn't recognize the entities. I replace it like that:
function prepareXML(req){
    str = req.replace(/</g,"<")
    str = str.replace(/>/g,">")
    console.log(str)
    return str
}

But now it prints the String > instead of the sign >. So to summarize I want the output to look the same, but beeing > under the hood

A: The text() method internally do the same, so there is no need to call the prepareXML method.
$('#xmlTextArea').text(response)

Or use html() method instead.

$('#xmlTextArea').html(prepareXML(response))


text:
Q: Getting Nullpointerexception in fragment I am working on App where i am attaching 5 fragments on an activity. Everything is working great but when i put my app in background from any fragment and after some time when my app resumes it crashes. I get reference of my Activty as null. here is my code
This is code in Activty from where i am attaching fragment
   FragmentManager fragmentManager = getSupportFragmentManager();
   searchFragment = SearchFragment.newInstance(MainBaseActivity.this);
   fragmentTransaction = fragmentManager.beginTransaction();
   fragmentTransaction.add(R.id.frameLayoutMain, searchFragment, "SearchFragment");
   fragmentTransaction.commit();

And this is my Fragment class
   public static SearchFragment newInstance(MainBaseActivity mainBaseActivity) {

    fragment = new SearchFragment();
    fragment.mainBaseActivity = mainBaseActivity;
    fragment.inflater = (LayoutInflater) mainBaseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    fragment.myApplication = ((MyApplication) mainBaseActivity.getApplicationContext());
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.search_fragment, container, false);

    preferences = mainBaseActivity.getSharedPreferences(Constant.CHAI_APP, Context.MODE_PRIVATE);  // here i get null pointer
    editor = preferences.edit();

    return view;
}

A: Fragment has the getActivity() method to retrieve the activity to which it is attached. Use it in place of mainBaseActivity

A: Fragments can be killed and recreated by the system at various times. You cannot trust the kind of initialization you do in your newInstance() - when the fragment is recreated, the fields won't be initialized.
Remove these initializations:
fragment.mainBaseActivity = mainBaseActivity;
fragment.inflater = (LayoutInflater) mainBaseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
fragment.myApplication = ((MyApplication) mainBaseActivity.getApplicationContext());

and use getActivity() in your fragment when you need to access your hosting activity or the Application.
For inflater, one is already passed in as an argument to onCreateView(). No need to fetch it yourself.
(To pass params to a fragment that persist over fragment recreation, use setArguments().)


text:
Q: Java Web Services and returning Vector> Little different from my previous question. I want to keep these as 2 individual questions (as the other one was answered).
I have a web service which I want to pass back a Vector<Vector<Object>> or ArrayList<ArrayList<Object>> to the client. For this I have created a simple POJO class (thanks Abhisek Bose) for this called VectorWS. The implementation using the Vector is as follows:
public class VectorWS {
    private Vector vector;

    public VectorWS() {
    }

    public VectorWS(Vector v) {
        vector = v;
    }

    public Vector getVector() {
        return vector;
    }

    public void setVector(Vector vector) {
        this.vector = vector;
    }
}

The interface implementation is as follows:
@WebService
@SOAPBinding(style = Style.RPC)
public interface ISQLServerConnectionWS {

    @WebMethod
    VectorWS executeSelectSQL(@WebParam(name = "sqlStatements") String sqlStatements);
}

The server implementation is as follows:
@WebService(endpointInterface="WebServices.ISQLServerConnectionWS")
public class SQLConnectionWSServer
    implements ISQLServerConnectionWS {

    @Override
    public VectorWS executeSelectSQL(String sqlStatements) {
        System.out.println("You are calling executeSelectSQL with " + sqlStatements );
        Vector results = new Vector();
        Vector row1 = new Vector();
        Vector row2 = new Vector();
        row1.add( "Name" );
        row2.add( "Asamoah" );
        results.add( row1 );
        results.add( row2 );

        VectorWS vws = new VectorWS(new ArrayList(results));

        return vws;
    }
}

Client calls the server service method as:
VectorWS results = server.executeSelectSQL( sqlStatements );

However, the server throws an exception when the vws is returned. I have tried this for both Vector and ArrayList.
The exception (from the ArrayList) in this instance can be found at the end of the post.
My question is if we cannot return ArrayList<ArrayList<Object>> what would one recommend?
Only thing that comes to mind would be ArrayList<Object[]>.  Any ideas?
Many thanks,
Andez
Here is the exception stack trace:
javax.xml.ws.WebServiceException: javax.xml.bind.MarshalException
 - with linked exception:
[javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]
at com.sun.xml.internal.ws.message.jaxb.JAXBMessage.writePayloadTo(JAXBMessage.java:318)
at com.sun.xml.internal.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:131)
at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:98)
at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:249)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.encodePacket(HttpAdapter.java:328)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.access$100(HttpAdapter.java:82)
at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:470)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:233)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:95)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:80)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:65)
at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:65)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:68)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:555)
at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:65)
at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:527)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: javax.xml.bind.MarshalException
 - with linked exception:
[javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:268)
at com.sun.xml.internal.bind.v2.runtime.BridgeImpl.marshal(BridgeImpl.java:89)
at com.sun.xml.internal.bind.api.Bridge.marshal(Bridge.java:130)
at com.sun.xml.internal.ws.message.jaxb.JAXBMessage.writePayloadTo(JAXBMessage.java:310)
... 18 more
Caused by: javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:234)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:249)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:641)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.serializeItem(ArrayElementNodeProperty.java:54)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:157)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:141)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:321)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:687)
at com.sun.xml.internal.bind.v2.runtime.BridgeImpl.marshal(BridgeImpl.java:136)
at com.sun.xml.internal.bind.v2.runtime.CompositeStructureBeanInfo.serializeBody(CompositeStructureBeanInfo.java:96)
at com.sun.xml.internal.bind.v2.runtime.CompositeStructureBeanInfo.serializeBody(CompositeStructureBeanInfo.java:44)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:687)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:263)
... 21 more
Caused by: javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:554)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:636)
... 31 more

A: Have you tried Serializing the object, then running Base64 on the serialization, returning that over the wire, and then decoding the base64 and deserializing upon receipt?
Basically your method now would return a string, that is the Base64 encoded serialization of the List/Vectors, and the receiver would need to unencode the string and decode the object.
I have used this sort of technique to serialize and deserialize complex list and vector objects.

A: In a nutshell, following on from user756212's answer, the VectorWS can be serialized/deserialized with:
public String serialize(Object o) {
        String s;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream( stream ) );

        encoder.writeObject(o);
        encoder.close();
        s = stream.toString();
        return s;
    }

private Object deserialize(String s) {

    XMLDecoder decoder = new XMLDecoder( new ByteArrayInputStream( s.getBytes() ) );
    return decoder.readObject();
}

And called with:
VectorWS vws = (VectorWS) deserialize( results );


text:
Q: Appium Port occupied I'm trying to learn Appium but I'm already stuck in the beginning.
When I try to start Appium using the terminal I get an error message that looks like this:
Could not start REST http interface listener. The requested port may already be in use. Please make sure there is no other instance of this server running already.
Fatal Error: listen EADDRINUSE: address already in use 0.0.0.0:4723

So I tried to find out what instance is using that port using the statement lsof -i :4723
I found out there is a running node instance that uses this port so I tried to kill the instance with kill -9 PID . After I killed the instance I used lsof -i :4723 again to see if it worked but the node instance was still there but with a new PID. I guess the kill was successful but node just immediately starts a new instance and occupies the port 4237.
Is there anyone who might have an idea what I can try or maybe knows a solution to this problem?
I found a small workaround which works for now but shouldn't be final. When I use kill -9 PID | appium it works because Appium occupies the port immediately after kill got executed.
Thanks for your help in advance

A: Try running appium on different port appium -p 4725